Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

NumPico: Lua in less memory

Mason363f512a576332b
diff --git a/games/numpico/src/femto8/lua/lcode.c b/games/numpico/src/femto8/lua/lcode.c
index 68dde538..2680efdc 100644
--- a/games/numpico/src/femto8/lua/lcode.c
+++ b/games/numpico/src/femto8/lua/lcode.c
@@ -2,6 +2,8 @@
** $Id: lcode.c,v 2.62 2012/08/16 17:34:28 roberto Exp $
** Code generator for Lua
** See Copyright Notice in lua.h
+** Changed for NumPico: no line numbers kept for the instructions (see ldebug.h); constants found
+** without a table.
*/
@@ -216,10 +218,7 @@ static int luaK_code (FuncState *fs, Instruction i) {
luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,
MAX_INT, "opcodes");
f->code[fs->pc] = i;
- /* save corresponding line information */
- luaM_growvector(fs->ls->L, f->lineinfo, fs->pc, f->sizelineinfo, int,
- MAX_INT, "opcodes");
- f->lineinfo[fs->pc] = fs->ls->lastline;
+ /* (NumPico: no line for each instruction, see ldebug.h) */
return fs->pc++;
}
@@ -290,23 +289,17 @@ static void freeexp (FuncState *fs, expdesc *e) {
static int addk (FuncState *fs, TValue *key, TValue *v) {
lua_State *L = fs->ls->L;
- TValue *idx = luaH_set(L, fs->h, key);
Proto *f = fs->f;
int k, oldsize;
- if (ttisnumber(idx)) {
- lua_Number n = nvalue(idx);
- lua_number2int(k, n);
+ (void)key;
+ /* (NumPico: the function's constants looked through in turn, not in a table: such tables took
+ kilobytes the calculator doesn't have) */
+ for (k = 0; k < fs->nk; k++)
if (luaV_rawequalobj(&f->k[k], v))
return k;
- /* else may be a collision (e.g., between 0.0 and "\0\0\0\0\0\0\0\0");
- go through and create a new entry for this value */
- }
/* constant not found; create a new entry */
oldsize = f->sizek;
k = fs->nk;
- /* numerical value does not need GC barrier;
- table has no metatable, so it does not need to invalidate cache */
- setnvalue(idx, cast_num(k));
luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants");
while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
setobj(L, &f->k[k], v);
@@ -328,14 +321,8 @@ int luaK_numberK (FuncState *fs, lua_Number r) {
lua_State *L = fs->ls->L;
TValue o;
setnvalue(&o, r);
- if (r == 0 || luai_numisnan(NULL, r)) { /* handle -0 and NaN */
- /* use raw representation as key to avoid numeric problems */
- setsvalue(L, L->top++, luaS_newlstr(L, (char *)&r, sizeof(r)));
- n = addk(fs, L->top - 1, &o);
- L->top--;
- }
- else
- n = addk(fs, &o, &o); /* regular case */
+ (void)L;
+ n = addk(fs, &o, &o); /* (NumPico: fixed point numbers have no -0 and no NaN) */
return n;
}
@@ -891,7 +878,7 @@ void luaK_posfix (FuncState *fs, BinOpr op,
void luaK_fixline (FuncState *fs, int line) {
- fs->f->lineinfo[fs->pc - 1] = line;
+ (void)fs; (void)line;
}
diff --git a/games/numpico/src/femto8/lua/ldebug.c b/games/numpico/src/femto8/lua/ldebug.c
index 7868d0fe..4bae6daa 100644
--- a/games/numpico/src/femto8/lua/ldebug.c
+++ b/games/numpico/src/femto8/lua/ldebug.c
@@ -2,6 +2,7 @@
** $Id: ldebug.c,v 2.90.1.3 2013/05/16 16:04:15 roberto Exp roberto $
** Debug Interface
** See Copyright Notice in lua.h
+** Changed for NumPico: 2-byte line numbers.
*/
@@ -216,7 +217,7 @@ static void collectvalidlines (lua_State *L, Closure *f) {
else {
int i;
TValue v;
- int *lineinfo = f->l.p->lineinfo;
+ lineinfo_t *lineinfo = f->l.p->lineinfo;
Table *t = luaH_new(L); /* new table to store active lines */
sethvalue(L, L->top, t); /* push it on stack */
api_incr_top(L);
diff --git a/games/numpico/src/femto8/lua/ldebug.h b/games/numpico/src/femto8/lua/ldebug.h
index fe39556b..1b6014e4 100644
--- a/games/numpico/src/femto8/lua/ldebug.h
+++ b/games/numpico/src/femto8/lua/ldebug.h
@@ -13,7 +13,9 @@
#define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1)
-#define getfuncline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : 0)
+/* (NumPico: an instruction's line is its function's first: lines would take 2 bytes for each
+ instruction, too much for the calculator's RAM) */
+#define getfuncline(f,pc) ((void)(pc), (f)->linedefined)
#define resethookcount(L) (L->hookcount = L->basehookcount)
diff --git a/games/numpico/src/femto8/lua/lgc.c b/games/numpico/src/femto8/lua/lgc.c
index 9e77f9b3..10042f95 100644
--- a/games/numpico/src/femto8/lua/lgc.c
+++ b/games/numpico/src/femto8/lua/lgc.c
@@ -2,6 +2,7 @@
** $Id: lgc.c,v 2.140.1.2 2013/04/26 18:22:05 roberto Exp roberto $
** Garbage Collector
** See Copyright Notice in lua.h
+** Changed for NumPico: 2-byte line numbers.
*/
#include <string.h>
@@ -470,7 +471,7 @@ static int traverseproto (global_State *g, Proto *f) {
return sizeof(Proto) + sizeof(Instruction) * f->sizecode +
sizeof(Proto *) * f->sizep +
sizeof(TValue) * f->sizek +
- sizeof(int) * f->sizelineinfo +
+ sizeof(lineinfo_t) * f->sizelineinfo +
sizeof(LocVar) * f->sizelocvars +
sizeof(Upvaldesc) * f->sizeupvalues;
}
diff --git a/games/numpico/src/femto8/lua/linit.c b/games/numpico/src/femto8/lua/linit.c
index 3c953947..3ea93dd2 100644
--- a/games/numpico/src/femto8/lua/linit.c
+++ b/games/numpico/src/femto8/lua/linit.c
@@ -2,6 +2,7 @@
** $Id: linit.c,v 1.32 2011/04/08 19:17:36 roberto Exp $
** Initialization of libraries for lua.c and other clients
** See Copyright Notice in lua.h
+** Changed for NumPico: no coroutine and string tables (PICO-8 has cocreate, coresume, sub, chr and the others instead).
*/
@@ -29,8 +30,6 @@
static const luaL_Reg loadedlibs[] = {
{"_G", luaopen_base},
{"_G", luaopen_pico8},
- {LUA_COLIBNAME, luaopen_coroutine},
- {LUA_STRLIBNAME, luaopen_string},
{NULL, NULL}
};
diff --git a/games/numpico/src/femto8/lua/llex.c b/games/numpico/src/femto8/lua/llex.c
index ee91ad21..427cb471 100644
--- a/games/numpico/src/femto8/lua/llex.c
+++ b/games/numpico/src/femto8/lua/llex.c
@@ -2,6 +2,7 @@
** $Id: llex.c,v 2.63.1.2 2013/08/30 15:49:41 roberto Exp roberto $
** Lexical Analyzer
** See Copyright Notice in lua.h
+** Changed for NumPico: no table keeping the strings while the code is read (the collector is stopped then).
*/
@@ -130,22 +131,9 @@ l_noret luaX_syntaxerror (LexState *ls, const char *msg) {
** (by that time it should be anchored in function's prototype)
*/
TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
- lua_State *L = ls->L;
- TValue *o; /* entry for `str' */
- TString *ts = luaS_newlstr(L, str, l); /* create new string */
- setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */
- o = luaH_set(L, ls->fs->h, L->top - 1);
- if (ttisnil(o)) { /* not in use yet? (see 'addK') */
- /* boolean value does not need GC barrier;
- table has no metatable, so it does not need to invalidate cache */
- setbvalue(o, 1); /* t[string] = true */
- luaC_checkGC(L);
- }
- else { /* string already present */
- ts = rawtsvalue(keyfromval(o)); /* re-use value previously stored */
- }
- L->top--; /* remove string from stack */
- return ts;
+ /* (NumPico: the collector is stopped while the code is read, pico.c, so the strings need no table
+ to keep them: such tables took kilobytes the calculator doesn't have) */
+ return luaS_newlstr(ls->L, str, l);
}
diff --git a/games/numpico/src/femto8/lua/llimits.h b/games/numpico/src/femto8/lua/llimits.h
index 927ad490..4508502d 100644
--- a/games/numpico/src/femto8/lua/llimits.h
+++ b/games/numpico/src/femto8/lua/llimits.h
@@ -2,6 +2,7 @@
** $Id: llimits.h,v 1.103 2013/02/20 14:08:56 roberto Exp $
** Limits, basic types, and some other `installation-dependent' definitions
** See Copyright Notice in lua.h
+** Changed for NumPico: fewer nested C calls and parser levels (the stack is 32 KB).
*/
#ifndef llimits_h
@@ -116,7 +117,10 @@ typedef LUAI_UACNUMBER l_uacNumber;
** in a program. (Value must fit in an unsigned short int.)
*/
#if !defined(LUAI_MAXCCALLS)
-#define LUAI_MAXCCALLS 200
+/* (NumPico: the calculator's stack is 32 KB, and a C call into Lua takes about 400 bytes of it, a level
+ of the parser 150: 32 calls and 64 levels fit, beside 14 KB of Lua's memory, pico.h) */
+#define LUAI_MAXCCALLS 32
+#define LUAI_MAXPARSE 64
#endif
/*
diff --git a/games/numpico/src/femto8/lua/lobject.h b/games/numpico/src/femto8/lua/lobject.h
index 411dbd85..f8973edf 100644
--- a/games/numpico/src/femto8/lua/lobject.h
+++ b/games/numpico/src/femto8/lua/lobject.h
@@ -2,6 +2,7 @@
** $Id: lobject.h,v 2.71.1.1 2013/04/12 18:48:47 roberto Exp roberto $
** Type definitions for Lua objects
** See Copyright Notice in lua.h
+** Changed for NumPico: 2-byte line numbers.
*/
@@ -454,6 +455,9 @@ typedef struct Upvaldesc {
** Description of a local variable for function prototypes
** (used for debug information)
*/
+/* (NumPico: a cart's code has fewer than 65536 lines, so a line takes 2 bytes, not 4) */
+typedef unsigned short lineinfo_t;
+
typedef struct LocVar {
TString *varname;
int startpc; /* first point where variable is active */
@@ -469,7 +473,7 @@ typedef struct Proto {
TValue *k; /* constants used by the function */
Instruction *code;
struct Proto **p; /* functions defined inside the function */
- int *lineinfo; /* map from opcodes to source lines (debug information) */
+ lineinfo_t *lineinfo; /* map from opcodes to source lines (debug information) */
LocVar *locvars; /* information about local variables (debug information) */
Upvaldesc *upvalues; /* upvalue information */
union Closure *cache; /* last created closure with this prototype */
diff --git a/games/numpico/src/femto8/lua/lparser.c b/games/numpico/src/femto8/lua/lparser.c
index 601fbdf5..71c26864 100644
--- a/games/numpico/src/femto8/lua/lparser.c
+++ b/games/numpico/src/femto8/lua/lparser.c
@@ -2,6 +2,7 @@
** $Id: lparser.c,v 2.130 2013/02/06 13:37:39 roberto Exp $
** Lua Parser
** See Copyright Notice in lua.h
+** Changed for NumPico: no instruction lines (ldebug.h); a function's local names freed once it's read (the calculator's RAM is small).
*/
@@ -376,7 +377,7 @@ static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
static void enterlevel (LexState *ls) {
lua_State *L = ls->L;
++L->nCcalls;
- checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, "C levels");
+ checklimit(ls->fs, L->nCcalls, LUAI_MAXPARSE, "C levels");
}
@@ -606,14 +607,14 @@ static void close_func (LexState *ls) {
leaveblock(fs);
luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
f->sizecode = fs->pc;
- luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
- f->sizelineinfo = fs->pc;
luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
f->sizek = fs->nk;
luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
f->sizep = fs->np;
- luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
- f->sizelocvars = fs->nlocvars;
+ /* (the names of the locals were for the parser: errors say "a nil value", not "local 'x'") */
+ luaM_freearray(L, f->locvars, f->sizelocvars);
+ f->locvars = NULL;
+ f->sizelocvars = 0;
luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
f->sizeupvalues = fs->nups;
lua_assert(fs->bl == NULL);
@@ -1212,7 +1213,7 @@ static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
suffixedexp(ls, &nv.v);
if (nv.v.k != VINDEXED)
check_conflict(ls, lh, &nv.v);
- checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS,
+ checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXPARSE,
"C levels");
assignment(ls, &nv, nvars+1);
}
diff --git a/games/numpico/src/femto8/lua/lstring.c b/games/numpico/src/femto8/lua/lstring.c
index 8b5af0b2..68478111 100644
--- a/games/numpico/src/femto8/lua/lstring.c
+++ b/games/numpico/src/femto8/lua/lstring.c
@@ -2,6 +2,7 @@
** $Id: lstring.c,v 2.26 2013/01/08 13:50:10 roberto Exp $
** String table (keeps all strings handled by Lua)
** See Copyright Notice in lua.h
+** Changed for NumPico: the table of strings stops growing at 1024 lists.
*/
@@ -118,7 +119,8 @@ static TString *newshrstr (lua_State *L, const char *str, size_t l,
GCObject **list; /* (pointer to) list where it will be inserted */
stringtable *tb = &G(L)->strt;
TString *s;
- if (tb->nuse >= cast(lu_int32, tb->size) && tb->size <= MAX_INT/2)
+ /* (NumPico: 1024 lists at most, 4 KB: longer lists rather than a bigger table) */
+ if (tb->nuse >= cast(lu_int32, tb->size) && tb->size < 1024)
luaS_resize(L, tb->size*2); /* too crowded */
list = &tb->hash[lmod(h, tb->size)];
s = createstrobj(L, str, l, LUA_TSHRSTR, h, list);
diff --git a/games/numpico/src/femto8/p8_lua.c b/games/numpico/src/femto8/p8_lua.c
index a135ce18..7623773c 100644
--- a/games/numpico/src/femto8/p8_lua.c
+++ b/games/numpico/src/femto8/p8_lua.c
@@ -32,6 +32,7 @@
#include "lualib.h"
#include "lauxlib.h"
#include "../pico.h"
+#include "../heap.h"
lua_State *L = NULL;
static int m_status = 0;
@@ -2053,10 +2054,18 @@ int lua_init_script(const char *file_name, const char *script, size_t script_len
(void)file_name;
lua_settop(L, 0);
+ // (the collector stopped while the code is read: the strings the parser makes aren't kept by a
+ // table, llex.c; then what it left behind goes)
+ lua_gc(L, LUA_GCSTOP, 0);
m_status = luaL_loadbuffer(L, script, script_len, "=cart");
-
+ lua_gc(L, LUA_GCRESTART, 0);
if (m_status)
return m_status;
+ lua_gc(L, LUA_GCCOLLECT, 0);
+ {
+ extern uint32_t perf_load_used, perf_load_peak;
+ perf_load_used = heap_used(), perf_load_peak = heap_peak();
+ }
m_status = lua_pcall(L, 0, 0, 0);
return m_status;
diff --git a/games/numpico/src/heap.c b/games/numpico/src/heap.c
index 8eb81ef8..7956971f 100644
--- a/games/numpico/src/heap.c
+++ b/games/numpico/src/heap.c
@@ -1,45 +1,44 @@
-/* Lua's memory: all the RAM the app has after its own (plat_heap), without a header on any block.
+/* Lua's memory: the RAM the app has after its own (plat_heap), and more on main's stack, without a
+ * header on any block.
+ *
* Lua says how big a block is when it frees or resizes it, so a block is just its bytes, rounded up
- * to 8 (a free block's size and link; 16 on a 64-bit computer). Small blocks (up to 256 bytes,
- * most of Lua's) go back to a list of their size and come out first from there; bigger ones go back to a list kept in address order, merged with their
- * free neighbours. When a block doesn't fit anywhere, the small free blocks go back to that list
- * too, merged, and the search is made again. */
+ * to 8 (a free block's size and link; 16 on a 64-bit computer). The free blocks are in a list kept
+ * in address order, merged with their free neighbours. Small blocks (up to 256 bytes: strings,
+ * tables, closures, most of Lua's) are taken from the low end of the lowest free block they fit in,
+ * big ones (arrays: code, a table's slots, the stack) from the high end of the highest, so the two
+ * kinds don't leave holes in each other. A small block freed goes to a list of its size and is used
+ * again from there; when a block fits nowhere, those go back to the big list, merged, and the search
+ * is made again. */
#include "heap.h"
+#include <stdbool.h>
#include <stddef.h>
#include <string.h>
-#define SMALL_MAX 256
-#define GRAIN ((uint32_t)sizeof(blk_t))
-#define CLASSES (SMALL_MAX / GRAIN)
-
typedef struct blk {
uint32_t size;
struct blk *next;
} blk_t;
+#define SMALL_MAX 256
+#define GRAIN ((uint32_t)sizeof(blk_t))
+#define CLASSES (SMALL_MAX / GRAIN)
+
static blk_t *small[CLASSES];
static blk_t *big; /* address order */
-static uint8_t *lo, *hi;
-static uint32_t used, peak;
+static uint32_t used, peak, size;
-static uint32_t r8(size_t n) { return n ? (uint32_t)((n + GRAIN - 1) & ~(size_t)(GRAIN - 1)) : GRAIN; }
+static uint32_t round_up(size_t n) { return n ? (uint32_t)((n + GRAIN - 1) & ~(size_t)(GRAIN - 1)) : GRAIN; }
void heap_init(uint8_t *start, uint8_t *end) {
- lo = (uint8_t *)(((uintptr_t)start + GRAIN - 1) & ~(uintptr_t)(GRAIN - 1));
- hi = (uint8_t *)((uintptr_t)end & ~(uintptr_t)(GRAIN - 1));
memset(small, 0, sizeof small);
big = NULL;
- if (hi > lo + 16) {
- big = (blk_t *)lo;
- big->size = (uint32_t)(hi - lo);
- big->next = NULL;
- }
- used = peak = 0;
+ used = peak = size = 0;
+ heap_add(start, end);
}
uint32_t heap_used(void) { return used; }
uint32_t heap_peak(void) { return peak; }
-uint32_t heap_size(void) { return hi > lo ? (uint32_t)(hi - lo) : 0; }
+uint32_t heap_size(void) { return size; }
/* back into the address-ordered list, merged with the blocks around it */
static void put_big(uint8_t *p, uint32_t n) {
@@ -59,21 +58,45 @@ static void put_big(uint8_t *p, uint32_t n) {
*at = b;
}
-/* the first free block it fits in: its end */
-static void *take_big(uint32_t n) {
+void heap_add(uint8_t *start, uint8_t *end) {
+ uint8_t *a = (uint8_t *)(((uintptr_t)start + GRAIN - 1) & ~(uintptr_t)(GRAIN - 1));
+ uint8_t *b = (uint8_t *)((uintptr_t)end & ~(uintptr_t)(GRAIN - 1));
+ if (b <= a + 4 * GRAIN) return;
+ size += (uint32_t)(b - a);
+ put_big(a, (uint32_t)(b - a));
+}
+
+static void *take_low(uint32_t n) {
for (blk_t **at = &big; *at; at = &(*at)->next) {
blk_t *b = *at;
if (b->size < n) continue;
- if (b->size - n < GRAIN) { /* (it can't be less but 0 or GRAIN or more) */
+ if (b->size == n) {
*at = b->next;
return b;
}
- b->size -= n;
- return (uint8_t *)b + b->size;
+ blk_t *rest = (blk_t *)((uint8_t *)b + n);
+ rest->size = b->size - n;
+ rest->next = b->next;
+ *at = rest;
+ return b;
}
return NULL;
}
+static void *take_high(uint32_t n) {
+ blk_t **found = NULL;
+ for (blk_t **at = &big; *at; at = &(*at)->next)
+ if ((*at)->size >= n) found = at;
+ if (!found) return NULL;
+ blk_t *b = *found;
+ if (b->size == n) {
+ *found = b->next;
+ return b;
+ }
+ b->size -= n;
+ return (uint8_t *)b + b->size;
+}
+
/* a sorted list of blocks (merge sort on the list itself) */
static blk_t *sort(blk_t *l, int n) {
if (n <= 1) {
@@ -99,7 +122,7 @@ static blk_t *sort(blk_t *l, int n) {
static void reclaim(void) {
blk_t *all = NULL;
int n = 0;
- for (int c = 0; c < CLASSES; c++) {
+ for (int c = 0; c < (int)CLASSES; c++) {
while (small[c]) {
blk_t *b = small[c];
small[c] = b->next;
@@ -113,7 +136,6 @@ static void reclaim(void) {
all = sort(all, n);
/* (merge the two sorted lists, joining neighbours) */
blk_t *a = big, *out = NULL, *last = NULL;
- big = NULL;
while (a || all) {
blk_t **m = !all || (a && (uint8_t *)a < (uint8_t *)all) ? &a : &all;
blk_t *b = *m;
@@ -132,20 +154,30 @@ static void reclaim(void) {
static void *alloc(uint32_t n) {
void *p = NULL;
- if (n <= SMALL_MAX && small[n / GRAIN - 1]) {
+ bool tiny = n <= SMALL_MAX;
+ if (tiny && small[n / GRAIN - 1]) {
blk_t *b = small[n / GRAIN - 1];
small[n / GRAIN - 1] = b->next;
p = b;
} else {
- p = take_big(n);
+ p = tiny ? take_low(n) : take_high(n);
if (!p) {
reclaim();
- p = take_big(n);
+ p = tiny ? take_low(n) : take_high(n);
}
}
if (p) {
used += n;
if (used > peak) peak = used;
+ } else { /* (for tests/perf.py) */
+ extern uint32_t perf_fail_size, perf_fail_used, perf_fail_largest, perf_fail_map[128];
+ perf_fail_size = n, perf_fail_used = used, perf_fail_largest = 0;
+ int k = 0;
+ for (blk_t *b = big; b; b = b->next) {
+ if (b->size > perf_fail_largest) perf_fail_largest = b->size;
+ if (k < 128) perf_fail_map[k++] = (uint32_t)(uintptr_t)b, perf_fail_map[k++] = b->size;
+ }
+ if (k < 128) perf_fail_map[k] = 0;
}
return p;
}
@@ -163,21 +195,57 @@ static void release(void *p, uint32_t n) {
void *heap_alloc(void *ud, void *ptr, size_t osize, size_t nsize) {
(void)ud;
- if (!ptr) return nsize ? alloc(r8(nsize)) : NULL;
- uint32_t o = r8(osize);
+ if (!ptr) return nsize ? alloc(round_up(nsize)) : NULL;
+ uint32_t o = round_up(osize);
if (!nsize) {
release(ptr, o);
return NULL;
}
- uint32_t n = r8(nsize);
+ uint32_t n = round_up(nsize);
if (n == o) return ptr;
- if (n < o) { /* the end of it goes back */
- release((uint8_t *)ptr + n, o - n);
- return ptr;
+ /* a big block growing: into the free block just before it or just after it, when one's big enough
+ (a table's slots and Lua's stack grow by doubling: moved each time, they'd leave holes) */
+ if (n > o && o > SMALL_MAX) {
+ uint8_t *p = ptr;
+ blk_t **at = &big;
+ while (*at && (uint8_t *)*at + (*at)->size < p) at = &(*at)->next;
+ blk_t *b = *at;
+ if (b && (uint8_t *)b + b->size == p && b->size >= n - o) { /* (before: the data moves down) */
+ uint8_t *q = p - (n - o);
+ if (b->size == n - o) *at = b->next;
+ else b->size -= n - o;
+ memmove(q, p, o);
+ used += n - o;
+ if (used > peak) peak = used;
+ return q;
+ }
+ if (b && (uint8_t *)b + b->size == p) b = b->next;
+ if (b && (uint8_t *)b == p + o && b->size >= n - o) { /* (after) */
+ blk_t **link = (uint8_t *)*at == p + o ? at : &(*at)->next;
+ if (b->size == n - o) {
+ *link = b->next;
+ } else {
+ blk_t *rest = (blk_t *)(p + n);
+ rest->size = b->size - (n - o);
+ rest->next = b->next;
+ *link = rest;
+ }
+ used += n - o;
+ if (used > peak) peak = used;
+ return p;
+ }
+ }
+ /* bigger, or a big block becoming small: moved, so it goes where its size belongs */
+ if (n > o || (o > SMALL_MAX && n <= SMALL_MAX)) {
+ void *q = alloc(n);
+ if (q) {
+ memcpy(q, ptr, n < o ? n : o);
+ release(ptr, o);
+ return q;
+ }
+ if (n > o) return NULL;
}
- void *q = alloc(n);
- if (!q) return NULL;
- memcpy(q, ptr, o);
- release(ptr, o);
- return q;
+ /* smaller: the end of it goes back (that never fails) */
+ release((uint8_t *)ptr + n, o - n);
+ return ptr;
}
diff --git a/games/numpico/src/heap.h b/games/numpico/src/heap.h
index 529ee728..abb07602 100644
--- a/games/numpico/src/heap.h
+++ b/games/numpico/src/heap.h
@@ -4,6 +4,8 @@
#include <stddef.h>
#include <stdint.h>
void heap_init(uint8_t *start, uint8_t *end);
+/* more RAM for it */
+void heap_add(uint8_t *start, uint8_t *end);
/* lua_Alloc */
void *heap_alloc(void *ud, void *ptr, size_t osize, size_t nsize);
uint32_t heap_used(void);
diff --git a/games/numpico/src/main.c b/games/numpico/src/main.c
index ebcbf333..5ec2ce77 100644
--- a/games/numpico/src/main.c
+++ b/games/numpico/src/main.c
@@ -225,10 +225,11 @@ static void end_scene(void *ctx) {
/* ------------------------------------------------------------ keys */
static uint32_t held;
+/* the keys just pressed (Home: held, too) */
static uint32_t hits(void) {
uint32_t k = plat_keys(), hit = k & ~held;
held = k;
- return hit;
+ return hit | (k & PK_HOME);
}
/* ------------------------------------------------------------ playing */
@@ -266,6 +267,8 @@ static int play(int i) {
}
int numpico_main(void) {
+ uint8_t extra[PICO_EXTRA] __attribute__((aligned(8)));
+ pico_extra = extra;
plat_begin();
strips_init();
cfg_load();
diff --git a/games/numpico/src/pico.c b/games/numpico/src/pico.c
index 69b248ca..526c1262 100644
--- a/games/numpico/src/pico.c
+++ b/games/numpico/src/pico.c
@@ -40,6 +40,7 @@ p8_cart_t pico_carts[P8_MAX_CARTS];
int pico_ncarts;
pico_error_t pico_error;
int pico_next = -1;
+uint8_t *pico_extra;
uint32_t pico_peak;
static int cart = -1, breadcrumb = -1;
@@ -172,7 +173,8 @@ static uint8_t high_color(uint8_t hc, uint8_t pix, int sx, int sy) {
}
/* (for tools/emu.py and tests/perf.py: pictures shown, frames run, Lua's memory at its most) */
-__attribute__((used)) uint32_t perf_frames, perf_updates, perf_heap, perf_heap_size, perf_end;
+__attribute__((used)) uint32_t perf_frames, perf_updates, perf_heap, perf_heap_size, perf_end, perf_base, perf_load_used,
+ perf_load_peak, perf_fail_size, perf_fail_used, perf_fail_largest, perf_fail_map[128];
void p8_render(void) {
perf_frames++;
@@ -602,7 +604,9 @@ static int start(void) {
uint8_t *a, *b;
plat_heap(&a, &b);
heap_init(a, b);
+ if (pico_extra) heap_add(pico_extra, pico_extra + PICO_EXTRA);
if (lua_load_api() != 0) return PICO_MEMORY;
+ perf_base = heap_used();
lua_gc(L, LUA_GCSETPAUSE, 150);
in_lua = true;
int st = lua_init_script(NULL, c->code, c->code_len);
diff --git a/games/numpico/src/pico.h b/games/numpico/src/pico.h
index 06239e32..5f646a47 100644
--- a/games/numpico/src/pico.h
+++ b/games/numpico/src/pico.h
@@ -40,6 +40,10 @@ extern pico_error_t pico_error;
extern int pico_next;
extern uint32_t pico_peak; /* the most memory Lua had, in bytes, the last time a cart ran */
+/* more RAM for Lua, on main's stack (its 32 KB are more than the calculator needs: see llimits.h) */
+#define PICO_EXTRA 14336
+extern uint8_t *pico_extra;
+
extern p8_cart_t pico_carts[P8_MAX_CARTS];
extern int pico_ncarts;
diff --git a/games/numpico/tests/host.c b/games/numpico/tests/host.c
index 0f966e5e..8076605e 100644
--- a/games/numpico/tests/host.c
+++ b/games/numpico/tests/host.c
@@ -57,7 +57,7 @@ void plat_push(int x, int y, int w, int h, const uint16_t *px) {
}
uint32_t plat_keys(void) {
- if (frames >= limit) return PK_HOME;
+ if (frames >= limit || now_ms > 1200000) return PK_HOME; /* (or after 20 minutes on the clock: a cart stuck) */
/* the list: the cart to play */
if (cart_pick >= 0 && !picked) {
static int step;
diff --git a/games/numpico/tests/perf.py b/games/numpico/tests/perf.py
index d7aab8f8..c8ccdeed 100644
--- a/games/numpico/tests/perf.py
+++ b/games/numpico/tests/perf.py
@@ -61,7 +61,18 @@ def main():
heap, size = word(c, "perf_heap"), word(c, "perf_heap_size")
end = ["playing", "quit", "home", "error", "OUT OF MEMORY", "load"][min(word(c, "perf_end"), 5)]
print(f"{name:28s} {frames / secs:5.1f} pictures/s {updates / secs:5.1f} frames/s Lua {heap // 1024:3d} KB "
- f"of {size // 1024} KB {end}", flush=True)
+ f"of {size // 1024} KB {end} (API {word(c, 'perf_base') // 1024} KB, code {word(c, 'perf_load_used') // 1024} KB, "
+ f"{word(c, 'perf_load_peak') // 1024} KB while read)", flush=True)
+ # the stack: the deepest word written (it starts as zeros)
+ st = bytes(c.uc.mem_read(emu.EXT_RAM_END, emu.STACK_TOP - emu.EXT_RAM_END))
+ deep = next((i for i in range(0, len(st), 4) if st[i:i + 4] != bytes(4)), len(st))
+ print(f" stack {(len(st) - deep) // 1024} KB of {len(st) // 1024} KB")
+ if word(c, "perf_fail_size"):
+ print(f" last failed: {word(c, 'perf_fail_size')} bytes with {word(c, 'perf_fail_used')} used, "
+ f"the largest free block {word(c, 'perf_fail_largest')}")
+ if os.environ.get("MAP"):
+ m = struct.unpack("<128I", bytes(c.uc.mem_read(c.symbols["perf_fail_map"], 512)))
+ print(" free:", " ".join(f"{m[i] & 0xfffff:05x}+{m[i + 1]}" for i in range(0, 128, 2) if m[i]))
if a.shots:
os.makedirs(a.shots, exist_ok=True)
c.save_png(os.path.join(a.shots, name.split(".")[0] + ".png"))