Browse Source

+ WASI: use an initial heap area, that exists between the end of the stack area,
and before the end of initially allocated memory. This recovers some memory
that was previously wasted and delays the first call to memory.grow

Nikolay Nikolov 1 year ago
parent
commit
c95dfe24e7
2 changed files with 20 additions and 5 deletions
  1. 19 5
      rtl/wasi/sysheap.inc
  2. 1 0
      rtl/wasi/system.pp

+ 19 - 5
rtl/wasi/sysheap.inc

@@ -20,27 +20,41 @@
                               Heap Management
                               Heap Management
 *****************************************************************************}
 *****************************************************************************}
 
 
+const
+  WasmMemoryPageSize=65536;
+
 var
 var
   InitialHeapBlockStart: Pointer;
   InitialHeapBlockStart: Pointer;
+  InitialHeapBlockEnd: Pointer;
 
 
 procedure SetInitialHeapBlockStart(p: Pointer);[Public, Alias : 'FPC_WASM_SETINITIALHEAPBLOCKSTART'];
 procedure SetInitialHeapBlockStart(p: Pointer);[Public, Alias : 'FPC_WASM_SETINITIALHEAPBLOCKSTART'];
 begin
 begin
   InitialHeapBlockStart:=p;
   InitialHeapBlockStart:=p;
 end;
 end;
 
 
+procedure InitInitialHeapBlock;
+begin
+  InitialHeapBlockEnd:=Pointer(PtrUInt(fpc_wasm32_memory_size)*WasmMemoryPageSize);
+end;
+
 function SysOSAlloc(size: ptruint): pointer;
 function SysOSAlloc(size: ptruint): pointer;
 const
 const
-  page_size = 65536;
   err = high(longword);
   err = high(longword);
 var
 var
   res: ptruint;
   res: ptruint;
 begin
 begin
-  res:=fpc_wasm32_memory_grow((size + page_size - 1) div page_size);
-  if res<>err then
-    SysOSAlloc:=pointer(res*page_size)
+  if (PtrUInt(InitialHeapBlockEnd)-PtrUInt(InitialHeapBlockStart))>=size then
+    begin
+      SysOSAlloc:=InitialHeapBlockStart;
+      Inc(InitialHeapBlockStart,size);
+    end
   else
   else
     begin
     begin
-    SysOSAlloc:=nil;
+      res:=fpc_wasm32_memory_grow((size + WasmMemoryPageSize - 1) div WasmMemoryPageSize);
+      if res<>err then
+        SysOSAlloc:=pointer(res*WasmMemoryPageSize)
+      else
+        SysOSAlloc:=nil;
     end;
     end;
 end;
 end;
 
 

+ 1 - 0
rtl/wasi/system.pp

@@ -435,6 +435,7 @@ begin
   IsLibrary := FALSE;
   IsLibrary := FALSE;
 {$endif def FPC_HAS_FEATURE_DYNLIBS}
 {$endif def FPC_HAS_FEATURE_DYNLIBS}
   { Setup heap }
   { Setup heap }
+  InitInitialHeapBlock;
   InitHeap;
   InitHeap;
   SysInitExceptions;
   SysInitExceptions;
   initunicodestringmanager;
   initunicodestringmanager;