summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMaurus Cuelenaere <mcuelenaere@gmail.com>2009-05-21 19:01:41 +0000
committerMaurus Cuelenaere <mcuelenaere@gmail.com>2009-05-21 19:01:41 +0000
commitcf87597226f5d6b269f1f2c4d6f402aa1eccb852 (patch)
tree4ba1f3ae53b3bd9cae0e2c6c4dd57836b43a5ece
parentc483efadc63eaed35b5fb5e4e02c2282daf32470 (diff)
downloadrockbox-cf87597226f5d6b269f1f2c4d6f402aa1eccb852.tar.gz
rockbox-cf87597226f5d6b269f1f2c4d6f402aa1eccb852.zip
Commit FS#9174: Lua scripting language by Dan Everton
git-svn-id: svn://svn.rockbox.org/rockbox/trunk@21020 a1c6a512-1295-4272-9138-f99709370657
-rw-r--r--apps/plugin.h2
-rw-r--r--apps/plugins/CATEGORIES1
-rw-r--r--apps/plugins/SOURCES5
-rw-r--r--apps/plugins/SUBDIRS5
-rw-r--r--apps/plugins/lua.c33
-rw-r--r--apps/plugins/lua/Makefile86
-rw-r--r--apps/plugins/lua/README19
-rw-r--r--apps/plugins/lua/SOURCES33
-rwxr-xr-xapps/plugins/lua/action_helper.pl40
-rw-r--r--apps/plugins/lua/lapi.c1087
-rw-r--r--apps/plugins/lua/lapi.h16
-rw-r--r--apps/plugins/lua/lauxlib.c669
-rw-r--r--apps/plugins/lua/lauxlib.h174
-rw-r--r--apps/plugins/lua/lbaselib.c657
-rw-r--r--apps/plugins/lua/lcode.c839
-rw-r--r--apps/plugins/lua/lcode.h76
-rw-r--r--apps/plugins/lua/ldebug.c638
-rw-r--r--apps/plugins/lua/ldebug.h33
-rw-r--r--apps/plugins/lua/ldo.c518
-rw-r--r--apps/plugins/lua/ldo.h57
-rw-r--r--apps/plugins/lua/ldump.c164
-rw-r--r--apps/plugins/lua/lfunc.c174
-rw-r--r--apps/plugins/lua/lfunc.h34
-rw-r--r--apps/plugins/lua/lgc.c711
-rw-r--r--apps/plugins/lua/lgc.h110
-rw-r--r--apps/plugins/lua/llex.c462
-rw-r--r--apps/plugins/lua/llex.h81
-rw-r--r--apps/plugins/lua/llimits.h128
-rw-r--r--apps/plugins/lua/lmem.c86
-rw-r--r--apps/plugins/lua/lmem.h49
-rw-r--r--apps/plugins/lua/lobject.c214
-rw-r--r--apps/plugins/lua/lobject.h381
-rw-r--r--apps/plugins/lua/lopcodes.c102
-rw-r--r--apps/plugins/lua/lopcodes.h268
-rw-r--r--apps/plugins/lua/lparser.c1339
-rw-r--r--apps/plugins/lua/lparser.h82
-rw-r--r--apps/plugins/lua/lstate.c214
-rw-r--r--apps/plugins/lua/lstate.h169
-rw-r--r--apps/plugins/lua/lstring.c111
-rw-r--r--apps/plugins/lua/lstring.h31
-rw-r--r--apps/plugins/lua/lstrlib.c869
-rw-r--r--apps/plugins/lua/ltable.c588
-rw-r--r--apps/plugins/lua/ltable.h40
-rw-r--r--apps/plugins/lua/ltablib.c287
-rw-r--r--apps/plugins/lua/ltm.c75
-rw-r--r--apps/plugins/lua/ltm.h54
-rw-r--r--apps/plugins/lua/lua.h388
-rw-r--r--apps/plugins/lua/lua.make46
-rw-r--r--apps/plugins/lua/luaconf.h763
-rw-r--r--apps/plugins/lua/lualib.h53
-rw-r--r--apps/plugins/lua/lundump.c227
-rw-r--r--apps/plugins/lua/lundump.h36
-rw-r--r--apps/plugins/lua/lvm.c763
-rw-r--r--apps/plugins/lua/lvm.h36
-rw-r--r--apps/plugins/lua/lzio.c82
-rw-r--r--apps/plugins/lua/lzio.h67
-rw-r--r--apps/plugins/lua/malloc.c5061
-rw-r--r--apps/plugins/lua/rockaux.c61
-rw-r--r--apps/plugins/lua/rockconf.h64
-rw-r--r--apps/plugins/lua/rocklib.c364
-rw-r--r--apps/plugins/lua/rocklib.h29
-rw-r--r--apps/plugins/lua/rocklibc.h45
-rw-r--r--apps/plugins/lua/rocklua.c105
-rw-r--r--apps/plugins/lua/rockmalloc.c63
-rw-r--r--apps/plugins/lua/rockmalloc.h46
-rw-r--r--apps/plugins/lua/strcspn.c16
-rw-r--r--apps/plugins/lua/strncat.c21
-rw-r--r--apps/plugins/lua/strpbrk.c10
-rw-r--r--apps/plugins/lua/strstr.c16
-rw-r--r--apps/plugins/lua/strtol.c27
-rw-r--r--apps/plugins/lua/strtoul.c53
-rw-r--r--apps/plugins/viewers.config1
-rw-r--r--firmware/include/ctype.h2
73 files changed, 20254 insertions, 2 deletions
diff --git a/apps/plugin.h b/apps/plugin.h
index 3dc63f7420..5eb4b88f28 100644
--- a/apps/plugin.h
+++ b/apps/plugin.h
@@ -511,7 +511,7 @@ struct plugin_api {
511 void* (*memset)(void *dst, int c, size_t length); 511 void* (*memset)(void *dst, int c, size_t length);
512 void* (*memcpy)(void *out, const void *in, size_t n); 512 void* (*memcpy)(void *out, const void *in, size_t n);
513 void* (*memmove)(void *out, const void *in, size_t n); 513 void* (*memmove)(void *out, const void *in, size_t n);
514 const unsigned char *_ctype_; 514 const unsigned char *_rbctype_;
515 int (*atoi)(const char *str); 515 int (*atoi)(const char *str);
516 char *(*strchr)(const char *s, int c); 516 char *(*strchr)(const char *s, int c);
517 char *(*strcat)(char *s1, const char *s2); 517 char *(*strcat)(char *s1, const char *s2);
diff --git a/apps/plugins/CATEGORIES b/apps/plugins/CATEGORIES
index c7cdd3fe53..4b759b080f 100644
--- a/apps/plugins/CATEGORIES
+++ b/apps/plugins/CATEGORIES
@@ -37,6 +37,7 @@ jpeg,viewers
37keybox,apps 37keybox,apps
38lamp,apps 38lamp,apps
39logo,demos 39logo,demos
40lua,viewers
40mandelbrot,demos 41mandelbrot,demos
41matrix,demos 42matrix,demos
42maze,games 43maze,games
diff --git a/apps/plugins/SOURCES b/apps/plugins/SOURCES
index a695478e40..5fb62a9117 100644
--- a/apps/plugins/SOURCES
+++ b/apps/plugins/SOURCES
@@ -159,3 +159,8 @@ superdom.c
159#endif 159#endif
160 160
161md5sum.c 161md5sum.c
162
163#if (PLUGIN_BUFFER_SIZE >= 0x80000)
164lua.c
165#endif
166
diff --git a/apps/plugins/SUBDIRS b/apps/plugins/SUBDIRS
index 597df41b8f..9c7745fd24 100644
--- a/apps/plugins/SUBDIRS
+++ b/apps/plugins/SUBDIRS
@@ -52,4 +52,9 @@ mpegplayer
52#endif 52#endif
53#endif 53#endif
54 54
55/* Lua needs at least 160 KB to work in */
56#if (PLUGIN_BUFFER_SIZE >= 0x80000)
57lua
58#endif
59
55#endif /* IRIVER_IFP7XX_SERIES */ 60#endif /* IRIVER_IFP7XX_SERIES */
diff --git a/apps/plugins/lua.c b/apps/plugins/lua.c
new file mode 100644
index 0000000000..a68e5c149a
--- /dev/null
+++ b/apps/plugins/lua.c
@@ -0,0 +1,33 @@
1/***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 *
9 * Overlay loader stub plugin for lua
10 *
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU General Public License
13 * as published by the Free Software Foundation; either version 2
14 * of the License, or (at your option) any later version.
15 *
16 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
17 * KIND, either express or implied.
18 *
19 ****************************************************************************/
20#include "plugin.h"
21
22#if PLUGIN_BUFFER_SIZE >= 0x80000 && !defined(SIMULATOR)
23
24#include "lib/overlay.h"
25
26PLUGIN_HEADER
27
28/* this is the plugin entry point */
29enum plugin_status plugin_start(const void* parameter)
30{
31 return run_overlay(parameter, VIEWERS_DIR "/lua.ovl", "LuaViewer");
32}
33#endif
diff --git a/apps/plugins/lua/Makefile b/apps/plugins/lua/Makefile
new file mode 100644
index 0000000000..d2a40d38ad
--- /dev/null
+++ b/apps/plugins/lua/Makefile
@@ -0,0 +1,86 @@
1# __________ __ ___.
2# Open \______ \ ____ ____ | | _\_ |__ _______ ___
3# Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
4# Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
5# Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
6# \/ \/ \/ \/ \/
7#
8OPT_FLAGS=-O0
9
10INCLUDES = -I$(APPSDIR) -I.. -I. -I$(FIRMDIR)/include -I$(FIRMDIR)/export \
11 -I$(FIRMDIR)/common -I$(FIRMDIR)/drivers -I$(OUTDIR) -I$(BUILDDIR) -I. $(TARGET_INC)
12CFLAGS = $(INCLUDES) $(GCCOPTS) $(TARGET) $(EXTRA_DEFINES) \
13 -DTARGET_ID=$(TARGET_ID) -DMEM=${MEMORYSIZE} -DPLUGIN $(OPT_FLAGS) $(PROFILE_OPTS)
14
15ifdef APPEXTRA
16 INCLUDES += $(patsubst %,-I$(APPSDIR)/%,$(subst :, ,$(APPEXTRA)))
17endif
18
19LINKFILE := $(OBJDIR)/link.lds
20DEPFILE = $(OBJDIR)/dep-lua
21
22# This sets up 'SRC' based on the files mentioned in SOURCES
23include $(TOOLSDIR)/makesrc.inc
24
25SOURCES = $(SRC)
26OBJS2 := $(SRC:%.c=$(OBJDIR)/%.o)
27OBJS = $(patsubst %.S, $(OBJDIR)/%.o, $(OBJS2))
28DIRS = .
29
30ifndef SIMVER
31ifneq (,$(strip $(foreach tgt,RECORDER ONDIO,$(findstring $(tgt),$(TARGET)))))
32 LDS := archos.lds
33 OUTPUT = $(OUTDIR)/lua.ovl
34else ## iRiver/iPod/... targets
35 LDS := ../plugin.lds
36 OUTPUT = $(OUTDIR)/lua.rock
37endif
38else ## simulators
39 OUTPUT = $(OUTDIR)/lua.rock
40endif
41
42all: $(OUTPUT)
43
44ifndef SIMVER
45$(OBJDIR)/lua.elf: $(OBJS) $(LINKFILE)
46 $(call PRINTS,LD $(@F))$(CC) $(CFLAGS) -o $@ $(OBJS) -L$(BUILDDIR) -lplugin -lgcc \
47 -T$(LINKFILE) -Wl,--gc-sections -Wl,-Map,$(OBJDIR)/lua.map
48
49$(OUTPUT): $(OBJDIR)/lua.elf
50 $(call PRINTS,OBJCOPY $(@F))$(OC) -O binary $< $@
51else
52
53ifeq ($(SIMVER), sdl)
54###################################################
55# This is the SDL simulator version
56
57$(OUTPUT): $(OBJS)
58 $(call PRINTS,LD $(@F))$(CC) $(CFLAGS) $(SHARED_FLAG) $(OBJS) -L$(BUILDDIR) -lplugin -o $@
59ifeq ($(findstring CYGWIN,$(UNAME)),CYGWIN)
60# 'x' must be kept or you'll have "Win32 error 5"
61# $ fgrep 5 /usr/include/w32api/winerror.h | head -1
62# #define ERROR_ACCESS_DENIED 5L
63else
64 @chmod -x $@
65endif
66
67endif
68endif # end of simulator section
69
70
71include $(TOOLSDIR)/make.inc
72
73# MEMORYSIZE should be passed on to this makefile with the chosen memory size
74# given in number of MB
75$(LINKFILE): $(LDS)
76 $(call PRINTS,build $(@F))cat $< | $(CC) -DMEMORYSIZE=$(MEMORYSIZE) $(INCLUDES) $(TARGET) \
77 $(DEFINES) -E -P - >$@
78 ./action_helper.pl > actions.lua
79 echo $(pwd)
80
81clean:
82 $(call PRINTS,cleaning lua)rm -rf $(OBJDIR)/lua
83 $(SILENT)rm -f $(OBJDIR)/lua.* $(DEPFILE)
84
85-include $(DEPFILE)
86
diff --git a/apps/plugins/lua/README b/apps/plugins/lua/README
new file mode 100644
index 0000000000..593aad2ee7
--- /dev/null
+++ b/apps/plugins/lua/README
@@ -0,0 +1,19 @@
1The following files are (with slight modifications for Rockbox) from dietlibc
2version 0.31 which is licensed under the GPL version 2:
3
4 strcspn.c
5 strncat.c
6 strpbrk.c
7 strtol.c
8 strtoul.c
9 strstr.c
10
11The malloc routine is Doug Lea's malloc with the following license:
12
13 Version 2.8.3 Thu Sep 22 11:16:15 2005 Doug Lea (dl at gee)
14
15 This is a version (aka dlmalloc) of malloc/free/realloc written by
16 Doug Lea and released to the public domain, as explained at
17 http://creativecommons.org/licenses/publicdomain. Send questions,
18 comments, complaints, performance data, etc to dl@cs.oswego.edu
19
diff --git a/apps/plugins/lua/SOURCES b/apps/plugins/lua/SOURCES
new file mode 100644
index 0000000000..3b9f9348bd
--- /dev/null
+++ b/apps/plugins/lua/SOURCES
@@ -0,0 +1,33 @@
1lauxlib.c
2lapi.c
3lbaselib.c
4lcode.c
5ldebug.c
6ldo.c
7ldump.c
8lfunc.c
9lgc.c
10llex.c
11lmem.c
12lobject.c
13lopcodes.c
14lparser.c
15lstate.c
16lstring.c
17lstrlib.c
18ltable.c
19ltablib.c
20ltm.c
21lundump.c
22lvm.c
23lzio.c
24rockaux.c
25rocklib.c
26rockmalloc.c
27strcspn.c
28strncat.c
29strpbrk.c
30strtoul.c
31strtol.c
32strstr.c
33rocklua.c
diff --git a/apps/plugins/lua/action_helper.pl b/apps/plugins/lua/action_helper.pl
new file mode 100755
index 0000000000..fdf45798b5
--- /dev/null
+++ b/apps/plugins/lua/action_helper.pl
@@ -0,0 +1,40 @@
1#!/usr/bin/env perl
2############################################################################
3# __________ __ ___.
4# Open \______ \ ____ ____ | | _\_ |__ _______ ___
5# Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
6# Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
7# Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
8# \/ \/ \/ \/ \/
9# $Id$
10#
11# Copyright (C) 2009 by Maurus Cuelenaere
12#
13# All files in this archive are subject to the GNU General Public License.
14# See the file COPYING in the source tree root for full license agreement.
15#
16# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
17# KIND, either express or implied.
18#
19############################################################################
20
21$input = "../../action.h";
22
23open(ACTION, "<$input") or die "Can't open $input!";
24
25print "rb.actions = {\n";
26
27$i = 0;
28while(my $line = <ACTION>)
29{
30 chomp($line);
31 if($line =~ /^\s*(ACTION_[^\s]+)(\s*=.*)?,$/)
32 {
33 printf "\t%s = %d,\n", $1, $i;
34 $i++;
35 }
36}
37
38print "}\n";
39
40close(ACTION);
diff --git a/apps/plugins/lua/lapi.c b/apps/plugins/lua/lapi.c
new file mode 100644
index 0000000000..487d6b173a
--- /dev/null
+++ b/apps/plugins/lua/lapi.c
@@ -0,0 +1,1087 @@
1/*
2** $Id: lapi.c,v 2.55.1.5 2008/07/04 18:41:18 roberto Exp $
3** Lua API
4** See Copyright Notice in lua.h
5*/
6
7
8/* #include <assert.h> */
9#include <math.h>
10#include <stdarg.h>
11#include <string.h>
12
13#define lapi_c
14#define LUA_CORE
15
16#include "lua.h"
17
18#include "lapi.h"
19#include "ldebug.h"
20#include "ldo.h"
21#include "lfunc.h"
22#include "lgc.h"
23#include "lmem.h"
24#include "lobject.h"
25#include "lstate.h"
26#include "lstring.h"
27#include "ltable.h"
28#include "ltm.h"
29#include "lundump.h"
30#include "lvm.h"
31
32
33
34const char lua_ident[] =
35 "$Lua: " LUA_RELEASE " " LUA_COPYRIGHT " $\n"
36 "$Authors: " LUA_AUTHORS " $\n"
37 "$URL: www.lua.org $\n";
38
39
40
41#define api_checknelems(L, n) api_check(L, (n) <= (L->top - L->base))
42
43#define api_checkvalidindex(L, i) api_check(L, (i) != luaO_nilobject)
44
45#define api_incr_top(L) {api_check(L, L->top < L->ci->top); L->top++;}
46
47
48
49static TValue *index2adr (lua_State *L, int idx) {
50 if (idx > 0) {
51 TValue *o = L->base + (idx - 1);
52 api_check(L, idx <= L->ci->top - L->base);
53 if (o >= L->top) return cast(TValue *, luaO_nilobject);
54 else return o;
55 }
56 else if (idx > LUA_REGISTRYINDEX) {
57 api_check(L, idx != 0 && -idx <= L->top - L->base);
58 return L->top + idx;
59 }
60 else switch (idx) { /* pseudo-indices */
61 case LUA_REGISTRYINDEX: return registry(L);
62 case LUA_ENVIRONINDEX: {
63 Closure *func = curr_func(L);
64 sethvalue(L, &L->env, func->c.env);
65 return &L->env;
66 }
67 case LUA_GLOBALSINDEX: return gt(L);
68 default: {
69 Closure *func = curr_func(L);
70 idx = LUA_GLOBALSINDEX - idx;
71 return (idx <= func->c.nupvalues)
72 ? &func->c.upvalue[idx-1]
73 : cast(TValue *, luaO_nilobject);
74 }
75 }
76}
77
78
79static Table *getcurrenv (lua_State *L) {
80 if (L->ci == L->base_ci) /* no enclosing function? */
81 return hvalue(gt(L)); /* use global table as environment */
82 else {
83 Closure *func = curr_func(L);
84 return func->c.env;
85 }
86}
87
88
89void luaA_pushobject (lua_State *L, const TValue *o) {
90 setobj2s(L, L->top, o);
91 api_incr_top(L);
92}
93
94
95LUA_API int lua_checkstack (lua_State *L, int size) {
96 int res = 1;
97 lua_lock(L);
98 if (size > LUAI_MAXCSTACK || (L->top - L->base + size) > LUAI_MAXCSTACK)
99 res = 0; /* stack overflow */
100 else if (size > 0) {
101 luaD_checkstack(L, size);
102 if (L->ci->top < L->top + size)
103 L->ci->top = L->top + size;
104 }
105 lua_unlock(L);
106 return res;
107}
108
109
110LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) {
111 int i;
112 if (from == to) return;
113 lua_lock(to);
114 api_checknelems(from, n);
115 api_check(from, G(from) == G(to));
116 api_check(from, to->ci->top - to->top >= n);
117 from->top -= n;
118 for (i = 0; i < n; i++) {
119 setobj2s(to, to->top++, from->top + i);
120 }
121 lua_unlock(to);
122}
123
124
125LUA_API void lua_setlevel (lua_State *from, lua_State *to) {
126 to->nCcalls = from->nCcalls;
127}
128
129
130LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) {
131 lua_CFunction old;
132 lua_lock(L);
133 old = G(L)->panic;
134 G(L)->panic = panicf;
135 lua_unlock(L);
136 return old;
137}
138
139
140LUA_API lua_State *lua_newthread (lua_State *L) {
141 lua_State *L1;
142 lua_lock(L);
143 luaC_checkGC(L);
144 L1 = luaE_newthread(L);
145 setthvalue(L, L->top, L1);
146 api_incr_top(L);
147 lua_unlock(L);
148 luai_userstatethread(L, L1);
149 return L1;
150}
151
152
153
154/*
155** basic stack manipulation
156*/
157
158
159LUA_API int lua_gettop (lua_State *L) {
160 return cast_int(L->top - L->base);
161}
162
163
164LUA_API void lua_settop (lua_State *L, int idx) {
165 lua_lock(L);
166 if (idx >= 0) {
167 api_check(L, idx <= L->stack_last - L->base);
168 while (L->top < L->base + idx)
169 setnilvalue(L->top++);
170 L->top = L->base + idx;
171 }
172 else {
173 api_check(L, -(idx+1) <= (L->top - L->base));
174 L->top += idx+1; /* `subtract' index (index is negative) */
175 }
176 lua_unlock(L);
177}
178
179
180LUA_API void lua_remove (lua_State *L, int idx) {
181 StkId p;
182 lua_lock(L);
183 p = index2adr(L, idx);
184 api_checkvalidindex(L, p);
185 while (++p < L->top) setobjs2s(L, p-1, p);
186 L->top--;
187 lua_unlock(L);
188}
189
190
191LUA_API void lua_insert (lua_State *L, int idx) {
192 StkId p;
193 StkId q;
194 lua_lock(L);
195 p = index2adr(L, idx);
196 api_checkvalidindex(L, p);
197 for (q = L->top; q>p; q--) setobjs2s(L, q, q-1);
198 setobjs2s(L, p, L->top);
199 lua_unlock(L);
200}
201
202
203LUA_API void lua_replace (lua_State *L, int idx) {
204 StkId o;
205 lua_lock(L);
206 /* explicit test for incompatible code */
207 if (idx == LUA_ENVIRONINDEX && L->ci == L->base_ci)
208 luaG_runerror(L, "no calling environment");
209 api_checknelems(L, 1);
210 o = index2adr(L, idx);
211 api_checkvalidindex(L, o);
212 if (idx == LUA_ENVIRONINDEX) {
213 Closure *func = curr_func(L);
214 api_check(L, ttistable(L->top - 1));
215 func->c.env = hvalue(L->top - 1);
216 luaC_barrier(L, func, L->top - 1);
217 }
218 else {
219 setobj(L, o, L->top - 1);
220 if (idx < LUA_GLOBALSINDEX) /* function upvalue? */
221 luaC_barrier(L, curr_func(L), L->top - 1);
222 }
223 L->top--;
224 lua_unlock(L);
225}
226
227
228LUA_API void lua_pushvalue (lua_State *L, int idx) {
229 lua_lock(L);
230 setobj2s(L, L->top, index2adr(L, idx));
231 api_incr_top(L);
232 lua_unlock(L);
233}
234
235
236
237/*
238** access functions (stack -> C)
239*/
240
241
242LUA_API int lua_type (lua_State *L, int idx) {
243 StkId o = index2adr(L, idx);
244 return (o == luaO_nilobject) ? LUA_TNONE : ttype(o);
245}
246
247
248LUA_API const char *lua_typename (lua_State *L, int t) {
249 UNUSED(L);
250 return (t == LUA_TNONE) ? "no value" : luaT_typenames[t];
251}
252
253
254LUA_API int lua_iscfunction (lua_State *L, int idx) {
255 StkId o = index2adr(L, idx);
256 return iscfunction(o);
257}
258
259
260LUA_API int lua_isnumber (lua_State *L, int idx) {
261 TValue n;
262 const TValue *o = index2adr(L, idx);
263 return tonumber(o, &n);
264}
265
266
267LUA_API int lua_isstring (lua_State *L, int idx) {
268 int t = lua_type(L, idx);
269 return (t == LUA_TSTRING || t == LUA_TNUMBER);
270}
271
272
273LUA_API int lua_isuserdata (lua_State *L, int idx) {
274 const TValue *o = index2adr(L, idx);
275 return (ttisuserdata(o) || ttislightuserdata(o));
276}
277
278
279LUA_API int lua_rawequal (lua_State *L, int index1, int index2) {
280 StkId o1 = index2adr(L, index1);
281 StkId o2 = index2adr(L, index2);
282 return (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0
283 : luaO_rawequalObj(o1, o2);
284}
285
286
287LUA_API int lua_equal (lua_State *L, int index1, int index2) {
288 StkId o1, o2;
289 int i;
290 lua_lock(L); /* may call tag method */
291 o1 = index2adr(L, index1);
292 o2 = index2adr(L, index2);
293 i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : equalobj(L, o1, o2);
294 lua_unlock(L);
295 return i;
296}
297
298
299LUA_API int lua_lessthan (lua_State *L, int index1, int index2) {
300 StkId o1, o2;
301 int i;
302 lua_lock(L); /* may call tag method */
303 o1 = index2adr(L, index1);
304 o2 = index2adr(L, index2);
305 i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0
306 : luaV_lessthan(L, o1, o2);
307 lua_unlock(L);
308 return i;
309}
310
311
312
313LUA_API lua_Number lua_tonumber (lua_State *L, int idx) {
314 TValue n;
315 const TValue *o = index2adr(L, idx);
316 if (tonumber(o, &n))
317 return nvalue(o);
318 else
319 return 0;
320}
321
322
323LUA_API lua_Integer lua_tointeger (lua_State *L, int idx) {
324 TValue n;
325 const TValue *o = index2adr(L, idx);
326 if (tonumber(o, &n)) {
327 lua_Integer res;
328 lua_Number num = nvalue(o);
329 lua_number2integer(res, num);
330 return res;
331 }
332 else
333 return 0;
334}
335
336
337LUA_API int lua_toboolean (lua_State *L, int idx) {
338 const TValue *o = index2adr(L, idx);
339 return !l_isfalse(o);
340}
341
342
343LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
344 StkId o = index2adr(L, idx);
345 if (!ttisstring(o)) {
346 lua_lock(L); /* `luaV_tostring' may create a new string */
347 if (!luaV_tostring(L, o)) { /* conversion failed? */
348 if (len != NULL) *len = 0;
349 lua_unlock(L);
350 return NULL;
351 }
352 luaC_checkGC(L);
353 o = index2adr(L, idx); /* previous call may reallocate the stack */
354 lua_unlock(L);
355 }
356 if (len != NULL) *len = tsvalue(o)->len;
357 return svalue(o);
358}
359
360
361LUA_API size_t lua_objlen (lua_State *L, int idx) {
362 StkId o = index2adr(L, idx);
363 switch (ttype(o)) {
364 case LUA_TSTRING: return tsvalue(o)->len;
365 case LUA_TUSERDATA: return uvalue(o)->len;
366 case LUA_TTABLE: return luaH_getn(hvalue(o));
367 case LUA_TNUMBER: {
368 size_t l;
369 lua_lock(L); /* `luaV_tostring' may create a new string */
370 l = (luaV_tostring(L, o) ? tsvalue(o)->len : 0);
371 lua_unlock(L);
372 return l;
373 }
374 default: return 0;
375 }
376}
377
378
379LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {
380 StkId o = index2adr(L, idx);
381 return (!iscfunction(o)) ? NULL : clvalue(o)->c.f;
382}
383
384
385LUA_API void *lua_touserdata (lua_State *L, int idx) {
386 StkId o = index2adr(L, idx);
387 switch (ttype(o)) {
388 case LUA_TUSERDATA: return (rawuvalue(o) + 1);
389 case LUA_TLIGHTUSERDATA: return pvalue(o);
390 default: return NULL;
391 }
392}
393
394
395LUA_API lua_State *lua_tothread (lua_State *L, int idx) {
396 StkId o = index2adr(L, idx);
397 return (!ttisthread(o)) ? NULL : thvalue(o);
398}
399
400
401LUA_API const void *lua_topointer (lua_State *L, int idx) {
402 StkId o = index2adr(L, idx);
403 switch (ttype(o)) {
404 case LUA_TTABLE: return hvalue(o);
405 case LUA_TFUNCTION: return clvalue(o);
406 case LUA_TTHREAD: return thvalue(o);
407 case LUA_TUSERDATA:
408 case LUA_TLIGHTUSERDATA:
409 return lua_touserdata(L, idx);
410 default: return NULL;
411 }
412}
413
414
415
416/*
417** push functions (C -> stack)
418*/
419
420
421LUA_API void lua_pushnil (lua_State *L) {
422 lua_lock(L);
423 setnilvalue(L->top);
424 api_incr_top(L);
425 lua_unlock(L);
426}
427
428
429LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {
430 lua_lock(L);
431 setnvalue(L->top, n);
432 api_incr_top(L);
433 lua_unlock(L);
434}
435
436
437LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) {
438 lua_lock(L);
439 setnvalue(L->top, cast_num(n));
440 api_incr_top(L);
441 lua_unlock(L);
442}
443
444
445LUA_API void lua_pushlstring (lua_State *L, const char *s, size_t len) {
446 lua_lock(L);
447 luaC_checkGC(L);
448 setsvalue2s(L, L->top, luaS_newlstr(L, s, len));
449 api_incr_top(L);
450 lua_unlock(L);
451}
452
453
454LUA_API void lua_pushstring (lua_State *L, const char *s) {
455 if (s == NULL)
456 lua_pushnil(L);
457 else
458 lua_pushlstring(L, s, strlen(s));
459}
460
461
462LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt,
463 va_list argp) {
464 const char *ret;
465 lua_lock(L);
466 luaC_checkGC(L);
467 ret = luaO_pushvfstring(L, fmt, argp);
468 lua_unlock(L);
469 return ret;
470}
471
472
473LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) {
474 const char *ret;
475 va_list argp;
476 lua_lock(L);
477 luaC_checkGC(L);
478 va_start(argp, fmt);
479 ret = luaO_pushvfstring(L, fmt, argp);
480 va_end(argp);
481 lua_unlock(L);
482 return ret;
483}
484
485
486LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
487 Closure *cl;
488 lua_lock(L);
489 luaC_checkGC(L);
490 api_checknelems(L, n);
491 cl = luaF_newCclosure(L, n, getcurrenv(L));
492 cl->c.f = fn;
493 L->top -= n;
494 while (n--)
495 setobj2n(L, &cl->c.upvalue[n], L->top+n);
496 setclvalue(L, L->top, cl);
497 lua_assert(iswhite(obj2gco(cl)));
498 api_incr_top(L);
499 lua_unlock(L);
500}
501
502
503LUA_API void lua_pushboolean (lua_State *L, int b) {
504 lua_lock(L);
505 setbvalue(L->top, (b != 0)); /* ensure that true is 1 */
506 api_incr_top(L);
507 lua_unlock(L);
508}
509
510
511LUA_API void lua_pushlightuserdata (lua_State *L, void *p) {
512 lua_lock(L);
513 setpvalue(L->top, p);
514 api_incr_top(L);
515 lua_unlock(L);
516}
517
518
519LUA_API int lua_pushthread (lua_State *L) {
520 lua_lock(L);
521 setthvalue(L, L->top, L);
522 api_incr_top(L);
523 lua_unlock(L);
524 return (G(L)->mainthread == L);
525}
526
527
528
529/*
530** get functions (Lua -> stack)
531*/
532
533
534LUA_API void lua_gettable (lua_State *L, int idx) {
535 StkId t;
536 lua_lock(L);
537 t = index2adr(L, idx);
538 api_checkvalidindex(L, t);
539 luaV_gettable(L, t, L->top - 1, L->top - 1);
540 lua_unlock(L);
541}
542
543
544LUA_API void lua_getfield (lua_State *L, int idx, const char *k) {
545 StkId t;
546 TValue key;
547 lua_lock(L);
548 t = index2adr(L, idx);
549 api_checkvalidindex(L, t);
550 setsvalue(L, &key, luaS_new(L, k));
551 luaV_gettable(L, t, &key, L->top);
552 api_incr_top(L);
553 lua_unlock(L);
554}
555
556
557LUA_API void lua_rawget (lua_State *L, int idx) {
558 StkId t;
559 lua_lock(L);
560 t = index2adr(L, idx);
561 api_check(L, ttistable(t));
562 setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1));
563 lua_unlock(L);
564}
565
566
567LUA_API void lua_rawgeti (lua_State *L, int idx, int n) {
568 StkId o;
569 lua_lock(L);
570 o = index2adr(L, idx);
571 api_check(L, ttistable(o));
572 setobj2s(L, L->top, luaH_getnum(hvalue(o), n));
573 api_incr_top(L);
574 lua_unlock(L);
575}
576
577
578LUA_API void lua_createtable (lua_State *L, int narray, int nrec) {
579 lua_lock(L);
580 luaC_checkGC(L);
581 sethvalue(L, L->top, luaH_new(L, narray, nrec));
582 api_incr_top(L);
583 lua_unlock(L);
584}
585
586
587LUA_API int lua_getmetatable (lua_State *L, int objindex) {
588 const TValue *obj;
589 Table *mt = NULL;
590 int res;
591 lua_lock(L);
592 obj = index2adr(L, objindex);
593 switch (ttype(obj)) {
594 case LUA_TTABLE:
595 mt = hvalue(obj)->metatable;
596 break;
597 case LUA_TUSERDATA:
598 mt = uvalue(obj)->metatable;
599 break;
600 default:
601 mt = G(L)->mt[ttype(obj)];
602 break;
603 }
604 if (mt == NULL)
605 res = 0;
606 else {
607 sethvalue(L, L->top, mt);
608 api_incr_top(L);
609 res = 1;
610 }
611 lua_unlock(L);
612 return res;
613}
614
615
616LUA_API void lua_getfenv (lua_State *L, int idx) {
617 StkId o;
618 lua_lock(L);
619 o = index2adr(L, idx);
620 api_checkvalidindex(L, o);
621 switch (ttype(o)) {
622 case LUA_TFUNCTION:
623 sethvalue(L, L->top, clvalue(o)->c.env);
624 break;
625 case LUA_TUSERDATA:
626 sethvalue(L, L->top, uvalue(o)->env);
627 break;
628 case LUA_TTHREAD:
629 setobj2s(L, L->top, gt(thvalue(o)));
630 break;
631 default:
632 setnilvalue(L->top);
633 break;
634 }
635 api_incr_top(L);
636 lua_unlock(L);
637}
638
639
640/*
641** set functions (stack -> Lua)
642*/
643
644
645LUA_API void lua_settable (lua_State *L, int idx) {
646 StkId t;
647 lua_lock(L);
648 api_checknelems(L, 2);
649 t = index2adr(L, idx);
650 api_checkvalidindex(L, t);
651 luaV_settable(L, t, L->top - 2, L->top - 1);
652 L->top -= 2; /* pop index and value */
653 lua_unlock(L);
654}
655
656
657LUA_API void lua_setfield (lua_State *L, int idx, const char *k) {
658 StkId t;
659 TValue key;
660 lua_lock(L);
661 api_checknelems(L, 1);
662 t = index2adr(L, idx);
663 api_checkvalidindex(L, t);
664 setsvalue(L, &key, luaS_new(L, k));
665 luaV_settable(L, t, &key, L->top - 1);
666 L->top--; /* pop value */
667 lua_unlock(L);
668}
669
670
671LUA_API void lua_rawset (lua_State *L, int idx) {
672 StkId t;
673 lua_lock(L);
674 api_checknelems(L, 2);
675 t = index2adr(L, idx);
676 api_check(L, ttistable(t));
677 setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1);
678 luaC_barriert(L, hvalue(t), L->top-1);
679 L->top -= 2;
680 lua_unlock(L);
681}
682
683
684LUA_API void lua_rawseti (lua_State *L, int idx, int n) {
685 StkId o;
686 lua_lock(L);
687 api_checknelems(L, 1);
688 o = index2adr(L, idx);
689 api_check(L, ttistable(o));
690 setobj2t(L, luaH_setnum(L, hvalue(o), n), L->top-1);
691 luaC_barriert(L, hvalue(o), L->top-1);
692 L->top--;
693 lua_unlock(L);
694}
695
696
697LUA_API int lua_setmetatable (lua_State *L, int objindex) {
698 TValue *obj;
699 Table *mt;
700 lua_lock(L);
701 api_checknelems(L, 1);
702 obj = index2adr(L, objindex);
703 api_checkvalidindex(L, obj);
704 if (ttisnil(L->top - 1))
705 mt = NULL;
706 else {
707 api_check(L, ttistable(L->top - 1));
708 mt = hvalue(L->top - 1);
709 }
710 switch (ttype(obj)) {
711 case LUA_TTABLE: {
712 hvalue(obj)->metatable = mt;
713 if (mt)
714 luaC_objbarriert(L, hvalue(obj), mt);
715 break;
716 }
717 case LUA_TUSERDATA: {
718 uvalue(obj)->metatable = mt;
719 if (mt)
720 luaC_objbarrier(L, rawuvalue(obj), mt);
721 break;
722 }
723 default: {
724 G(L)->mt[ttype(obj)] = mt;
725 break;
726 }
727 }
728 L->top--;
729 lua_unlock(L);
730 return 1;
731}
732
733
734LUA_API int lua_setfenv (lua_State *L, int idx) {
735 StkId o;
736 int res = 1;
737 lua_lock(L);
738 api_checknelems(L, 1);
739 o = index2adr(L, idx);
740 api_checkvalidindex(L, o);
741 api_check(L, ttistable(L->top - 1));
742 switch (ttype(o)) {
743 case LUA_TFUNCTION:
744 clvalue(o)->c.env = hvalue(L->top - 1);
745 break;
746 case LUA_TUSERDATA:
747 uvalue(o)->env = hvalue(L->top - 1);
748 break;
749 case LUA_TTHREAD:
750 sethvalue(L, gt(thvalue(o)), hvalue(L->top - 1));
751 break;
752 default:
753 res = 0;
754 break;
755 }
756 if (res) luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1));
757 L->top--;
758 lua_unlock(L);
759 return res;
760}
761
762
763/*
764** `load' and `call' functions (run Lua code)
765*/
766
767
768#define adjustresults(L,nres) \
769 { if (nres == LUA_MULTRET && L->top >= L->ci->top) L->ci->top = L->top; }
770
771
772#define checkresults(L,na,nr) \
773 api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)))
774
775
776LUA_API void lua_call (lua_State *L, int nargs, int nresults) {
777 StkId func;
778 lua_lock(L);
779 api_checknelems(L, nargs+1);
780 checkresults(L, nargs, nresults);
781 func = L->top - (nargs+1);
782 luaD_call(L, func, nresults);
783 adjustresults(L, nresults);
784 lua_unlock(L);
785}
786
787
788
789/*
790** Execute a protected call.
791*/
792struct CallS { /* data to `f_call' */
793 StkId func;
794 int nresults;
795};
796
797
798static void f_call (lua_State *L, void *ud) {
799 struct CallS *c = cast(struct CallS *, ud);
800 luaD_call(L, c->func, c->nresults);
801}
802
803
804
805LUA_API int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc) {
806 struct CallS c;
807 int status;
808 ptrdiff_t func;
809 lua_lock(L);
810 api_checknelems(L, nargs+1);
811 checkresults(L, nargs, nresults);
812 if (errfunc == 0)
813 func = 0;
814 else {
815 StkId o = index2adr(L, errfunc);
816 api_checkvalidindex(L, o);
817 func = savestack(L, o);
818 }
819 c.func = L->top - (nargs+1); /* function to be called */
820 c.nresults = nresults;
821 status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func);
822 adjustresults(L, nresults);
823 lua_unlock(L);
824 return status;
825}
826
827
828/*
829** Execute a protected C call.
830*/
831struct CCallS { /* data to `f_Ccall' */
832 lua_CFunction func;
833 void *ud;
834};
835
836
837static void f_Ccall (lua_State *L, void *ud) {
838 struct CCallS *c = cast(struct CCallS *, ud);
839 Closure *cl;
840 cl = luaF_newCclosure(L, 0, getcurrenv(L));
841 cl->c.f = c->func;
842 setclvalue(L, L->top, cl); /* push function */
843 api_incr_top(L);
844 setpvalue(L->top, c->ud); /* push only argument */
845 api_incr_top(L);
846 luaD_call(L, L->top - 2, 0);
847}
848
849
850LUA_API int lua_cpcall (lua_State *L, lua_CFunction func, void *ud) {
851 struct CCallS c;
852 int status;
853 lua_lock(L);
854 c.func = func;
855 c.ud = ud;
856 status = luaD_pcall(L, f_Ccall, &c, savestack(L, L->top), 0);
857 lua_unlock(L);
858 return status;
859}
860
861
862LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data,
863 const char *chunkname) {
864 ZIO z;
865 int status;
866 lua_lock(L);
867 if (!chunkname) chunkname = "?";
868 luaZ_init(L, &z, reader, data);
869 status = luaD_protectedparser(L, &z, chunkname);
870 lua_unlock(L);
871 return status;
872}
873
874
875LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) {
876 int status;
877 TValue *o;
878 lua_lock(L);
879 api_checknelems(L, 1);
880 o = L->top - 1;
881 if (isLfunction(o))
882 status = luaU_dump(L, clvalue(o)->l.p, writer, data, 0);
883 else
884 status = 1;
885 lua_unlock(L);
886 return status;
887}
888
889
890LUA_API int lua_status (lua_State *L) {
891 return L->status;
892}
893
894
895/*
896** Garbage-collection function
897*/
898
899LUA_API int lua_gc (lua_State *L, int what, int data) {
900 int res = 0;
901 global_State *g;
902 lua_lock(L);
903 g = G(L);
904 switch (what) {
905 case LUA_GCSTOP: {
906 g->GCthreshold = MAX_LUMEM;
907 break;
908 }
909 case LUA_GCRESTART: {
910 g->GCthreshold = g->totalbytes;
911 break;
912 }
913 case LUA_GCCOLLECT: {
914 luaC_fullgc(L);
915 break;
916 }
917 case LUA_GCCOUNT: {
918 /* GC values are expressed in Kbytes: #bytes/2^10 */
919 res = cast_int(g->totalbytes >> 10);
920 break;
921 }
922 case LUA_GCCOUNTB: {
923 res = cast_int(g->totalbytes & 0x3ff);
924 break;
925 }
926 case LUA_GCSTEP: {
927 lu_mem a = (cast(lu_mem, data) << 10);
928 if (a <= g->totalbytes)
929 g->GCthreshold = g->totalbytes - a;
930 else
931 g->GCthreshold = 0;
932 while (g->GCthreshold <= g->totalbytes) {
933 luaC_step(L);
934 if (g->gcstate == GCSpause) { /* end of cycle? */
935 res = 1; /* signal it */
936 break;
937 }
938 }
939 break;
940 }
941 case LUA_GCSETPAUSE: {
942 res = g->gcpause;
943 g->gcpause = data;
944 break;
945 }
946 case LUA_GCSETSTEPMUL: {
947 res = g->gcstepmul;
948 g->gcstepmul = data;
949 break;
950 }
951 default: res = -1; /* invalid option */
952 }
953 lua_unlock(L);
954 return res;
955}
956
957
958
959/*
960** miscellaneous functions
961*/
962
963
964LUA_API int lua_error (lua_State *L) {
965 lua_lock(L);
966 api_checknelems(L, 1);
967 luaG_errormsg(L);
968 lua_unlock(L);
969 return 0; /* to avoid warnings */
970}
971
972
973LUA_API int lua_next (lua_State *L, int idx) {
974 StkId t;
975 int more;
976 lua_lock(L);
977 t = index2adr(L, idx);
978 api_check(L, ttistable(t));
979 more = luaH_next(L, hvalue(t), L->top - 1);
980 if (more) {
981 api_incr_top(L);
982 }
983 else /* no more elements */
984 L->top -= 1; /* remove key */
985 lua_unlock(L);
986 return more;
987}
988
989
990LUA_API void lua_concat (lua_State *L, int n) {
991 lua_lock(L);
992 api_checknelems(L, n);
993 if (n >= 2) {
994 luaC_checkGC(L);
995 luaV_concat(L, n, cast_int(L->top - L->base) - 1);
996 L->top -= (n-1);
997 }
998 else if (n == 0) { /* push empty string */
999 setsvalue2s(L, L->top, luaS_newlstr(L, "", 0));
1000 api_incr_top(L);
1001 }
1002 /* else n == 1; nothing to do */
1003 lua_unlock(L);
1004}
1005
1006
1007LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) {
1008 lua_Alloc f;
1009 lua_lock(L);
1010 if (ud) *ud = G(L)->ud;
1011 f = G(L)->frealloc;
1012 lua_unlock(L);
1013 return f;
1014}
1015
1016
1017LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) {
1018 lua_lock(L);
1019 G(L)->ud = ud;
1020 G(L)->frealloc = f;
1021 lua_unlock(L);
1022}
1023
1024
1025LUA_API void *lua_newuserdata (lua_State *L, size_t size) {
1026 Udata *u;
1027 lua_lock(L);
1028 luaC_checkGC(L);
1029 u = luaS_newudata(L, size, getcurrenv(L));
1030 setuvalue(L, L->top, u);
1031 api_incr_top(L);
1032 lua_unlock(L);
1033 return u + 1;
1034}
1035
1036
1037
1038
1039static const char *aux_upvalue (StkId fi, int n, TValue **val) {
1040 Closure *f;
1041 if (!ttisfunction(fi)) return NULL;
1042 f = clvalue(fi);
1043 if (f->c.isC) {
1044 if (!(1 <= n && n <= f->c.nupvalues)) return NULL;
1045 *val = &f->c.upvalue[n-1];
1046 return "";
1047 }
1048 else {
1049 Proto *p = f->l.p;
1050 if (!(1 <= n && n <= p->sizeupvalues)) return NULL;
1051 *val = f->l.upvals[n-1]->v;
1052 return getstr(p->upvalues[n-1]);
1053 }
1054}
1055
1056
1057LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) {
1058 const char *name;
1059 TValue *val;
1060 lua_lock(L);
1061 name = aux_upvalue(index2adr(L, funcindex), n, &val);
1062 if (name) {
1063 setobj2s(L, L->top, val);
1064 api_incr_top(L);
1065 }
1066 lua_unlock(L);
1067 return name;
1068}
1069
1070
1071LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
1072 const char *name;
1073 TValue *val;
1074 StkId fi;
1075 lua_lock(L);
1076 fi = index2adr(L, funcindex);
1077 api_checknelems(L, 1);
1078 name = aux_upvalue(fi, n, &val);
1079 if (name) {
1080 L->top--;
1081 setobj(L, val, L->top);
1082 luaC_barrier(L, clvalue(fi), L->top);
1083 }
1084 lua_unlock(L);
1085 return name;
1086}
1087
diff --git a/apps/plugins/lua/lapi.h b/apps/plugins/lua/lapi.h
new file mode 100644
index 0000000000..f968ffc992
--- /dev/null
+++ b/apps/plugins/lua/lapi.h
@@ -0,0 +1,16 @@
1/*
2** $Id$
3** Auxiliary functions from Lua API
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lapi_h
8#define lapi_h
9
10
11#include "lobject.h"
12
13
14LUAI_FUNC void luaA_pushobject (lua_State *L, const TValue *o);
15
16#endif
diff --git a/apps/plugins/lua/lauxlib.c b/apps/plugins/lua/lauxlib.c
new file mode 100644
index 0000000000..a755266bde
--- /dev/null
+++ b/apps/plugins/lua/lauxlib.c
@@ -0,0 +1,669 @@
1/*
2** $Id: lauxlib.c,v 1.159.1.3 2008/01/21 13:20:51 roberto Exp $
3** Auxiliary functions for building Lua libraries
4** See Copyright Notice in lua.h
5*/
6
7
8#include <ctype.h>
9#include <errno.h>
10#include <stdarg.h>
11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
14
15
16/* This file uses only the official API of Lua.
17** Any function declared here could be written as an application function.
18*/
19
20#define lauxlib_c
21#define LUA_LIB
22
23#include "lua.h"
24
25#include "lauxlib.h"
26
27
28#define FREELIST_REF 0 /* free list of references */
29
30
31/* convert a stack index to positive */
32#define abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \
33 lua_gettop(L) + (i) + 1)
34
35
36/*
37** {======================================================
38** Error-report functions
39** =======================================================
40*/
41
42
43LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
44 lua_Debug ar;
45 if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
46 return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
47 lua_getinfo(L, "n", &ar);
48 if (strcmp(ar.namewhat, "method") == 0) {
49 narg--; /* do not count `self' */
50 if (narg == 0) /* error is in the self argument itself? */
51 return luaL_error(L, "calling " LUA_QS " on bad self (%s)",
52 ar.name, extramsg);
53 }
54 if (ar.name == NULL)
55 ar.name = "?";
56 return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",
57 narg, ar.name, extramsg);
58}
59
60
61LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname) {
62 const char *msg = lua_pushfstring(L, "%s expected, got %s",
63 tname, luaL_typename(L, narg));
64 return luaL_argerror(L, narg, msg);
65}
66
67
68static void tag_error (lua_State *L, int narg, int tag) {
69 luaL_typerror(L, narg, lua_typename(L, tag));
70}
71
72
73LUALIB_API void luaL_where (lua_State *L, int level) {
74 lua_Debug ar;
75 if (lua_getstack(L, level, &ar)) { /* check function at level */
76 lua_getinfo(L, "Sl", &ar); /* get info about it */
77 if (ar.currentline > 0) { /* is there info? */
78 lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
79 return;
80 }
81 }
82 lua_pushliteral(L, ""); /* else, no information available... */
83}
84
85
86LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
87 va_list argp;
88 va_start(argp, fmt);
89 luaL_where(L, 1);
90 lua_pushvfstring(L, fmt, argp);
91 va_end(argp);
92 lua_concat(L, 2);
93 return lua_error(L);
94}
95
96/* }====================================================== */
97
98
99LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,
100 const char *const lst[]) {
101 const char *name = (def) ? luaL_optstring(L, narg, def) :
102 luaL_checkstring(L, narg);
103 int i;
104 for (i=0; lst[i]; i++)
105 if (strcmp(lst[i], name) == 0)
106 return i;
107 return luaL_argerror(L, narg,
108 lua_pushfstring(L, "invalid option " LUA_QS, name));
109}
110
111
112LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
113 lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */
114 if (!lua_isnil(L, -1)) /* name already in use? */
115 return 0; /* leave previous value on top, but return 0 */
116 lua_pop(L, 1);
117 lua_newtable(L); /* create metatable */
118 lua_pushvalue(L, -1);
119 lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
120 return 1;
121}
122
123
124LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
125 void *p = lua_touserdata(L, ud);
126 if (p != NULL) { /* value is a userdata? */
127 if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
128 lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */
129 if (lua_rawequal(L, -1, -2)) { /* does it have the correct mt? */
130 lua_pop(L, 2); /* remove both metatables */
131 return p;
132 }
133 }
134 }
135 luaL_typerror(L, ud, tname); /* else error */
136 return NULL; /* to avoid warnings */
137}
138
139
140LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) {
141 if (!lua_checkstack(L, space))
142 luaL_error(L, "stack overflow (%s)", mes);
143}
144
145
146LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
147 if (lua_type(L, narg) != t)
148 tag_error(L, narg, t);
149}
150
151
152LUALIB_API void luaL_checkany (lua_State *L, int narg) {
153 if (lua_type(L, narg) == LUA_TNONE)
154 luaL_argerror(L, narg, "value expected");
155}
156
157
158LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
159 const char *s = lua_tolstring(L, narg, len);
160 if (!s) tag_error(L, narg, LUA_TSTRING);
161 return s;
162}
163
164
165LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
166 const char *def, size_t *len) {
167 if (lua_isnoneornil(L, narg)) {
168 if (len)
169 *len = (def ? strlen(def) : 0);
170 return def;
171 }
172 else return luaL_checklstring(L, narg, len);
173}
174
175
176LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
177 lua_Number d = lua_tonumber(L, narg);
178 if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
179 tag_error(L, narg, LUA_TNUMBER);
180 return d;
181}
182
183
184LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
185 return luaL_opt(L, luaL_checknumber, narg, def);
186}
187
188
189LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
190 lua_Integer d = lua_tointeger(L, narg);
191 if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
192 tag_error(L, narg, LUA_TNUMBER);
193 return d;
194}
195
196
197LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
198 lua_Integer def) {
199 return luaL_opt(L, luaL_checkinteger, narg, def);
200}
201
202
203LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
204 if (!lua_getmetatable(L, obj)) /* no metatable? */
205 return 0;
206 lua_pushstring(L, event);
207 lua_rawget(L, -2);
208 if (lua_isnil(L, -1)) {
209 lua_pop(L, 2); /* remove metatable and metafield */
210 return 0;
211 }
212 else {
213 lua_remove(L, -2); /* remove only metatable */
214 return 1;
215 }
216}
217
218
219LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
220 obj = abs_index(L, obj);
221 if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
222 return 0;
223 lua_pushvalue(L, obj);
224 lua_call(L, 1, 1);
225 return 1;
226}
227
228
229LUALIB_API void (luaL_register) (lua_State *L, const char *libname,
230 const luaL_Reg *l) {
231 luaI_openlib(L, libname, l, 0);
232}
233
234
235static int libsize (const luaL_Reg *l) {
236 int size = 0;
237 for (; l->name; l++) size++;
238 return size;
239}
240
241
242LUALIB_API void luaI_openlib (lua_State *L, const char *libname,
243 const luaL_Reg *l, int nup) {
244 if (libname) {
245 int size = libsize(l);
246 /* check whether lib already exists */
247 luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1);
248 lua_getfield(L, -1, libname); /* get _LOADED[libname] */
249 if (!lua_istable(L, -1)) { /* not found? */
250 lua_pop(L, 1); /* remove previous result */
251 /* try global variable (and create one if it does not exist) */
252 if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, size) != NULL)
253 luaL_error(L, "name conflict for module " LUA_QS, libname);
254 lua_pushvalue(L, -1);
255 lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */
256 }
257 lua_remove(L, -2); /* remove _LOADED table */
258 lua_insert(L, -(nup+1)); /* move library table to below upvalues */
259 }
260 for (; l->name; l++) {
261 int i;
262 for (i=0; i<nup; i++) /* copy upvalues to the top */
263 lua_pushvalue(L, -nup);
264 lua_pushcclosure(L, l->func, nup);
265 lua_setfield(L, -(nup+2), l->name);
266 }
267 lua_pop(L, nup); /* remove upvalues */
268}
269
270
271
272/*
273** {======================================================
274** getn-setn: size for arrays
275** =======================================================
276*/
277
278#if defined(LUA_COMPAT_GETN)
279
280static int checkint (lua_State *L, int topop) {
281 int n = (lua_type(L, -1) == LUA_TNUMBER) ? lua_tointeger(L, -1) : -1;
282 lua_pop(L, topop);
283 return n;
284}
285
286
287static void getsizes (lua_State *L) {
288 lua_getfield(L, LUA_REGISTRYINDEX, "LUA_SIZES");
289 if (lua_isnil(L, -1)) { /* no `size' table? */
290 lua_pop(L, 1); /* remove nil */
291 lua_newtable(L); /* create it */
292 lua_pushvalue(L, -1); /* `size' will be its own metatable */
293 lua_setmetatable(L, -2);
294 lua_pushliteral(L, "kv");
295 lua_setfield(L, -2, "__mode"); /* metatable(N).__mode = "kv" */
296 lua_pushvalue(L, -1);
297 lua_setfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); /* store in register */
298 }
299}
300
301
302LUALIB_API void luaL_setn (lua_State *L, int t, int n) {
303 t = abs_index(L, t);
304 lua_pushliteral(L, "n");
305 lua_rawget(L, t);
306 if (checkint(L, 1) >= 0) { /* is there a numeric field `n'? */
307 lua_pushliteral(L, "n"); /* use it */
308 lua_pushinteger(L, n);
309 lua_rawset(L, t);
310 }
311 else { /* use `sizes' */
312 getsizes(L);
313 lua_pushvalue(L, t);
314 lua_pushinteger(L, n);
315 lua_rawset(L, -3); /* sizes[t] = n */
316 lua_pop(L, 1); /* remove `sizes' */
317 }
318}
319
320
321LUALIB_API int luaL_getn (lua_State *L, int t) {
322 int n;
323 t = abs_index(L, t);
324 lua_pushliteral(L, "n"); /* try t.n */
325 lua_rawget(L, t);
326 if ((n = checkint(L, 1)) >= 0) return n;
327 getsizes(L); /* else try sizes[t] */
328 lua_pushvalue(L, t);
329 lua_rawget(L, -2);
330 if ((n = checkint(L, 2)) >= 0) return n;
331 return (int)lua_objlen(L, t);
332}
333
334#endif
335
336/* }====================================================== */
337
338
339
340LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
341 const char *r) {
342 const char *wild;
343 size_t l = strlen(p);
344 luaL_Buffer b;
345 luaL_buffinit(L, &b);
346 while ((wild = strstr(s, p)) != NULL) {
347 luaL_addlstring(&b, s, wild - s); /* push prefix */
348 luaL_addstring(&b, r); /* push replacement in place of pattern */
349 s = wild + l; /* continue after `p' */
350 }
351 luaL_addstring(&b, s); /* push last suffix */
352 luaL_pushresult(&b);
353 return lua_tostring(L, -1);
354}
355
356
357LUALIB_API const char *luaL_findtable (lua_State *L, int idx,
358 const char *fname, int szhint) {
359 const char *e;
360 lua_pushvalue(L, idx);
361 do {
362 e = strchr(fname, '.');
363 if (e == NULL) e = fname + strlen(fname);
364 lua_pushlstring(L, fname, e - fname);
365 lua_rawget(L, -2);
366 if (lua_isnil(L, -1)) { /* no such field? */
367 lua_pop(L, 1); /* remove this nil */
368 lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
369 lua_pushlstring(L, fname, e - fname);
370 lua_pushvalue(L, -2);
371 lua_settable(L, -4); /* set new table into field */
372 }
373 else if (!lua_istable(L, -1)) { /* field has a non-table value? */
374 lua_pop(L, 2); /* remove table and value */
375 return fname; /* return problematic part of the name */
376 }
377 lua_remove(L, -2); /* remove previous table */
378 fname = e + 1;
379 } while (*e == '.');
380 return NULL;
381}
382
383
384
385/*
386** {======================================================
387** Generic Buffer manipulation
388** =======================================================
389*/
390
391
392#define bufflen(B) ((B)->p - (B)->buffer)
393#define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B)))
394
395#define LIMIT (LUA_MINSTACK/2)
396
397
398static int emptybuffer (luaL_Buffer *B) {
399 size_t l = bufflen(B);
400 if (l == 0) return 0; /* put nothing on stack */
401 else {
402 lua_pushlstring(B->L, B->buffer, l);
403 B->p = B->buffer;
404 B->lvl++;
405 return 1;
406 }
407}
408
409
410static void adjuststack (luaL_Buffer *B) {
411 if (B->lvl > 1) {
412 lua_State *L = B->L;
413 int toget = 1; /* number of levels to concat */
414 size_t toplen = lua_strlen(L, -1);
415 do {
416 size_t l = lua_strlen(L, -(toget+1));
417 if (B->lvl - toget + 1 >= LIMIT || toplen > l) {
418 toplen += l;
419 toget++;
420 }
421 else break;
422 } while (toget < B->lvl);
423 lua_concat(L, toget);
424 B->lvl = B->lvl - toget + 1;
425 }
426}
427
428
429LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) {
430 if (emptybuffer(B))
431 adjuststack(B);
432 return B->buffer;
433}
434
435
436LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
437 while (l--)
438 luaL_addchar(B, *s++);
439}
440
441
442LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
443 luaL_addlstring(B, s, strlen(s));
444}
445
446
447LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
448 emptybuffer(B);
449 lua_concat(B->L, B->lvl);
450 B->lvl = 1;
451}
452
453
454LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
455 lua_State *L = B->L;
456 size_t vl;
457 const char *s = lua_tolstring(L, -1, &vl);
458 if (vl <= bufffree(B)) { /* fit into buffer? */
459 memcpy(B->p, s, vl); /* put it there */
460 B->p += vl;
461 lua_pop(L, 1); /* remove from stack */
462 }
463 else {
464 if (emptybuffer(B))
465 lua_insert(L, -2); /* put buffer before new value */
466 B->lvl++; /* add new value into B stack */
467 adjuststack(B);
468 }
469}
470
471
472LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
473 B->L = L;
474 B->p = B->buffer;
475 B->lvl = 0;
476}
477
478/* }====================================================== */
479
480
481LUALIB_API int luaL_ref (lua_State *L, int t) {
482 int ref;
483 t = abs_index(L, t);
484 if (lua_isnil(L, -1)) {
485 lua_pop(L, 1); /* remove from stack */
486 return LUA_REFNIL; /* `nil' has a unique fixed reference */
487 }
488 lua_rawgeti(L, t, FREELIST_REF); /* get first free element */
489 ref = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */
490 lua_pop(L, 1); /* remove it from stack */
491 if (ref != 0) { /* any free element? */
492 lua_rawgeti(L, t, ref); /* remove it from list */
493 lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */
494 }
495 else { /* no free elements */
496 ref = (int)lua_objlen(L, t);
497 ref++; /* create new reference */
498 }
499 lua_rawseti(L, t, ref);
500 return ref;
501}
502
503
504LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
505 if (ref >= 0) {
506 t = abs_index(L, t);
507 lua_rawgeti(L, t, FREELIST_REF);
508 lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */
509 lua_pushinteger(L, ref);
510 lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */
511 }
512}
513
514
515
516/*
517** {======================================================
518** Load functions
519** =======================================================
520*/
521
522typedef struct LoadF {
523 int extraline;
524 int f;
525 char buff[LUAL_BUFFERSIZE];
526} LoadF;
527
528static const char *getF(lua_State *L, void *ud, size_t *size) {
529 LoadF *lf = (LoadF *)ud;
530 (void)L;
531 if (lf->extraline) {
532 lf->extraline = 0;
533 *size = 1;
534 return "\n";
535 }
536 *size = rb->read(lf->f, lf->buff, LUAL_BUFFERSIZE);
537 if (*size <= 0) return NULL;
538 return (*size > 0) ? lf->buff : NULL;
539}
540
541
542static int errfile (lua_State *L, const char *what, int fnameindex) {
543 const char *serr = strerror(errno);
544 const char *filename = lua_tostring(L, fnameindex) + 1;
545 lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
546 lua_remove(L, fnameindex);
547 return LUA_ERRFILE;
548}
549
550
551LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
552 LoadF lf;
553 int status; //, readstatus;
554 char buffer[MAX_PATH];
555// int c;
556 int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
557 lf.extraline = 0;
558// if (filename == NULL) {
559// lua_pushliteral(L, "=stdin");
560// lf.f = stdin;
561// }
562// else {
563 lua_pushfstring(L, "@%s", filename);
564 lf.f = rb->open(filename, O_RDONLY);
565 if (lf.f < 0)
566 {
567 /* Fallback */
568 snprintf(buffer, sizeof(buffer), "%s/%s", curpath, filename);
569 lf.f = rb->open(buffer, O_RDONLY);
570
571 if(lf.f < 0)
572 {
573 snprintf(buffer, sizeof(buffer), "%s/%s", VIEWERS_DIR, filename);
574 lf.f = rb->open(buffer, O_RDONLY);
575
576 if(lf.f < 0)
577 return errfile(L, "open", fnameindex);
578 }
579 }
580// }
581// c = getc(lf.f);
582// if (c == '#') { /* Unix exec. file? */
583// lf.extraline = 1;
584// while ((c = getc(lf.f)) != EOF && c != '\n') ; /* skip first line */
585// if (c == '\n') c = getc(lf.f);
586// }
587// if (c == LUA_SIGNATURE[0]) { // && lf.f != stdin) { /* binary file? */
588// rb->close(lf.f);
589// lf.f = rb->open(filename, O_RDONLY); /* reopen in binary mode */
590// if (lf.f < 0) return errfile(L, "reopen", fnameindex);
591 /* skip eventual `#!...' */
592// while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ;
593// lf.extraline = 0;
594// }
595// ungetc(c, lf.f);
596 status = lua_load(L, getF, &lf, lua_tostring(L, -1));
597// readstatus = ferror(lf.f);
598 //if (lf.f != stdin) rb->close(lf.f); /* close file (even in case of errors) */
599 rb->close(lf.f);
600// if (readstatus) {
601// lua_settop(L, fnameindex); /* ignore results from `lua_load' */
602// return errfile(L, "read", fnameindex);
603// }
604 lua_remove(L, fnameindex);
605 return status;
606}
607
608
609typedef struct LoadS {
610 const char *s;
611 size_t size;
612} LoadS;
613
614
615static const char *getS (lua_State *L, void *ud, size_t *size) {
616 LoadS *ls = (LoadS *)ud;
617 (void)L;
618 if (ls->size == 0) return NULL;
619 *size = ls->size;
620 ls->size = 0;
621 return ls->s;
622}
623
624
625LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size,
626 const char *name) {
627 LoadS ls;
628 ls.s = buff;
629 ls.size = size;
630 return lua_load(L, getS, &ls, name);
631}
632
633
634LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s) {
635 return luaL_loadbuffer(L, s, strlen(s), s);
636}
637
638
639
640/* }====================================================== */
641
642
643static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
644 (void)ud;
645 (void)osize;
646 if (nsize == 0) {
647 free(ptr);
648 return NULL;
649 }
650 else
651 return realloc(ptr, nsize);
652}
653
654
655static int panic (lua_State *L) {
656 (void)L; /* to avoid warnings */
657 DEBUGF("PANIC: unprotected error in call to Lua API (%s)\n",
658 lua_tostring(L, -1));
659
660 return 0;
661}
662
663
664LUALIB_API lua_State *luaL_newstate (void) {
665 lua_State *L = lua_newstate(l_alloc, NULL);
666 if (L) lua_atpanic(L, &panic);
667 return L;
668}
669
diff --git a/apps/plugins/lua/lauxlib.h b/apps/plugins/lua/lauxlib.h
new file mode 100644
index 0000000000..d58f290527
--- /dev/null
+++ b/apps/plugins/lua/lauxlib.h
@@ -0,0 +1,174 @@
1/*
2** $Id$
3** Auxiliary functions for building Lua libraries
4** See Copyright Notice in lua.h
5*/
6
7
8#ifndef lauxlib_h
9#define lauxlib_h
10
11
12#include <stddef.h>
13#include <stdio.h>
14
15#include "lua.h"
16
17
18#if defined(LUA_COMPAT_GETN)
19LUALIB_API int (luaL_getn) (lua_State *L, int t);
20LUALIB_API void (luaL_setn) (lua_State *L, int t, int n);
21#else
22#define luaL_getn(L,i) ((int)lua_objlen(L, i))
23#define luaL_setn(L,i,j) ((void)0) /* no op! */
24#endif
25
26#if defined(LUA_COMPAT_OPENLIB)
27#define luaI_openlib luaL_openlib
28#endif
29
30
31/* extra error code for `luaL_load' */
32#define LUA_ERRFILE (LUA_ERRERR+1)
33
34
35typedef struct luaL_Reg {
36 const char *name;
37 lua_CFunction func;
38} luaL_Reg;
39
40
41
42LUALIB_API void (luaI_openlib) (lua_State *L, const char *libname,
43 const luaL_Reg *l, int nup);
44LUALIB_API void (luaL_register) (lua_State *L, const char *libname,
45 const luaL_Reg *l);
46LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e);
47LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e);
48LUALIB_API int (luaL_typerror) (lua_State *L, int narg, const char *tname);
49LUALIB_API int (luaL_argerror) (lua_State *L, int numarg, const char *extramsg);
50LUALIB_API const char *(luaL_checklstring) (lua_State *L, int numArg,
51 size_t *l);
52LUALIB_API const char *(luaL_optlstring) (lua_State *L, int numArg,
53 const char *def, size_t *l);
54LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int numArg);
55LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int nArg, lua_Number def);
56
57LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int numArg);
58LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int nArg,
59 lua_Integer def);
60
61LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg);
62LUALIB_API void (luaL_checktype) (lua_State *L, int narg, int t);
63LUALIB_API void (luaL_checkany) (lua_State *L, int narg);
64
65LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname);
66LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname);
67
68LUALIB_API void (luaL_where) (lua_State *L, int lvl);
69LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...);
70
71LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def,
72 const char *const lst[]);
73
74LUALIB_API int (luaL_ref) (lua_State *L, int t);
75LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref);
76
77LUALIB_API int (luaL_loadfile) (lua_State *L, const char *filename);
78LUALIB_API int (luaL_loadbuffer) (lua_State *L, const char *buff, size_t sz,
79 const char *name);
80LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s);
81
82LUALIB_API lua_State *(luaL_newstate) (void);
83
84
85LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p,
86 const char *r);
87
88LUALIB_API const char *(luaL_findtable) (lua_State *L, int idx,
89 const char *fname, int szhint);
90
91
92
93
94/*
95** ===============================================================
96** some useful macros
97** ===============================================================
98*/
99
100#define luaL_argcheck(L, cond,numarg,extramsg) \
101 ((void)((cond) || luaL_argerror(L, (numarg), (extramsg))))
102#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL))
103#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL))
104#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n)))
105#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d)))
106#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n)))
107#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d)))
108
109#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i)))
110
111#define luaL_dofile(L, fn) \
112 (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0))
113
114#define luaL_dostring(L, s) \
115 (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0))
116
117#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n)))
118
119#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n)))
120
121/*
122** {======================================================
123** Generic Buffer manipulation
124** =======================================================
125*/
126
127
128
129typedef struct luaL_Buffer {
130 char *p; /* current position in buffer */
131 int lvl; /* number of strings in the stack (level) */
132 lua_State *L;
133 char buffer[LUAL_BUFFERSIZE];
134} luaL_Buffer;
135
136#define luaL_addchar(B,c) \
137 ((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \
138 (*(B)->p++ = (char)(c)))
139
140/* compatibility only */
141#define luaL_putchar(B,c) luaL_addchar(B,c)
142
143#define luaL_addsize(B,n) ((B)->p += (n))
144
145LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B);
146LUALIB_API char *(luaL_prepbuffer) (luaL_Buffer *B);
147LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l);
148LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s);
149LUALIB_API void (luaL_addvalue) (luaL_Buffer *B);
150LUALIB_API void (luaL_pushresult) (luaL_Buffer *B);
151
152
153/* }====================================================== */
154
155
156/* compatibility with ref system */
157
158/* pre-defined references */
159#define LUA_NOREF (-2)
160#define LUA_REFNIL (-1)
161
162#define lua_ref(L,lock) ((lock) ? luaL_ref(L, LUA_REGISTRYINDEX) : \
163 (lua_pushstring(L, "unlocked references are obsolete"), lua_error(L), 0))
164
165#define lua_unref(L,ref) luaL_unref(L, LUA_REGISTRYINDEX, (ref))
166
167#define lua_getref(L,ref) lua_rawgeti(L, LUA_REGISTRYINDEX, (ref))
168
169
170#define luaL_reg luaL_Reg
171
172#endif
173
174
diff --git a/apps/plugins/lua/lbaselib.c b/apps/plugins/lua/lbaselib.c
new file mode 100644
index 0000000000..008e3629fe
--- /dev/null
+++ b/apps/plugins/lua/lbaselib.c
@@ -0,0 +1,657 @@
1/*
2** $Id: lbaselib.c,v 1.191.1.6 2008/02/14 16:46:22 roberto Exp $
3** Basic library
4** See Copyright Notice in lua.h
5*/
6
7
8
9#include <ctype.h>
10#include <stdio.h>
11#include <stdlib.h>
12#include <string.h>
13
14#define lbaselib_c
15#define LUA_LIB
16
17#include "lua.h"
18
19#include "lauxlib.h"
20#include "lualib.h"
21
22
23
24
25/*
26** If your system does not support `stdout', you can just remove this function.
27** If you need, you can define your own `print' function, following this
28** model but changing `fputs' to put the strings at a proper place
29** (a console window or a log file, for instance).
30*/
31#if 0
32static int luaB_print (lua_State *L) {
33 int n = lua_gettop(L); /* number of arguments */
34 int i;
35 lua_getglobal(L, "tostring");
36 for (i=1; i<=n; i++) {
37 const char *s;
38 lua_pushvalue(L, -1); /* function to be called */
39 lua_pushvalue(L, i); /* value to print */
40 lua_call(L, 1, 1);
41 s = lua_tostring(L, -1); /* get result */
42 if (s == NULL)
43 return luaL_error(L, LUA_QL("tostring") " must return a string to "
44 LUA_QL("print"));
45 if (i>1) fputs("\t", stdout);
46 fputs(s, stdout);
47 lua_pop(L, 1); /* pop result */
48 }
49 fputs("\n", stdout);
50 return 0;
51}
52#endif
53
54
55static int luaB_tonumber (lua_State *L) {
56 int base = luaL_optint(L, 2, 10);
57 if (base == 10) { /* standard conversion */
58 luaL_checkany(L, 1);
59 if (lua_isnumber(L, 1)) {
60 lua_pushnumber(L, lua_tonumber(L, 1));
61 return 1;
62 }
63 }
64 else {
65 const char *s1 = luaL_checkstring(L, 1);
66 char *s2;
67 unsigned long n;
68 luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
69 n = strtoul(s1, &s2, base);
70 if (s1 != s2) { /* at least one valid digit? */
71 while (isspace((unsigned char)(*s2))) s2++; /* skip trailing spaces */
72 if (*s2 == '\0') { /* no invalid trailing characters? */
73 lua_pushnumber(L, (lua_Number)n);
74 return 1;
75 }
76 }
77 }
78 lua_pushnil(L); /* else not a number */
79 return 1;
80}
81
82
83static int luaB_error (lua_State *L) {
84 int level = luaL_optint(L, 2, 1);
85 lua_settop(L, 1);
86 if (lua_isstring(L, 1) && level > 0) { /* add extra information? */
87 luaL_where(L, level);
88 lua_pushvalue(L, 1);
89 lua_concat(L, 2);
90 }
91 return lua_error(L);
92}
93
94
95static int luaB_getmetatable (lua_State *L) {
96 luaL_checkany(L, 1);
97 if (!lua_getmetatable(L, 1)) {
98 lua_pushnil(L);
99 return 1; /* no metatable */
100 }
101 luaL_getmetafield(L, 1, "__metatable");
102 return 1; /* returns either __metatable field (if present) or metatable */
103}
104
105
106static int luaB_setmetatable (lua_State *L) {
107 int t = lua_type(L, 2);
108 luaL_checktype(L, 1, LUA_TTABLE);
109 luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
110 "nil or table expected");
111 if (luaL_getmetafield(L, 1, "__metatable"))
112 luaL_error(L, "cannot change a protected metatable");
113 lua_settop(L, 2);
114 lua_setmetatable(L, 1);
115 return 1;
116}
117
118
119static void getfunc (lua_State *L, int opt) {
120 if (lua_isfunction(L, 1)) lua_pushvalue(L, 1);
121 else {
122 lua_Debug ar;
123 int level = opt ? luaL_optint(L, 1, 1) : luaL_checkint(L, 1);
124 luaL_argcheck(L, level >= 0, 1, "level must be non-negative");
125 if (lua_getstack(L, level, &ar) == 0)
126 luaL_argerror(L, 1, "invalid level");
127 lua_getinfo(L, "f", &ar);
128 if (lua_isnil(L, -1))
129 luaL_error(L, "no function environment for tail call at level %d",
130 level);
131 }
132}
133
134
135static int luaB_getfenv (lua_State *L) {
136 getfunc(L, 1);
137 if (lua_iscfunction(L, -1)) /* is a C function? */
138 lua_pushvalue(L, LUA_GLOBALSINDEX); /* return the thread's global env. */
139 else
140 lua_getfenv(L, -1);
141 return 1;
142}
143
144
145static int luaB_setfenv (lua_State *L) {
146 luaL_checktype(L, 2, LUA_TTABLE);
147 getfunc(L, 0);
148 lua_pushvalue(L, 2);
149 if (lua_isnumber(L, 1) && lua_tonumber(L, 1) == 0) {
150 /* change environment of current thread */
151 lua_pushthread(L);
152 lua_insert(L, -2);
153 lua_setfenv(L, -2);
154 return 0;
155 }
156 else if (lua_iscfunction(L, -2) || lua_setfenv(L, -2) == 0)
157 luaL_error(L,
158 LUA_QL("setfenv") " cannot change environment of given object");
159 return 1;
160}
161
162
163static int luaB_rawequal (lua_State *L) {
164 luaL_checkany(L, 1);
165 luaL_checkany(L, 2);
166 lua_pushboolean(L, lua_rawequal(L, 1, 2));
167 return 1;
168}
169
170
171static int luaB_rawget (lua_State *L) {
172 luaL_checktype(L, 1, LUA_TTABLE);
173 luaL_checkany(L, 2);
174 lua_settop(L, 2);
175 lua_rawget(L, 1);
176 return 1;
177}
178
179static int luaB_rawset (lua_State *L) {
180 luaL_checktype(L, 1, LUA_TTABLE);
181 luaL_checkany(L, 2);
182 luaL_checkany(L, 3);
183 lua_settop(L, 3);
184 lua_rawset(L, 1);
185 return 1;
186}
187
188
189static int luaB_gcinfo (lua_State *L) {
190 lua_pushinteger(L, lua_getgccount(L));
191 return 1;
192}
193
194
195static int luaB_collectgarbage (lua_State *L) {
196 static const char *const opts[] = {"stop", "restart", "collect",
197 "count", "step", "setpause", "setstepmul", NULL};
198 static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
199 LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL};
200 int o = luaL_checkoption(L, 1, "collect", opts);
201 int ex = luaL_optint(L, 2, 0);
202 int res = lua_gc(L, optsnum[o], ex);
203 switch (optsnum[o]) {
204 case LUA_GCCOUNT: {
205 int b = lua_gc(L, LUA_GCCOUNTB, 0);
206 lua_pushnumber(L, res + ((lua_Number)b/1024));
207 return 1;
208 }
209 case LUA_GCSTEP: {
210 lua_pushboolean(L, res);
211 return 1;
212 }
213 default: {
214 lua_pushnumber(L, res);
215 return 1;
216 }
217 }
218}
219
220
221static int luaB_type (lua_State *L) {
222 luaL_checkany(L, 1);
223 lua_pushstring(L, luaL_typename(L, 1));
224 return 1;
225}
226
227
228static int luaB_next (lua_State *L) {
229 luaL_checktype(L, 1, LUA_TTABLE);
230 lua_settop(L, 2); /* create a 2nd argument if there isn't one */
231 if (lua_next(L, 1))
232 return 2;
233 else {
234 lua_pushnil(L);
235 return 1;
236 }
237}
238
239
240static int luaB_pairs (lua_State *L) {
241 luaL_checktype(L, 1, LUA_TTABLE);
242 lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */
243 lua_pushvalue(L, 1); /* state, */
244 lua_pushnil(L); /* and initial value */
245 return 3;
246}
247
248
249static int ipairsaux (lua_State *L) {
250 int i = luaL_checkint(L, 2);
251 luaL_checktype(L, 1, LUA_TTABLE);
252 i++; /* next value */
253 lua_pushinteger(L, i);
254 lua_rawgeti(L, 1, i);
255 return (lua_isnil(L, -1)) ? 0 : 2;
256}
257
258
259static int luaB_ipairs (lua_State *L) {
260 luaL_checktype(L, 1, LUA_TTABLE);
261 lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */
262 lua_pushvalue(L, 1); /* state, */
263 lua_pushinteger(L, 0); /* and initial value */
264 return 3;
265}
266
267
268static int load_aux (lua_State *L, int status) {
269 if (status == 0) /* OK? */
270 return 1;
271 else {
272 lua_pushnil(L);
273 lua_insert(L, -2); /* put before error message */
274 return 2; /* return nil plus error message */
275 }
276}
277
278
279static int luaB_loadstring (lua_State *L) {
280 size_t l;
281 const char *s = luaL_checklstring(L, 1, &l);
282 const char *chunkname = luaL_optstring(L, 2, s);
283 return load_aux(L, luaL_loadbuffer(L, s, l, chunkname));
284}
285
286
287static int luaB_loadfile (lua_State *L) {
288 const char *fname = luaL_optstring(L, 1, NULL);
289 return load_aux(L, luaL_loadfile(L, fname));
290}
291
292
293/*
294** Reader for generic `load' function: `lua_load' uses the
295** stack for internal stuff, so the reader cannot change the
296** stack top. Instead, it keeps its resulting string in a
297** reserved slot inside the stack.
298*/
299static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
300 (void)ud; /* to avoid warnings */
301 luaL_checkstack(L, 2, "too many nested functions");
302 lua_pushvalue(L, 1); /* get function */
303 lua_call(L, 0, 1); /* call it */
304 if (lua_isnil(L, -1)) {
305 *size = 0;
306 return NULL;
307 }
308 else if (lua_isstring(L, -1)) {
309 lua_replace(L, 3); /* save string in a reserved stack slot */
310 return lua_tolstring(L, 3, size);
311 }
312 else luaL_error(L, "reader function must return a string");
313 return NULL; /* to avoid warnings */
314}
315
316
317static int luaB_load (lua_State *L) {
318 int status;
319 const char *cname = luaL_optstring(L, 2, "=(load)");
320 luaL_checktype(L, 1, LUA_TFUNCTION);
321 lua_settop(L, 3); /* function, eventual name, plus one reserved slot */
322 status = lua_load(L, generic_reader, NULL, cname);
323 return load_aux(L, status);
324}
325
326
327static int luaB_dofile (lua_State *L) {
328 const char *fname = luaL_optstring(L, 1, NULL);
329 int n = lua_gettop(L);
330 if (luaL_loadfile(L, fname) != 0) lua_error(L);
331 lua_call(L, 0, LUA_MULTRET);
332 return lua_gettop(L) - n;
333}
334
335
336static int luaB_assert (lua_State *L) {
337 luaL_checkany(L, 1);
338 if (!lua_toboolean(L, 1))
339 return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!"));
340 return lua_gettop(L);
341}
342
343
344static int luaB_unpack (lua_State *L) {
345 int i, e, n;
346 luaL_checktype(L, 1, LUA_TTABLE);
347 i = luaL_optint(L, 2, 1);
348 e = luaL_opt(L, luaL_checkint, 3, luaL_getn(L, 1));
349 if (i > e) return 0; /* empty range */
350 n = e - i + 1; /* number of elements */
351 if (n <= 0 || !lua_checkstack(L, n)) /* n <= 0 means arith. overflow */
352 return luaL_error(L, "too many results to unpack");
353 lua_rawgeti(L, 1, i); /* push arg[i] (avoiding overflow problems) */
354 while (i++ < e) /* push arg[i + 1...e] */
355 lua_rawgeti(L, 1, i);
356 return n;
357}
358
359
360static int luaB_select (lua_State *L) {
361 int n = lua_gettop(L);
362 if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {
363 lua_pushinteger(L, n-1);
364 return 1;
365 }
366 else {
367 int i = luaL_checkint(L, 1);
368 if (i < 0) i = n + i;
369 else if (i > n) i = n;
370 luaL_argcheck(L, 1 <= i, 1, "index out of range");
371 return n - i;
372 }
373}
374
375
376static int luaB_pcall (lua_State *L) {
377 int status;
378 luaL_checkany(L, 1);
379 status = lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0);
380 lua_pushboolean(L, (status == 0));
381 lua_insert(L, 1);
382 return lua_gettop(L); /* return status + all results */
383}
384
385
386static int luaB_xpcall (lua_State *L) {
387 int status;
388 luaL_checkany(L, 2);
389 lua_settop(L, 2);
390 lua_insert(L, 1); /* put error function under function to be called */
391 status = lua_pcall(L, 0, LUA_MULTRET, 1);
392 lua_pushboolean(L, (status == 0));
393 lua_replace(L, 1);
394 return lua_gettop(L); /* return status + all results */
395}
396
397
398static int luaB_tostring (lua_State *L) {
399 luaL_checkany(L, 1);
400 if (luaL_callmeta(L, 1, "__tostring")) /* is there a metafield? */
401 return 1; /* use its value */
402 switch (lua_type(L, 1)) {
403 case LUA_TNUMBER:
404 lua_pushstring(L, lua_tostring(L, 1));
405 break;
406 case LUA_TSTRING:
407 lua_pushvalue(L, 1);
408 break;
409 case LUA_TBOOLEAN:
410 lua_pushstring(L, (lua_toboolean(L, 1) ? "true" : "false"));
411 break;
412 case LUA_TNIL:
413 lua_pushliteral(L, "nil");
414 break;
415 default:
416 lua_pushfstring(L, "%s: %p", luaL_typename(L, 1), lua_topointer(L, 1));
417 break;
418 }
419 return 1;
420}
421
422
423static int luaB_newproxy (lua_State *L) {
424 lua_settop(L, 1);
425 lua_newuserdata(L, 0); /* create proxy */
426 if (lua_toboolean(L, 1) == 0)
427 return 1; /* no metatable */
428 else if (lua_isboolean(L, 1)) {
429 lua_newtable(L); /* create a new metatable `m' ... */
430 lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */
431 lua_pushboolean(L, 1);
432 lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */
433 }
434 else {
435 int validproxy = 0; /* to check if weaktable[metatable(u)] == true */
436 if (lua_getmetatable(L, 1)) {
437 lua_rawget(L, lua_upvalueindex(1));
438 validproxy = lua_toboolean(L, -1);
439 lua_pop(L, 1); /* remove value */
440 }
441 luaL_argcheck(L, validproxy, 1, "boolean or proxy expected");
442 lua_getmetatable(L, 1); /* metatable is valid; get it */
443 }
444 lua_setmetatable(L, 2);
445 return 1;
446}
447
448
449static const luaL_Reg base_funcs[] = {
450 {"assert", luaB_assert},
451 {"collectgarbage", luaB_collectgarbage},
452 {"dofile", luaB_dofile},
453 {"error", luaB_error},
454 {"gcinfo", luaB_gcinfo},
455 {"getfenv", luaB_getfenv},
456 {"getmetatable", luaB_getmetatable},
457 {"loadfile", luaB_loadfile},
458 {"load", luaB_load},
459 {"loadstring", luaB_loadstring},
460 {"next", luaB_next},
461 {"pcall", luaB_pcall},
462#if 0
463 {"print", luaB_print},
464#endif
465 {"rawequal", luaB_rawequal},
466 {"rawget", luaB_rawget},
467 {"rawset", luaB_rawset},
468 {"select", luaB_select},
469 {"setfenv", luaB_setfenv},
470 {"setmetatable", luaB_setmetatable},
471 {"tonumber", luaB_tonumber},
472 {"tostring", luaB_tostring},
473 {"type", luaB_type},
474 {"unpack", luaB_unpack},
475 {"xpcall", luaB_xpcall},
476 {NULL, NULL}
477};
478
479
480/*
481** {======================================================
482** Coroutine library
483** =======================================================
484*/
485
486#define CO_RUN 0 /* running */
487#define CO_SUS 1 /* suspended */
488#define CO_NOR 2 /* 'normal' (it resumed another coroutine) */
489#define CO_DEAD 3
490
491static const char *const statnames[] =
492 {"running", "suspended", "normal", "dead"};
493
494static int costatus (lua_State *L, lua_State *co) {
495 if (L == co) return CO_RUN;
496 switch (lua_status(co)) {
497 case LUA_YIELD:
498 return CO_SUS;
499 case 0: {
500 lua_Debug ar;
501 if (lua_getstack(co, 0, &ar) > 0) /* does it have frames? */
502 return CO_NOR; /* it is running */
503 else if (lua_gettop(co) == 0)
504 return CO_DEAD;
505 else
506 return CO_SUS; /* initial state */
507 }
508 default: /* some error occured */
509 return CO_DEAD;
510 }
511}
512
513
514static int luaB_costatus (lua_State *L) {
515 lua_State *co = lua_tothread(L, 1);
516 luaL_argcheck(L, co, 1, "coroutine expected");
517 lua_pushstring(L, statnames[costatus(L, co)]);
518 return 1;
519}
520
521
522static int auxresume (lua_State *L, lua_State *co, int narg) {
523 int status = costatus(L, co);
524 if (!lua_checkstack(co, narg))
525 luaL_error(L, "too many arguments to resume");
526 if (status != CO_SUS) {
527 lua_pushfstring(L, "cannot resume %s coroutine", statnames[status]);
528 return -1; /* error flag */
529 }
530 lua_xmove(L, co, narg);
531 lua_setlevel(L, co);
532 status = lua_resume(co, narg);
533 if (status == 0 || status == LUA_YIELD) {
534 int nres = lua_gettop(co);
535 if (!lua_checkstack(L, nres + 1))
536 luaL_error(L, "too many results to resume");
537 lua_xmove(co, L, nres); /* move yielded values */
538 return nres;
539 }
540 else {
541 lua_xmove(co, L, 1); /* move error message */
542 return -1; /* error flag */
543 }
544}
545
546
547static int luaB_coresume (lua_State *L) {
548 lua_State *co = lua_tothread(L, 1);
549 int r;
550 luaL_argcheck(L, co, 1, "coroutine expected");
551 r = auxresume(L, co, lua_gettop(L) - 1);
552 if (r < 0) {
553 lua_pushboolean(L, 0);
554 lua_insert(L, -2);
555 return 2; /* return false + error message */
556 }
557 else {
558 lua_pushboolean(L, 1);
559 lua_insert(L, -(r + 1));
560 return r + 1; /* return true + `resume' returns */
561 }
562}
563
564
565static int luaB_auxwrap (lua_State *L) {
566 lua_State *co = lua_tothread(L, lua_upvalueindex(1));
567 int r = auxresume(L, co, lua_gettop(L));
568 if (r < 0) {
569 if (lua_isstring(L, -1)) { /* error object is a string? */
570 luaL_where(L, 1); /* add extra info */
571 lua_insert(L, -2);
572 lua_concat(L, 2);
573 }
574 lua_error(L); /* propagate error */
575 }
576 return r;
577}
578
579
580static int luaB_cocreate (lua_State *L) {
581 lua_State *NL = lua_newthread(L);
582 luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1,
583 "Lua function expected");
584 lua_pushvalue(L, 1); /* move function to top */
585 lua_xmove(L, NL, 1); /* move function from L to NL */
586 return 1;
587}
588
589
590static int luaB_cowrap (lua_State *L) {
591 luaB_cocreate(L);
592 lua_pushcclosure(L, luaB_auxwrap, 1);
593 return 1;
594}
595
596
597static int luaB_yield (lua_State *L) {
598 return lua_yield(L, lua_gettop(L));
599}
600
601
602static int luaB_corunning (lua_State *L) {
603 if (lua_pushthread(L))
604 lua_pushnil(L); /* main thread is not a coroutine */
605 return 1;
606}
607
608
609static const luaL_Reg co_funcs[] = {
610 {"create", luaB_cocreate},
611 {"resume", luaB_coresume},
612 {"running", luaB_corunning},
613 {"status", luaB_costatus},
614 {"wrap", luaB_cowrap},
615 {"yield", luaB_yield},
616 {NULL, NULL}
617};
618
619/* }====================================================== */
620
621
622static void auxopen (lua_State *L, const char *name,
623 lua_CFunction f, lua_CFunction u) {
624 lua_pushcfunction(L, u);
625 lua_pushcclosure(L, f, 1);
626 lua_setfield(L, -2, name);
627}
628
629
630static void base_open (lua_State *L) {
631 /* set global _G */
632 lua_pushvalue(L, LUA_GLOBALSINDEX);
633 lua_setglobal(L, "_G");
634 /* open lib into global table */
635 luaL_register(L, "_G", base_funcs);
636 lua_pushliteral(L, LUA_VERSION);
637 lua_setglobal(L, "_VERSION"); /* set global _VERSION */
638 /* `ipairs' and `pairs' need auxliliary functions as upvalues */
639 auxopen(L, "ipairs", luaB_ipairs, ipairsaux);
640 auxopen(L, "pairs", luaB_pairs, luaB_next);
641 /* `newproxy' needs a weaktable as upvalue */
642 lua_createtable(L, 0, 1); /* new table `w' */
643 lua_pushvalue(L, -1); /* `w' will be its own metatable */
644 lua_setmetatable(L, -2);
645 lua_pushliteral(L, "kv");
646 lua_setfield(L, -2, "__mode"); /* metatable(w).__mode = "kv" */
647 lua_pushcclosure(L, luaB_newproxy, 1);
648 lua_setglobal(L, "newproxy"); /* set global `newproxy' */
649}
650
651
652LUALIB_API int luaopen_base (lua_State *L) {
653 base_open(L);
654 luaL_register(L, LUA_COLIBNAME, co_funcs);
655 return 2;
656}
657
diff --git a/apps/plugins/lua/lcode.c b/apps/plugins/lua/lcode.c
new file mode 100644
index 0000000000..cff626b7fa
--- /dev/null
+++ b/apps/plugins/lua/lcode.c
@@ -0,0 +1,839 @@
1/*
2** $Id: lcode.c,v 2.25.1.3 2007/12/28 15:32:23 roberto Exp $
3** Code generator for Lua
4** See Copyright Notice in lua.h
5*/
6
7
8#include <stdlib.h>
9
10#define lcode_c
11#define LUA_CORE
12
13#include "lua.h"
14
15#include "lcode.h"
16#include "ldebug.h"
17#include "ldo.h"
18#include "lgc.h"
19#include "llex.h"
20#include "lmem.h"
21#include "lobject.h"
22#include "lopcodes.h"
23#include "lparser.h"
24#include "ltable.h"
25
26
27#define hasjumps(e) ((e)->t != (e)->f)
28
29
30static int isnumeral(expdesc *e) {
31 return (e->k == VKNUM && e->t == NO_JUMP && e->f == NO_JUMP);
32}
33
34
35void luaK_nil (FuncState *fs, int from, int n) {
36 Instruction *previous;
37 if (fs->pc > fs->lasttarget) { /* no jumps to current position? */
38 if (fs->pc == 0) { /* function start? */
39 if (from >= fs->nactvar)
40 return; /* positions are already clean */
41 }
42 else {
43 previous = &fs->f->code[fs->pc-1];
44 if (GET_OPCODE(*previous) == OP_LOADNIL) {
45 int pfrom = GETARG_A(*previous);
46 int pto = GETARG_B(*previous);
47 if (pfrom <= from && from <= pto+1) { /* can connect both? */
48 if (from+n-1 > pto)
49 SETARG_B(*previous, from+n-1);
50 return;
51 }
52 }
53 }
54 }
55 luaK_codeABC(fs, OP_LOADNIL, from, from+n-1, 0); /* else no optimization */
56}
57
58
59int luaK_jump (FuncState *fs) {
60 int jpc = fs->jpc; /* save list of jumps to here */
61 int j;
62 fs->jpc = NO_JUMP;
63 j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP);
64 luaK_concat(fs, &j, jpc); /* keep them on hold */
65 return j;
66}
67
68
69void luaK_ret (FuncState *fs, int first, int nret) {
70 luaK_codeABC(fs, OP_RETURN, first, nret+1, 0);
71}
72
73
74static int condjump (FuncState *fs, OpCode op, int A, int B, int C) {
75 luaK_codeABC(fs, op, A, B, C);
76 return luaK_jump(fs);
77}
78
79
80static void fixjump (FuncState *fs, int pc, int dest) {
81 Instruction *jmp = &fs->f->code[pc];
82 int offset = dest-(pc+1);
83 lua_assert(dest != NO_JUMP);
84 if (abs(offset) > MAXARG_sBx)
85 luaX_syntaxerror(fs->ls, "control structure too long");
86 SETARG_sBx(*jmp, offset);
87}
88
89
90/*
91** returns current `pc' and marks it as a jump target (to avoid wrong
92** optimizations with consecutive instructions not in the same basic block).
93*/
94int luaK_getlabel (FuncState *fs) {
95 fs->lasttarget = fs->pc;
96 return fs->pc;
97}
98
99
100static int getjump (FuncState *fs, int pc) {
101 int offset = GETARG_sBx(fs->f->code[pc]);
102 if (offset == NO_JUMP) /* point to itself represents end of list */
103 return NO_JUMP; /* end of list */
104 else
105 return (pc+1)+offset; /* turn offset into absolute position */
106}
107
108
109static Instruction *getjumpcontrol (FuncState *fs, int pc) {
110 Instruction *pi = &fs->f->code[pc];
111 if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1))))
112 return pi-1;
113 else
114 return pi;
115}
116
117
118/*
119** check whether list has any jump that do not produce a value
120** (or produce an inverted value)
121*/
122static int need_value (FuncState *fs, int list) {
123 for (; list != NO_JUMP; list = getjump(fs, list)) {
124 Instruction i = *getjumpcontrol(fs, list);
125 if (GET_OPCODE(i) != OP_TESTSET) return 1;
126 }
127 return 0; /* not found */
128}
129
130
131static int patchtestreg (FuncState *fs, int node, int reg) {
132 Instruction *i = getjumpcontrol(fs, node);
133 if (GET_OPCODE(*i) != OP_TESTSET)
134 return 0; /* cannot patch other instructions */
135 if (reg != NO_REG && reg != GETARG_B(*i))
136 SETARG_A(*i, reg);
137 else /* no register to put value or register already has the value */
138 *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i));
139
140 return 1;
141}
142
143
144static void removevalues (FuncState *fs, int list) {
145 for (; list != NO_JUMP; list = getjump(fs, list))
146 patchtestreg(fs, list, NO_REG);
147}
148
149
150static void patchlistaux (FuncState *fs, int list, int vtarget, int reg,
151 int dtarget) {
152 while (list != NO_JUMP) {
153 int next = getjump(fs, list);
154 if (patchtestreg(fs, list, reg))
155 fixjump(fs, list, vtarget);
156 else
157 fixjump(fs, list, dtarget); /* jump to default target */
158 list = next;
159 }
160}
161
162
163static void dischargejpc (FuncState *fs) {
164 patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc);
165 fs->jpc = NO_JUMP;
166}
167
168
169void luaK_patchlist (FuncState *fs, int list, int target) {
170 if (target == fs->pc)
171 luaK_patchtohere(fs, list);
172 else {
173 lua_assert(target < fs->pc);
174 patchlistaux(fs, list, target, NO_REG, target);
175 }
176}
177
178
179void luaK_patchtohere (FuncState *fs, int list) {
180 luaK_getlabel(fs);
181 luaK_concat(fs, &fs->jpc, list);
182}
183
184
185void luaK_concat (FuncState *fs, int *l1, int l2) {
186 if (l2 == NO_JUMP) return;
187 else if (*l1 == NO_JUMP)
188 *l1 = l2;
189 else {
190 int list = *l1;
191 int next;
192 while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */
193 list = next;
194 fixjump(fs, list, l2);
195 }
196}
197
198
199void luaK_checkstack (FuncState *fs, int n) {
200 int newstack = fs->freereg + n;
201 if (newstack > fs->f->maxstacksize) {
202 if (newstack >= MAXSTACK)
203 luaX_syntaxerror(fs->ls, "function or expression too complex");
204 fs->f->maxstacksize = cast_byte(newstack);
205 }
206}
207
208
209void luaK_reserveregs (FuncState *fs, int n) {
210 luaK_checkstack(fs, n);
211 fs->freereg += n;
212}
213
214
215static void freereg (FuncState *fs, int reg) {
216 if (!ISK(reg) && reg >= fs->nactvar) {
217 fs->freereg--;
218 lua_assert(reg == fs->freereg);
219 }
220}
221
222
223static void freeexp (FuncState *fs, expdesc *e) {
224 if (e->k == VNONRELOC)
225 freereg(fs, e->u.s.info);
226}
227
228
229static int addk (FuncState *fs, TValue *k, TValue *v) {
230 lua_State *L = fs->L;
231 TValue *idx = luaH_set(L, fs->h, k);
232 Proto *f = fs->f;
233 int oldsize = f->sizek;
234 if (ttisnumber(idx)) {
235 lua_assert(luaO_rawequalObj(&fs->f->k[cast_int(nvalue(idx))], v));
236 return cast_int(nvalue(idx));
237 }
238 else { /* constant not found; create a new entry */
239 setnvalue(idx, cast_num(fs->nk));
240 luaM_growvector(L, f->k, fs->nk, f->sizek, TValue,
241 MAXARG_Bx, "constant table overflow");
242 while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
243 setobj(L, &f->k[fs->nk], v);
244 luaC_barrier(L, f, v);
245 return fs->nk++;
246 }
247}
248
249
250int luaK_stringK (FuncState *fs, TString *s) {
251 TValue o;
252 setsvalue(fs->L, &o, s);
253 return addk(fs, &o, &o);
254}
255
256
257int luaK_numberK (FuncState *fs, lua_Number r) {
258 TValue o;
259 setnvalue(&o, r);
260 return addk(fs, &o, &o);
261}
262
263
264static int boolK (FuncState *fs, int b) {
265 TValue o;
266 setbvalue(&o, b);
267 return addk(fs, &o, &o);
268}
269
270
271static int nilK (FuncState *fs) {
272 TValue k, v;
273 setnilvalue(&v);
274 /* cannot use nil as key; instead use table itself to represent nil */
275 sethvalue(fs->L, &k, fs->h);
276 return addk(fs, &k, &v);
277}
278
279
280void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) {
281 if (e->k == VCALL) { /* expression is an open function call? */
282 SETARG_C(getcode(fs, e), nresults+1);
283 }
284 else if (e->k == VVARARG) {
285 SETARG_B(getcode(fs, e), nresults+1);
286 SETARG_A(getcode(fs, e), fs->freereg);
287 luaK_reserveregs(fs, 1);
288 }
289}
290
291
292void luaK_setoneret (FuncState *fs, expdesc *e) {
293 if (e->k == VCALL) { /* expression is an open function call? */
294 e->k = VNONRELOC;
295 e->u.s.info = GETARG_A(getcode(fs, e));
296 }
297 else if (e->k == VVARARG) {
298 SETARG_B(getcode(fs, e), 2);
299 e->k = VRELOCABLE; /* can relocate its simple result */
300 }
301}
302
303
304void luaK_dischargevars (FuncState *fs, expdesc *e) {
305 switch (e->k) {
306 case VLOCAL: {
307 e->k = VNONRELOC;
308 break;
309 }
310 case VUPVAL: {
311 e->u.s.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.s.info, 0);
312 e->k = VRELOCABLE;
313 break;
314 }
315 case VGLOBAL: {
316 e->u.s.info = luaK_codeABx(fs, OP_GETGLOBAL, 0, e->u.s.info);
317 e->k = VRELOCABLE;
318 break;
319 }
320 case VINDEXED: {
321 freereg(fs, e->u.s.aux);
322 freereg(fs, e->u.s.info);
323 e->u.s.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.s.info, e->u.s.aux);
324 e->k = VRELOCABLE;
325 break;
326 }
327 case VVARARG:
328 case VCALL: {
329 luaK_setoneret(fs, e);
330 break;
331 }
332 default: break; /* there is one value available (somewhere) */
333 }
334}
335
336
337static int code_label (FuncState *fs, int A, int b, int jump) {
338 luaK_getlabel(fs); /* those instructions may be jump targets */
339 return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump);
340}
341
342
343static void discharge2reg (FuncState *fs, expdesc *e, int reg) {
344 luaK_dischargevars(fs, e);
345 switch (e->k) {
346 case VNIL: {
347 luaK_nil(fs, reg, 1);
348 break;
349 }
350 case VFALSE: case VTRUE: {
351 luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0);
352 break;
353 }
354 case VK: {
355 luaK_codeABx(fs, OP_LOADK, reg, e->u.s.info);
356 break;
357 }
358 case VKNUM: {
359 luaK_codeABx(fs, OP_LOADK, reg, luaK_numberK(fs, e->u.nval));
360 break;
361 }
362 case VRELOCABLE: {
363 Instruction *pc = &getcode(fs, e);
364 SETARG_A(*pc, reg);
365 break;
366 }
367 case VNONRELOC: {
368 if (reg != e->u.s.info)
369 luaK_codeABC(fs, OP_MOVE, reg, e->u.s.info, 0);
370 break;
371 }
372 default: {
373 lua_assert(e->k == VVOID || e->k == VJMP);
374 return; /* nothing to do... */
375 }
376 }
377 e->u.s.info = reg;
378 e->k = VNONRELOC;
379}
380
381
382static void discharge2anyreg (FuncState *fs, expdesc *e) {
383 if (e->k != VNONRELOC) {
384 luaK_reserveregs(fs, 1);
385 discharge2reg(fs, e, fs->freereg-1);
386 }
387}
388
389
390static void exp2reg (FuncState *fs, expdesc *e, int reg) {
391 discharge2reg(fs, e, reg);
392 if (e->k == VJMP)
393 luaK_concat(fs, &e->t, e->u.s.info); /* put this jump in `t' list */
394 if (hasjumps(e)) {
395 int final; /* position after whole expression */
396 int p_f = NO_JUMP; /* position of an eventual LOAD false */
397 int p_t = NO_JUMP; /* position of an eventual LOAD true */
398 if (need_value(fs, e->t) || need_value(fs, e->f)) {
399 int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs);
400 p_f = code_label(fs, reg, 0, 1);
401 p_t = code_label(fs, reg, 1, 0);
402 luaK_patchtohere(fs, fj);
403 }
404 final = luaK_getlabel(fs);
405 patchlistaux(fs, e->f, final, reg, p_f);
406 patchlistaux(fs, e->t, final, reg, p_t);
407 }
408 e->f = e->t = NO_JUMP;
409 e->u.s.info = reg;
410 e->k = VNONRELOC;
411}
412
413
414void luaK_exp2nextreg (FuncState *fs, expdesc *e) {
415 luaK_dischargevars(fs, e);
416 freeexp(fs, e);
417 luaK_reserveregs(fs, 1);
418 exp2reg(fs, e, fs->freereg - 1);
419}
420
421
422int luaK_exp2anyreg (FuncState *fs, expdesc *e) {
423 luaK_dischargevars(fs, e);
424 if (e->k == VNONRELOC) {
425 if (!hasjumps(e)) return e->u.s.info; /* exp is already in a register */
426 if (e->u.s.info >= fs->nactvar) { /* reg. is not a local? */
427 exp2reg(fs, e, e->u.s.info); /* put value on it */
428 return e->u.s.info;
429 }
430 }
431 luaK_exp2nextreg(fs, e); /* default */
432 return e->u.s.info;
433}
434
435
436void luaK_exp2val (FuncState *fs, expdesc *e) {
437 if (hasjumps(e))
438 luaK_exp2anyreg(fs, e);
439 else
440 luaK_dischargevars(fs, e);
441}
442
443
444int luaK_exp2RK (FuncState *fs, expdesc *e) {
445 luaK_exp2val(fs, e);
446 switch (e->k) {
447 case VKNUM:
448 case VTRUE:
449 case VFALSE:
450 case VNIL: {
451 if (fs->nk <= MAXINDEXRK) { /* constant fit in RK operand? */
452 e->u.s.info = (e->k == VNIL) ? nilK(fs) :
453 (e->k == VKNUM) ? luaK_numberK(fs, e->u.nval) :
454 boolK(fs, (e->k == VTRUE));
455 e->k = VK;
456 return RKASK(e->u.s.info);
457 }
458 else break;
459 }
460 case VK: {
461 if (e->u.s.info <= MAXINDEXRK) /* constant fit in argC? */
462 return RKASK(e->u.s.info);
463 else break;
464 }
465 default: break;
466 }
467 /* not a constant in the right range: put it in a register */
468 return luaK_exp2anyreg(fs, e);
469}
470
471
472void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) {
473 switch (var->k) {
474 case VLOCAL: {
475 freeexp(fs, ex);
476 exp2reg(fs, ex, var->u.s.info);
477 return;
478 }
479 case VUPVAL: {
480 int e = luaK_exp2anyreg(fs, ex);
481 luaK_codeABC(fs, OP_SETUPVAL, e, var->u.s.info, 0);
482 break;
483 }
484 case VGLOBAL: {
485 int e = luaK_exp2anyreg(fs, ex);
486 luaK_codeABx(fs, OP_SETGLOBAL, e, var->u.s.info);
487 break;
488 }
489 case VINDEXED: {
490 int e = luaK_exp2RK(fs, ex);
491 luaK_codeABC(fs, OP_SETTABLE, var->u.s.info, var->u.s.aux, e);
492 break;
493 }
494 default: {
495 lua_assert(0); /* invalid var kind to store */
496 break;
497 }
498 }
499 freeexp(fs, ex);
500}
501
502
503void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {
504 int func;
505 luaK_exp2anyreg(fs, e);
506 freeexp(fs, e);
507 func = fs->freereg;
508 luaK_reserveregs(fs, 2);
509 luaK_codeABC(fs, OP_SELF, func, e->u.s.info, luaK_exp2RK(fs, key));
510 freeexp(fs, key);
511 e->u.s.info = func;
512 e->k = VNONRELOC;
513}
514
515
516static void invertjump (FuncState *fs, expdesc *e) {
517 Instruction *pc = getjumpcontrol(fs, e->u.s.info);
518 lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET &&
519 GET_OPCODE(*pc) != OP_TEST);
520 SETARG_A(*pc, !(GETARG_A(*pc)));
521}
522
523
524static int jumponcond (FuncState *fs, expdesc *e, int cond) {
525 if (e->k == VRELOCABLE) {
526 Instruction ie = getcode(fs, e);
527 if (GET_OPCODE(ie) == OP_NOT) {
528 fs->pc--; /* remove previous OP_NOT */
529 return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond);
530 }
531 /* else go through */
532 }
533 discharge2anyreg(fs, e);
534 freeexp(fs, e);
535 return condjump(fs, OP_TESTSET, NO_REG, e->u.s.info, cond);
536}
537
538
539void luaK_goiftrue (FuncState *fs, expdesc *e) {
540 int pc; /* pc of last jump */
541 luaK_dischargevars(fs, e);
542 switch (e->k) {
543 case VK: case VKNUM: case VTRUE: {
544 pc = NO_JUMP; /* always true; do nothing */
545 break;
546 }
547 case VFALSE: {
548 pc = luaK_jump(fs); /* always jump */
549 break;
550 }
551 case VJMP: {
552 invertjump(fs, e);
553 pc = e->u.s.info;
554 break;
555 }
556 default: {
557 pc = jumponcond(fs, e, 0);
558 break;
559 }
560 }
561 luaK_concat(fs, &e->f, pc); /* insert last jump in `f' list */
562 luaK_patchtohere(fs, e->t);
563 e->t = NO_JUMP;
564}
565
566
567static void luaK_goiffalse (FuncState *fs, expdesc *e) {
568 int pc; /* pc of last jump */
569 luaK_dischargevars(fs, e);
570 switch (e->k) {
571 case VNIL: case VFALSE: {
572 pc = NO_JUMP; /* always false; do nothing */
573 break;
574 }
575 case VTRUE: {
576 pc = luaK_jump(fs); /* always jump */
577 break;
578 }
579 case VJMP: {
580 pc = e->u.s.info;
581 break;
582 }
583 default: {
584 pc = jumponcond(fs, e, 1);
585 break;
586 }
587 }
588 luaK_concat(fs, &e->t, pc); /* insert last jump in `t' list */
589 luaK_patchtohere(fs, e->f);
590 e->f = NO_JUMP;
591}
592
593
594static void codenot (FuncState *fs, expdesc *e) {
595 luaK_dischargevars(fs, e);
596 switch (e->k) {
597 case VNIL: case VFALSE: {
598 e->k = VTRUE;
599 break;
600 }
601 case VK: case VKNUM: case VTRUE: {
602 e->k = VFALSE;
603 break;
604 }
605 case VJMP: {
606 invertjump(fs, e);
607 break;
608 }
609 case VRELOCABLE:
610 case VNONRELOC: {
611 discharge2anyreg(fs, e);
612 freeexp(fs, e);
613 e->u.s.info = luaK_codeABC(fs, OP_NOT, 0, e->u.s.info, 0);
614 e->k = VRELOCABLE;
615 break;
616 }
617 default: {
618 lua_assert(0); /* cannot happen */
619 break;
620 }
621 }
622 /* interchange true and false lists */
623 { int temp = e->f; e->f = e->t; e->t = temp; }
624 removevalues(fs, e->f);
625 removevalues(fs, e->t);
626}
627
628
629void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {
630 t->u.s.aux = luaK_exp2RK(fs, k);
631 t->k = VINDEXED;
632}
633
634
635static int constfolding (OpCode op, expdesc *e1, expdesc *e2) {
636 lua_Number v1, v2, r;
637 if (!isnumeral(e1) || !isnumeral(e2)) return 0;
638 v1 = e1->u.nval;
639 v2 = e2->u.nval;
640 switch (op) {
641 case OP_ADD: r = luai_numadd(v1, v2); break;
642 case OP_SUB: r = luai_numsub(v1, v2); break;
643 case OP_MUL: r = luai_nummul(v1, v2); break;
644 case OP_DIV:
645 if (v2 == 0) return 0; /* do not attempt to divide by 0 */
646 r = luai_numdiv(v1, v2); break;
647 case OP_MOD:
648 if (v2 == 0) return 0; /* do not attempt to divide by 0 */
649 r = luai_nummod(v1, v2); break;
650 case OP_POW: r = luai_numpow(v1, v2); break;
651 case OP_UNM: r = luai_numunm(v1); break;
652 case OP_LEN: return 0; /* no constant folding for 'len' */
653 default: lua_assert(0); r = 0; break;
654 }
655 if (luai_numisnan(r)) return 0; /* do not attempt to produce NaN */
656 e1->u.nval = r;
657 return 1;
658}
659
660
661static void codearith (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2) {
662 if (constfolding(op, e1, e2))
663 return;
664 else {
665 int o2 = (op != OP_UNM && op != OP_LEN) ? luaK_exp2RK(fs, e2) : 0;
666 int o1 = luaK_exp2RK(fs, e1);
667 if (o1 > o2) {
668 freeexp(fs, e1);
669 freeexp(fs, e2);
670 }
671 else {
672 freeexp(fs, e2);
673 freeexp(fs, e1);
674 }
675 e1->u.s.info = luaK_codeABC(fs, op, 0, o1, o2);
676 e1->k = VRELOCABLE;
677 }
678}
679
680
681static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1,
682 expdesc *e2) {
683 int o1 = luaK_exp2RK(fs, e1);
684 int o2 = luaK_exp2RK(fs, e2);
685 freeexp(fs, e2);
686 freeexp(fs, e1);
687 if (cond == 0 && op != OP_EQ) {
688 int temp; /* exchange args to replace by `<' or `<=' */
689 temp = o1; o1 = o2; o2 = temp; /* o1 <==> o2 */
690 cond = 1;
691 }
692 e1->u.s.info = condjump(fs, op, cond, o1, o2);
693 e1->k = VJMP;
694}
695
696
697void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e) {
698 expdesc e2;
699 e2.t = e2.f = NO_JUMP; e2.k = VKNUM; e2.u.nval = 0;
700 switch (op) {
701 case OPR_MINUS: {
702 if (!isnumeral(e))
703 luaK_exp2anyreg(fs, e); /* cannot operate on non-numeric constants */
704 codearith(fs, OP_UNM, e, &e2);
705 break;
706 }
707 case OPR_NOT: codenot(fs, e); break;
708 case OPR_LEN: {
709 luaK_exp2anyreg(fs, e); /* cannot operate on constants */
710 codearith(fs, OP_LEN, e, &e2);
711 break;
712 }
713 default: lua_assert(0);
714 }
715}
716
717
718void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
719 switch (op) {
720 case OPR_AND: {
721 luaK_goiftrue(fs, v);
722 break;
723 }
724 case OPR_OR: {
725 luaK_goiffalse(fs, v);
726 break;
727 }
728 case OPR_CONCAT: {
729 luaK_exp2nextreg(fs, v); /* operand must be on the `stack' */
730 break;
731 }
732 case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV:
733 case OPR_MOD: case OPR_POW: {
734 if (!isnumeral(v)) luaK_exp2RK(fs, v);
735 break;
736 }
737 default: {
738 luaK_exp2RK(fs, v);
739 break;
740 }
741 }
742}
743
744
745void luaK_posfix (FuncState *fs, BinOpr op, expdesc *e1, expdesc *e2) {
746 switch (op) {
747 case OPR_AND: {
748 lua_assert(e1->t == NO_JUMP); /* list must be closed */
749 luaK_dischargevars(fs, e2);
750 luaK_concat(fs, &e2->f, e1->f);
751 *e1 = *e2;
752 break;
753 }
754 case OPR_OR: {
755 lua_assert(e1->f == NO_JUMP); /* list must be closed */
756 luaK_dischargevars(fs, e2);
757 luaK_concat(fs, &e2->t, e1->t);
758 *e1 = *e2;
759 break;
760 }
761 case OPR_CONCAT: {
762 luaK_exp2val(fs, e2);
763 if (e2->k == VRELOCABLE && GET_OPCODE(getcode(fs, e2)) == OP_CONCAT) {
764 lua_assert(e1->u.s.info == GETARG_B(getcode(fs, e2))-1);
765 freeexp(fs, e1);
766 SETARG_B(getcode(fs, e2), e1->u.s.info);
767 e1->k = VRELOCABLE; e1->u.s.info = e2->u.s.info;
768 }
769 else {
770 luaK_exp2nextreg(fs, e2); /* operand must be on the 'stack' */
771 codearith(fs, OP_CONCAT, e1, e2);
772 }
773 break;
774 }
775 case OPR_ADD: codearith(fs, OP_ADD, e1, e2); break;
776 case OPR_SUB: codearith(fs, OP_SUB, e1, e2); break;
777 case OPR_MUL: codearith(fs, OP_MUL, e1, e2); break;
778 case OPR_DIV: codearith(fs, OP_DIV, e1, e2); break;
779 case OPR_MOD: codearith(fs, OP_MOD, e1, e2); break;
780 case OPR_POW: codearith(fs, OP_POW, e1, e2); break;
781 case OPR_EQ: codecomp(fs, OP_EQ, 1, e1, e2); break;
782 case OPR_NE: codecomp(fs, OP_EQ, 0, e1, e2); break;
783 case OPR_LT: codecomp(fs, OP_LT, 1, e1, e2); break;
784 case OPR_LE: codecomp(fs, OP_LE, 1, e1, e2); break;
785 case OPR_GT: codecomp(fs, OP_LT, 0, e1, e2); break;
786 case OPR_GE: codecomp(fs, OP_LE, 0, e1, e2); break;
787 default: lua_assert(0);
788 }
789}
790
791
792void luaK_fixline (FuncState *fs, int line) {
793 fs->f->lineinfo[fs->pc - 1] = line;
794}
795
796
797static int luaK_code (FuncState *fs, Instruction i, int line) {
798 Proto *f = fs->f;
799 dischargejpc(fs); /* `pc' will change */
800 /* put new instruction in code array */
801 luaM_growvector(fs->L, f->code, fs->pc, f->sizecode, Instruction,
802 MAX_INT, "code size overflow");
803 f->code[fs->pc] = i;
804 /* save corresponding line information */
805 luaM_growvector(fs->L, f->lineinfo, fs->pc, f->sizelineinfo, int,
806 MAX_INT, "code size overflow");
807 f->lineinfo[fs->pc] = line;
808 return fs->pc++;
809}
810
811
812int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) {
813 lua_assert(getOpMode(o) == iABC);
814 lua_assert(getBMode(o) != OpArgN || b == 0);
815 lua_assert(getCMode(o) != OpArgN || c == 0);
816 return luaK_code(fs, CREATE_ABC(o, a, b, c), fs->ls->lastline);
817}
818
819
820int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) {
821 lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx);
822 lua_assert(getCMode(o) == OpArgN);
823 return luaK_code(fs, CREATE_ABx(o, a, bc), fs->ls->lastline);
824}
825
826
827void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) {
828 int c = (nelems - 1)/LFIELDS_PER_FLUSH + 1;
829 int b = (tostore == LUA_MULTRET) ? 0 : tostore;
830 lua_assert(tostore != 0);
831 if (c <= MAXARG_C)
832 luaK_codeABC(fs, OP_SETLIST, base, b, c);
833 else {
834 luaK_codeABC(fs, OP_SETLIST, base, b, 0);
835 luaK_code(fs, cast(Instruction, c), fs->ls->lastline);
836 }
837 fs->freereg = base + 1; /* free registers with list values */
838}
839
diff --git a/apps/plugins/lua/lcode.h b/apps/plugins/lua/lcode.h
new file mode 100644
index 0000000000..751b2b5695
--- /dev/null
+++ b/apps/plugins/lua/lcode.h
@@ -0,0 +1,76 @@
1/*
2** $Id$
3** Code generator for Lua
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lcode_h
8#define lcode_h
9
10#include "llex.h"
11#include "lobject.h"
12#include "lopcodes.h"
13#include "lparser.h"
14
15
16/*
17** Marks the end of a patch list. It is an invalid value both as an absolute
18** address, and as a list link (would link an element to itself).
19*/
20#define NO_JUMP (-1)
21
22
23/*
24** grep "ORDER OPR" if you change these enums
25*/
26typedef enum BinOpr {
27 OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_MOD, OPR_POW,
28 OPR_CONCAT,
29 OPR_NE, OPR_EQ,
30 OPR_LT, OPR_LE, OPR_GT, OPR_GE,
31 OPR_AND, OPR_OR,
32 OPR_NOBINOPR
33} BinOpr;
34
35
36typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr;
37
38
39#define getcode(fs,e) ((fs)->f->code[(e)->u.s.info])
40
41#define luaK_codeAsBx(fs,o,A,sBx) luaK_codeABx(fs,o,A,(sBx)+MAXARG_sBx)
42
43#define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET)
44
45LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx);
46LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C);
47LUAI_FUNC void luaK_fixline (FuncState *fs, int line);
48LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n);
49LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n);
50LUAI_FUNC void luaK_checkstack (FuncState *fs, int n);
51LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s);
52LUAI_FUNC int luaK_numberK (FuncState *fs, lua_Number r);
53LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e);
54LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e);
55LUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e);
56LUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e);
57LUAI_FUNC int luaK_exp2RK (FuncState *fs, expdesc *e);
58LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key);
59LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k);
60LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e);
61LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e);
62LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults);
63LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e);
64LUAI_FUNC int luaK_jump (FuncState *fs);
65LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret);
66LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target);
67LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list);
68LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2);
69LUAI_FUNC int luaK_getlabel (FuncState *fs);
70LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v);
71LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v);
72LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1, expdesc *v2);
73LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore);
74
75
76#endif
diff --git a/apps/plugins/lua/ldebug.c b/apps/plugins/lua/ldebug.c
new file mode 100644
index 0000000000..50ad3d3803
--- /dev/null
+++ b/apps/plugins/lua/ldebug.c
@@ -0,0 +1,638 @@
1/*
2** $Id: ldebug.c,v 2.29.1.6 2008/05/08 16:56:26 roberto Exp $
3** Debug Interface
4** See Copyright Notice in lua.h
5*/
6
7
8#include <stdarg.h>
9#include <stddef.h>
10#include <string.h>
11
12
13#define ldebug_c
14#define LUA_CORE
15
16#include "lua.h"
17
18#include "lapi.h"
19#include "lcode.h"
20#include "ldebug.h"
21#include "ldo.h"
22#include "lfunc.h"
23#include "lobject.h"
24#include "lopcodes.h"
25#include "lstate.h"
26#include "lstring.h"
27#include "ltable.h"
28#include "ltm.h"
29#include "lvm.h"
30
31
32
33static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name);
34
35
36static int currentpc (lua_State *L, CallInfo *ci) {
37 if (!isLua(ci)) return -1; /* function is not a Lua function? */
38 if (ci == L->ci)
39 ci->savedpc = L->savedpc;
40 return pcRel(ci->savedpc, ci_func(ci)->l.p);
41}
42
43
44static int currentline (lua_State *L, CallInfo *ci) {
45 int pc = currentpc(L, ci);
46 if (pc < 0)
47 return -1; /* only active lua functions have current-line information */
48 else
49 return getline(ci_func(ci)->l.p, pc);
50}
51
52
53/*
54** this function can be called asynchronous (e.g. during a signal)
55*/
56LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
57 if (func == NULL || mask == 0) { /* turn off hooks? */
58 mask = 0;
59 func = NULL;
60 }
61 L->hook = func;
62 L->basehookcount = count;
63 resethookcount(L);
64 L->hookmask = cast_byte(mask);
65 return 1;
66}
67
68
69LUA_API lua_Hook lua_gethook (lua_State *L) {
70 return L->hook;
71}
72
73
74LUA_API int lua_gethookmask (lua_State *L) {
75 return L->hookmask;
76}
77
78
79LUA_API int lua_gethookcount (lua_State *L) {
80 return L->basehookcount;
81}
82
83
84LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {
85 int status;
86 CallInfo *ci;
87 lua_lock(L);
88 for (ci = L->ci; level > 0 && ci > L->base_ci; ci--) {
89 level--;
90 if (f_isLua(ci)) /* Lua function? */
91 level -= ci->tailcalls; /* skip lost tail calls */
92 }
93 if (level == 0 && ci > L->base_ci) { /* level found? */
94 status = 1;
95 ar->i_ci = cast_int(ci - L->base_ci);
96 }
97 else if (level < 0) { /* level is of a lost tail call? */
98 status = 1;
99 ar->i_ci = 0;
100 }
101 else status = 0; /* no such level */
102 lua_unlock(L);
103 return status;
104}
105
106
107static Proto *getluaproto (CallInfo *ci) {
108 return (isLua(ci) ? ci_func(ci)->l.p : NULL);
109}
110
111
112static const char *findlocal (lua_State *L, CallInfo *ci, int n) {
113 const char *name;
114 Proto *fp = getluaproto(ci);
115 if (fp && (name = luaF_getlocalname(fp, n, currentpc(L, ci))) != NULL)
116 return name; /* is a local variable in a Lua function */
117 else {
118 StkId limit = (ci == L->ci) ? L->top : (ci+1)->func;
119 if (limit - ci->base >= n && n > 0) /* is 'n' inside 'ci' stack? */
120 return "(*temporary)";
121 else
122 return NULL;
123 }
124}
125
126
127LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {
128 CallInfo *ci = L->base_ci + ar->i_ci;
129 const char *name = findlocal(L, ci, n);
130 lua_lock(L);
131 if (name)
132 luaA_pushobject(L, ci->base + (n - 1));
133 lua_unlock(L);
134 return name;
135}
136
137
138LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {
139 CallInfo *ci = L->base_ci + ar->i_ci;
140 const char *name = findlocal(L, ci, n);
141 lua_lock(L);
142 if (name)
143 setobjs2s(L, ci->base + (n - 1), L->top - 1);
144 L->top--; /* pop value */
145 lua_unlock(L);
146 return name;
147}
148
149
150static void funcinfo (lua_Debug *ar, Closure *cl) {
151 if (cl->c.isC) {
152 ar->source = "=[C]";
153 ar->linedefined = -1;
154 ar->lastlinedefined = -1;
155 ar->what = "C";
156 }
157 else {
158 ar->source = getstr(cl->l.p->source);
159 ar->linedefined = cl->l.p->linedefined;
160 ar->lastlinedefined = cl->l.p->lastlinedefined;
161 ar->what = (ar->linedefined == 0) ? "main" : "Lua";
162 }
163 luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE);
164}
165
166
167static void info_tailcall (lua_Debug *ar) {
168 ar->name = ar->namewhat = "";
169 ar->what = "tail";
170 ar->lastlinedefined = ar->linedefined = ar->currentline = -1;
171 ar->source = "=(tail call)";
172 luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE);
173 ar->nups = 0;
174}
175
176
177static void collectvalidlines (lua_State *L, Closure *f) {
178 if (f == NULL || f->c.isC) {
179 setnilvalue(L->top);
180 }
181 else {
182 Table *t = luaH_new(L, 0, 0);
183 int *lineinfo = f->l.p->lineinfo;
184 int i;
185 for (i=0; i<f->l.p->sizelineinfo; i++)
186 setbvalue(luaH_setnum(L, t, lineinfo[i]), 1);
187 sethvalue(L, L->top, t);
188 }
189 incr_top(L);
190}
191
192
193static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,
194 Closure *f, CallInfo *ci) {
195 int status = 1;
196 if (f == NULL) {
197 info_tailcall(ar);
198 return status;
199 }
200 for (; *what; what++) {
201 switch (*what) {
202 case 'S': {
203 funcinfo(ar, f);
204 break;
205 }
206 case 'l': {
207 ar->currentline = (ci) ? currentline(L, ci) : -1;
208 break;
209 }
210 case 'u': {
211 ar->nups = f->c.nupvalues;
212 break;
213 }
214 case 'n': {
215 ar->namewhat = (ci) ? getfuncname(L, ci, &ar->name) : NULL;
216 if (ar->namewhat == NULL) {
217 ar->namewhat = ""; /* not found */
218 ar->name = NULL;
219 }
220 break;
221 }
222 case 'L':
223 case 'f': /* handled by lua_getinfo */
224 break;
225 default: status = 0; /* invalid option */
226 }
227 }
228 return status;
229}
230
231
232LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
233 int status;
234 Closure *f = NULL;
235 CallInfo *ci = NULL;
236 lua_lock(L);
237 if (*what == '>') {
238 StkId func = L->top - 1;
239 luai_apicheck(L, ttisfunction(func));
240 what++; /* skip the '>' */
241 f = clvalue(func);
242 L->top--; /* pop function */
243 }
244 else if (ar->i_ci != 0) { /* no tail call? */
245 ci = L->base_ci + ar->i_ci;
246 lua_assert(ttisfunction(ci->func));
247 f = clvalue(ci->func);
248 }
249 status = auxgetinfo(L, what, ar, f, ci);
250 if (strchr(what, 'f')) {
251 if (f == NULL) setnilvalue(L->top);
252 else setclvalue(L, L->top, f);
253 incr_top(L);
254 }
255 if (strchr(what, 'L'))
256 collectvalidlines(L, f);
257 lua_unlock(L);
258 return status;
259}
260
261
262/*
263** {======================================================
264** Symbolic Execution and code checker
265** =======================================================
266*/
267
268#define check(x) if (!(x)) return 0;
269
270#define checkjump(pt,pc) check(0 <= pc && pc < pt->sizecode)
271
272#define checkreg(pt,reg) check((reg) < (pt)->maxstacksize)
273
274
275
276static int precheck (const Proto *pt) {
277 check(pt->maxstacksize <= MAXSTACK);
278 check(pt->numparams+(pt->is_vararg & VARARG_HASARG) <= pt->maxstacksize);
279 check(!(pt->is_vararg & VARARG_NEEDSARG) ||
280 (pt->is_vararg & VARARG_HASARG));
281 check(pt->sizeupvalues <= pt->nups);
282 check(pt->sizelineinfo == pt->sizecode || pt->sizelineinfo == 0);
283 check(pt->sizecode > 0 && GET_OPCODE(pt->code[pt->sizecode-1]) == OP_RETURN);
284 return 1;
285}
286
287
288#define checkopenop(pt,pc) luaG_checkopenop((pt)->code[(pc)+1])
289
290int luaG_checkopenop (Instruction i) {
291 switch (GET_OPCODE(i)) {
292 case OP_CALL:
293 case OP_TAILCALL:
294 case OP_RETURN:
295 case OP_SETLIST: {
296 check(GETARG_B(i) == 0);
297 return 1;
298 }
299 default: return 0; /* invalid instruction after an open call */
300 }
301}
302
303
304static int checkArgMode (const Proto *pt, int r, enum OpArgMask mode) {
305 switch (mode) {
306 case OpArgN: check(r == 0); break;
307 case OpArgU: break;
308 case OpArgR: checkreg(pt, r); break;
309 case OpArgK:
310 check(ISK(r) ? INDEXK(r) < pt->sizek : r < pt->maxstacksize);
311 break;
312 }
313 return 1;
314}
315
316
317static Instruction symbexec (const Proto *pt, int lastpc, int reg) {
318 int pc;
319 int last; /* stores position of last instruction that changed `reg' */
320 last = pt->sizecode-1; /* points to final return (a `neutral' instruction) */
321 check(precheck(pt));
322 for (pc = 0; pc < lastpc; pc++) {
323 Instruction i = pt->code[pc];
324 OpCode op = GET_OPCODE(i);
325 int a = GETARG_A(i);
326 int b = 0;
327 int c = 0;
328 check(op < NUM_OPCODES);
329 checkreg(pt, a);
330 switch (getOpMode(op)) {
331 case iABC: {
332 b = GETARG_B(i);
333 c = GETARG_C(i);
334 check(checkArgMode(pt, b, getBMode(op)));
335 check(checkArgMode(pt, c, getCMode(op)));
336 break;
337 }
338 case iABx: {
339 b = GETARG_Bx(i);
340 if (getBMode(op) == OpArgK) check(b < pt->sizek);
341 break;
342 }
343 case iAsBx: {
344 b = GETARG_sBx(i);
345 if (getBMode(op) == OpArgR) {
346 int dest = pc+1+b;
347 check(0 <= dest && dest < pt->sizecode);
348 if (dest > 0) {
349 int j;
350 /* check that it does not jump to a setlist count; this
351 is tricky, because the count from a previous setlist may
352 have the same value of an invalid setlist; so, we must
353 go all the way back to the first of them (if any) */
354 for (j = 0; j < dest; j++) {
355 Instruction d = pt->code[dest-1-j];
356 if (!(GET_OPCODE(d) == OP_SETLIST && GETARG_C(d) == 0)) break;
357 }
358 /* if 'j' is even, previous value is not a setlist (even if
359 it looks like one) */
360 check((j&1) == 0);
361 }
362 }
363 break;
364 }
365 }
366 if (testAMode(op)) {
367 if (a == reg) last = pc; /* change register `a' */
368 }
369 if (testTMode(op)) {
370 check(pc+2 < pt->sizecode); /* check skip */
371 check(GET_OPCODE(pt->code[pc+1]) == OP_JMP);
372 }
373 switch (op) {
374 case OP_LOADBOOL: {
375 if (c == 1) { /* does it jump? */
376 check(pc+2 < pt->sizecode); /* check its jump */
377 check(GET_OPCODE(pt->code[pc+1]) != OP_SETLIST ||
378 GETARG_C(pt->code[pc+1]) != 0);
379 }
380 break;
381 }
382 case OP_LOADNIL: {
383 if (a <= reg && reg <= b)
384 last = pc; /* set registers from `a' to `b' */
385 break;
386 }
387 case OP_GETUPVAL:
388 case OP_SETUPVAL: {
389 check(b < pt->nups);
390 break;
391 }
392 case OP_GETGLOBAL:
393 case OP_SETGLOBAL: {
394 check(ttisstring(&pt->k[b]));
395 break;
396 }
397 case OP_SELF: {
398 checkreg(pt, a+1);
399 if (reg == a+1) last = pc;
400 break;
401 }
402 case OP_CONCAT: {
403 check(b < c); /* at least two operands */
404 break;
405 }
406 case OP_TFORLOOP: {
407 check(c >= 1); /* at least one result (control variable) */
408 checkreg(pt, a+2+c); /* space for results */
409 if (reg >= a+2) last = pc; /* affect all regs above its base */
410 break;
411 }
412 case OP_FORLOOP:
413 case OP_FORPREP:
414 checkreg(pt, a+3);
415 /* go through */
416 case OP_JMP: {
417 int dest = pc+1+b;
418 /* not full check and jump is forward and do not skip `lastpc'? */
419 if (reg != NO_REG && pc < dest && dest <= lastpc)
420 pc += b; /* do the jump */
421 break;
422 }
423 case OP_CALL:
424 case OP_TAILCALL: {
425 if (b != 0) {
426 checkreg(pt, a+b-1);
427 }
428 c--; /* c = num. returns */
429 if (c == LUA_MULTRET) {
430 check(checkopenop(pt, pc));
431 }
432 else if (c != 0)
433 checkreg(pt, a+c-1);
434 if (reg >= a) last = pc; /* affect all registers above base */
435 break;
436 }
437 case OP_RETURN: {
438 b--; /* b = num. returns */
439 if (b > 0) checkreg(pt, a+b-1);
440 break;
441 }
442 case OP_SETLIST: {
443 if (b > 0) checkreg(pt, a + b);
444 if (c == 0) {
445 pc++;
446 check(pc < pt->sizecode - 1);
447 }
448 break;
449 }
450 case OP_CLOSURE: {
451 int nup, j;
452 check(b < pt->sizep);
453 nup = pt->p[b]->nups;
454 check(pc + nup < pt->sizecode);
455 for (j = 1; j <= nup; j++) {
456 OpCode op1 = GET_OPCODE(pt->code[pc + j]);
457 check(op1 == OP_GETUPVAL || op1 == OP_MOVE);
458 }
459 if (reg != NO_REG) /* tracing? */
460 pc += nup; /* do not 'execute' these pseudo-instructions */
461 break;
462 }
463 case OP_VARARG: {
464 check((pt->is_vararg & VARARG_ISVARARG) &&
465 !(pt->is_vararg & VARARG_NEEDSARG));
466 b--;
467 if (b == LUA_MULTRET) check(checkopenop(pt, pc));
468 checkreg(pt, a+b-1);
469 break;
470 }
471 default: break;
472 }
473 }
474 return pt->code[last];
475}
476
477#undef check
478#undef checkjump
479#undef checkreg
480
481/* }====================================================== */
482
483
484int luaG_checkcode (const Proto *pt) {
485 return (symbexec(pt, pt->sizecode, NO_REG) != 0);
486}
487
488
489static const char *kname (Proto *p, int c) {
490 if (ISK(c) && ttisstring(&p->k[INDEXK(c)]))
491 return svalue(&p->k[INDEXK(c)]);
492 else
493 return "?";
494}
495
496
497static const char *getobjname (lua_State *L, CallInfo *ci, int stackpos,
498 const char **name) {
499 if (isLua(ci)) { /* a Lua function? */
500 Proto *p = ci_func(ci)->l.p;
501 int pc = currentpc(L, ci);
502 Instruction i;
503 *name = luaF_getlocalname(p, stackpos+1, pc);
504 if (*name) /* is a local? */
505 return "local";
506 i = symbexec(p, pc, stackpos); /* try symbolic execution */
507 lua_assert(pc != -1);
508 switch (GET_OPCODE(i)) {
509 case OP_GETGLOBAL: {
510 int g = GETARG_Bx(i); /* global index */
511 lua_assert(ttisstring(&p->k[g]));
512 *name = svalue(&p->k[g]);
513 return "global";
514 }
515 case OP_MOVE: {
516 int a = GETARG_A(i);
517 int b = GETARG_B(i); /* move from `b' to `a' */
518 if (b < a)
519 return getobjname(L, ci, b, name); /* get name for `b' */
520 break;
521 }
522 case OP_GETTABLE: {
523 int k = GETARG_C(i); /* key index */
524 *name = kname(p, k);
525 return "field";
526 }
527 case OP_GETUPVAL: {
528 int u = GETARG_B(i); /* upvalue index */
529 *name = p->upvalues ? getstr(p->upvalues[u]) : "?";
530 return "upvalue";
531 }
532 case OP_SELF: {
533 int k = GETARG_C(i); /* key index */
534 *name = kname(p, k);
535 return "method";
536 }
537 default: break;
538 }
539 }
540 return NULL; /* no useful name found */
541}
542
543
544static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
545 Instruction i;
546 if ((isLua(ci) && ci->tailcalls > 0) || !isLua(ci - 1))
547 return NULL; /* calling function is not Lua (or is unknown) */
548 ci--; /* calling function */
549 i = ci_func(ci)->l.p->code[currentpc(L, ci)];
550 if (GET_OPCODE(i) == OP_CALL || GET_OPCODE(i) == OP_TAILCALL ||
551 GET_OPCODE(i) == OP_TFORLOOP)
552 return getobjname(L, ci, GETARG_A(i), name);
553 else
554 return NULL; /* no useful name can be found */
555}
556
557
558/* only ANSI way to check whether a pointer points to an array */
559static int isinstack (CallInfo *ci, const TValue *o) {
560 StkId p;
561 for (p = ci->base; p < ci->top; p++)
562 if (o == p) return 1;
563 return 0;
564}
565
566
567void luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
568 const char *name = NULL;
569 const char *t = luaT_typenames[ttype(o)];
570 const char *kind = (isinstack(L->ci, o)) ?
571 getobjname(L, L->ci, cast_int(o - L->base), &name) :
572 NULL;
573 if (kind)
574 luaG_runerror(L, "attempt to %s %s " LUA_QS " (a %s value)",
575 op, kind, name, t);
576 else
577 luaG_runerror(L, "attempt to %s a %s value", op, t);
578}
579
580
581void luaG_concaterror (lua_State *L, StkId p1, StkId p2) {
582 if (ttisstring(p1) || ttisnumber(p1)) p1 = p2;
583 lua_assert(!ttisstring(p1) && !ttisnumber(p1));
584 luaG_typeerror(L, p1, "concatenate");
585}
586
587
588void luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) {
589 TValue temp;
590 if (luaV_tonumber(p1, &temp) == NULL)
591 p2 = p1; /* first operand is wrong */
592 luaG_typeerror(L, p2, "perform arithmetic on");
593}
594
595
596int luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {
597 const char *t1 = luaT_typenames[ttype(p1)];
598 const char *t2 = luaT_typenames[ttype(p2)];
599 if (t1[2] == t2[2])
600 luaG_runerror(L, "attempt to compare two %s values", t1);
601 else
602 luaG_runerror(L, "attempt to compare %s with %s", t1, t2);
603 return 0;
604}
605
606
607static void addinfo (lua_State *L, const char *msg) {
608 CallInfo *ci = L->ci;
609 if (isLua(ci)) { /* is Lua code? */
610 char buff[LUA_IDSIZE]; /* add file:line information */
611 int line = currentline(L, ci);
612 luaO_chunkid(buff, getstr(getluaproto(ci)->source), LUA_IDSIZE);
613 luaO_pushfstring(L, "%s:%d: %s", buff, line, msg);
614 }
615}
616
617
618void luaG_errormsg (lua_State *L) {
619 if (L->errfunc != 0) { /* is there an error handling function? */
620 StkId errfunc = restorestack(L, L->errfunc);
621 if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR);
622 setobjs2s(L, L->top, L->top - 1); /* move argument */
623 setobjs2s(L, L->top - 1, errfunc); /* push function */
624 incr_top(L);
625 luaD_call(L, L->top - 2, 1); /* call it */
626 }
627 luaD_throw(L, LUA_ERRRUN);
628}
629
630
631void luaG_runerror (lua_State *L, const char *fmt, ...) {
632 va_list argp;
633 va_start(argp, fmt);
634 addinfo(L, luaO_pushvfstring(L, fmt, argp));
635 va_end(argp);
636 luaG_errormsg(L);
637}
638
diff --git a/apps/plugins/lua/ldebug.h b/apps/plugins/lua/ldebug.h
new file mode 100644
index 0000000000..22226b4096
--- /dev/null
+++ b/apps/plugins/lua/ldebug.h
@@ -0,0 +1,33 @@
1/*
2** $Id$
3** Auxiliary functions from Debug Interface module
4** See Copyright Notice in lua.h
5*/
6
7#ifndef ldebug_h
8#define ldebug_h
9
10
11#include "lstate.h"
12
13
14#define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1)
15
16#define getline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : 0)
17
18#define resethookcount(L) (L->hookcount = L->basehookcount)
19
20
21LUAI_FUNC void luaG_typeerror (lua_State *L, const TValue *o,
22 const char *opname);
23LUAI_FUNC void luaG_concaterror (lua_State *L, StkId p1, StkId p2);
24LUAI_FUNC void luaG_aritherror (lua_State *L, const TValue *p1,
25 const TValue *p2);
26LUAI_FUNC int luaG_ordererror (lua_State *L, const TValue *p1,
27 const TValue *p2);
28LUAI_FUNC void luaG_runerror (lua_State *L, const char *fmt, ...);
29LUAI_FUNC void luaG_errormsg (lua_State *L);
30LUAI_FUNC int luaG_checkcode (const Proto *pt);
31LUAI_FUNC int luaG_checkopenop (Instruction i);
32
33#endif
diff --git a/apps/plugins/lua/ldo.c b/apps/plugins/lua/ldo.c
new file mode 100644
index 0000000000..f303c744c7
--- /dev/null
+++ b/apps/plugins/lua/ldo.c
@@ -0,0 +1,518 @@
1/*
2** $Id: ldo.c,v 2.38.1.3 2008/01/18 22:31:22 roberto Exp $
3** Stack and Call structure of Lua
4** See Copyright Notice in lua.h
5*/
6
7
8/* #include <setjmp.h> */
9#include <stdlib.h>
10#include <string.h>
11
12#define ldo_c
13#define LUA_CORE
14
15#include "lua.h"
16
17#include "ldebug.h"
18#include "ldo.h"
19#include "lfunc.h"
20#include "lgc.h"
21#include "lmem.h"
22#include "lobject.h"
23#include "lopcodes.h"
24#include "lparser.h"
25#include "lstate.h"
26#include "lstring.h"
27#include "ltable.h"
28#include "ltm.h"
29#include "lundump.h"
30#include "lvm.h"
31#include "lzio.h"
32
33
34
35
36/*
37** {======================================================
38** Error-recovery functions
39** =======================================================
40*/
41
42
43/* chain list of long jump buffers */
44struct lua_longjmp {
45 struct lua_longjmp *previous;
46 luai_jmpbuf b;
47 volatile int status; /* error code */
48};
49
50
51void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) {
52 switch (errcode) {
53 case LUA_ERRMEM: {
54 setsvalue2s(L, oldtop, luaS_newliteral(L, MEMERRMSG));
55 break;
56 }
57 case LUA_ERRERR: {
58 setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling"));
59 break;
60 }
61 case LUA_ERRSYNTAX:
62 case LUA_ERRRUN: {
63 setobjs2s(L, oldtop, L->top - 1); /* error message on current top */
64 break;
65 }
66 }
67 L->top = oldtop + 1;
68}
69
70
71static void restore_stack_limit (lua_State *L) {
72 lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1);
73 if (L->size_ci > LUAI_MAXCALLS) { /* there was an overflow? */
74 int inuse = cast_int(L->ci - L->base_ci);
75 if (inuse + 1 < LUAI_MAXCALLS) /* can `undo' overflow? */
76 luaD_reallocCI(L, LUAI_MAXCALLS);
77 }
78}
79
80
81static void resetstack (lua_State *L, int status) {
82 L->ci = L->base_ci;
83 L->base = L->ci->base;
84 luaF_close(L, L->base); /* close eventual pending closures */
85 luaD_seterrorobj(L, status, L->base);
86 L->nCcalls = L->baseCcalls;
87 L->allowhook = 1;
88 restore_stack_limit(L);
89 L->errfunc = 0;
90 L->errorJmp = NULL;
91}
92
93
94void luaD_throw (lua_State *L, int errcode) {
95 if (L->errorJmp) {
96 L->errorJmp->status = errcode;
97 LUAI_THROW(L, L->errorJmp);
98 }
99 else {
100 L->status = cast_byte(errcode);
101 if (G(L)->panic) {
102 resetstack(L, errcode);
103 lua_unlock(L);
104 G(L)->panic(L);
105 }
106 exit(EXIT_FAILURE);
107 }
108}
109
110
111int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
112 struct lua_longjmp lj;
113 lj.status = 0;
114 lj.previous = L->errorJmp; /* chain new error handler */
115 L->errorJmp = &lj;
116 LUAI_TRY(L, &lj,
117 (*f)(L, ud);
118 );
119 L->errorJmp = lj.previous; /* restore old error handler */
120 return lj.status;
121}
122
123/* }====================================================== */
124
125
126static void correctstack (lua_State *L, TValue *oldstack) {
127 CallInfo *ci;
128 GCObject *up;
129 L->top = (L->top - oldstack) + L->stack;
130 for (up = L->openupval; up != NULL; up = up->gch.next)
131 gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack;
132 for (ci = L->base_ci; ci <= L->ci; ci++) {
133 ci->top = (ci->top - oldstack) + L->stack;
134 ci->base = (ci->base - oldstack) + L->stack;
135 ci->func = (ci->func - oldstack) + L->stack;
136 }
137 L->base = (L->base - oldstack) + L->stack;
138}
139
140
141void luaD_reallocstack (lua_State *L, int newsize) {
142 TValue *oldstack = L->stack;
143 int realsize = newsize + 1 + EXTRA_STACK;
144 lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1);
145 luaM_reallocvector(L, L->stack, L->stacksize, realsize, TValue);
146 L->stacksize = realsize;
147 L->stack_last = L->stack+newsize;
148 correctstack(L, oldstack);
149}
150
151
152void luaD_reallocCI (lua_State *L, int newsize) {
153 CallInfo *oldci = L->base_ci;
154 luaM_reallocvector(L, L->base_ci, L->size_ci, newsize, CallInfo);
155 L->size_ci = newsize;
156 L->ci = (L->ci - oldci) + L->base_ci;
157 L->end_ci = L->base_ci + L->size_ci - 1;
158}
159
160
161void luaD_growstack (lua_State *L, int n) {
162 if (n <= L->stacksize) /* double size is enough? */
163 luaD_reallocstack(L, 2*L->stacksize);
164 else
165 luaD_reallocstack(L, L->stacksize + n);
166}
167
168
169static CallInfo *growCI (lua_State *L) {
170 if (L->size_ci > LUAI_MAXCALLS) /* overflow while handling overflow? */
171 luaD_throw(L, LUA_ERRERR);
172 else {
173 luaD_reallocCI(L, 2*L->size_ci);
174 if (L->size_ci > LUAI_MAXCALLS)
175 luaG_runerror(L, "stack overflow");
176 }
177 return ++L->ci;
178}
179
180
181void luaD_callhook (lua_State *L, int event, int line) {
182 lua_Hook hook = L->hook;
183 if (hook && L->allowhook) {
184 ptrdiff_t top = savestack(L, L->top);
185 ptrdiff_t ci_top = savestack(L, L->ci->top);
186 lua_Debug ar;
187 ar.event = event;
188 ar.currentline = line;
189 if (event == LUA_HOOKTAILRET)
190 ar.i_ci = 0; /* tail call; no debug information about it */
191 else
192 ar.i_ci = cast_int(L->ci - L->base_ci);
193 luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
194 L->ci->top = L->top + LUA_MINSTACK;
195 lua_assert(L->ci->top <= L->stack_last);
196 L->allowhook = 0; /* cannot call hooks inside a hook */
197 lua_unlock(L);
198 (*hook)(L, &ar);
199 lua_lock(L);
200 lua_assert(!L->allowhook);
201 L->allowhook = 1;
202 L->ci->top = restorestack(L, ci_top);
203 L->top = restorestack(L, top);
204 }
205}
206
207
208static StkId adjust_varargs (lua_State *L, Proto *p, int actual) {
209 int i;
210 int nfixargs = p->numparams;
211 Table *htab = NULL;
212 StkId base, fixed;
213 for (; actual < nfixargs; ++actual)
214 setnilvalue(L->top++);
215#if defined(LUA_COMPAT_VARARG)
216 if (p->is_vararg & VARARG_NEEDSARG) { /* compat. with old-style vararg? */
217 int nvar = actual - nfixargs; /* number of extra arguments */
218 lua_assert(p->is_vararg & VARARG_HASARG);
219 luaC_checkGC(L);
220 htab = luaH_new(L, nvar, 1); /* create `arg' table */
221 for (i=0; i<nvar; i++) /* put extra arguments into `arg' table */
222 setobj2n(L, luaH_setnum(L, htab, i+1), L->top - nvar + i);
223 /* store counter in field `n' */
224 setnvalue(luaH_setstr(L, htab, luaS_newliteral(L, "n")), cast_num(nvar));
225 }
226#endif
227 /* move fixed parameters to final position */
228 fixed = L->top - actual; /* first fixed argument */
229 base = L->top; /* final position of first argument */
230 for (i=0; i<nfixargs; i++) {
231 setobjs2s(L, L->top++, fixed+i);
232 setnilvalue(fixed+i);
233 }
234 /* add `arg' parameter */
235 if (htab) {
236 sethvalue(L, L->top++, htab);
237 lua_assert(iswhite(obj2gco(htab)));
238 }
239 return base;
240}
241
242
243static StkId tryfuncTM (lua_State *L, StkId func) {
244 const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL);
245 StkId p;
246 ptrdiff_t funcr = savestack(L, func);
247 if (!ttisfunction(tm))
248 luaG_typeerror(L, func, "call");
249 /* Open a hole inside the stack at `func' */
250 for (p = L->top; p > func; p--) setobjs2s(L, p, p-1);
251 incr_top(L);
252 func = restorestack(L, funcr); /* previous call may change stack */
253 setobj2s(L, func, tm); /* tag method is the new function to be called */
254 return func;
255}
256
257
258
259#define inc_ci(L) \
260 ((L->ci == L->end_ci) ? growCI(L) : \
261 (condhardstacktests(luaD_reallocCI(L, L->size_ci)), ++L->ci))
262
263
264int luaD_precall (lua_State *L, StkId func, int nresults) {
265 LClosure *cl;
266 ptrdiff_t funcr;
267 if (!ttisfunction(func)) /* `func' is not a function? */
268 func = tryfuncTM(L, func); /* check the `function' tag method */
269 funcr = savestack(L, func);
270 cl = &clvalue(func)->l;
271 L->ci->savedpc = L->savedpc;
272 if (!cl->isC) { /* Lua function? prepare its call */
273 CallInfo *ci;
274 StkId st, base;
275 Proto *p = cl->p;
276 luaD_checkstack(L, p->maxstacksize);
277 func = restorestack(L, funcr);
278 if (!p->is_vararg) { /* no varargs? */
279 base = func + 1;
280 if (L->top > base + p->numparams)
281 L->top = base + p->numparams;
282 }
283 else { /* vararg function */
284 int nargs = cast_int(L->top - func) - 1;
285 base = adjust_varargs(L, p, nargs);
286 func = restorestack(L, funcr); /* previous call may change the stack */
287 }
288 ci = inc_ci(L); /* now `enter' new function */
289 ci->func = func;
290 L->base = ci->base = base;
291 ci->top = L->base + p->maxstacksize;
292 lua_assert(ci->top <= L->stack_last);
293 L->savedpc = p->code; /* starting point */
294 ci->tailcalls = 0;
295 ci->nresults = nresults;
296 for (st = L->top; st < ci->top; st++)
297 setnilvalue(st);
298 L->top = ci->top;
299 if (L->hookmask & LUA_MASKCALL) {
300 L->savedpc++; /* hooks assume 'pc' is already incremented */
301 luaD_callhook(L, LUA_HOOKCALL, -1);
302 L->savedpc--; /* correct 'pc' */
303 }
304 return PCRLUA;
305 }
306 else { /* if is a C function, call it */
307 CallInfo *ci;
308 int n;
309 luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
310 ci = inc_ci(L); /* now `enter' new function */
311 ci->func = restorestack(L, funcr);
312 L->base = ci->base = ci->func + 1;
313 ci->top = L->top + LUA_MINSTACK;
314 lua_assert(ci->top <= L->stack_last);
315 ci->nresults = nresults;
316 if (L->hookmask & LUA_MASKCALL)
317 luaD_callhook(L, LUA_HOOKCALL, -1);
318 lua_unlock(L);
319 n = (*curr_func(L)->c.f)(L); /* do the actual call */
320 lua_lock(L);
321 if (n < 0) /* yielding? */
322 return PCRYIELD;
323 else {
324 luaD_poscall(L, L->top - n);
325 return PCRC;
326 }
327 }
328}
329
330
331static StkId callrethooks (lua_State *L, StkId firstResult) {
332 ptrdiff_t fr = savestack(L, firstResult); /* next call may change stack */
333 luaD_callhook(L, LUA_HOOKRET, -1);
334 if (f_isLua(L->ci)) { /* Lua function? */
335 while ((L->hookmask & LUA_MASKRET) && L->ci->tailcalls--) /* tail calls */
336 luaD_callhook(L, LUA_HOOKTAILRET, -1);
337 }
338 return restorestack(L, fr);
339}
340
341
342int luaD_poscall (lua_State *L, StkId firstResult) {
343 StkId res;
344 int wanted, i;
345 CallInfo *ci;
346 if (L->hookmask & LUA_MASKRET)
347 firstResult = callrethooks(L, firstResult);
348 ci = L->ci--;
349 res = ci->func; /* res == final position of 1st result */
350 wanted = ci->nresults;
351 L->base = (ci - 1)->base; /* restore base */
352 L->savedpc = (ci - 1)->savedpc; /* restore savedpc */
353 /* move results to correct place */
354 for (i = wanted; i != 0 && firstResult < L->top; i--)
355 setobjs2s(L, res++, firstResult++);
356 while (i-- > 0)
357 setnilvalue(res++);
358 L->top = res;
359 return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */
360}
361
362
363/*
364** Call a function (C or Lua). The function to be called is at *func.
365** The arguments are on the stack, right after the function.
366** When returns, all the results are on the stack, starting at the original
367** function position.
368*/
369void luaD_call (lua_State *L, StkId func, int nResults) {
370 if (++L->nCcalls >= LUAI_MAXCCALLS) {
371 if (L->nCcalls == LUAI_MAXCCALLS)
372 luaG_runerror(L, "C stack overflow");
373 else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3)))
374 luaD_throw(L, LUA_ERRERR); /* error while handing stack error */
375 }
376 if (luaD_precall(L, func, nResults) == PCRLUA) /* is a Lua function? */
377 luaV_execute(L, 1); /* call it */
378 L->nCcalls--;
379 luaC_checkGC(L);
380}
381
382
383static void resume (lua_State *L, void *ud) {
384 StkId firstArg = cast(StkId, ud);
385 CallInfo *ci = L->ci;
386 if (L->status == 0) { /* start coroutine? */
387 lua_assert(ci == L->base_ci && firstArg > L->base);
388 if (luaD_precall(L, firstArg - 1, LUA_MULTRET) != PCRLUA)
389 return;
390 }
391 else { /* resuming from previous yield */
392 lua_assert(L->status == LUA_YIELD);
393 L->status = 0;
394 if (!f_isLua(ci)) { /* `common' yield? */
395 /* finish interrupted execution of `OP_CALL' */
396 lua_assert(GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_CALL ||
397 GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_TAILCALL);
398 if (luaD_poscall(L, firstArg)) /* complete it... */
399 L->top = L->ci->top; /* and correct top if not multiple results */
400 }
401 else /* yielded inside a hook: just continue its execution */
402 L->base = L->ci->base;
403 }
404 luaV_execute(L, cast_int(L->ci - L->base_ci));
405}
406
407
408static int resume_error (lua_State *L, const char *msg) {
409 L->top = L->ci->base;
410 setsvalue2s(L, L->top, luaS_new(L, msg));
411 incr_top(L);
412 lua_unlock(L);
413 return LUA_ERRRUN;
414}
415
416
417LUA_API int lua_resume (lua_State *L, int nargs) {
418 int status;
419 lua_lock(L);
420 if (L->status != LUA_YIELD && (L->status != 0 || L->ci != L->base_ci))
421 return resume_error(L, "cannot resume non-suspended coroutine");
422 if (L->nCcalls >= LUAI_MAXCCALLS)
423 return resume_error(L, "C stack overflow");
424 luai_userstateresume(L, nargs);
425 lua_assert(L->errfunc == 0);
426 L->baseCcalls = ++L->nCcalls;
427 status = luaD_rawrunprotected(L, resume, L->top - nargs);
428 if (status != 0) { /* error? */
429 L->status = cast_byte(status); /* mark thread as `dead' */
430 luaD_seterrorobj(L, status, L->top);
431 L->ci->top = L->top;
432 }
433 else {
434 lua_assert(L->nCcalls == L->baseCcalls);
435 status = L->status;
436 }
437 --L->nCcalls;
438 lua_unlock(L);
439 return status;
440}
441
442
443LUA_API int lua_yield (lua_State *L, int nresults) {
444 luai_userstateyield(L, nresults);
445 lua_lock(L);
446 if (L->nCcalls > L->baseCcalls)
447 luaG_runerror(L, "attempt to yield across metamethod/C-call boundary");
448 L->base = L->top - nresults; /* protect stack slots below */
449 L->status = LUA_YIELD;
450 lua_unlock(L);
451 return -1;
452}
453
454
455int luaD_pcall (lua_State *L, Pfunc func, void *u,
456 ptrdiff_t old_top, ptrdiff_t ef) {
457 int status;
458 unsigned short oldnCcalls = L->nCcalls;
459 ptrdiff_t old_ci = saveci(L, L->ci);
460 lu_byte old_allowhooks = L->allowhook;
461 ptrdiff_t old_errfunc = L->errfunc;
462 L->errfunc = ef;
463 status = luaD_rawrunprotected(L, func, u);
464 if (status != 0) { /* an error occurred? */
465 StkId oldtop = restorestack(L, old_top);
466 luaF_close(L, oldtop); /* close eventual pending closures */
467 luaD_seterrorobj(L, status, oldtop);
468 L->nCcalls = oldnCcalls;
469 L->ci = restoreci(L, old_ci);
470 L->base = L->ci->base;
471 L->savedpc = L->ci->savedpc;
472 L->allowhook = old_allowhooks;
473 restore_stack_limit(L);
474 }
475 L->errfunc = old_errfunc;
476 return status;
477}
478
479
480
481/*
482** Execute a protected parser.
483*/
484struct SParser { /* data to `f_parser' */
485 ZIO *z;
486 Mbuffer buff; /* buffer to be used by the scanner */
487 const char *name;
488};
489
490static void f_parser (lua_State *L, void *ud) {
491 int i;
492 Proto *tf;
493 Closure *cl;
494 struct SParser *p = cast(struct SParser *, ud);
495 int c = luaZ_lookahead(p->z);
496 luaC_checkGC(L);
497 tf = ((c == LUA_SIGNATURE[0]) ? luaU_undump : luaY_parser)(L, p->z,
498 &p->buff, p->name);
499 cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L)));
500 cl->l.p = tf;
501 for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */
502 cl->l.upvals[i] = luaF_newupval(L);
503 setclvalue(L, L->top, cl);
504 incr_top(L);
505}
506
507
508int luaD_protectedparser (lua_State *L, ZIO *z, const char *name) {
509 struct SParser p;
510 int status;
511 p.z = z; p.name = name;
512 luaZ_initbuffer(L, &p.buff);
513 status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
514 luaZ_freebuffer(L, &p.buff);
515 return status;
516}
517
518
diff --git a/apps/plugins/lua/ldo.h b/apps/plugins/lua/ldo.h
new file mode 100644
index 0000000000..4c97134805
--- /dev/null
+++ b/apps/plugins/lua/ldo.h
@@ -0,0 +1,57 @@
1/*
2** $Id$
3** Stack and Call structure of Lua
4** See Copyright Notice in lua.h
5*/
6
7#ifndef ldo_h
8#define ldo_h
9
10
11#include "lobject.h"
12#include "lstate.h"
13#include "lzio.h"
14
15
16#define luaD_checkstack(L,n) \
17 if ((char *)L->stack_last - (char *)L->top <= (n)*(int)sizeof(TValue)) \
18 luaD_growstack(L, n); \
19 else condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1));
20
21
22#define incr_top(L) {luaD_checkstack(L,1); L->top++;}
23
24#define savestack(L,p) ((char *)(p) - (char *)L->stack)
25#define restorestack(L,n) ((TValue *)((char *)L->stack + (n)))
26
27#define saveci(L,p) ((char *)(p) - (char *)L->base_ci)
28#define restoreci(L,n) ((CallInfo *)((char *)L->base_ci + (n)))
29
30
31/* results from luaD_precall */
32#define PCRLUA 0 /* initiated a call to a Lua function */
33#define PCRC 1 /* did a call to a C function */
34#define PCRYIELD 2 /* C funtion yielded */
35
36
37/* type of protected functions, to be ran by `runprotected' */
38typedef void (*Pfunc) (lua_State *L, void *ud);
39
40LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name);
41LUAI_FUNC void luaD_callhook (lua_State *L, int event, int line);
42LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults);
43LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults);
44LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u,
45 ptrdiff_t oldtop, ptrdiff_t ef);
46LUAI_FUNC int luaD_poscall (lua_State *L, StkId firstResult);
47LUAI_FUNC void luaD_reallocCI (lua_State *L, int newsize);
48LUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize);
49LUAI_FUNC void luaD_growstack (lua_State *L, int n);
50
51LUAI_FUNC void luaD_throw (lua_State *L, int errcode);
52LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud);
53
54LUAI_FUNC void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop);
55
56#endif
57
diff --git a/apps/plugins/lua/ldump.c b/apps/plugins/lua/ldump.c
new file mode 100644
index 0000000000..c9d3d4870f
--- /dev/null
+++ b/apps/plugins/lua/ldump.c
@@ -0,0 +1,164 @@
1/*
2** $Id: ldump.c,v 2.8.1.1 2007/12/27 13:02:25 roberto Exp $
3** save precompiled Lua chunks
4** See Copyright Notice in lua.h
5*/
6
7#include <stddef.h>
8
9#define ldump_c
10#define LUA_CORE
11
12#include "lua.h"
13
14#include "lobject.h"
15#include "lstate.h"
16#include "lundump.h"
17
18typedef struct {
19 lua_State* L;
20 lua_Writer writer;
21 void* data;
22 int strip;
23 int status;
24} DumpState;
25
26#define DumpMem(b,n,size,D) DumpBlock(b,(n)*(size),D)
27#define DumpVar(x,D) DumpMem(&x,1,sizeof(x),D)
28
29static void DumpBlock(const void* b, size_t size, DumpState* D)
30{
31 if (D->status==0)
32 {
33 lua_unlock(D->L);
34 D->status=(*D->writer)(D->L,b,size,D->data);
35 lua_lock(D->L);
36 }
37}
38
39static void DumpChar(int y, DumpState* D)
40{
41 char x=(char)y;
42 DumpVar(x,D);
43}
44
45static void DumpInt(int x, DumpState* D)
46{
47 DumpVar(x,D);
48}
49
50static void DumpNumber(lua_Number x, DumpState* D)
51{
52 DumpVar(x,D);
53}
54
55static void DumpVector(const void* b, int n, size_t size, DumpState* D)
56{
57 DumpInt(n,D);
58 DumpMem(b,n,size,D);
59}
60
61static void DumpString(const TString* s, DumpState* D)
62{
63 if (s==NULL || getstr(s)==NULL)
64 {
65 size_t size=0;
66 DumpVar(size,D);
67 }
68 else
69 {
70 size_t size=s->tsv.len+1; /* include trailing '\0' */
71 DumpVar(size,D);
72 DumpBlock(getstr(s),size,D);
73 }
74}
75
76#define DumpCode(f,D) DumpVector(f->code,f->sizecode,sizeof(Instruction),D)
77
78static void DumpFunction(const Proto* f, const TString* p, DumpState* D);
79
80static void DumpConstants(const Proto* f, DumpState* D)
81{
82 int i,n=f->sizek;
83 DumpInt(n,D);
84 for (i=0; i<n; i++)
85 {
86 const TValue* o=&f->k[i];
87 DumpChar(ttype(o),D);
88 switch (ttype(o))
89 {
90 case LUA_TNIL:
91 break;
92 case LUA_TBOOLEAN:
93 DumpChar(bvalue(o),D);
94 break;
95 case LUA_TNUMBER:
96 DumpNumber(nvalue(o),D);
97 break;
98 case LUA_TSTRING:
99 DumpString(rawtsvalue(o),D);
100 break;
101 default:
102 lua_assert(0); /* cannot happen */
103 break;
104 }
105 }
106 n=f->sizep;
107 DumpInt(n,D);
108 for (i=0; i<n; i++) DumpFunction(f->p[i],f->source,D);
109}
110
111static void DumpDebug(const Proto* f, DumpState* D)
112{
113 int i,n;
114 n= (D->strip) ? 0 : f->sizelineinfo;
115 DumpVector(f->lineinfo,n,sizeof(int),D);
116 n= (D->strip) ? 0 : f->sizelocvars;
117 DumpInt(n,D);
118 for (i=0; i<n; i++)
119 {
120 DumpString(f->locvars[i].varname,D);
121 DumpInt(f->locvars[i].startpc,D);
122 DumpInt(f->locvars[i].endpc,D);
123 }
124 n= (D->strip) ? 0 : f->sizeupvalues;
125 DumpInt(n,D);
126 for (i=0; i<n; i++) DumpString(f->upvalues[i],D);
127}
128
129static void DumpFunction(const Proto* f, const TString* p, DumpState* D)
130{
131 DumpString((f->source==p || D->strip) ? NULL : f->source,D);
132 DumpInt(f->linedefined,D);
133 DumpInt(f->lastlinedefined,D);
134 DumpChar(f->nups,D);
135 DumpChar(f->numparams,D);
136 DumpChar(f->is_vararg,D);
137 DumpChar(f->maxstacksize,D);
138 DumpCode(f,D);
139 DumpConstants(f,D);
140 DumpDebug(f,D);
141}
142
143static void DumpHeader(DumpState* D)
144{
145 char h[LUAC_HEADERSIZE];
146 luaU_header(h);
147 DumpBlock(h,LUAC_HEADERSIZE,D);
148}
149
150/*
151** dump Lua function as precompiled chunk
152*/
153int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip)
154{
155 DumpState D;
156 D.L=L;
157 D.writer=w;
158 D.data=data;
159 D.strip=strip;
160 D.status=0;
161 DumpHeader(&D);
162 DumpFunction(f,NULL,&D);
163 return D.status;
164}
diff --git a/apps/plugins/lua/lfunc.c b/apps/plugins/lua/lfunc.c
new file mode 100644
index 0000000000..813e88f583
--- /dev/null
+++ b/apps/plugins/lua/lfunc.c
@@ -0,0 +1,174 @@
1/*
2** $Id: lfunc.c,v 2.12.1.2 2007/12/28 14:58:43 roberto Exp $
3** Auxiliary functions to manipulate prototypes and closures
4** See Copyright Notice in lua.h
5*/
6
7
8#include <stddef.h>
9
10#define lfunc_c
11#define LUA_CORE
12
13#include "lua.h"
14
15#include "lfunc.h"
16#include "lgc.h"
17#include "lmem.h"
18#include "lobject.h"
19#include "lstate.h"
20
21
22
23Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e) {
24 Closure *c = cast(Closure *, luaM_malloc(L, sizeCclosure(nelems)));
25 luaC_link(L, obj2gco(c), LUA_TFUNCTION);
26 c->c.isC = 1;
27 c->c.env = e;
28 c->c.nupvalues = cast_byte(nelems);
29 return c;
30}
31
32
33Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e) {
34 Closure *c = cast(Closure *, luaM_malloc(L, sizeLclosure(nelems)));
35 luaC_link(L, obj2gco(c), LUA_TFUNCTION);
36 c->l.isC = 0;
37 c->l.env = e;
38 c->l.nupvalues = cast_byte(nelems);
39 while (nelems--) c->l.upvals[nelems] = NULL;
40 return c;
41}
42
43
44UpVal *luaF_newupval (lua_State *L) {
45 UpVal *uv = luaM_new(L, UpVal);
46 luaC_link(L, obj2gco(uv), LUA_TUPVAL);
47 uv->v = &uv->u.value;
48 setnilvalue(uv->v);
49 return uv;
50}
51
52
53UpVal *luaF_findupval (lua_State *L, StkId level) {
54 global_State *g = G(L);
55 GCObject **pp = &L->openupval;
56 UpVal *p;
57 UpVal *uv;
58 while (*pp != NULL && (p = ngcotouv(*pp))->v >= level) {
59 lua_assert(p->v != &p->u.value);
60 if (p->v == level) { /* found a corresponding upvalue? */
61 if (isdead(g, obj2gco(p))) /* is it dead? */
62 changewhite(obj2gco(p)); /* ressurect it */
63 return p;
64 }
65 pp = &p->next;
66 }
67 uv = luaM_new(L, UpVal); /* not found: create a new one */
68 uv->tt = LUA_TUPVAL;
69 uv->marked = luaC_white(g);
70 uv->v = level; /* current value lives in the stack */
71 uv->next = *pp; /* chain it in the proper position */
72 *pp = obj2gco(uv);
73 uv->u.l.prev = &g->uvhead; /* double link it in `uvhead' list */
74 uv->u.l.next = g->uvhead.u.l.next;
75 uv->u.l.next->u.l.prev = uv;
76 g->uvhead.u.l.next = uv;
77 lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv);
78 return uv;
79}
80
81
82static void unlinkupval (UpVal *uv) {
83 lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv);
84 uv->u.l.next->u.l.prev = uv->u.l.prev; /* remove from `uvhead' list */
85 uv->u.l.prev->u.l.next = uv->u.l.next;
86}
87
88
89void luaF_freeupval (lua_State *L, UpVal *uv) {
90 if (uv->v != &uv->u.value) /* is it open? */
91 unlinkupval(uv); /* remove from open list */
92 luaM_free(L, uv); /* free upvalue */
93}
94
95
96void luaF_close (lua_State *L, StkId level) {
97 UpVal *uv;
98 global_State *g = G(L);
99 while (L->openupval != NULL && (uv = ngcotouv(L->openupval))->v >= level) {
100 GCObject *o = obj2gco(uv);
101 lua_assert(!isblack(o) && uv->v != &uv->u.value);
102 L->openupval = uv->next; /* remove from `open' list */
103 if (isdead(g, o))
104 luaF_freeupval(L, uv); /* free upvalue */
105 else {
106 unlinkupval(uv);
107 setobj(L, &uv->u.value, uv->v);
108 uv->v = &uv->u.value; /* now current value lives here */
109 luaC_linkupval(L, uv); /* link upvalue into `gcroot' list */
110 }
111 }
112}
113
114
115Proto *luaF_newproto (lua_State *L) {
116 Proto *f = luaM_new(L, Proto);
117 luaC_link(L, obj2gco(f), LUA_TPROTO);
118 f->k = NULL;
119 f->sizek = 0;
120 f->p = NULL;
121 f->sizep = 0;
122 f->code = NULL;
123 f->sizecode = 0;
124 f->sizelineinfo = 0;
125 f->sizeupvalues = 0;
126 f->nups = 0;
127 f->upvalues = NULL;
128 f->numparams = 0;
129 f->is_vararg = 0;
130 f->maxstacksize = 0;
131 f->lineinfo = NULL;
132 f->sizelocvars = 0;
133 f->locvars = NULL;
134 f->linedefined = 0;
135 f->lastlinedefined = 0;
136 f->source = NULL;
137 return f;
138}
139
140
141void luaF_freeproto (lua_State *L, Proto *f) {
142 luaM_freearray(L, f->code, f->sizecode, Instruction);
143 luaM_freearray(L, f->p, f->sizep, Proto *);
144 luaM_freearray(L, f->k, f->sizek, TValue);
145 luaM_freearray(L, f->lineinfo, f->sizelineinfo, int);
146 luaM_freearray(L, f->locvars, f->sizelocvars, struct LocVar);
147 luaM_freearray(L, f->upvalues, f->sizeupvalues, TString *);
148 luaM_free(L, f);
149}
150
151
152void luaF_freeclosure (lua_State *L, Closure *c) {
153 int size = (c->c.isC) ? sizeCclosure(c->c.nupvalues) :
154 sizeLclosure(c->l.nupvalues);
155 luaM_freemem(L, c, size);
156}
157
158
159/*
160** Look for n-th local variable at line `line' in function `func'.
161** Returns NULL if not found.
162*/
163const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {
164 int i;
165 for (i = 0; i<f->sizelocvars && f->locvars[i].startpc <= pc; i++) {
166 if (pc < f->locvars[i].endpc) { /* is variable active? */
167 local_number--;
168 if (local_number == 0)
169 return getstr(f->locvars[i].varname);
170 }
171 }
172 return NULL; /* not found */
173}
174
diff --git a/apps/plugins/lua/lfunc.h b/apps/plugins/lua/lfunc.h
new file mode 100644
index 0000000000..4c2b7fd138
--- /dev/null
+++ b/apps/plugins/lua/lfunc.h
@@ -0,0 +1,34 @@
1/*
2** $Id$
3** Auxiliary functions to manipulate prototypes and closures
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lfunc_h
8#define lfunc_h
9
10
11#include "lobject.h"
12
13
14#define sizeCclosure(n) (cast(int, sizeof(CClosure)) + \
15 cast(int, sizeof(TValue)*((n)-1)))
16
17#define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \
18 cast(int, sizeof(TValue *)*((n)-1)))
19
20
21LUAI_FUNC Proto *luaF_newproto (lua_State *L);
22LUAI_FUNC Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e);
23LUAI_FUNC Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e);
24LUAI_FUNC UpVal *luaF_newupval (lua_State *L);
25LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);
26LUAI_FUNC void luaF_close (lua_State *L, StkId level);
27LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f);
28LUAI_FUNC void luaF_freeclosure (lua_State *L, Closure *c);
29LUAI_FUNC void luaF_freeupval (lua_State *L, UpVal *uv);
30LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number,
31 int pc);
32
33
34#endif
diff --git a/apps/plugins/lua/lgc.c b/apps/plugins/lua/lgc.c
new file mode 100644
index 0000000000..d9e0b78294
--- /dev/null
+++ b/apps/plugins/lua/lgc.c
@@ -0,0 +1,711 @@
1/*
2** $Id: lgc.c,v 2.38.1.1 2007/12/27 13:02:25 roberto Exp $
3** Garbage Collector
4** See Copyright Notice in lua.h
5*/
6
7#include <string.h>
8
9#define lgc_c
10#define LUA_CORE
11
12#include "lua.h"
13
14#include "ldebug.h"
15#include "ldo.h"
16#include "lfunc.h"
17#include "lgc.h"
18#include "lmem.h"
19#include "lobject.h"
20#include "lstate.h"
21#include "lstring.h"
22#include "ltable.h"
23#include "ltm.h"
24
25
26#define GCSTEPSIZE 1024u
27#define GCSWEEPMAX 40
28#define GCSWEEPCOST 10
29#define GCFINALIZECOST 100
30
31
32#define maskmarks cast_byte(~(bitmask(BLACKBIT)|WHITEBITS))
33
34#define makewhite(g,x) \
35 ((x)->gch.marked = cast_byte(((x)->gch.marked & maskmarks) | luaC_white(g)))
36
37#define white2gray(x) reset2bits((x)->gch.marked, WHITE0BIT, WHITE1BIT)
38#define black2gray(x) resetbit((x)->gch.marked, BLACKBIT)
39
40#define stringmark(s) reset2bits((s)->tsv.marked, WHITE0BIT, WHITE1BIT)
41
42
43#define isfinalized(u) testbit((u)->marked, FINALIZEDBIT)
44#define markfinalized(u) l_setbit((u)->marked, FINALIZEDBIT)
45
46
47#define KEYWEAK bitmask(KEYWEAKBIT)
48#define VALUEWEAK bitmask(VALUEWEAKBIT)
49
50
51
52#define markvalue(g,o) { checkconsistency(o); \
53 if (iscollectable(o) && iswhite(gcvalue(o))) reallymarkobject(g,gcvalue(o)); }
54
55#define markobject(g,t) { if (iswhite(obj2gco(t))) \
56 reallymarkobject(g, obj2gco(t)); }
57
58
59#define setthreshold(g) (g->GCthreshold = (g->estimate/100) * g->gcpause)
60
61
62static void removeentry (Node *n) {
63 lua_assert(ttisnil(gval(n)));
64 if (iscollectable(gkey(n)))
65 setttype(gkey(n), LUA_TDEADKEY); /* dead key; remove it */
66}
67
68
69static void reallymarkobject (global_State *g, GCObject *o) {
70 lua_assert(iswhite(o) && !isdead(g, o));
71 white2gray(o);
72 switch (o->gch.tt) {
73 case LUA_TSTRING: {
74 return;
75 }
76 case LUA_TUSERDATA: {
77 Table *mt = gco2u(o)->metatable;
78 gray2black(o); /* udata are never gray */
79 if (mt) markobject(g, mt);
80 markobject(g, gco2u(o)->env);
81 return;
82 }
83 case LUA_TUPVAL: {
84 UpVal *uv = gco2uv(o);
85 markvalue(g, uv->v);
86 if (uv->v == &uv->u.value) /* closed? */
87 gray2black(o); /* open upvalues are never black */
88 return;
89 }
90 case LUA_TFUNCTION: {
91 gco2cl(o)->c.gclist = g->gray;
92 g->gray = o;
93 break;
94 }
95 case LUA_TTABLE: {
96 gco2h(o)->gclist = g->gray;
97 g->gray = o;
98 break;
99 }
100 case LUA_TTHREAD: {
101 gco2th(o)->gclist = g->gray;
102 g->gray = o;
103 break;
104 }
105 case LUA_TPROTO: {
106 gco2p(o)->gclist = g->gray;
107 g->gray = o;
108 break;
109 }
110 default: lua_assert(0);
111 }
112}
113
114
115static void marktmu (global_State *g) {
116 GCObject *u = g->tmudata;
117 if (u) {
118 do {
119 u = u->gch.next;
120 makewhite(g, u); /* may be marked, if left from previous GC */
121 reallymarkobject(g, u);
122 } while (u != g->tmudata);
123 }
124}
125
126
127/* move `dead' udata that need finalization to list `tmudata' */
128size_t luaC_separateudata (lua_State *L, int all) {
129 global_State *g = G(L);
130 size_t deadmem = 0;
131 GCObject **p = &g->mainthread->next;
132 GCObject *curr;
133 while ((curr = *p) != NULL) {
134 if (!(iswhite(curr) || all) || isfinalized(gco2u(curr)))
135 p = &curr->gch.next; /* don't bother with them */
136 else if (fasttm(L, gco2u(curr)->metatable, TM_GC) == NULL) {
137 markfinalized(gco2u(curr)); /* don't need finalization */
138 p = &curr->gch.next;
139 }
140 else { /* must call its gc method */
141 deadmem += sizeudata(gco2u(curr));
142 markfinalized(gco2u(curr));
143 *p = curr->gch.next;
144 /* link `curr' at the end of `tmudata' list */
145 if (g->tmudata == NULL) /* list is empty? */
146 g->tmudata = curr->gch.next = curr; /* creates a circular list */
147 else {
148 curr->gch.next = g->tmudata->gch.next;
149 g->tmudata->gch.next = curr;
150 g->tmudata = curr;
151 }
152 }
153 }
154 return deadmem;
155}
156
157
158static int traversetable (global_State *g, Table *h) {
159 int i;
160 int weakkey = 0;
161 int weakvalue = 0;
162 const TValue *mode;
163 if (h->metatable)
164 markobject(g, h->metatable);
165 mode = gfasttm(g, h->metatable, TM_MODE);
166 if (mode && ttisstring(mode)) { /* is there a weak mode? */
167 weakkey = (strchr(svalue(mode), 'k') != NULL);
168 weakvalue = (strchr(svalue(mode), 'v') != NULL);
169 if (weakkey || weakvalue) { /* is really weak? */
170 h->marked &= ~(KEYWEAK | VALUEWEAK); /* clear bits */
171 h->marked |= cast_byte((weakkey << KEYWEAKBIT) |
172 (weakvalue << VALUEWEAKBIT));
173 h->gclist = g->weak; /* must be cleared after GC, ... */
174 g->weak = obj2gco(h); /* ... so put in the appropriate list */
175 }
176 }
177 if (weakkey && weakvalue) return 1;
178 if (!weakvalue) {
179 i = h->sizearray;
180 while (i--)
181 markvalue(g, &h->array[i]);
182 }
183 i = sizenode(h);
184 while (i--) {
185 Node *n = gnode(h, i);
186 lua_assert(ttype(gkey(n)) != LUA_TDEADKEY || ttisnil(gval(n)));
187 if (ttisnil(gval(n)))
188 removeentry(n); /* remove empty entries */
189 else {
190 lua_assert(!ttisnil(gkey(n)));
191 if (!weakkey) markvalue(g, gkey(n));
192 if (!weakvalue) markvalue(g, gval(n));
193 }
194 }
195 return weakkey || weakvalue;
196}
197
198
199/*
200** All marks are conditional because a GC may happen while the
201** prototype is still being created
202*/
203static void traverseproto (global_State *g, Proto *f) {
204 int i;
205 if (f->source) stringmark(f->source);
206 for (i=0; i<f->sizek; i++) /* mark literals */
207 markvalue(g, &f->k[i]);
208 for (i=0; i<f->sizeupvalues; i++) { /* mark upvalue names */
209 if (f->upvalues[i])
210 stringmark(f->upvalues[i]);
211 }
212 for (i=0; i<f->sizep; i++) { /* mark nested protos */
213 if (f->p[i])
214 markobject(g, f->p[i]);
215 }
216 for (i=0; i<f->sizelocvars; i++) { /* mark local-variable names */
217 if (f->locvars[i].varname)
218 stringmark(f->locvars[i].varname);
219 }
220}
221
222
223
224static void traverseclosure (global_State *g, Closure *cl) {
225 markobject(g, cl->c.env);
226 if (cl->c.isC) {
227 int i;
228 for (i=0; i<cl->c.nupvalues; i++) /* mark its upvalues */
229 markvalue(g, &cl->c.upvalue[i]);
230 }
231 else {
232 int i;
233 lua_assert(cl->l.nupvalues == cl->l.p->nups);
234 markobject(g, cl->l.p);
235 for (i=0; i<cl->l.nupvalues; i++) /* mark its upvalues */
236 markobject(g, cl->l.upvals[i]);
237 }
238}
239
240
241static void checkstacksizes (lua_State *L, StkId max) {
242 int ci_used = cast_int(L->ci - L->base_ci); /* number of `ci' in use */
243 int s_used = cast_int(max - L->stack); /* part of stack in use */
244 if (L->size_ci > LUAI_MAXCALLS) /* handling overflow? */
245 return; /* do not touch the stacks */
246 if (4*ci_used < L->size_ci && 2*BASIC_CI_SIZE < L->size_ci)
247 luaD_reallocCI(L, L->size_ci/2); /* still big enough... */
248 condhardstacktests(luaD_reallocCI(L, ci_used + 1));
249 if (4*s_used < L->stacksize &&
250 2*(BASIC_STACK_SIZE+EXTRA_STACK) < L->stacksize)
251 luaD_reallocstack(L, L->stacksize/2); /* still big enough... */
252 condhardstacktests(luaD_reallocstack(L, s_used));
253}
254
255
256static void traversestack (global_State *g, lua_State *l) {
257 StkId o, lim;
258 CallInfo *ci;
259 markvalue(g, gt(l));
260 lim = l->top;
261 for (ci = l->base_ci; ci <= l->ci; ci++) {
262 lua_assert(ci->top <= l->stack_last);
263 if (lim < ci->top) lim = ci->top;
264 }
265 for (o = l->stack; o < l->top; o++)
266 markvalue(g, o);
267 for (; o <= lim; o++)
268 setnilvalue(o);
269 checkstacksizes(l, lim);
270}
271
272
273/*
274** traverse one gray object, turning it to black.
275** Returns `quantity' traversed.
276*/
277static l_mem propagatemark (global_State *g) {
278 GCObject *o = g->gray;
279 lua_assert(isgray(o));
280 gray2black(o);
281 switch (o->gch.tt) {
282 case LUA_TTABLE: {
283 Table *h = gco2h(o);
284 g->gray = h->gclist;
285 if (traversetable(g, h)) /* table is weak? */
286 black2gray(o); /* keep it gray */
287 return sizeof(Table) + sizeof(TValue) * h->sizearray +
288 sizeof(Node) * sizenode(h);
289 }
290 case LUA_TFUNCTION: {
291 Closure *cl = gco2cl(o);
292 g->gray = cl->c.gclist;
293 traverseclosure(g, cl);
294 return (cl->c.isC) ? sizeCclosure(cl->c.nupvalues) :
295 sizeLclosure(cl->l.nupvalues);
296 }
297 case LUA_TTHREAD: {
298 lua_State *th = gco2th(o);
299 g->gray = th->gclist;
300 th->gclist = g->grayagain;
301 g->grayagain = o;
302 black2gray(o);
303 traversestack(g, th);
304 return sizeof(lua_State) + sizeof(TValue) * th->stacksize +
305 sizeof(CallInfo) * th->size_ci;
306 }
307 case LUA_TPROTO: {
308 Proto *p = gco2p(o);
309 g->gray = p->gclist;
310 traverseproto(g, p);
311 return sizeof(Proto) + sizeof(Instruction) * p->sizecode +
312 sizeof(Proto *) * p->sizep +
313 sizeof(TValue) * p->sizek +
314 sizeof(int) * p->sizelineinfo +
315 sizeof(LocVar) * p->sizelocvars +
316 sizeof(TString *) * p->sizeupvalues;
317 }
318 default: lua_assert(0); return 0;
319 }
320}
321
322
323static size_t propagateall (global_State *g) {
324 size_t m = 0;
325 while (g->gray) m += propagatemark(g);
326 return m;
327}
328
329
330/*
331** The next function tells whether a key or value can be cleared from
332** a weak table. Non-collectable objects are never removed from weak
333** tables. Strings behave as `values', so are never removed too. for
334** other objects: if really collected, cannot keep them; for userdata
335** being finalized, keep them in keys, but not in values
336*/
337static int iscleared (const TValue *o, int iskey) {
338 if (!iscollectable(o)) return 0;
339 if (ttisstring(o)) {
340 stringmark(rawtsvalue(o)); /* strings are `values', so are never weak */
341 return 0;
342 }
343 return iswhite(gcvalue(o)) ||
344 (ttisuserdata(o) && (!iskey && isfinalized(uvalue(o))));
345}
346
347
348/*
349** clear collected entries from weaktables
350*/
351static void cleartable (GCObject *l) {
352 while (l) {
353 Table *h = gco2h(l);
354 int i = h->sizearray;
355 lua_assert(testbit(h->marked, VALUEWEAKBIT) ||
356 testbit(h->marked, KEYWEAKBIT));
357 if (testbit(h->marked, VALUEWEAKBIT)) {
358 while (i--) {
359 TValue *o = &h->array[i];
360 if (iscleared(o, 0)) /* value was collected? */
361 setnilvalue(o); /* remove value */
362 }
363 }
364 i = sizenode(h);
365 while (i--) {
366 Node *n = gnode(h, i);
367 if (!ttisnil(gval(n)) && /* non-empty entry? */
368 (iscleared(key2tval(n), 1) || iscleared(gval(n), 0))) {
369 setnilvalue(gval(n)); /* remove value ... */
370 removeentry(n); /* remove entry from table */
371 }
372 }
373 l = h->gclist;
374 }
375}
376
377
378static void freeobj (lua_State *L, GCObject *o) {
379 switch (o->gch.tt) {
380 case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
381 case LUA_TFUNCTION: luaF_freeclosure(L, gco2cl(o)); break;
382 case LUA_TUPVAL: luaF_freeupval(L, gco2uv(o)); break;
383 case LUA_TTABLE: luaH_free(L, gco2h(o)); break;
384 case LUA_TTHREAD: {
385 lua_assert(gco2th(o) != L && gco2th(o) != G(L)->mainthread);
386 luaE_freethread(L, gco2th(o));
387 break;
388 }
389 case LUA_TSTRING: {
390 G(L)->strt.nuse--;
391 luaM_freemem(L, o, sizestring(gco2ts(o)));
392 break;
393 }
394 case LUA_TUSERDATA: {
395 luaM_freemem(L, o, sizeudata(gco2u(o)));
396 break;
397 }
398 default: lua_assert(0);
399 }
400}
401
402
403
404#define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM)
405
406
407static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
408 GCObject *curr;
409 global_State *g = G(L);
410 int deadmask = otherwhite(g);
411 while ((curr = *p) != NULL && count-- > 0) {
412 if (curr->gch.tt == LUA_TTHREAD) /* sweep open upvalues of each thread */
413 sweepwholelist(L, &gco2th(curr)->openupval);
414 if ((curr->gch.marked ^ WHITEBITS) & deadmask) { /* not dead? */
415 lua_assert(!isdead(g, curr) || testbit(curr->gch.marked, FIXEDBIT));
416 makewhite(g, curr); /* make it white (for next cycle) */
417 p = &curr->gch.next;
418 }
419 else { /* must erase `curr' */
420 lua_assert(isdead(g, curr) || deadmask == bitmask(SFIXEDBIT));
421 *p = curr->gch.next;
422 if (curr == g->rootgc) /* is the first element of the list? */
423 g->rootgc = curr->gch.next; /* adjust first */
424 freeobj(L, curr);
425 }
426 }
427 return p;
428}
429
430
431static void checkSizes (lua_State *L) {
432 global_State *g = G(L);
433 /* check size of string hash */
434 if (g->strt.nuse < cast(lu_int32, g->strt.size/4) &&
435 g->strt.size > MINSTRTABSIZE*2)
436 luaS_resize(L, g->strt.size/2); /* table is too big */
437 /* check size of buffer */
438 if (luaZ_sizebuffer(&g->buff) > LUA_MINBUFFER*2) { /* buffer too big? */
439 size_t newsize = luaZ_sizebuffer(&g->buff) / 2;
440 luaZ_resizebuffer(L, &g->buff, newsize);
441 }
442}
443
444
445static void GCTM (lua_State *L) {
446 global_State *g = G(L);
447 GCObject *o = g->tmudata->gch.next; /* get first element */
448 Udata *udata = rawgco2u(o);
449 const TValue *tm;
450 /* remove udata from `tmudata' */
451 if (o == g->tmudata) /* last element? */
452 g->tmudata = NULL;
453 else
454 g->tmudata->gch.next = udata->uv.next;
455 udata->uv.next = g->mainthread->next; /* return it to `root' list */
456 g->mainthread->next = o;
457 makewhite(g, o);
458 tm = fasttm(L, udata->uv.metatable, TM_GC);
459 if (tm != NULL) {
460 lu_byte oldah = L->allowhook;
461 lu_mem oldt = g->GCthreshold;
462 L->allowhook = 0; /* stop debug hooks during GC tag method */
463 g->GCthreshold = 2*g->totalbytes; /* avoid GC steps */
464 setobj2s(L, L->top, tm);
465 setuvalue(L, L->top+1, udata);
466 L->top += 2;
467 luaD_call(L, L->top - 2, 0);
468 L->allowhook = oldah; /* restore hooks */
469 g->GCthreshold = oldt; /* restore threshold */
470 }
471}
472
473
474/*
475** Call all GC tag methods
476*/
477void luaC_callGCTM (lua_State *L) {
478 while (G(L)->tmudata)
479 GCTM(L);
480}
481
482
483void luaC_freeall (lua_State *L) {
484 global_State *g = G(L);
485 int i;
486 g->currentwhite = WHITEBITS | bitmask(SFIXEDBIT); /* mask to collect all elements */
487 sweepwholelist(L, &g->rootgc);
488 for (i = 0; i < g->strt.size; i++) /* free all string lists */
489 sweepwholelist(L, &g->strt.hash[i]);
490}
491
492
493static void markmt (global_State *g) {
494 int i;
495 for (i=0; i<NUM_TAGS; i++)
496 if (g->mt[i]) markobject(g, g->mt[i]);
497}
498
499
500/* mark root set */
501static void markroot (lua_State *L) {
502 global_State *g = G(L);
503 g->gray = NULL;
504 g->grayagain = NULL;
505 g->weak = NULL;
506 markobject(g, g->mainthread);
507 /* make global table be traversed before main stack */
508 markvalue(g, gt(g->mainthread));
509 markvalue(g, registry(L));
510 markmt(g);
511 g->gcstate = GCSpropagate;
512}
513
514
515static void remarkupvals (global_State *g) {
516 UpVal *uv;
517 for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) {
518 lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv);
519 if (isgray(obj2gco(uv)))
520 markvalue(g, uv->v);
521 }
522}
523
524
525static void atomic (lua_State *L) {
526 global_State *g = G(L);
527 size_t udsize; /* total size of userdata to be finalized */
528 /* remark occasional upvalues of (maybe) dead threads */
529 remarkupvals(g);
530 /* traverse objects cautch by write barrier and by 'remarkupvals' */
531 propagateall(g);
532 /* remark weak tables */
533 g->gray = g->weak;
534 g->weak = NULL;
535 lua_assert(!iswhite(obj2gco(g->mainthread)));
536 markobject(g, L); /* mark running thread */
537 markmt(g); /* mark basic metatables (again) */
538 propagateall(g);
539 /* remark gray again */
540 g->gray = g->grayagain;
541 g->grayagain = NULL;
542 propagateall(g);
543 udsize = luaC_separateudata(L, 0); /* separate userdata to be finalized */
544 marktmu(g); /* mark `preserved' userdata */
545 udsize += propagateall(g); /* remark, to propagate `preserveness' */
546 cleartable(g->weak); /* remove collected objects from weak tables */
547 /* flip current white */
548 g->currentwhite = cast_byte(otherwhite(g));
549 g->sweepstrgc = 0;
550 g->sweepgc = &g->rootgc;
551 g->gcstate = GCSsweepstring;
552 g->estimate = g->totalbytes - udsize; /* first estimate */
553}
554
555
556static l_mem singlestep (lua_State *L) {
557 global_State *g = G(L);
558 /*lua_checkmemory(L);*/
559 switch (g->gcstate) {
560 case GCSpause: {
561 markroot(L); /* start a new collection */
562 return 0;
563 }
564 case GCSpropagate: {
565 if (g->gray)
566 return propagatemark(g);
567 else { /* no more `gray' objects */
568 atomic(L); /* finish mark phase */
569 return 0;
570 }
571 }
572 case GCSsweepstring: {
573 lu_mem old = g->totalbytes;
574 sweepwholelist(L, &g->strt.hash[g->sweepstrgc++]);
575 if (g->sweepstrgc >= g->strt.size) /* nothing more to sweep? */
576 g->gcstate = GCSsweep; /* end sweep-string phase */
577 lua_assert(old >= g->totalbytes);
578 g->estimate -= old - g->totalbytes;
579 return GCSWEEPCOST;
580 }
581 case GCSsweep: {
582 lu_mem old = g->totalbytes;
583 g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
584 if (*g->sweepgc == NULL) { /* nothing more to sweep? */
585 checkSizes(L);
586 g->gcstate = GCSfinalize; /* end sweep phase */
587 }
588 lua_assert(old >= g->totalbytes);
589 g->estimate -= old - g->totalbytes;
590 return GCSWEEPMAX*GCSWEEPCOST;
591 }
592 case GCSfinalize: {
593 if (g->tmudata) {
594 GCTM(L);
595 if (g->estimate > GCFINALIZECOST)
596 g->estimate -= GCFINALIZECOST;
597 return GCFINALIZECOST;
598 }
599 else {
600 g->gcstate = GCSpause; /* end collection */
601 g->gcdept = 0;
602 return 0;
603 }
604 }
605 default: lua_assert(0); return 0;
606 }
607}
608
609
610void luaC_step (lua_State *L) {
611 global_State *g = G(L);
612 l_mem lim = (GCSTEPSIZE/100) * g->gcstepmul;
613 if (lim == 0)
614 lim = (MAX_LUMEM-1)/2; /* no limit */
615 g->gcdept += g->totalbytes - g->GCthreshold;
616 do {
617 lim -= singlestep(L);
618 if (g->gcstate == GCSpause)
619 break;
620 } while (lim > 0);
621 if (g->gcstate != GCSpause) {
622 if (g->gcdept < GCSTEPSIZE)
623 g->GCthreshold = g->totalbytes + GCSTEPSIZE; /* - lim/g->gcstepmul;*/
624 else {
625 g->gcdept -= GCSTEPSIZE;
626 g->GCthreshold = g->totalbytes;
627 }
628 }
629 else {
630 lua_assert(g->totalbytes >= g->estimate);
631 setthreshold(g);
632 }
633}
634
635
636void luaC_fullgc (lua_State *L) {
637 global_State *g = G(L);
638 if (g->gcstate <= GCSpropagate) {
639 /* reset sweep marks to sweep all elements (returning them to white) */
640 g->sweepstrgc = 0;
641 g->sweepgc = &g->rootgc;
642 /* reset other collector lists */
643 g->gray = NULL;
644 g->grayagain = NULL;
645 g->weak = NULL;
646 g->gcstate = GCSsweepstring;
647 }
648 lua_assert(g->gcstate != GCSpause && g->gcstate != GCSpropagate);
649 /* finish any pending sweep phase */
650 while (g->gcstate != GCSfinalize) {
651 lua_assert(g->gcstate == GCSsweepstring || g->gcstate == GCSsweep);
652 singlestep(L);
653 }
654 markroot(L);
655 while (g->gcstate != GCSpause) {
656 singlestep(L);
657 }
658 setthreshold(g);
659}
660
661
662void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v) {
663 global_State *g = G(L);
664 lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
665 lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause);
666 lua_assert(ttype(&o->gch) != LUA_TTABLE);
667 /* must keep invariant? */
668 if (g->gcstate == GCSpropagate)
669 reallymarkobject(g, v); /* restore invariant */
670 else /* don't mind */
671 makewhite(g, o); /* mark as white just to avoid other barriers */
672}
673
674
675void luaC_barrierback (lua_State *L, Table *t) {
676 global_State *g = G(L);
677 GCObject *o = obj2gco(t);
678 lua_assert(isblack(o) && !isdead(g, o));
679 lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause);
680 black2gray(o); /* make table gray (again) */
681 t->gclist = g->grayagain;
682 g->grayagain = o;
683}
684
685
686void luaC_link (lua_State *L, GCObject *o, lu_byte tt) {
687 global_State *g = G(L);
688 o->gch.next = g->rootgc;
689 g->rootgc = o;
690 o->gch.marked = luaC_white(g);
691 o->gch.tt = tt;
692}
693
694
695void luaC_linkupval (lua_State *L, UpVal *uv) {
696 global_State *g = G(L);
697 GCObject *o = obj2gco(uv);
698 o->gch.next = g->rootgc; /* link upvalue into `rootgc' list */
699 g->rootgc = o;
700 if (isgray(o)) {
701 if (g->gcstate == GCSpropagate) {
702 gray2black(o); /* closed upvalues need barrier */
703 luaC_barrier(L, uv, uv->v);
704 }
705 else { /* sweep phase: sweep it (turning it into white) */
706 makewhite(g, o);
707 lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause);
708 }
709 }
710}
711
diff --git a/apps/plugins/lua/lgc.h b/apps/plugins/lua/lgc.h
new file mode 100644
index 0000000000..5123ccb479
--- /dev/null
+++ b/apps/plugins/lua/lgc.h
@@ -0,0 +1,110 @@
1/*
2** $Id$
3** Garbage Collector
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lgc_h
8#define lgc_h
9
10
11#include "lobject.h"
12
13
14/*
15** Possible states of the Garbage Collector
16*/
17#define GCSpause 0
18#define GCSpropagate 1
19#define GCSsweepstring 2
20#define GCSsweep 3
21#define GCSfinalize 4
22
23
24/*
25** some userful bit tricks
26*/
27#define resetbits(x,m) ((x) &= cast(lu_byte, ~(m)))
28#define setbits(x,m) ((x) |= (m))
29#define testbits(x,m) ((x) & (m))
30#define bitmask(b) (1<<(b))
31#define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2))
32#define l_setbit(x,b) setbits(x, bitmask(b))
33#define resetbit(x,b) resetbits(x, bitmask(b))
34#define testbit(x,b) testbits(x, bitmask(b))
35#define set2bits(x,b1,b2) setbits(x, (bit2mask(b1, b2)))
36#define reset2bits(x,b1,b2) resetbits(x, (bit2mask(b1, b2)))
37#define test2bits(x,b1,b2) testbits(x, (bit2mask(b1, b2)))
38
39
40
41/*
42** Layout for bit use in `marked' field:
43** bit 0 - object is white (type 0)
44** bit 1 - object is white (type 1)
45** bit 2 - object is black
46** bit 3 - for userdata: has been finalized
47** bit 3 - for tables: has weak keys
48** bit 4 - for tables: has weak values
49** bit 5 - object is fixed (should not be collected)
50** bit 6 - object is "super" fixed (only the main thread)
51*/
52
53
54#define WHITE0BIT 0
55#define WHITE1BIT 1
56#define BLACKBIT 2
57#define FINALIZEDBIT 3
58#define KEYWEAKBIT 3
59#define VALUEWEAKBIT 4
60#define FIXEDBIT 5
61#define SFIXEDBIT 6
62#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT)
63
64
65#define iswhite(x) test2bits((x)->gch.marked, WHITE0BIT, WHITE1BIT)
66#define isblack(x) testbit((x)->gch.marked, BLACKBIT)
67#define isgray(x) (!isblack(x) && !iswhite(x))
68
69#define otherwhite(g) (g->currentwhite ^ WHITEBITS)
70#define isdead(g,v) ((v)->gch.marked & otherwhite(g) & WHITEBITS)
71
72#define changewhite(x) ((x)->gch.marked ^= WHITEBITS)
73#define gray2black(x) l_setbit((x)->gch.marked, BLACKBIT)
74
75#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
76
77#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS)
78
79
80#define luaC_checkGC(L) { \
81 condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1)); \
82 if (G(L)->totalbytes >= G(L)->GCthreshold) \
83 luaC_step(L); }
84
85
86#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \
87 luaC_barrierf(L,obj2gco(p),gcvalue(v)); }
88
89#define luaC_barriert(L,t,v) { if (valiswhite(v) && isblack(obj2gco(t))) \
90 luaC_barrierback(L,t); }
91
92#define luaC_objbarrier(L,p,o) \
93 { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \
94 luaC_barrierf(L,obj2gco(p),obj2gco(o)); }
95
96#define luaC_objbarriert(L,t,o) \
97 { if (iswhite(obj2gco(o)) && isblack(obj2gco(t))) luaC_barrierback(L,t); }
98
99LUAI_FUNC size_t luaC_separateudata (lua_State *L, int all);
100LUAI_FUNC void luaC_callGCTM (lua_State *L);
101LUAI_FUNC void luaC_freeall (lua_State *L);
102LUAI_FUNC void luaC_step (lua_State *L);
103LUAI_FUNC void luaC_fullgc (lua_State *L);
104LUAI_FUNC void luaC_link (lua_State *L, GCObject *o, lu_byte tt);
105LUAI_FUNC void luaC_linkupval (lua_State *L, UpVal *uv);
106LUAI_FUNC void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v);
107LUAI_FUNC void luaC_barrierback (lua_State *L, Table *t);
108
109
110#endif
diff --git a/apps/plugins/lua/llex.c b/apps/plugins/lua/llex.c
new file mode 100644
index 0000000000..3d0ca5b58e
--- /dev/null
+++ b/apps/plugins/lua/llex.c
@@ -0,0 +1,462 @@
1/*
2** $Id: llex.c,v 2.20.1.1 2007/12/27 13:02:25 roberto Exp $
3** Lexical Analyzer
4** See Copyright Notice in lua.h
5*/
6
7
8#include <ctype.h>
9/* #include <locale.h> */
10#include <string.h>
11
12#define llex_c
13#define LUA_CORE
14
15#include "lua.h"
16
17#include "ldo.h"
18#include "llex.h"
19#include "lobject.h"
20#include "lparser.h"
21#include "lstate.h"
22#include "lstring.h"
23#include "ltable.h"
24#include "lzio.h"
25
26
27
28#define next(ls) (ls->current = zgetc(ls->z))
29
30
31
32
33#define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r')
34
35
36/* ORDER RESERVED */
37const char *const luaX_tokens [] = {
38 "and", "break", "do", "else", "elseif",
39 "end", "false", "for", "function", "if",
40 "in", "local", "nil", "not", "or", "repeat",
41 "return", "then", "true", "until", "while",
42 "..", "...", "==", ">=", "<=", "~=",
43 "<number>", "<name>", "<string>", "<eof>",
44 NULL
45};
46
47
48#define save_and_next(ls) (save(ls, ls->current), next(ls))
49
50
51static void save (LexState *ls, int c) {
52 Mbuffer *b = ls->buff;
53 if (b->n + 1 > b->buffsize) {
54 size_t newsize;
55 if (b->buffsize >= MAX_SIZET/2)
56 luaX_lexerror(ls, "lexical element too long", 0);
57 newsize = b->buffsize * 2;
58 luaZ_resizebuffer(ls->L, b, newsize);
59 }
60 b->buffer[b->n++] = cast(char, c);
61}
62
63
64void luaX_init (lua_State *L) {
65 int i;
66 for (i=0; i<NUM_RESERVED; i++) {
67 TString *ts = luaS_new(L, luaX_tokens[i]);
68 luaS_fix(ts); /* reserved words are never collected */
69 lua_assert(strlen(luaX_tokens[i])+1 <= TOKEN_LEN);
70 ts->tsv.reserved = cast_byte(i+1); /* reserved word */
71 }
72}
73
74
75#define MAXSRC 80
76
77
78const char *luaX_token2str (LexState *ls, int token) {
79 if (token < FIRST_RESERVED) {
80 lua_assert(token == cast(unsigned char, token));
81 return (iscntrl(token)) ? luaO_pushfstring(ls->L, "char(%d)", token) :
82 luaO_pushfstring(ls->L, "%c", token);
83 }
84 else
85 return luaX_tokens[token-FIRST_RESERVED];
86}
87
88
89static const char *txtToken (LexState *ls, int token) {
90 switch (token) {
91 case TK_NAME:
92 case TK_STRING:
93 case TK_NUMBER:
94 save(ls, '\0');
95 return luaZ_buffer(ls->buff);
96 default:
97 return luaX_token2str(ls, token);
98 }
99}
100
101
102void luaX_lexerror (LexState *ls, const char *msg, int token) {
103 char buff[MAXSRC];
104 luaO_chunkid(buff, getstr(ls->source), MAXSRC);
105 rb->splashf(3*HZ, "%d %c 0x%X", ls->linenumber, ls->linenumber, ls->linenumber);
106 msg = luaO_pushfstring(ls->L, "%s:%d: %s", buff, ls->linenumber, msg);
107 if (token)
108 luaO_pushfstring(ls->L, "%s near " LUA_QS, msg, txtToken(ls, token));
109 luaD_throw(ls->L, LUA_ERRSYNTAX);
110}
111
112
113void luaX_syntaxerror (LexState *ls, const char *msg) {
114 luaX_lexerror(ls, msg, ls->t.token);
115}
116
117
118TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
119 lua_State *L = ls->L;
120 TString *ts = luaS_newlstr(L, str, l);
121 TValue *o = luaH_setstr(L, ls->fs->h, ts); /* entry for `str' */
122 if (ttisnil(o))
123 setbvalue(o, 1); /* make sure `str' will not be collected */
124 return ts;
125}
126
127
128static void inclinenumber (LexState *ls) {
129 int old = ls->current;
130 lua_assert(currIsNewline(ls));
131 next(ls); /* skip `\n' or `\r' */
132 if (currIsNewline(ls) && ls->current != old)
133 next(ls); /* skip `\n\r' or `\r\n' */
134 if (++ls->linenumber >= MAX_INT)
135 luaX_syntaxerror(ls, "chunk has too many lines");
136}
137
138
139void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source) {
140 ls->decpoint = '.';
141 ls->L = L;
142 ls->lookahead.token = TK_EOS; /* no look-ahead token */
143 ls->z = z;
144 ls->fs = NULL;
145 ls->linenumber = 1;
146 ls->lastline = 1;
147 ls->source = source;
148 luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */
149 next(ls); /* read first char */
150}
151
152
153
154/*
155** =======================================================
156** LEXICAL ANALYZER
157** =======================================================
158*/
159
160
161
162static int check_next (LexState *ls, const char *set) {
163 if (!strchr(set, ls->current))
164 return 0;
165 save_and_next(ls);
166 return 1;
167}
168
169
170static void buffreplace (LexState *ls, char from, char to) {
171 size_t n = luaZ_bufflen(ls->buff);
172 char *p = luaZ_buffer(ls->buff);
173 while (n--)
174 if (p[n] == from) p[n] = to;
175}
176
177
178static void trydecpoint (LexState *ls, SemInfo *seminfo) {
179 /* format error: try to update decimal point separator */
180 /* struct lconv *cv = localeconv(); */
181 char old = ls->decpoint;
182 ls->decpoint = '.'; /* (cv ? cv->decimal_point[0] : '.'); */
183 buffreplace(ls, old, ls->decpoint); /* try updated decimal separator */
184 if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) {
185 /* format error with correct decimal point: no more options */
186 buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */
187 luaX_lexerror(ls, "malformed number", TK_NUMBER);
188 }
189}
190
191
192/* LUA_NUMBER */
193static void read_numeral (LexState *ls, SemInfo *seminfo) {
194 lua_assert(isdigit(ls->current));
195 do {
196 save_and_next(ls);
197 } while (isdigit(ls->current) || ls->current == '.');
198 if (check_next(ls, "Ee")) /* `E'? */
199 check_next(ls, "+-"); /* optional exponent sign */
200 while (isalnum(ls->current) || ls->current == '_')
201 save_and_next(ls);
202 save(ls, '\0');
203 buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */
204 if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) /* format error? */
205 trydecpoint(ls, seminfo); /* try to update decimal point separator */
206}
207
208
209static int skip_sep (LexState *ls) {
210 int count = 0;
211 int s = ls->current;
212 lua_assert(s == '[' || s == ']');
213 save_and_next(ls);
214 while (ls->current == '=') {
215 save_and_next(ls);
216 count++;
217 }
218 return (ls->current == s) ? count : (-count) - 1;
219}
220
221
222static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) {
223 int cont = 0;
224 (void)(cont); /* avoid warnings when `cont' is not used */
225 save_and_next(ls); /* skip 2nd `[' */
226 if (currIsNewline(ls)) /* string starts with a newline? */
227 inclinenumber(ls); /* skip it */
228 for (;;) {
229 switch (ls->current) {
230 case EOZ:
231 luaX_lexerror(ls, (seminfo) ? "unfinished long string" :
232 "unfinished long comment", TK_EOS);
233 break; /* to avoid warnings */
234#if defined(LUA_COMPAT_LSTR)
235 case '[': {
236 if (skip_sep(ls) == sep) {
237 save_and_next(ls); /* skip 2nd `[' */
238 cont++;
239#if LUA_COMPAT_LSTR == 1
240 if (sep == 0)
241 luaX_lexerror(ls, "nesting of [[...]] is deprecated", '[');
242#endif
243 }
244 break;
245 }
246#endif
247 case ']': {
248 if (skip_sep(ls) == sep) {
249 save_and_next(ls); /* skip 2nd `]' */
250#if defined(LUA_COMPAT_LSTR) && LUA_COMPAT_LSTR == 2
251 cont--;
252 if (sep == 0 && cont >= 0) break;
253#endif
254 goto endloop;
255 }
256 break;
257 }
258 case '\n':
259 case '\r': {
260 save(ls, '\n');
261 inclinenumber(ls);
262 if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */
263 break;
264 }
265 default: {
266 if (seminfo) save_and_next(ls);
267 else next(ls);
268 }
269 }
270 } endloop:
271 if (seminfo)
272 seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep),
273 luaZ_bufflen(ls->buff) - 2*(2 + sep));
274}
275
276
277static void read_string (LexState *ls, int del, SemInfo *seminfo) {
278 save_and_next(ls);
279 while (ls->current != del) {
280 switch (ls->current) {
281 case EOZ:
282 luaX_lexerror(ls, "unfinished string", TK_EOS);
283 continue; /* to avoid warnings */
284 case '\n':
285 case '\r':
286 luaX_lexerror(ls, "unfinished string", TK_STRING);
287 continue; /* to avoid warnings */
288 case '\\': {
289 int c;
290 next(ls); /* do not save the `\' */
291 switch (ls->current) {
292 case 'a': c = '\a'; break;
293 case 'b': c = '\b'; break;
294 case 'f': c = '\f'; break;
295 case 'n': c = '\n'; break;
296 case 'r': c = '\r'; break;
297 case 't': c = '\t'; break;
298 case 'v': c = '\v'; break;
299 case '\n': /* go through */
300 case '\r': save(ls, '\n'); inclinenumber(ls); continue;
301 case EOZ: continue; /* will raise an error next loop */
302 default: {
303 if (!isdigit(ls->current))
304 save_and_next(ls); /* handles \\, \", \', and \? */
305 else { /* \xxx */
306 int i = 0;
307 c = 0;
308 do {
309 c = 10*c + (ls->current-'0');
310 next(ls);
311 } while (++i<3 && isdigit(ls->current));
312 if (c > UCHAR_MAX)
313 luaX_lexerror(ls, "escape sequence too large", TK_STRING);
314 save(ls, c);
315 }
316 continue;
317 }
318 }
319 save(ls, c);
320 next(ls);
321 continue;
322 }
323 default:
324 save_and_next(ls);
325 }
326 }
327 save_and_next(ls); /* skip delimiter */
328 seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1,
329 luaZ_bufflen(ls->buff) - 2);
330}
331
332
333static int llex (LexState *ls, SemInfo *seminfo) {
334 luaZ_resetbuffer(ls->buff);
335 for (;;) {
336 switch (ls->current) {
337 case '\n':
338 case '\r': {
339 inclinenumber(ls);
340 continue;
341 }
342 case '-': {
343 next(ls);
344 if (ls->current != '-') return '-';
345 /* else is a comment */
346 next(ls);
347 if (ls->current == '[') {
348 int sep = skip_sep(ls);
349 luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */
350 if (sep >= 0) {
351 read_long_string(ls, NULL, sep); /* long comment */
352 luaZ_resetbuffer(ls->buff);
353 continue;
354 }
355 }
356 /* else short comment */
357 while (!currIsNewline(ls) && ls->current != EOZ)
358 next(ls);
359 continue;
360 }
361 case '[': {
362 int sep = skip_sep(ls);
363 if (sep >= 0) {
364 read_long_string(ls, seminfo, sep);
365 return TK_STRING;
366 }
367 else if (sep == -1) return '[';
368 else luaX_lexerror(ls, "invalid long string delimiter", TK_STRING);
369 }
370 case '=': {
371 next(ls);
372 if (ls->current != '=') return '=';
373 else { next(ls); return TK_EQ; }
374 }
375 case '<': {
376 next(ls);
377 if (ls->current != '=') return '<';
378 else { next(ls); return TK_LE; }
379 }
380 case '>': {
381 next(ls);
382 if (ls->current != '=') return '>';
383 else { next(ls); return TK_GE; }
384 }
385 case '~': {
386 next(ls);
387 if (ls->current != '=') return '~';
388 else { next(ls); return TK_NE; }
389 }
390 case '"':
391 case '\'': {
392 read_string(ls, ls->current, seminfo);
393 return TK_STRING;
394 }
395 case '.': {
396 save_and_next(ls);
397 if (check_next(ls, ".")) {
398 if (check_next(ls, "."))
399 return TK_DOTS; /* ... */
400 else return TK_CONCAT; /* .. */
401 }
402 else if (!isdigit(ls->current)) return '.';
403 else {
404 read_numeral(ls, seminfo);
405 return TK_NUMBER;
406 }
407 }
408 case EOZ: {
409 return TK_EOS;
410 }
411 default: {
412 if (isspace(ls->current)) {
413 lua_assert(!currIsNewline(ls));
414 next(ls);
415 continue;
416 }
417 else if (isdigit(ls->current)) {
418 read_numeral(ls, seminfo);
419 return TK_NUMBER;
420 }
421 else if (isalpha(ls->current) || ls->current == '_') {
422 /* identifier or reserved word */
423 TString *ts;
424 do {
425 save_and_next(ls);
426 } while (isalnum(ls->current) || ls->current == '_');
427 ts = luaX_newstring(ls, luaZ_buffer(ls->buff),
428 luaZ_bufflen(ls->buff));
429 if (ts->tsv.reserved > 0) /* reserved word? */
430 return ts->tsv.reserved - 1 + FIRST_RESERVED;
431 else {
432 seminfo->ts = ts;
433 return TK_NAME;
434 }
435 }
436 else {
437 int c = ls->current;
438 next(ls);
439 return c; /* single-char tokens (+ - / ...) */
440 }
441 }
442 }
443 }
444}
445
446
447void luaX_next (LexState *ls) {
448 ls->lastline = ls->linenumber;
449 if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */
450 ls->t = ls->lookahead; /* use this one */
451 ls->lookahead.token = TK_EOS; /* and discharge it */
452 }
453 else
454 ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */
455}
456
457
458void luaX_lookahead (LexState *ls) {
459 lua_assert(ls->lookahead.token == TK_EOS);
460 ls->lookahead.token = llex(ls, &ls->lookahead.seminfo);
461}
462
diff --git a/apps/plugins/lua/llex.h b/apps/plugins/lua/llex.h
new file mode 100644
index 0000000000..fa8b7a2a28
--- /dev/null
+++ b/apps/plugins/lua/llex.h
@@ -0,0 +1,81 @@
1/*
2** $Id$
3** Lexical Analyzer
4** See Copyright Notice in lua.h
5*/
6
7#ifndef llex_h
8#define llex_h
9
10#include "lobject.h"
11#include "lzio.h"
12
13
14#define FIRST_RESERVED 257
15
16/* maximum length of a reserved word */
17#define TOKEN_LEN (sizeof("function")/sizeof(char))
18
19
20/*
21* WARNING: if you change the order of this enumeration,
22* grep "ORDER RESERVED"
23*/
24enum RESERVED {
25 /* terminal symbols denoted by reserved words */
26 TK_AND = FIRST_RESERVED, TK_BREAK,
27 TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION,
28 TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT,
29 TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,
30 /* other terminal symbols */
31 TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_NUMBER,
32 TK_NAME, TK_STRING, TK_EOS
33};
34
35/* number of reserved words */
36#define NUM_RESERVED (cast(int, TK_WHILE-FIRST_RESERVED+1))
37
38
39/* array with token `names' */
40LUAI_DATA const char *const luaX_tokens [];
41
42
43typedef union {
44 lua_Number r;
45 TString *ts;
46} SemInfo; /* semantics information */
47
48
49typedef struct Token {
50 int token;
51 SemInfo seminfo;
52} Token;
53
54
55typedef struct LexState {
56 int current; /* current character (charint) */
57 int linenumber; /* input line counter */
58 int lastline; /* line of last token `consumed' */
59 Token t; /* current token */
60 Token lookahead; /* look ahead token */
61 struct FuncState *fs; /* `FuncState' is private to the parser */
62 struct lua_State *L;
63 ZIO *z; /* input stream */
64 Mbuffer *buff; /* buffer for tokens */
65 TString *source; /* current source name */
66 char decpoint; /* locale decimal point */
67} LexState;
68
69
70LUAI_FUNC void luaX_init (lua_State *L);
71LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z,
72 TString *source);
73LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l);
74LUAI_FUNC void luaX_next (LexState *ls);
75LUAI_FUNC void luaX_lookahead (LexState *ls);
76LUAI_FUNC void luaX_lexerror (LexState *ls, const char *msg, int token);
77LUAI_FUNC void luaX_syntaxerror (LexState *ls, const char *s);
78LUAI_FUNC const char *luaX_token2str (LexState *ls, int token);
79
80
81#endif
diff --git a/apps/plugins/lua/llimits.h b/apps/plugins/lua/llimits.h
new file mode 100644
index 0000000000..a31ad160ad
--- /dev/null
+++ b/apps/plugins/lua/llimits.h
@@ -0,0 +1,128 @@
1/*
2** $Id$
3** Limits, basic types, and some other `installation-dependent' definitions
4** See Copyright Notice in lua.h
5*/
6
7#ifndef llimits_h
8#define llimits_h
9
10
11#include <limits.h>
12#include <stddef.h>
13
14
15#include "lua.h"
16
17
18typedef LUAI_UINT32 lu_int32;
19
20typedef LUAI_UMEM lu_mem;
21
22typedef LUAI_MEM l_mem;
23
24
25
26/* chars used as small naturals (so that `char' is reserved for characters) */
27typedef unsigned char lu_byte;
28
29
30#define MAX_SIZET ((size_t)(~(size_t)0)-2)
31
32#define MAX_LUMEM ((lu_mem)(~(lu_mem)0)-2)
33
34
35#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */
36
37/*
38** conversion of pointer to integer
39** this is for hashing only; there is no problem if the integer
40** cannot hold the whole pointer value
41*/
42#define IntPoint(p) ((unsigned int)(lu_mem)(p))
43
44
45
46/* type to ensure maximum alignment */
47typedef LUAI_USER_ALIGNMENT_T L_Umaxalign;
48
49
50/* result of a `usual argument conversion' over lua_Number */
51typedef LUAI_UACNUMBER l_uacNumber;
52
53
54/* internal assertions for in-house debugging */
55#ifdef lua_assert
56
57#define check_exp(c,e) (lua_assert(c), (e))
58#define api_check(l,e) lua_assert(e)
59
60#else
61
62#define lua_assert(c) ((void)0)
63#define check_exp(c,e) (e)
64#define api_check luai_apicheck
65
66#endif
67
68
69#ifndef UNUSED
70#define UNUSED(x) ((void)(x)) /* to avoid warnings */
71#endif
72
73
74#ifndef cast
75#define cast(t, exp) ((t)(exp))
76#endif
77
78#define cast_byte(i) cast(lu_byte, (i))
79#define cast_num(i) cast(lua_Number, (i))
80#define cast_int(i) cast(int, (i))
81
82
83
84/*
85** type for virtual-machine instructions
86** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h)
87*/
88typedef lu_int32 Instruction;
89
90
91
92/* maximum stack for a Lua function */
93#define MAXSTACK 250
94
95
96
97/* minimum size for the string table (must be power of 2) */
98#ifndef MINSTRTABSIZE
99#define MINSTRTABSIZE 32
100#endif
101
102
103/* minimum size for string buffer */
104#ifndef LUA_MINBUFFER
105#define LUA_MINBUFFER 32
106#endif
107
108
109#ifndef lua_lock
110#define lua_lock(L) ((void) 0)
111#define lua_unlock(L) ((void) 0)
112#endif
113
114#ifndef luai_threadyield
115#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);}
116#endif
117
118
119/*
120** macro to control inclusion of some hard tests on stack reallocation
121*/
122#ifndef HARDSTACKTESTS
123#define condhardstacktests(x) ((void)0)
124#else
125#define condhardstacktests(x) x
126#endif
127
128#endif
diff --git a/apps/plugins/lua/lmem.c b/apps/plugins/lua/lmem.c
new file mode 100644
index 0000000000..ae7d8c965f
--- /dev/null
+++ b/apps/plugins/lua/lmem.c
@@ -0,0 +1,86 @@
1/*
2** $Id: lmem.c,v 1.70.1.1 2007/12/27 13:02:25 roberto Exp $
3** Interface to Memory Manager
4** See Copyright Notice in lua.h
5*/
6
7
8#include <stddef.h>
9
10#define lmem_c
11#define LUA_CORE
12
13#include "lua.h"
14
15#include "ldebug.h"
16#include "ldo.h"
17#include "lmem.h"
18#include "lobject.h"
19#include "lstate.h"
20
21
22
23/*
24** About the realloc function:
25** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize);
26** (`osize' is the old size, `nsize' is the new size)
27**
28** Lua ensures that (ptr == NULL) iff (osize == 0).
29**
30** * frealloc(ud, NULL, 0, x) creates a new block of size `x'
31**
32** * frealloc(ud, p, x, 0) frees the block `p'
33** (in this specific case, frealloc must return NULL).
34** particularly, frealloc(ud, NULL, 0, 0) does nothing
35** (which is equivalent to free(NULL) in ANSI C)
36**
37** frealloc returns NULL if it cannot create or reallocate the area
38** (any reallocation to an equal or smaller size cannot fail!)
39*/
40
41
42
43#define MINSIZEARRAY 4
44
45
46void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems,
47 int limit, const char *errormsg) {
48 void *newblock;
49 int newsize;
50 if (*size >= limit/2) { /* cannot double it? */
51 if (*size >= limit) /* cannot grow even a little? */
52 luaG_runerror(L, errormsg);
53 newsize = limit; /* still have at least one free place */
54 }
55 else {
56 newsize = (*size)*2;
57 if (newsize < MINSIZEARRAY)
58 newsize = MINSIZEARRAY; /* minimum size */
59 }
60 newblock = luaM_reallocv(L, block, *size, newsize, size_elems);
61 *size = newsize; /* update only when everything else is OK */
62 return newblock;
63}
64
65
66void *luaM_toobig (lua_State *L) {
67 luaG_runerror(L, "memory allocation error: block too big");
68 return NULL; /* to avoid warnings */
69}
70
71
72
73/*
74** generic allocation routine.
75*/
76void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
77 global_State *g = G(L);
78 lua_assert((osize == 0) == (block == NULL));
79 block = (*g->frealloc)(g->ud, block, osize, nsize);
80 if (block == NULL && nsize > 0)
81 luaD_throw(L, LUA_ERRMEM);
82 lua_assert((nsize == 0) == (block == NULL));
83 g->totalbytes = (g->totalbytes - osize) + nsize;
84 return block;
85}
86
diff --git a/apps/plugins/lua/lmem.h b/apps/plugins/lua/lmem.h
new file mode 100644
index 0000000000..97a888c7f8
--- /dev/null
+++ b/apps/plugins/lua/lmem.h
@@ -0,0 +1,49 @@
1/*
2** $Id$
3** Interface to Memory Manager
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lmem_h
8#define lmem_h
9
10
11#include <stddef.h>
12
13#include "llimits.h"
14#include "lua.h"
15
16#define MEMERRMSG "not enough memory"
17
18
19#define luaM_reallocv(L,b,on,n,e) \
20 ((cast(size_t, (n)+1) <= MAX_SIZET/(e)) ? /* +1 to avoid warnings */ \
21 luaM_realloc_(L, (b), (on)*(e), (n)*(e)) : \
22 luaM_toobig(L))
23
24#define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0)
25#define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), 0)
26#define luaM_freearray(L, b, n, t) luaM_reallocv(L, (b), n, 0, sizeof(t))
27
28#define luaM_malloc(L,t) luaM_realloc_(L, NULL, 0, (t))
29#define luaM_new(L,t) cast(t *, luaM_malloc(L, sizeof(t)))
30#define luaM_newvector(L,n,t) \
31 cast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t)))
32
33#define luaM_growvector(L,v,nelems,size,t,limit,e) \
34 if ((nelems)+1 > (size)) \
35 ((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e)))
36
37#define luaM_reallocvector(L, v,oldn,n,t) \
38 ((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t))))
39
40
41LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize,
42 size_t size);
43LUAI_FUNC void *luaM_toobig (lua_State *L);
44LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int *size,
45 size_t size_elem, int limit,
46 const char *errormsg);
47
48#endif
49
diff --git a/apps/plugins/lua/lobject.c b/apps/plugins/lua/lobject.c
new file mode 100644
index 0000000000..62ad8e9359
--- /dev/null
+++ b/apps/plugins/lua/lobject.c
@@ -0,0 +1,214 @@
1/*
2** $Id: lobject.c,v 2.22.1.1 2007/12/27 13:02:25 roberto Exp $
3** Some generic functions over Lua objects
4** See Copyright Notice in lua.h
5*/
6
7#include <ctype.h>
8#include <stdarg.h>
9#include <stdio.h>
10#include <stdlib.h>
11#include <string.h>
12
13#define lobject_c
14#define LUA_CORE
15
16#include "lua.h"
17
18#include "ldo.h"
19#include "lmem.h"
20#include "lobject.h"
21#include "lstate.h"
22#include "lstring.h"
23#include "lvm.h"
24
25
26
27const TValue luaO_nilobject_ = {{NULL}, LUA_TNIL};
28
29
30/*
31** converts an integer to a "floating point byte", represented as
32** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if
33** eeeee != 0 and (xxx) otherwise.
34*/
35int luaO_int2fb (unsigned int x) {
36 int e = 0; /* expoent */
37 while (x >= 16) {
38 x = (x+1) >> 1;
39 e++;
40 }
41 if (x < 8) return x;
42 else return ((e+1) << 3) | (cast_int(x) - 8);
43}
44
45
46/* converts back */
47int luaO_fb2int (int x) {
48 int e = (x >> 3) & 31;
49 if (e == 0) return x;
50 else return ((x & 7)+8) << (e - 1);
51}
52
53
54int luaO_log2 (unsigned int x) {
55 static const lu_byte log_2[256] = {
56 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
57 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
58 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
59 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
60 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
61 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
62 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
63 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
64 };
65 int l = -1;
66 while (x >= 256) { l += 8; x >>= 8; }
67 return l + log_2[x];
68
69}
70
71
72int luaO_rawequalObj (const TValue *t1, const TValue *t2) {
73 if (ttype(t1) != ttype(t2)) return 0;
74 else switch (ttype(t1)) {
75 case LUA_TNIL:
76 return 1;
77 case LUA_TNUMBER:
78 return luai_numeq(nvalue(t1), nvalue(t2));
79 case LUA_TBOOLEAN:
80 return bvalue(t1) == bvalue(t2); /* boolean true must be 1 !! */
81 case LUA_TLIGHTUSERDATA:
82 return pvalue(t1) == pvalue(t2);
83 default:
84 lua_assert(iscollectable(t1));
85 return gcvalue(t1) == gcvalue(t2);
86 }
87}
88
89
90int luaO_str2d (const char *s, lua_Number *result) {
91 char *endptr;
92 *result = lua_str2number(s, &endptr);
93 if (endptr == s) return 0; /* conversion failed */
94 if (*endptr == 'x' || *endptr == 'X') /* maybe an hexadecimal constant? */
95 *result = cast_num(strtoul(s, &endptr, 16));
96 if (*endptr == '\0') return 1; /* most common case */
97 while (isspace(cast(unsigned char, *endptr))) endptr++;
98 if (*endptr != '\0') return 0; /* invalid trailing characters? */
99 return 1;
100}
101
102
103
104static void pushstr (lua_State *L, const char *str) {
105 setsvalue2s(L, L->top, luaS_new(L, str));
106 incr_top(L);
107}
108
109
110/* this function handles only `%d', `%c', %f, %p, and `%s' formats */
111const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
112 int n = 1;
113 pushstr(L, "");
114 for (;;) {
115 const char *e = strchr(fmt, '%');
116 if (e == NULL) break;
117 setsvalue2s(L, L->top, luaS_newlstr(L, fmt, e-fmt));
118 incr_top(L);
119 switch (*(e+1)) {
120 case 's': {
121 const char *s = va_arg(argp, char *);
122 if (s == NULL) s = "(null)";
123 pushstr(L, s);
124 break;
125 }
126 case 'c': {
127 char buff[2];
128 buff[0] = cast(char, va_arg(argp, int));
129 buff[1] = '\0';
130 pushstr(L, buff);
131 break;
132 }
133 case 'd': {
134 setnvalue(L->top, cast_num(va_arg(argp, int)));
135 incr_top(L);
136 break;
137 }
138 case 'f': {
139 setnvalue(L->top, cast_num(va_arg(argp, l_uacNumber)));
140 incr_top(L);
141 break;
142 }
143 case 'p': {
144 char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */
145 snprintf(buff, 4*sizeof(void *) + 8, "%p", va_arg(argp, void *));
146 pushstr(L, buff);
147 break;
148 }
149 case '%': {
150 pushstr(L, "%");
151 break;
152 }
153 default: {
154 char buff[3];
155 buff[0] = '%';
156 buff[1] = *(e+1);
157 buff[2] = '\0';
158 pushstr(L, buff);
159 break;
160 }
161 }
162 n += 2;
163 fmt = e+2;
164 }
165 pushstr(L, fmt);
166 luaV_concat(L, n+1, cast_int(L->top - L->base) - 1);
167 L->top -= n;
168 return svalue(L->top - 1);
169}
170
171
172const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
173 const char *msg;
174 va_list argp;
175 va_start(argp, fmt);
176 msg = luaO_pushvfstring(L, fmt, argp);
177 va_end(argp);
178 return msg;
179}
180
181
182void luaO_chunkid (char *out, const char *source, size_t bufflen) {
183 if (*source == '=') {
184 strncpy(out, source+1, bufflen); /* remove first char */
185 out[bufflen-1] = '\0'; /* ensures null termination */
186 }
187 else { /* out = "source", or "...source" */
188 if (*source == '@') {
189 size_t l;
190 source++; /* skip the `@' */
191 bufflen -= sizeof(" '...' ");
192 l = strlen(source);
193 strcpy(out, "");
194 if (l > bufflen) {
195 source += (l-bufflen); /* get last part of file name */
196 strcat(out, "...");
197 }
198 strcat(out, source);
199 }
200 else { /* out = [string "string"] */
201 size_t len = strcspn(source, "\n\r"); /* stop at first newline */
202 bufflen -= sizeof(" [string \"...\"] ");
203 if (len > bufflen) len = bufflen;
204 strcpy(out, "[string \"");
205 if (source[len] != '\0') { /* must truncate? */
206 strncat(out, source, len);
207 strcat(out, "...");
208 }
209 else
210 strcat(out, source);
211 strcat(out, "\"]");
212 }
213 }
214}
diff --git a/apps/plugins/lua/lobject.h b/apps/plugins/lua/lobject.h
new file mode 100644
index 0000000000..93288fe0fb
--- /dev/null
+++ b/apps/plugins/lua/lobject.h
@@ -0,0 +1,381 @@
1/*
2** $Id$
3** Type definitions for Lua objects
4** See Copyright Notice in lua.h
5*/
6
7
8#ifndef lobject_h
9#define lobject_h
10
11
12#include <stdarg.h>
13
14
15#include "llimits.h"
16#include "lua.h"
17
18
19/* tags for values visible from Lua */
20#define LAST_TAG LUA_TTHREAD
21
22#define NUM_TAGS (LAST_TAG+1)
23
24
25/*
26** Extra tags for non-values
27*/
28#define LUA_TPROTO (LAST_TAG+1)
29#define LUA_TUPVAL (LAST_TAG+2)
30#define LUA_TDEADKEY (LAST_TAG+3)
31
32
33/*
34** Union of all collectable objects
35*/
36typedef union GCObject GCObject;
37
38
39/*
40** Common Header for all collectable objects (in macro form, to be
41** included in other objects)
42*/
43#define CommonHeader GCObject *next; lu_byte tt; lu_byte marked
44
45
46/*
47** Common header in struct form
48*/
49typedef struct GCheader {
50 CommonHeader;
51} GCheader;
52
53
54
55
56/*
57** Union of all Lua values
58*/
59typedef union {
60 GCObject *gc;
61 void *p;
62 lua_Number n;
63 int b;
64} Value;
65
66
67/*
68** Tagged Values
69*/
70
71#define TValuefields Value value; int tt
72
73typedef struct lua_TValue {
74 TValuefields;
75} TValue;
76
77
78/* Macros to test type */
79#define ttisnil(o) (ttype(o) == LUA_TNIL)
80#define ttisnumber(o) (ttype(o) == LUA_TNUMBER)
81#define ttisstring(o) (ttype(o) == LUA_TSTRING)
82#define ttistable(o) (ttype(o) == LUA_TTABLE)
83#define ttisfunction(o) (ttype(o) == LUA_TFUNCTION)
84#define ttisboolean(o) (ttype(o) == LUA_TBOOLEAN)
85#define ttisuserdata(o) (ttype(o) == LUA_TUSERDATA)
86#define ttisthread(o) (ttype(o) == LUA_TTHREAD)
87#define ttislightuserdata(o) (ttype(o) == LUA_TLIGHTUSERDATA)
88
89/* Macros to access values */
90#define ttype(o) ((o)->tt)
91#define gcvalue(o) check_exp(iscollectable(o), (o)->value.gc)
92#define pvalue(o) check_exp(ttislightuserdata(o), (o)->value.p)
93#define nvalue(o) check_exp(ttisnumber(o), (o)->value.n)
94#define rawtsvalue(o) check_exp(ttisstring(o), &(o)->value.gc->ts)
95#define tsvalue(o) (&rawtsvalue(o)->tsv)
96#define rawuvalue(o) check_exp(ttisuserdata(o), &(o)->value.gc->u)
97#define uvalue(o) (&rawuvalue(o)->uv)
98#define clvalue(o) check_exp(ttisfunction(o), &(o)->value.gc->cl)
99#define hvalue(o) check_exp(ttistable(o), &(o)->value.gc->h)
100#define bvalue(o) check_exp(ttisboolean(o), (o)->value.b)
101#define thvalue(o) check_exp(ttisthread(o), &(o)->value.gc->th)
102
103#define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))
104
105/*
106** for internal debug only
107*/
108#define checkconsistency(obj) \
109 lua_assert(!iscollectable(obj) || (ttype(obj) == (obj)->value.gc->gch.tt))
110
111#define checkliveness(g,obj) \
112 lua_assert(!iscollectable(obj) || \
113 ((ttype(obj) == (obj)->value.gc->gch.tt) && !isdead(g, (obj)->value.gc)))
114
115
116/* Macros to set values */
117#define setnilvalue(obj) ((obj)->tt=LUA_TNIL)
118
119#define setnvalue(obj,x) \
120 { TValue *i_o=(obj); i_o->value.n=(x); i_o->tt=LUA_TNUMBER; }
121
122#define setpvalue(obj,x) \
123 { TValue *i_o=(obj); i_o->value.p=(x); i_o->tt=LUA_TLIGHTUSERDATA; }
124
125#define setbvalue(obj,x) \
126 { TValue *i_o=(obj); i_o->value.b=(x); i_o->tt=LUA_TBOOLEAN; }
127
128#define setsvalue(L,obj,x) \
129 { TValue *i_o=(obj); \
130 i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TSTRING; \
131 checkliveness(G(L),i_o); }
132
133#define setuvalue(L,obj,x) \
134 { TValue *i_o=(obj); \
135 i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TUSERDATA; \
136 checkliveness(G(L),i_o); }
137
138#define setthvalue(L,obj,x) \
139 { TValue *i_o=(obj); \
140 i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TTHREAD; \
141 checkliveness(G(L),i_o); }
142
143#define setclvalue(L,obj,x) \
144 { TValue *i_o=(obj); \
145 i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TFUNCTION; \
146 checkliveness(G(L),i_o); }
147
148#define sethvalue(L,obj,x) \
149 { TValue *i_o=(obj); \
150 i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TTABLE; \
151 checkliveness(G(L),i_o); }
152
153#define setptvalue(L,obj,x) \
154 { TValue *i_o=(obj); \
155 i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TPROTO; \
156 checkliveness(G(L),i_o); }
157
158
159
160
161#define setobj(L,obj1,obj2) \
162 { const TValue *o2=(obj2); TValue *o1=(obj1); \
163 o1->value = o2->value; o1->tt=o2->tt; \
164 checkliveness(G(L),o1); }
165
166
167/*
168** different types of sets, according to destination
169*/
170
171/* from stack to (same) stack */
172#define setobjs2s setobj
173/* to stack (not from same stack) */
174#define setobj2s setobj
175#define setsvalue2s setsvalue
176#define sethvalue2s sethvalue
177#define setptvalue2s setptvalue
178/* from table to same table */
179#define setobjt2t setobj
180/* to table */
181#define setobj2t setobj
182/* to new object */
183#define setobj2n setobj
184#define setsvalue2n setsvalue
185
186#define setttype(obj, tt) (ttype(obj) = (tt))
187
188
189#define iscollectable(o) (ttype(o) >= LUA_TSTRING)
190
191
192
193typedef TValue *StkId; /* index to stack elements */
194
195
196/*
197** String headers for string table
198*/
199typedef union TString {
200 L_Umaxalign dummy; /* ensures maximum alignment for strings */
201 struct {
202 CommonHeader;
203 lu_byte reserved;
204 unsigned int hash;
205 size_t len;
206 } tsv;
207} TString;
208
209
210#define getstr(ts) cast(const char *, (ts) + 1)
211#define svalue(o) getstr(rawtsvalue(o))
212
213
214
215typedef union Udata {
216 L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */
217 struct {
218 CommonHeader;
219 struct Table *metatable;
220 struct Table *env;
221 size_t len;
222 } uv;
223} Udata;
224
225
226
227
228/*
229** Function Prototypes
230*/
231typedef struct Proto {
232 CommonHeader;
233 TValue *k; /* constants used by the function */
234 Instruction *code;
235 struct Proto **p; /* functions defined inside the function */
236 int *lineinfo; /* map from opcodes to source lines */
237 struct LocVar *locvars; /* information about local variables */
238 TString **upvalues; /* upvalue names */
239 TString *source;
240 int sizeupvalues;
241 int sizek; /* size of `k' */
242 int sizecode;
243 int sizelineinfo;
244 int sizep; /* size of `p' */
245 int sizelocvars;
246 int linedefined;
247 int lastlinedefined;
248 GCObject *gclist;
249 lu_byte nups; /* number of upvalues */
250 lu_byte numparams;
251 lu_byte is_vararg;
252 lu_byte maxstacksize;
253} Proto;
254
255
256/* masks for new-style vararg */
257#define VARARG_HASARG 1
258#define VARARG_ISVARARG 2
259#define VARARG_NEEDSARG 4
260
261
262typedef struct LocVar {
263 TString *varname;
264 int startpc; /* first point where variable is active */
265 int endpc; /* first point where variable is dead */
266} LocVar;
267
268
269
270/*
271** Upvalues
272*/
273
274typedef struct UpVal {
275 CommonHeader;
276 TValue *v; /* points to stack or to its own value */
277 union {
278 TValue value; /* the value (when closed) */
279 struct { /* double linked list (when open) */
280 struct UpVal *prev;
281 struct UpVal *next;
282 } l;
283 } u;
284} UpVal;
285
286
287/*
288** Closures
289*/
290
291#define ClosureHeader \
292 CommonHeader; lu_byte isC; lu_byte nupvalues; GCObject *gclist; \
293 struct Table *env
294
295typedef struct CClosure {
296 ClosureHeader;
297 lua_CFunction f;
298 TValue upvalue[1];
299} CClosure;
300
301
302typedef struct LClosure {
303 ClosureHeader;
304 struct Proto *p;
305 UpVal *upvals[1];
306} LClosure;
307
308
309typedef union Closure {
310 CClosure c;
311 LClosure l;
312} Closure;
313
314
315#define iscfunction(o) (ttype(o) == LUA_TFUNCTION && clvalue(o)->c.isC)
316#define isLfunction(o) (ttype(o) == LUA_TFUNCTION && !clvalue(o)->c.isC)
317
318
319/*
320** Tables
321*/
322
323typedef union TKey {
324 struct {
325 TValuefields;
326 struct Node *next; /* for chaining */
327 } nk;
328 TValue tvk;
329} TKey;
330
331
332typedef struct Node {
333 TValue i_val;
334 TKey i_key;
335} Node;
336
337
338typedef struct Table {
339 CommonHeader;
340 lu_byte flags; /* 1<<p means tagmethod(p) is not present */
341 lu_byte lsizenode; /* log2 of size of `node' array */
342 struct Table *metatable;
343 TValue *array; /* array part */
344 Node *node;
345 Node *lastfree; /* any free position is before this position */
346 GCObject *gclist;
347 int sizearray; /* size of `array' array */
348} Table;
349
350
351
352/*
353** `module' operation for hashing (size is always a power of 2)
354*/
355#define lmod(s,size) \
356 (check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1)))))
357
358
359#define twoto(x) (1<<(x))
360#define sizenode(t) (twoto((t)->lsizenode))
361
362
363#define luaO_nilobject (&luaO_nilobject_)
364
365LUAI_DATA const TValue luaO_nilobject_;
366
367#define ceillog2(x) (luaO_log2((x)-1) + 1)
368
369LUAI_FUNC int luaO_log2 (unsigned int x);
370LUAI_FUNC int luaO_int2fb (unsigned int x);
371LUAI_FUNC int luaO_fb2int (int x);
372LUAI_FUNC int luaO_rawequalObj (const TValue *t1, const TValue *t2);
373LUAI_FUNC int luaO_str2d (const char *s, lua_Number *result);
374LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt,
375 va_list argp);
376LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...);
377LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t len);
378
379
380#endif
381
diff --git a/apps/plugins/lua/lopcodes.c b/apps/plugins/lua/lopcodes.c
new file mode 100644
index 0000000000..4cc745230b
--- /dev/null
+++ b/apps/plugins/lua/lopcodes.c
@@ -0,0 +1,102 @@
1/*
2** $Id: lopcodes.c,v 1.37.1.1 2007/12/27 13:02:25 roberto Exp $
3** See Copyright Notice in lua.h
4*/
5
6
7#define lopcodes_c
8#define LUA_CORE
9
10
11#include "lopcodes.h"
12
13
14/* ORDER OP */
15
16const char *const luaP_opnames[NUM_OPCODES+1] = {
17 "MOVE",
18 "LOADK",
19 "LOADBOOL",
20 "LOADNIL",
21 "GETUPVAL",
22 "GETGLOBAL",
23 "GETTABLE",
24 "SETGLOBAL",
25 "SETUPVAL",
26 "SETTABLE",
27 "NEWTABLE",
28 "SELF",
29 "ADD",
30 "SUB",
31 "MUL",
32 "DIV",
33 "MOD",
34 "POW",
35 "UNM",
36 "NOT",
37 "LEN",
38 "CONCAT",
39 "JMP",
40 "EQ",
41 "LT",
42 "LE",
43 "TEST",
44 "TESTSET",
45 "CALL",
46 "TAILCALL",
47 "RETURN",
48 "FORLOOP",
49 "FORPREP",
50 "TFORLOOP",
51 "SETLIST",
52 "CLOSE",
53 "CLOSURE",
54 "VARARG",
55 NULL
56};
57
58
59#define opmode(t,a,b,c,m) (((t)<<7) | ((a)<<6) | ((b)<<4) | ((c)<<2) | (m))
60
61const lu_byte luaP_opmodes[NUM_OPCODES] = {
62/* T A B C mode opcode */
63 opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_MOVE */
64 ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_LOADK */
65 ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_LOADBOOL */
66 ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LOADNIL */
67 ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_GETUPVAL */
68 ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_GETGLOBAL */
69 ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_GETTABLE */
70 ,opmode(0, 0, OpArgK, OpArgN, iABx) /* OP_SETGLOBAL */
71 ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_SETUPVAL */
72 ,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABLE */
73 ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_NEWTABLE */
74 ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_SELF */
75 ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_ADD */
76 ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SUB */
77 ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MUL */
78 ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_DIV */
79 ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MOD */
80 ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_POW */
81 ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_UNM */
82 ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_NOT */
83 ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LEN */
84 ,opmode(0, 1, OpArgR, OpArgR, iABC) /* OP_CONCAT */
85 ,opmode(0, 0, OpArgR, OpArgN, iAsBx) /* OP_JMP */
86 ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_EQ */
87 ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LT */
88 ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LE */
89 ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TEST */
90 ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TESTSET */
91 ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_CALL */
92 ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_TAILCALL */
93 ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_RETURN */
94 ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORLOOP */
95 ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORPREP */
96 ,opmode(1, 0, OpArgN, OpArgU, iABC) /* OP_TFORLOOP */
97 ,opmode(0, 0, OpArgU, OpArgU, iABC) /* OP_SETLIST */
98 ,opmode(0, 0, OpArgN, OpArgN, iABC) /* OP_CLOSE */
99 ,opmode(0, 1, OpArgU, OpArgN, iABx) /* OP_CLOSURE */
100 ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_VARARG */
101};
102
diff --git a/apps/plugins/lua/lopcodes.h b/apps/plugins/lua/lopcodes.h
new file mode 100644
index 0000000000..e1aed0f637
--- /dev/null
+++ b/apps/plugins/lua/lopcodes.h
@@ -0,0 +1,268 @@
1/*
2** $Id$
3** Opcodes for Lua virtual machine
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lopcodes_h
8#define lopcodes_h
9
10#include "llimits.h"
11
12
13/*===========================================================================
14 We assume that instructions are unsigned numbers.
15 All instructions have an opcode in the first 6 bits.
16 Instructions can have the following fields:
17 `A' : 8 bits
18 `B' : 9 bits
19 `C' : 9 bits
20 `Bx' : 18 bits (`B' and `C' together)
21 `sBx' : signed Bx
22
23 A signed argument is represented in excess K; that is, the number
24 value is the unsigned value minus K. K is exactly the maximum value
25 for that argument (so that -max is represented by 0, and +max is
26 represented by 2*max), which is half the maximum for the corresponding
27 unsigned argument.
28===========================================================================*/
29
30
31enum OpMode {iABC, iABx, iAsBx}; /* basic instruction format */
32
33
34/*
35** size and position of opcode arguments.
36*/
37#define SIZE_C 9
38#define SIZE_B 9
39#define SIZE_Bx (SIZE_C + SIZE_B)
40#define SIZE_A 8
41
42#define SIZE_OP 6
43
44#define POS_OP 0
45#define POS_A (POS_OP + SIZE_OP)
46#define POS_C (POS_A + SIZE_A)
47#define POS_B (POS_C + SIZE_C)
48#define POS_Bx POS_C
49
50
51/*
52** limits for opcode arguments.
53** we use (signed) int to manipulate most arguments,
54** so they must fit in LUAI_BITSINT-1 bits (-1 for sign)
55*/
56#if SIZE_Bx < LUAI_BITSINT-1
57#define MAXARG_Bx ((1<<SIZE_Bx)-1)
58#define MAXARG_sBx (MAXARG_Bx>>1) /* `sBx' is signed */
59#else
60#define MAXARG_Bx MAX_INT
61#define MAXARG_sBx MAX_INT
62#endif
63
64
65#define MAXARG_A ((1<<SIZE_A)-1)
66#define MAXARG_B ((1<<SIZE_B)-1)
67#define MAXARG_C ((1<<SIZE_C)-1)
68
69
70/* creates a mask with `n' 1 bits at position `p' */
71#define MASK1(n,p) ((~((~(Instruction)0)<<n))<<p)
72
73/* creates a mask with `n' 0 bits at position `p' */
74#define MASK0(n,p) (~MASK1(n,p))
75
76/*
77** the following macros help to manipulate instructions
78*/
79
80#define GET_OPCODE(i) (cast(OpCode, ((i)>>POS_OP) & MASK1(SIZE_OP,0)))
81#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \
82 ((cast(Instruction, o)<<POS_OP)&MASK1(SIZE_OP,POS_OP))))
83
84#define GETARG_A(i) (cast(int, ((i)>>POS_A) & MASK1(SIZE_A,0)))
85#define SETARG_A(i,u) ((i) = (((i)&MASK0(SIZE_A,POS_A)) | \
86 ((cast(Instruction, u)<<POS_A)&MASK1(SIZE_A,POS_A))))
87
88#define GETARG_B(i) (cast(int, ((i)>>POS_B) & MASK1(SIZE_B,0)))
89#define SETARG_B(i,b) ((i) = (((i)&MASK0(SIZE_B,POS_B)) | \
90 ((cast(Instruction, b)<<POS_B)&MASK1(SIZE_B,POS_B))))
91
92#define GETARG_C(i) (cast(int, ((i)>>POS_C) & MASK1(SIZE_C,0)))
93#define SETARG_C(i,b) ((i) = (((i)&MASK0(SIZE_C,POS_C)) | \
94 ((cast(Instruction, b)<<POS_C)&MASK1(SIZE_C,POS_C))))
95
96#define GETARG_Bx(i) (cast(int, ((i)>>POS_Bx) & MASK1(SIZE_Bx,0)))
97#define SETARG_Bx(i,b) ((i) = (((i)&MASK0(SIZE_Bx,POS_Bx)) | \
98 ((cast(Instruction, b)<<POS_Bx)&MASK1(SIZE_Bx,POS_Bx))))
99
100#define GETARG_sBx(i) (GETARG_Bx(i)-MAXARG_sBx)
101#define SETARG_sBx(i,b) SETARG_Bx((i),cast(unsigned int, (b)+MAXARG_sBx))
102
103
104#define CREATE_ABC(o,a,b,c) ((cast(Instruction, o)<<POS_OP) \
105 | (cast(Instruction, a)<<POS_A) \
106 | (cast(Instruction, b)<<POS_B) \
107 | (cast(Instruction, c)<<POS_C))
108
109#define CREATE_ABx(o,a,bc) ((cast(Instruction, o)<<POS_OP) \
110 | (cast(Instruction, a)<<POS_A) \
111 | (cast(Instruction, bc)<<POS_Bx))
112
113
114/*
115** Macros to operate RK indices
116*/
117
118/* this bit 1 means constant (0 means register) */
119#define BITRK (1 << (SIZE_B - 1))
120
121/* test whether value is a constant */
122#define ISK(x) ((x) & BITRK)
123
124/* gets the index of the constant */
125#define INDEXK(r) ((int)(r) & ~BITRK)
126
127#define MAXINDEXRK (BITRK - 1)
128
129/* code a constant index as a RK value */
130#define RKASK(x) ((x) | BITRK)
131
132
133/*
134** invalid register that fits in 8 bits
135*/
136#define NO_REG MAXARG_A
137
138
139/*
140** R(x) - register
141** Kst(x) - constant (in constant table)
142** RK(x) == if ISK(x) then Kst(INDEXK(x)) else R(x)
143*/
144
145
146/*
147** grep "ORDER OP" if you change these enums
148*/
149
150typedef enum {
151/*----------------------------------------------------------------------
152name args description
153------------------------------------------------------------------------*/
154OP_MOVE,/* A B R(A) := R(B) */
155OP_LOADK,/* A Bx R(A) := Kst(Bx) */
156OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) pc++ */
157OP_LOADNIL,/* A B R(A) := ... := R(B) := nil */
158OP_GETUPVAL,/* A B R(A) := UpValue[B] */
159
160OP_GETGLOBAL,/* A Bx R(A) := Gbl[Kst(Bx)] */
161OP_GETTABLE,/* A B C R(A) := R(B)[RK(C)] */
162
163OP_SETGLOBAL,/* A Bx Gbl[Kst(Bx)] := R(A) */
164OP_SETUPVAL,/* A B UpValue[B] := R(A) */
165OP_SETTABLE,/* A B C R(A)[RK(B)] := RK(C) */
166
167OP_NEWTABLE,/* A B C R(A) := {} (size = B,C) */
168
169OP_SELF,/* A B C R(A+1) := R(B); R(A) := R(B)[RK(C)] */
170
171OP_ADD,/* A B C R(A) := RK(B) + RK(C) */
172OP_SUB,/* A B C R(A) := RK(B) - RK(C) */
173OP_MUL,/* A B C R(A) := RK(B) * RK(C) */
174OP_DIV,/* A B C R(A) := RK(B) / RK(C) */
175OP_MOD,/* A B C R(A) := RK(B) % RK(C) */
176OP_POW,/* A B C R(A) := RK(B) ^ RK(C) */
177OP_UNM,/* A B R(A) := -R(B) */
178OP_NOT,/* A B R(A) := not R(B) */
179OP_LEN,/* A B R(A) := length of R(B) */
180
181OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */
182
183OP_JMP,/* sBx pc+=sBx */
184
185OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */
186OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */
187OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */
188
189OP_TEST,/* A C if not (R(A) <=> C) then pc++ */
190OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */
191
192OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */
193OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */
194OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */
195
196OP_FORLOOP,/* A sBx R(A)+=R(A+2);
197 if R(A) <?= R(A+1) then { pc+=sBx; R(A+3)=R(A) }*/
198OP_FORPREP,/* A sBx R(A)-=R(A+2); pc+=sBx */
199
200OP_TFORLOOP,/* A C R(A+3), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2));
201 if R(A+3) ~= nil then R(A+2)=R(A+3) else pc++ */
202OP_SETLIST,/* A B C R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B */
203
204OP_CLOSE,/* A close all variables in the stack up to (>=) R(A)*/
205OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx], R(A), ... ,R(A+n)) */
206
207OP_VARARG/* A B R(A), R(A+1), ..., R(A+B-1) = vararg */
208} OpCode;
209
210
211#define NUM_OPCODES (cast(int, OP_VARARG) + 1)
212
213
214
215/*===========================================================================
216 Notes:
217 (*) In OP_CALL, if (B == 0) then B = top. C is the number of returns - 1,
218 and can be 0: OP_CALL then sets `top' to last_result+1, so
219 next open instruction (OP_CALL, OP_RETURN, OP_SETLIST) may use `top'.
220
221 (*) In OP_VARARG, if (B == 0) then use actual number of varargs and
222 set top (like in OP_CALL with C == 0).
223
224 (*) In OP_RETURN, if (B == 0) then return up to `top'
225
226 (*) In OP_SETLIST, if (B == 0) then B = `top';
227 if (C == 0) then next `instruction' is real C
228
229 (*) For comparisons, A specifies what condition the test should accept
230 (true or false).
231
232 (*) All `skips' (pc++) assume that next instruction is a jump
233===========================================================================*/
234
235
236/*
237** masks for instruction properties. The format is:
238** bits 0-1: op mode
239** bits 2-3: C arg mode
240** bits 4-5: B arg mode
241** bit 6: instruction set register A
242** bit 7: operator is a test
243*/
244
245enum OpArgMask {
246 OpArgN, /* argument is not used */
247 OpArgU, /* argument is used */
248 OpArgR, /* argument is a register or a jump offset */
249 OpArgK /* argument is a constant or register/constant */
250};
251
252LUAI_DATA const lu_byte luaP_opmodes[NUM_OPCODES];
253
254#define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 3))
255#define getBMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 4) & 3))
256#define getCMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 2) & 3))
257#define testAMode(m) (luaP_opmodes[m] & (1 << 6))
258#define testTMode(m) (luaP_opmodes[m] & (1 << 7))
259
260
261LUAI_DATA const char *const luaP_opnames[NUM_OPCODES+1]; /* opcode names */
262
263
264/* number of list items to accumulate before a SETLIST instruction */
265#define LFIELDS_PER_FLUSH 50
266
267
268#endif
diff --git a/apps/plugins/lua/lparser.c b/apps/plugins/lua/lparser.c
new file mode 100644
index 0000000000..800cdb1a3b
--- /dev/null
+++ b/apps/plugins/lua/lparser.c
@@ -0,0 +1,1339 @@
1/*
2** $Id: lparser.c,v 2.42.1.3 2007/12/28 15:32:23 roberto Exp $
3** Lua Parser
4** See Copyright Notice in lua.h
5*/
6
7
8#include <string.h>
9
10#define lparser_c
11#define LUA_CORE
12
13#include "lua.h"
14
15#include "lcode.h"
16#include "ldebug.h"
17#include "ldo.h"
18#include "lfunc.h"
19#include "llex.h"
20#include "lmem.h"
21#include "lobject.h"
22#include "lopcodes.h"
23#include "lparser.h"
24#include "lstate.h"
25#include "lstring.h"
26#include "ltable.h"
27
28
29
30#define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
31
32#define getlocvar(fs, i) ((fs)->f->locvars[(fs)->actvar[i]])
33
34#define luaY_checklimit(fs,v,l,m) if ((v)>(l)) errorlimit(fs,l,m)
35
36
37/*
38** nodes for block list (list of active blocks)
39*/
40typedef struct BlockCnt {
41 struct BlockCnt *previous; /* chain */
42 int breaklist; /* list of jumps out of this loop */
43 lu_byte nactvar; /* # active locals outside the breakable structure */
44 lu_byte upval; /* true if some variable in the block is an upvalue */
45 lu_byte isbreakable; /* true if `block' is a loop */
46} BlockCnt;
47
48
49
50/*
51** prototypes for recursive non-terminal functions
52*/
53static void chunk (LexState *ls);
54static void expr (LexState *ls, expdesc *v);
55
56
57static void anchor_token (LexState *ls) {
58 if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
59 TString *ts = ls->t.seminfo.ts;
60 luaX_newstring(ls, getstr(ts), ts->tsv.len);
61 }
62}
63
64
65static void error_expected (LexState *ls, int token) {
66 luaX_syntaxerror(ls,
67 luaO_pushfstring(ls->L, LUA_QS " expected", luaX_token2str(ls, token)));
68}
69
70
71static void errorlimit (FuncState *fs, int limit, const char *what) {
72 const char *msg = (fs->f->linedefined == 0) ?
73 luaO_pushfstring(fs->L, "main function has more than %d %s", limit, what) :
74 luaO_pushfstring(fs->L, "function at line %d has more than %d %s",
75 fs->f->linedefined, limit, what);
76 luaX_lexerror(fs->ls, msg, 0);
77}
78
79
80static int testnext (LexState *ls, int c) {
81 if (ls->t.token == c) {
82 luaX_next(ls);
83 return 1;
84 }
85 else return 0;
86}
87
88
89static void check (LexState *ls, int c) {
90 if (ls->t.token != c)
91 error_expected(ls, c);
92}
93
94static void checknext (LexState *ls, int c) {
95 check(ls, c);
96 luaX_next(ls);
97}
98
99
100#define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
101
102
103
104static void check_match (LexState *ls, int what, int who, int where) {
105 if (!testnext(ls, what)) {
106 if (where == ls->linenumber)
107 error_expected(ls, what);
108 else {
109 luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
110 LUA_QS " expected (to close " LUA_QS " at line %d)",
111 luaX_token2str(ls, what), luaX_token2str(ls, who), where));
112 }
113 }
114}
115
116
117static TString *str_checkname (LexState *ls) {
118 TString *ts;
119 check(ls, TK_NAME);
120 ts = ls->t.seminfo.ts;
121 luaX_next(ls);
122 return ts;
123}
124
125
126static void init_exp (expdesc *e, expkind k, int i) {
127 e->f = e->t = NO_JUMP;
128 e->k = k;
129 e->u.s.info = i;
130}
131
132
133static void codestring (LexState *ls, expdesc *e, TString *s) {
134 init_exp(e, VK, luaK_stringK(ls->fs, s));
135}
136
137
138static void checkname(LexState *ls, expdesc *e) {
139 codestring(ls, e, str_checkname(ls));
140}
141
142
143static int registerlocalvar (LexState *ls, TString *varname) {
144 FuncState *fs = ls->fs;
145 Proto *f = fs->f;
146 int oldsize = f->sizelocvars;
147 luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
148 LocVar, SHRT_MAX, "too many local variables");
149 while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL;
150 f->locvars[fs->nlocvars].varname = varname;
151 luaC_objbarrier(ls->L, f, varname);
152 return fs->nlocvars++;
153}
154
155
156#define new_localvarliteral(ls,v,n) \
157 new_localvar(ls, luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char))-1), n)
158
159
160static void new_localvar (LexState *ls, TString *name, int n) {
161 FuncState *fs = ls->fs;
162 luaY_checklimit(fs, fs->nactvar+n+1, LUAI_MAXVARS, "local variables");
163 fs->actvar[fs->nactvar+n] = cast(unsigned short, registerlocalvar(ls, name));
164}
165
166
167static void adjustlocalvars (LexState *ls, int nvars) {
168 FuncState *fs = ls->fs;
169 fs->nactvar = cast_byte(fs->nactvar + nvars);
170 for (; nvars; nvars--) {
171 getlocvar(fs, fs->nactvar - nvars).startpc = fs->pc;
172 }
173}
174
175
176static void removevars (LexState *ls, int tolevel) {
177 FuncState *fs = ls->fs;
178 while (fs->nactvar > tolevel)
179 getlocvar(fs, --fs->nactvar).endpc = fs->pc;
180}
181
182
183static int indexupvalue (FuncState *fs, TString *name, expdesc *v) {
184 int i;
185 Proto *f = fs->f;
186 int oldsize = f->sizeupvalues;
187 for (i=0; i<f->nups; i++) {
188 if (fs->upvalues[i].k == v->k && fs->upvalues[i].info == v->u.s.info) {
189 lua_assert(f->upvalues[i] == name);
190 return i;
191 }
192 }
193 /* new one */
194 luaY_checklimit(fs, f->nups + 1, LUAI_MAXUPVALUES, "upvalues");
195 luaM_growvector(fs->L, f->upvalues, f->nups, f->sizeupvalues,
196 TString *, MAX_INT, "");
197 while (oldsize < f->sizeupvalues) f->upvalues[oldsize++] = NULL;
198 f->upvalues[f->nups] = name;
199 luaC_objbarrier(fs->L, f, name);
200 lua_assert(v->k == VLOCAL || v->k == VUPVAL);
201 fs->upvalues[f->nups].k = cast_byte(v->k);
202 fs->upvalues[f->nups].info = cast_byte(v->u.s.info);
203 return f->nups++;
204}
205
206
207static int searchvar (FuncState *fs, TString *n) {
208 int i;
209 for (i=fs->nactvar-1; i >= 0; i--) {
210 if (n == getlocvar(fs, i).varname)
211 return i;
212 }
213 return -1; /* not found */
214}
215
216
217static void markupval (FuncState *fs, int level) {
218 BlockCnt *bl = fs->bl;
219 while (bl && bl->nactvar > level) bl = bl->previous;
220 if (bl) bl->upval = 1;
221}
222
223
224static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
225 if (fs == NULL) { /* no more levels? */
226 init_exp(var, VGLOBAL, NO_REG); /* default is global variable */
227 return VGLOBAL;
228 }
229 else {
230 int v = searchvar(fs, n); /* look up at current level */
231 if (v >= 0) {
232 init_exp(var, VLOCAL, v);
233 if (!base)
234 markupval(fs, v); /* local will be used as an upval */
235 return VLOCAL;
236 }
237 else { /* not found at current level; try upper one */
238 if (singlevaraux(fs->prev, n, var, 0) == VGLOBAL)
239 return VGLOBAL;
240 var->u.s.info = indexupvalue(fs, n, var); /* else was LOCAL or UPVAL */
241 var->k = VUPVAL; /* upvalue in this level */
242 return VUPVAL;
243 }
244 }
245}
246
247
248static void singlevar (LexState *ls, expdesc *var) {
249 TString *varname = str_checkname(ls);
250 FuncState *fs = ls->fs;
251 if (singlevaraux(fs, varname, var, 1) == VGLOBAL)
252 var->u.s.info = luaK_stringK(fs, varname); /* info points to global name */
253}
254
255
256static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
257 FuncState *fs = ls->fs;
258 int extra = nvars - nexps;
259 if (hasmultret(e->k)) {
260 extra++; /* includes call itself */
261 if (extra < 0) extra = 0;
262 luaK_setreturns(fs, e, extra); /* last exp. provides the difference */
263 if (extra > 1) luaK_reserveregs(fs, extra-1);
264 }
265 else {
266 if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */
267 if (extra > 0) {
268 int reg = fs->freereg;
269 luaK_reserveregs(fs, extra);
270 luaK_nil(fs, reg, extra);
271 }
272 }
273}
274
275
276static void enterlevel (LexState *ls) {
277 if (++ls->L->nCcalls > LUAI_MAXCCALLS)
278 luaX_lexerror(ls, "chunk has too many syntax levels", 0);
279}
280
281
282#define leavelevel(ls) ((ls)->L->nCcalls--)
283
284
285static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isbreakable) {
286 bl->breaklist = NO_JUMP;
287 bl->isbreakable = isbreakable;
288 bl->nactvar = fs->nactvar;
289 bl->upval = 0;
290 bl->previous = fs->bl;
291 fs->bl = bl;
292 lua_assert(fs->freereg == fs->nactvar);
293}
294
295
296static void leaveblock (FuncState *fs) {
297 BlockCnt *bl = fs->bl;
298 fs->bl = bl->previous;
299 removevars(fs->ls, bl->nactvar);
300 if (bl->upval)
301 luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
302 /* a block either controls scope or breaks (never both) */
303 lua_assert(!bl->isbreakable || !bl->upval);
304 lua_assert(bl->nactvar == fs->nactvar);
305 fs->freereg = fs->nactvar; /* free registers */
306 luaK_patchtohere(fs, bl->breaklist);
307}
308
309
310static void pushclosure (LexState *ls, FuncState *func, expdesc *v) {
311 FuncState *fs = ls->fs;
312 Proto *f = fs->f;
313 int oldsize = f->sizep;
314 int i;
315 luaM_growvector(ls->L, f->p, fs->np, f->sizep, Proto *,
316 MAXARG_Bx, "constant table overflow");
317 while (oldsize < f->sizep) f->p[oldsize++] = NULL;
318 f->p[fs->np++] = func->f;
319 luaC_objbarrier(ls->L, f, func->f);
320 init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));
321 for (i=0; i<func->f->nups; i++) {
322 OpCode o = (func->upvalues[i].k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
323 luaK_codeABC(fs, o, 0, func->upvalues[i].info, 0);
324 }
325}
326
327
328static void lparser_open_func (LexState *ls, FuncState *fs) {
329 lua_State *L = ls->L;
330 Proto *f = luaF_newproto(L);
331 fs->f = f;
332 fs->prev = ls->fs; /* linked list of funcstates */
333 fs->ls = ls;
334 fs->L = L;
335 ls->fs = fs;
336 fs->pc = 0;
337 fs->lasttarget = -1;
338 fs->jpc = NO_JUMP;
339 fs->freereg = 0;
340 fs->nk = 0;
341 fs->np = 0;
342 fs->nlocvars = 0;
343 fs->nactvar = 0;
344 fs->bl = NULL;
345 f->source = ls->source;
346 f->maxstacksize = 2; /* registers 0/1 are always valid */
347 fs->h = luaH_new(L, 0, 0);
348 /* anchor table of constants and prototype (to avoid being collected) */
349 sethvalue2s(L, L->top, fs->h);
350 incr_top(L);
351 setptvalue2s(L, L->top, f);
352 incr_top(L);
353}
354
355
356static void close_func (LexState *ls) {
357 lua_State *L = ls->L;
358 FuncState *fs = ls->fs;
359 Proto *f = fs->f;
360 removevars(ls, 0);
361 luaK_ret(fs, 0, 0); /* final return */
362 luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
363 f->sizecode = fs->pc;
364 luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
365 f->sizelineinfo = fs->pc;
366 luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
367 f->sizek = fs->nk;
368 luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
369 f->sizep = fs->np;
370 luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
371 f->sizelocvars = fs->nlocvars;
372 luaM_reallocvector(L, f->upvalues, f->sizeupvalues, f->nups, TString *);
373 f->sizeupvalues = f->nups;
374 lua_assert(luaG_checkcode(f));
375 lua_assert(fs->bl == NULL);
376 ls->fs = fs->prev;
377 L->top -= 2; /* remove table and prototype from the stack */
378 /* last token read was anchored in defunct function; must reanchor it */
379 if (fs) anchor_token(ls);
380}
381
382
383Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) {
384 struct LexState lexstate;
385 struct FuncState funcstate;
386 lexstate.buff = buff;
387 luaX_setinput(L, &lexstate, z, luaS_new(L, name));
388 lparser_open_func(&lexstate, &funcstate);
389 funcstate.f->is_vararg = VARARG_ISVARARG; /* main func. is always vararg */
390 luaX_next(&lexstate); /* read first token */
391 chunk(&lexstate);
392 check(&lexstate, TK_EOS);
393 close_func(&lexstate);
394 lua_assert(funcstate.prev == NULL);
395 lua_assert(funcstate.f->nups == 0);
396 lua_assert(lexstate.fs == NULL);
397 return funcstate.f;
398}
399
400
401
402/*============================================================*/
403/* GRAMMAR RULES */
404/*============================================================*/
405
406
407static void field (LexState *ls, expdesc *v) {
408 /* field -> ['.' | ':'] NAME */
409 FuncState *fs = ls->fs;
410 expdesc key;
411 luaK_exp2anyreg(fs, v);
412 luaX_next(ls); /* skip the dot or colon */
413 checkname(ls, &key);
414 luaK_indexed(fs, v, &key);
415}
416
417
418static void yindex (LexState *ls, expdesc *v) {
419 /* index -> '[' expr ']' */
420 luaX_next(ls); /* skip the '[' */
421 expr(ls, v);
422 luaK_exp2val(ls->fs, v);
423 checknext(ls, ']');
424}
425
426
427/*
428** {======================================================================
429** Rules for Constructors
430** =======================================================================
431*/
432
433
434struct ConsControl {
435 expdesc v; /* last list item read */
436 expdesc *t; /* table descriptor */
437 int nh; /* total number of `record' elements */
438 int na; /* total number of array elements */
439 int tostore; /* number of array elements pending to be stored */
440};
441
442
443static void recfield (LexState *ls, struct ConsControl *cc) {
444 /* recfield -> (NAME | `['exp1`]') = exp1 */
445 FuncState *fs = ls->fs;
446 int reg = ls->fs->freereg;
447 expdesc key, val;
448 int rkkey;
449 if (ls->t.token == TK_NAME) {
450 luaY_checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
451 checkname(ls, &key);
452 }
453 else /* ls->t.token == '[' */
454 yindex(ls, &key);
455 cc->nh++;
456 checknext(ls, '=');
457 rkkey = luaK_exp2RK(fs, &key);
458 expr(ls, &val);
459 luaK_codeABC(fs, OP_SETTABLE, cc->t->u.s.info, rkkey, luaK_exp2RK(fs, &val));
460 fs->freereg = reg; /* free registers */
461}
462
463
464static void closelistfield (FuncState *fs, struct ConsControl *cc) {
465 if (cc->v.k == VVOID) return; /* there is no list item */
466 luaK_exp2nextreg(fs, &cc->v);
467 cc->v.k = VVOID;
468 if (cc->tostore == LFIELDS_PER_FLUSH) {
469 luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore); /* flush */
470 cc->tostore = 0; /* no more items pending */
471 }
472}
473
474
475static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
476 if (cc->tostore == 0) return;
477 if (hasmultret(cc->v.k)) {
478 luaK_setmultret(fs, &cc->v);
479 luaK_setlist(fs, cc->t->u.s.info, cc->na, LUA_MULTRET);
480 cc->na--; /* do not count last expression (unknown number of elements) */
481 }
482 else {
483 if (cc->v.k != VVOID)
484 luaK_exp2nextreg(fs, &cc->v);
485 luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore);
486 }
487}
488
489
490static void listfield (LexState *ls, struct ConsControl *cc) {
491 expr(ls, &cc->v);
492 luaY_checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
493 cc->na++;
494 cc->tostore++;
495}
496
497
498static void constructor (LexState *ls, expdesc *t) {
499 /* constructor -> ?? */
500 FuncState *fs = ls->fs;
501 int line = ls->linenumber;
502 int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
503 struct ConsControl cc;
504 cc.na = cc.nh = cc.tostore = 0;
505 cc.t = t;
506 init_exp(t, VRELOCABLE, pc);
507 init_exp(&cc.v, VVOID, 0); /* no value (yet) */
508 luaK_exp2nextreg(ls->fs, t); /* fix it at stack top (for gc) */
509 checknext(ls, '{');
510 do {
511 lua_assert(cc.v.k == VVOID || cc.tostore > 0);
512 if (ls->t.token == '}') break;
513 closelistfield(fs, &cc);
514 switch(ls->t.token) {
515 case TK_NAME: { /* may be listfields or recfields */
516 luaX_lookahead(ls);
517 if (ls->lookahead.token != '=') /* expression? */
518 listfield(ls, &cc);
519 else
520 recfield(ls, &cc);
521 break;
522 }
523 case '[': { /* constructor_item -> recfield */
524 recfield(ls, &cc);
525 break;
526 }
527 default: { /* constructor_part -> listfield */
528 listfield(ls, &cc);
529 break;
530 }
531 }
532 } while (testnext(ls, ',') || testnext(ls, ';'));
533 check_match(ls, '}', '{', line);
534 lastlistfield(fs, &cc);
535 SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
536 SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */
537}
538
539/* }====================================================================== */
540
541
542
543static void parlist (LexState *ls) {
544 /* parlist -> [ param { `,' param } ] */
545 FuncState *fs = ls->fs;
546 Proto *f = fs->f;
547 int nparams = 0;
548 f->is_vararg = 0;
549 if (ls->t.token != ')') { /* is `parlist' not empty? */
550 do {
551 switch (ls->t.token) {
552 case TK_NAME: { /* param -> NAME */
553 new_localvar(ls, str_checkname(ls), nparams++);
554 break;
555 }
556 case TK_DOTS: { /* param -> `...' */
557 luaX_next(ls);
558#if defined(LUA_COMPAT_VARARG)
559 /* use `arg' as default name */
560 new_localvarliteral(ls, "arg", nparams++);
561 f->is_vararg = VARARG_HASARG | VARARG_NEEDSARG;
562#endif
563 f->is_vararg |= VARARG_ISVARARG;
564 break;
565 }
566 default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
567 }
568 } while (!f->is_vararg && testnext(ls, ','));
569 }
570 adjustlocalvars(ls, nparams);
571 f->numparams = cast_byte(fs->nactvar - (f->is_vararg & VARARG_HASARG));
572 luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */
573}
574
575
576static void body (LexState *ls, expdesc *e, int needself, int line) {
577 /* body -> `(' parlist `)' chunk END */
578 FuncState new_fs;
579 lparser_open_func(ls, &new_fs);
580 new_fs.f->linedefined = line;
581 checknext(ls, '(');
582 if (needself) {
583 new_localvarliteral(ls, "self", 0);
584 adjustlocalvars(ls, 1);
585 }
586 parlist(ls);
587 checknext(ls, ')');
588 chunk(ls);
589 new_fs.f->lastlinedefined = ls->linenumber;
590 check_match(ls, TK_END, TK_FUNCTION, line);
591 close_func(ls);
592 pushclosure(ls, &new_fs, e);
593}
594
595
596static int explist1 (LexState *ls, expdesc *v) {
597 /* explist1 -> expr { `,' expr } */
598 int n = 1; /* at least one expression */
599 expr(ls, v);
600 while (testnext(ls, ',')) {
601 luaK_exp2nextreg(ls->fs, v);
602 expr(ls, v);
603 n++;
604 }
605 return n;
606}
607
608
609static void funcargs (LexState *ls, expdesc *f) {
610 FuncState *fs = ls->fs;
611 expdesc args;
612 int base, nparams;
613 int line = ls->linenumber;
614 switch (ls->t.token) {
615 case '(': { /* funcargs -> `(' [ explist1 ] `)' */
616 if (line != ls->lastline)
617 luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)");
618 luaX_next(ls);
619 if (ls->t.token == ')') /* arg list is empty? */
620 args.k = VVOID;
621 else {
622 explist1(ls, &args);
623 luaK_setmultret(fs, &args);
624 }
625 check_match(ls, ')', '(', line);
626 break;
627 }
628 case '{': { /* funcargs -> constructor */
629 constructor(ls, &args);
630 break;
631 }
632 case TK_STRING: { /* funcargs -> STRING */
633 codestring(ls, &args, ls->t.seminfo.ts);
634 luaX_next(ls); /* must use `seminfo' before `next' */
635 break;
636 }
637 default: {
638 luaX_syntaxerror(ls, "function arguments expected");
639 return;
640 }
641 }
642 lua_assert(f->k == VNONRELOC);
643 base = f->u.s.info; /* base register for call */
644 if (hasmultret(args.k))
645 nparams = LUA_MULTRET; /* open call */
646 else {
647 if (args.k != VVOID)
648 luaK_exp2nextreg(fs, &args); /* close last argument */
649 nparams = fs->freereg - (base+1);
650 }
651 init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
652 luaK_fixline(fs, line);
653 fs->freereg = base+1; /* call remove function and arguments and leaves
654 (unless changed) one result */
655}
656
657
658
659
660/*
661** {======================================================================
662** Expression parsing
663** =======================================================================
664*/
665
666
667static void prefixexp (LexState *ls, expdesc *v) {
668 /* prefixexp -> NAME | '(' expr ')' */
669 switch (ls->t.token) {
670 case '(': {
671 int line = ls->linenumber;
672 luaX_next(ls);
673 expr(ls, v);
674 check_match(ls, ')', '(', line);
675 luaK_dischargevars(ls->fs, v);
676 return;
677 }
678 case TK_NAME: {
679 singlevar(ls, v);
680 return;
681 }
682 default: {
683 luaX_syntaxerror(ls, "unexpected symbol");
684 return;
685 }
686 }
687}
688
689
690static void primaryexp (LexState *ls, expdesc *v) {
691 /* primaryexp ->
692 prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
693 FuncState *fs = ls->fs;
694 prefixexp(ls, v);
695 for (;;) {
696 switch (ls->t.token) {
697 case '.': { /* field */
698 field(ls, v);
699 break;
700 }
701 case '[': { /* `[' exp1 `]' */
702 expdesc key;
703 luaK_exp2anyreg(fs, v);
704 yindex(ls, &key);
705 luaK_indexed(fs, v, &key);
706 break;
707 }
708 case ':': { /* `:' NAME funcargs */
709 expdesc key;
710 luaX_next(ls);
711 checkname(ls, &key);
712 luaK_self(fs, v, &key);
713 funcargs(ls, v);
714 break;
715 }
716 case '(': case TK_STRING: case '{': { /* funcargs */
717 luaK_exp2nextreg(fs, v);
718 funcargs(ls, v);
719 break;
720 }
721 default: return;
722 }
723 }
724}
725
726
727static void simpleexp (LexState *ls, expdesc *v) {
728 /* simpleexp -> NUMBER | STRING | NIL | true | false | ... |
729 constructor | FUNCTION body | primaryexp */
730 switch (ls->t.token) {
731 case TK_NUMBER: {
732 init_exp(v, VKNUM, 0);
733 v->u.nval = ls->t.seminfo.r;
734 break;
735 }
736 case TK_STRING: {
737 codestring(ls, v, ls->t.seminfo.ts);
738 break;
739 }
740 case TK_NIL: {
741 init_exp(v, VNIL, 0);
742 break;
743 }
744 case TK_TRUE: {
745 init_exp(v, VTRUE, 0);
746 break;
747 }
748 case TK_FALSE: {
749 init_exp(v, VFALSE, 0);
750 break;
751 }
752 case TK_DOTS: { /* vararg */
753 FuncState *fs = ls->fs;
754 check_condition(ls, fs->f->is_vararg,
755 "cannot use " LUA_QL("...") " outside a vararg function");
756 fs->f->is_vararg &= ~VARARG_NEEDSARG; /* don't need 'arg' */
757 init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
758 break;
759 }
760 case '{': { /* constructor */
761 constructor(ls, v);
762 return;
763 }
764 case TK_FUNCTION: {
765 luaX_next(ls);
766 body(ls, v, 0, ls->linenumber);
767 return;
768 }
769 default: {
770 primaryexp(ls, v);
771 return;
772 }
773 }
774 luaX_next(ls);
775}
776
777
778static UnOpr getunopr (int op) {
779 switch (op) {
780 case TK_NOT: return OPR_NOT;
781 case '-': return OPR_MINUS;
782 case '#': return OPR_LEN;
783 default: return OPR_NOUNOPR;
784 }
785}
786
787
788static BinOpr getbinopr (int op) {
789 switch (op) {
790 case '+': return OPR_ADD;
791 case '-': return OPR_SUB;
792 case '*': return OPR_MUL;
793 case '/': return OPR_DIV;
794 case '%': return OPR_MOD;
795 case '^': return OPR_POW;
796 case TK_CONCAT: return OPR_CONCAT;
797 case TK_NE: return OPR_NE;
798 case TK_EQ: return OPR_EQ;
799 case '<': return OPR_LT;
800 case TK_LE: return OPR_LE;
801 case '>': return OPR_GT;
802 case TK_GE: return OPR_GE;
803 case TK_AND: return OPR_AND;
804 case TK_OR: return OPR_OR;
805 default: return OPR_NOBINOPR;
806 }
807}
808
809
810static const struct {
811 lu_byte left; /* left priority for each binary operator */
812 lu_byte right; /* right priority */
813} priority[] = { /* ORDER OPR */
814 {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `/' `%' */
815 {10, 9}, {5, 4}, /* power and concat (right associative) */
816 {3, 3}, {3, 3}, /* equality and inequality */
817 {3, 3}, {3, 3}, {3, 3}, {3, 3}, /* order */
818 {2, 2}, {1, 1} /* logical (and/or) */
819};
820
821#define UNARY_PRIORITY 8 /* priority for unary operators */
822
823
824/*
825** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
826** where `binop' is any binary operator with a priority higher than `limit'
827*/
828static BinOpr subexpr (LexState *ls, expdesc *v, unsigned int limit) {
829 BinOpr op;
830 UnOpr uop;
831 enterlevel(ls);
832 uop = getunopr(ls->t.token);
833 if (uop != OPR_NOUNOPR) {
834 luaX_next(ls);
835 subexpr(ls, v, UNARY_PRIORITY);
836 luaK_prefix(ls->fs, uop, v);
837 }
838 else simpleexp(ls, v);
839 /* expand while operators have priorities higher than `limit' */
840 op = getbinopr(ls->t.token);
841 while (op != OPR_NOBINOPR && priority[op].left > limit) {
842 expdesc v2;
843 BinOpr nextop;
844 luaX_next(ls);
845 luaK_infix(ls->fs, op, v);
846 /* read sub-expression with higher priority */
847 nextop = subexpr(ls, &v2, priority[op].right);
848 luaK_posfix(ls->fs, op, v, &v2);
849 op = nextop;
850 }
851 leavelevel(ls);
852 return op; /* return first untreated operator */
853}
854
855
856static void expr (LexState *ls, expdesc *v) {
857 subexpr(ls, v, 0);
858}
859
860/* }==================================================================== */
861
862
863
864/*
865** {======================================================================
866** Rules for Statements
867** =======================================================================
868*/
869
870
871static int block_follow (int token) {
872 switch (token) {
873 case TK_ELSE: case TK_ELSEIF: case TK_END:
874 case TK_UNTIL: case TK_EOS:
875 return 1;
876 default: return 0;
877 }
878}
879
880
881static void block (LexState *ls) {
882 /* block -> chunk */
883 FuncState *fs = ls->fs;
884 BlockCnt bl;
885 enterblock(fs, &bl, 0);
886 chunk(ls);
887 lua_assert(bl.breaklist == NO_JUMP);
888 leaveblock(fs);
889}
890
891
892/*
893** structure to chain all variables in the left-hand side of an
894** assignment
895*/
896struct LHS_assign {
897 struct LHS_assign *prev;
898 expdesc v; /* variable (global, local, upvalue, or indexed) */
899};
900
901
902/*
903** check whether, in an assignment to a local variable, the local variable
904** is needed in a previous assignment (to a table). If so, save original
905** local value in a safe place and use this safe copy in the previous
906** assignment.
907*/
908static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
909 FuncState *fs = ls->fs;
910 int extra = fs->freereg; /* eventual position to save local variable */
911 int conflict = 0;
912 for (; lh; lh = lh->prev) {
913 if (lh->v.k == VINDEXED) {
914 if (lh->v.u.s.info == v->u.s.info) { /* conflict? */
915 conflict = 1;
916 lh->v.u.s.info = extra; /* previous assignment will use safe copy */
917 }
918 if (lh->v.u.s.aux == v->u.s.info) { /* conflict? */
919 conflict = 1;
920 lh->v.u.s.aux = extra; /* previous assignment will use safe copy */
921 }
922 }
923 }
924 if (conflict) {
925 luaK_codeABC(fs, OP_MOVE, fs->freereg, v->u.s.info, 0); /* make copy */
926 luaK_reserveregs(fs, 1);
927 }
928}
929
930
931static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
932 expdesc e;
933 check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED,
934 "syntax error");
935 if (testnext(ls, ',')) { /* assignment -> `,' primaryexp assignment */
936 struct LHS_assign nv;
937 nv.prev = lh;
938 primaryexp(ls, &nv.v);
939 if (nv.v.k == VLOCAL)
940 check_conflict(ls, lh, &nv.v);
941 luaY_checklimit(ls->fs, nvars, LUAI_MAXCCALLS - ls->L->nCcalls,
942 "variables in assignment");
943 assignment(ls, &nv, nvars+1);
944 }
945 else { /* assignment -> `=' explist1 */
946 int nexps;
947 checknext(ls, '=');
948 nexps = explist1(ls, &e);
949 if (nexps != nvars) {
950 adjust_assign(ls, nvars, nexps, &e);
951 if (nexps > nvars)
952 ls->fs->freereg -= nexps - nvars; /* remove extra values */
953 }
954 else {
955 luaK_setoneret(ls->fs, &e); /* close last expression */
956 luaK_storevar(ls->fs, &lh->v, &e);
957 return; /* avoid default */
958 }
959 }
960 init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
961 luaK_storevar(ls->fs, &lh->v, &e);
962}
963
964
965static int cond (LexState *ls) {
966 /* cond -> exp */
967 expdesc v;
968 expr(ls, &v); /* read condition */
969 if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */
970 luaK_goiftrue(ls->fs, &v);
971 return v.f;
972}
973
974
975static void breakstat (LexState *ls) {
976 FuncState *fs = ls->fs;
977 BlockCnt *bl = fs->bl;
978 int upval = 0;
979 while (bl && !bl->isbreakable) {
980 upval |= bl->upval;
981 bl = bl->previous;
982 }
983 if (!bl)
984 luaX_syntaxerror(ls, "no loop to break");
985 if (upval)
986 luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
987 luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
988}
989
990
991static void whilestat (LexState *ls, int line) {
992 /* whilestat -> WHILE cond DO block END */
993 FuncState *fs = ls->fs;
994 int whileinit;
995 int condexit;
996 BlockCnt bl;
997 luaX_next(ls); /* skip WHILE */
998 whileinit = luaK_getlabel(fs);
999 condexit = cond(ls);
1000 enterblock(fs, &bl, 1);
1001 checknext(ls, TK_DO);
1002 block(ls);
1003 luaK_patchlist(fs, luaK_jump(fs), whileinit);
1004 check_match(ls, TK_END, TK_WHILE, line);
1005 leaveblock(fs);
1006 luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
1007}
1008
1009
1010static void repeatstat (LexState *ls, int line) {
1011 /* repeatstat -> REPEAT block UNTIL cond */
1012 int condexit;
1013 FuncState *fs = ls->fs;
1014 int repeat_init = luaK_getlabel(fs);
1015 BlockCnt bl1, bl2;
1016 enterblock(fs, &bl1, 1); /* loop block */
1017 enterblock(fs, &bl2, 0); /* scope block */
1018 luaX_next(ls); /* skip REPEAT */
1019 chunk(ls);
1020 check_match(ls, TK_UNTIL, TK_REPEAT, line);
1021 condexit = cond(ls); /* read condition (inside scope block) */
1022 if (!bl2.upval) { /* no upvalues? */
1023 leaveblock(fs); /* finish scope */
1024 luaK_patchlist(ls->fs, condexit, repeat_init); /* close the loop */
1025 }
1026 else { /* complete semantics when there are upvalues */
1027 breakstat(ls); /* if condition then break */
1028 luaK_patchtohere(ls->fs, condexit); /* else... */
1029 leaveblock(fs); /* finish scope... */
1030 luaK_patchlist(ls->fs, luaK_jump(fs), repeat_init); /* and repeat */
1031 }
1032 leaveblock(fs); /* finish loop */
1033}
1034
1035
1036static int exp1 (LexState *ls) {
1037 expdesc e;
1038 int k;
1039 expr(ls, &e);
1040 k = e.k;
1041 luaK_exp2nextreg(ls->fs, &e);
1042 return k;
1043}
1044
1045
1046static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
1047 /* forbody -> DO block */
1048 BlockCnt bl;
1049 FuncState *fs = ls->fs;
1050 int prep, endfor;
1051 adjustlocalvars(ls, 3); /* control variables */
1052 checknext(ls, TK_DO);
1053 prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
1054 enterblock(fs, &bl, 0); /* scope for declared variables */
1055 adjustlocalvars(ls, nvars);
1056 luaK_reserveregs(fs, nvars);
1057 block(ls);
1058 leaveblock(fs); /* end of scope for declared variables */
1059 luaK_patchtohere(fs, prep);
1060 endfor = (isnum) ? luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP) :
1061 luaK_codeABC(fs, OP_TFORLOOP, base, 0, nvars);
1062 luaK_fixline(fs, line); /* pretend that `OP_FOR' starts the loop */
1063 luaK_patchlist(fs, (isnum ? endfor : luaK_jump(fs)), prep + 1);
1064}
1065
1066
1067static void fornum (LexState *ls, TString *varname, int line) {
1068 /* fornum -> NAME = exp1,exp1[,exp1] forbody */
1069 FuncState *fs = ls->fs;
1070 int base = fs->freereg;
1071 new_localvarliteral(ls, "(for index)", 0);
1072 new_localvarliteral(ls, "(for limit)", 1);
1073 new_localvarliteral(ls, "(for step)", 2);
1074 new_localvar(ls, varname, 3);
1075 checknext(ls, '=');
1076 exp1(ls); /* initial value */
1077 checknext(ls, ',');
1078 exp1(ls); /* limit */
1079 if (testnext(ls, ','))
1080 exp1(ls); /* optional step */
1081 else { /* default step = 1 */
1082 luaK_codeABx(fs, OP_LOADK, fs->freereg, luaK_numberK(fs, 1));
1083 luaK_reserveregs(fs, 1);
1084 }
1085 forbody(ls, base, line, 1, 1);
1086}
1087
1088
1089static void forlist (LexState *ls, TString *indexname) {
1090 /* forlist -> NAME {,NAME} IN explist1 forbody */
1091 FuncState *fs = ls->fs;
1092 expdesc e;
1093 int nvars = 0;
1094 int line;
1095 int base = fs->freereg;
1096 /* create control variables */
1097 new_localvarliteral(ls, "(for generator)", nvars++);
1098 new_localvarliteral(ls, "(for state)", nvars++);
1099 new_localvarliteral(ls, "(for control)", nvars++);
1100 /* create declared variables */
1101 new_localvar(ls, indexname, nvars++);
1102 while (testnext(ls, ','))
1103 new_localvar(ls, str_checkname(ls), nvars++);
1104 checknext(ls, TK_IN);
1105 line = ls->linenumber;
1106 adjust_assign(ls, 3, explist1(ls, &e), &e);
1107 luaK_checkstack(fs, 3); /* extra space to call generator */
1108 forbody(ls, base, line, nvars - 3, 0);
1109}
1110
1111
1112static void forstat (LexState *ls, int line) {
1113 /* forstat -> FOR (fornum | forlist) END */
1114 FuncState *fs = ls->fs;
1115 TString *varname;
1116 BlockCnt bl;
1117 enterblock(fs, &bl, 1); /* scope for loop and control variables */
1118 luaX_next(ls); /* skip `for' */
1119 varname = str_checkname(ls); /* first variable name */
1120 switch (ls->t.token) {
1121 case '=': fornum(ls, varname, line); break;
1122 case ',': case TK_IN: forlist(ls, varname); break;
1123 default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
1124 }
1125 check_match(ls, TK_END, TK_FOR, line);
1126 leaveblock(fs); /* loop scope (`break' jumps to this point) */
1127}
1128
1129
1130static int test_then_block (LexState *ls) {
1131 /* test_then_block -> [IF | ELSEIF] cond THEN block */
1132 int condexit;
1133 luaX_next(ls); /* skip IF or ELSEIF */
1134 condexit = cond(ls);
1135 checknext(ls, TK_THEN);
1136 block(ls); /* `then' part */
1137 return condexit;
1138}
1139
1140
1141static void ifstat (LexState *ls, int line) {
1142 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1143 FuncState *fs = ls->fs;
1144 int flist;
1145 int escapelist = NO_JUMP;
1146 flist = test_then_block(ls); /* IF cond THEN block */
1147 while (ls->t.token == TK_ELSEIF) {
1148 luaK_concat(fs, &escapelist, luaK_jump(fs));
1149 luaK_patchtohere(fs, flist);
1150 flist = test_then_block(ls); /* ELSEIF cond THEN block */
1151 }
1152 if (ls->t.token == TK_ELSE) {
1153 luaK_concat(fs, &escapelist, luaK_jump(fs));
1154 luaK_patchtohere(fs, flist);
1155 luaX_next(ls); /* skip ELSE (after patch, for correct line info) */
1156 block(ls); /* `else' part */
1157 }
1158 else
1159 luaK_concat(fs, &escapelist, flist);
1160 luaK_patchtohere(fs, escapelist);
1161 check_match(ls, TK_END, TK_IF, line);
1162}
1163
1164
1165static void localfunc (LexState *ls) {
1166 expdesc v, b;
1167 FuncState *fs = ls->fs;
1168 new_localvar(ls, str_checkname(ls), 0);
1169 init_exp(&v, VLOCAL, fs->freereg);
1170 luaK_reserveregs(fs, 1);
1171 adjustlocalvars(ls, 1);
1172 body(ls, &b, 0, ls->linenumber);
1173 luaK_storevar(fs, &v, &b);
1174 /* debug information will only see the variable after this point! */
1175 getlocvar(fs, fs->nactvar - 1).startpc = fs->pc;
1176}
1177
1178
1179static void localstat (LexState *ls) {
1180 /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
1181 int nvars = 0;
1182 int nexps;
1183 expdesc e;
1184 do {
1185 new_localvar(ls, str_checkname(ls), nvars++);
1186 } while (testnext(ls, ','));
1187 if (testnext(ls, '='))
1188 nexps = explist1(ls, &e);
1189 else {
1190 e.k = VVOID;
1191 nexps = 0;
1192 }
1193 adjust_assign(ls, nvars, nexps, &e);
1194 adjustlocalvars(ls, nvars);
1195}
1196
1197
1198static int funcname (LexState *ls, expdesc *v) {
1199 /* funcname -> NAME {field} [`:' NAME] */
1200 int needself = 0;
1201 singlevar(ls, v);
1202 while (ls->t.token == '.')
1203 field(ls, v);
1204 if (ls->t.token == ':') {
1205 needself = 1;
1206 field(ls, v);
1207 }
1208 return needself;
1209}
1210
1211
1212static void funcstat (LexState *ls, int line) {
1213 /* funcstat -> FUNCTION funcname body */
1214 int needself;
1215 expdesc v, b;
1216 luaX_next(ls); /* skip FUNCTION */
1217 needself = funcname(ls, &v);
1218 body(ls, &b, needself, line);
1219 luaK_storevar(ls->fs, &v, &b);
1220 luaK_fixline(ls->fs, line); /* definition `happens' in the first line */
1221}
1222
1223
1224static void exprstat (LexState *ls) {
1225 /* stat -> func | assignment */
1226 FuncState *fs = ls->fs;
1227 struct LHS_assign v;
1228 primaryexp(ls, &v.v);
1229 if (v.v.k == VCALL) /* stat -> func */
1230 SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */
1231 else { /* stat -> assignment */
1232 v.prev = NULL;
1233 assignment(ls, &v, 1);
1234 }
1235}
1236
1237
1238static void retstat (LexState *ls) {
1239 /* stat -> RETURN explist */
1240 FuncState *fs = ls->fs;
1241 expdesc e;
1242 int first, nret; /* registers with returned values */
1243 luaX_next(ls); /* skip RETURN */
1244 if (block_follow(ls->t.token) || ls->t.token == ';')
1245 first = nret = 0; /* return no values */
1246 else {
1247 nret = explist1(ls, &e); /* optional return values */
1248 if (hasmultret(e.k)) {
1249 luaK_setmultret(fs, &e);
1250 if (e.k == VCALL && nret == 1) { /* tail call? */
1251 SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
1252 lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
1253 }
1254 first = fs->nactvar;
1255 nret = LUA_MULTRET; /* return all values */
1256 }
1257 else {
1258 if (nret == 1) /* only one single value? */
1259 first = luaK_exp2anyreg(fs, &e);
1260 else {
1261 luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */
1262 first = fs->nactvar; /* return all `active' values */
1263 lua_assert(nret == fs->freereg - first);
1264 }
1265 }
1266 }
1267 luaK_ret(fs, first, nret);
1268}
1269
1270
1271static int statement (LexState *ls) {
1272 int line = ls->linenumber; /* may be needed for error messages */
1273 switch (ls->t.token) {
1274 case TK_IF: { /* stat -> ifstat */
1275 ifstat(ls, line);
1276 return 0;
1277 }
1278 case TK_WHILE: { /* stat -> whilestat */
1279 whilestat(ls, line);
1280 return 0;
1281 }
1282 case TK_DO: { /* stat -> DO block END */
1283 luaX_next(ls); /* skip DO */
1284 block(ls);
1285 check_match(ls, TK_END, TK_DO, line);
1286 return 0;
1287 }
1288 case TK_FOR: { /* stat -> forstat */
1289 forstat(ls, line);
1290 return 0;
1291 }
1292 case TK_REPEAT: { /* stat -> repeatstat */
1293 repeatstat(ls, line);
1294 return 0;
1295 }
1296 case TK_FUNCTION: {
1297 funcstat(ls, line); /* stat -> funcstat */
1298 return 0;
1299 }
1300 case TK_LOCAL: { /* stat -> localstat */
1301 luaX_next(ls); /* skip LOCAL */
1302 if (testnext(ls, TK_FUNCTION)) /* local function? */
1303 localfunc(ls);
1304 else
1305 localstat(ls);
1306 return 0;
1307 }
1308 case TK_RETURN: { /* stat -> retstat */
1309 retstat(ls);
1310 return 1; /* must be last statement */
1311 }
1312 case TK_BREAK: { /* stat -> breakstat */
1313 luaX_next(ls); /* skip BREAK */
1314 breakstat(ls);
1315 return 1; /* must be last statement */
1316 }
1317 default: {
1318 exprstat(ls);
1319 return 0; /* to avoid warnings */
1320 }
1321 }
1322}
1323
1324
1325static void chunk (LexState *ls) {
1326 /* chunk -> { stat [`;'] } */
1327 int islast = 0;
1328 enterlevel(ls);
1329 while (!islast && !block_follow(ls->t.token)) {
1330 islast = statement(ls);
1331 testnext(ls, ';');
1332 lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
1333 ls->fs->freereg >= ls->fs->nactvar);
1334 ls->fs->freereg = ls->fs->nactvar; /* free registers */
1335 }
1336 leavelevel(ls);
1337}
1338
1339/* }====================================================================== */
diff --git a/apps/plugins/lua/lparser.h b/apps/plugins/lua/lparser.h
new file mode 100644
index 0000000000..f9b8e24913
--- /dev/null
+++ b/apps/plugins/lua/lparser.h
@@ -0,0 +1,82 @@
1/*
2** $Id$
3** Lua Parser
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lparser_h
8#define lparser_h
9
10#include "llimits.h"
11#include "lobject.h"
12#include "lzio.h"
13
14
15/*
16** Expression descriptor
17*/
18
19typedef enum {
20 VVOID, /* no value */
21 VNIL,
22 VTRUE,
23 VFALSE,
24 VK, /* info = index of constant in `k' */
25 VKNUM, /* nval = numerical value */
26 VLOCAL, /* info = local register */
27 VUPVAL, /* info = index of upvalue in `upvalues' */
28 VGLOBAL, /* info = index of table; aux = index of global name in `k' */
29 VINDEXED, /* info = table register; aux = index register (or `k') */
30 VJMP, /* info = instruction pc */
31 VRELOCABLE, /* info = instruction pc */
32 VNONRELOC, /* info = result register */
33 VCALL, /* info = instruction pc */
34 VVARARG /* info = instruction pc */
35} expkind;
36
37typedef struct expdesc {
38 expkind k;
39 union {
40 struct { int info, aux; } s;
41 lua_Number nval;
42 } u;
43 int t; /* patch list of `exit when true' */
44 int f; /* patch list of `exit when false' */
45} expdesc;
46
47
48typedef struct upvaldesc {
49 lu_byte k;
50 lu_byte info;
51} upvaldesc;
52
53
54struct BlockCnt; /* defined in lparser.c */
55
56
57/* state needed to generate code for a given function */
58typedef struct FuncState {
59 Proto *f; /* current function header */
60 Table *h; /* table to find (and reuse) elements in `k' */
61 struct FuncState *prev; /* enclosing function */
62 struct LexState *ls; /* lexical state */
63 struct lua_State *L; /* copy of the Lua state */
64 struct BlockCnt *bl; /* chain of current blocks */
65 int pc; /* next position to code (equivalent to `ncode') */
66 int lasttarget; /* `pc' of last `jump target' */
67 int jpc; /* list of pending jumps to `pc' */
68 int freereg; /* first free register */
69 int nk; /* number of elements in `k' */
70 int np; /* number of elements in `p' */
71 short nlocvars; /* number of elements in `locvars' */
72 lu_byte nactvar; /* number of active local variables */
73 upvaldesc upvalues[LUAI_MAXUPVALUES]; /* upvalues */
74 unsigned short actvar[LUAI_MAXVARS]; /* declared-variable stack */
75} FuncState;
76
77
78LUAI_FUNC Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
79 const char *name);
80
81
82#endif
diff --git a/apps/plugins/lua/lstate.c b/apps/plugins/lua/lstate.c
new file mode 100644
index 0000000000..4313b83a0c
--- /dev/null
+++ b/apps/plugins/lua/lstate.c
@@ -0,0 +1,214 @@
1/*
2** $Id: lstate.c,v 2.36.1.2 2008/01/03 15:20:39 roberto Exp $
3** Global State
4** See Copyright Notice in lua.h
5*/
6
7
8#include <stddef.h>
9
10#define lstate_c
11#define LUA_CORE
12
13#include "lua.h"
14
15#include "ldebug.h"
16#include "ldo.h"
17#include "lfunc.h"
18#include "lgc.h"
19#include "llex.h"
20#include "lmem.h"
21#include "lstate.h"
22#include "lstring.h"
23#include "ltable.h"
24#include "ltm.h"
25
26
27#define state_size(x) (sizeof(x) + LUAI_EXTRASPACE)
28#define fromstate(l) (cast(lu_byte *, (l)) - LUAI_EXTRASPACE)
29#define tostate(l) (cast(lua_State *, cast(lu_byte *, l) + LUAI_EXTRASPACE))
30
31
32/*
33** Main thread combines a thread state and the global state
34*/
35typedef struct LG {
36 lua_State l;
37 global_State g;
38} LG;
39
40
41
42static void stack_init (lua_State *L1, lua_State *L) {
43 /* initialize CallInfo array */
44 L1->base_ci = luaM_newvector(L, BASIC_CI_SIZE, CallInfo);
45 L1->ci = L1->base_ci;
46 L1->size_ci = BASIC_CI_SIZE;
47 L1->end_ci = L1->base_ci + L1->size_ci - 1;
48 /* initialize stack array */
49 L1->stack = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, TValue);
50 L1->stacksize = BASIC_STACK_SIZE + EXTRA_STACK;
51 L1->top = L1->stack;
52 L1->stack_last = L1->stack+(L1->stacksize - EXTRA_STACK)-1;
53 /* initialize first ci */
54 L1->ci->func = L1->top;
55 setnilvalue(L1->top++); /* `function' entry for this `ci' */
56 L1->base = L1->ci->base = L1->top;
57 L1->ci->top = L1->top + LUA_MINSTACK;
58}
59
60
61static void freestack (lua_State *L, lua_State *L1) {
62 luaM_freearray(L, L1->base_ci, L1->size_ci, CallInfo);
63 luaM_freearray(L, L1->stack, L1->stacksize, TValue);
64}
65
66
67/*
68** open parts that may cause memory-allocation errors
69*/
70static void f_luaopen (lua_State *L, void *ud) {
71 global_State *g = G(L);
72 UNUSED(ud);
73 stack_init(L, L); /* init stack */
74 sethvalue(L, gt(L), luaH_new(L, 0, 2)); /* table of globals */
75 sethvalue(L, registry(L), luaH_new(L, 0, 2)); /* registry */
76 luaS_resize(L, MINSTRTABSIZE); /* initial size of string table */
77 luaT_init(L);
78 luaX_init(L);
79 luaS_fix(luaS_newliteral(L, MEMERRMSG));
80 g->GCthreshold = 4*g->totalbytes;
81}
82
83
84static void preinit_state (lua_State *L, global_State *g) {
85 G(L) = g;
86 L->stack = NULL;
87 L->stacksize = 0;
88 L->errorJmp = NULL;
89 L->hook = NULL;
90 L->hookmask = 0;
91 L->basehookcount = 0;
92 L->allowhook = 1;
93 resethookcount(L);
94 L->openupval = NULL;
95 L->size_ci = 0;
96 L->nCcalls = L->baseCcalls = 0;
97 L->status = 0;
98 L->base_ci = L->ci = NULL;
99 L->savedpc = NULL;
100 L->errfunc = 0;
101 setnilvalue(gt(L));
102}
103
104
105static void close_state (lua_State *L) {
106 global_State *g = G(L);
107 luaF_close(L, L->stack); /* close all upvalues for this thread */
108 luaC_freeall(L); /* collect all objects */
109 lua_assert(g->rootgc == obj2gco(L));
110 lua_assert(g->strt.nuse == 0);
111 luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size, TString *);
112 luaZ_freebuffer(L, &g->buff);
113 freestack(L, L);
114 lua_assert(g->totalbytes == sizeof(LG));
115 (*g->frealloc)(g->ud, fromstate(L), state_size(LG), 0);
116}
117
118
119lua_State *luaE_newthread (lua_State *L) {
120 lua_State *L1 = tostate(luaM_malloc(L, state_size(lua_State)));
121 luaC_link(L, obj2gco(L1), LUA_TTHREAD);
122 preinit_state(L1, G(L));
123 stack_init(L1, L); /* init stack */
124 setobj2n(L, gt(L1), gt(L)); /* share table of globals */
125 L1->hookmask = L->hookmask;
126 L1->basehookcount = L->basehookcount;
127 L1->hook = L->hook;
128 resethookcount(L1);
129 lua_assert(iswhite(obj2gco(L1)));
130 return L1;
131}
132
133
134void luaE_freethread (lua_State *L, lua_State *L1) {
135 luaF_close(L1, L1->stack); /* close all upvalues for this thread */
136 lua_assert(L1->openupval == NULL);
137 luai_userstatefree(L1);
138 freestack(L, L1);
139 luaM_freemem(L, fromstate(L1), state_size(lua_State));
140}
141
142
143LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {
144 int i;
145 lua_State *L;
146 global_State *g;
147 void *l = (*f)(ud, NULL, 0, state_size(LG));
148 if (l == NULL) return NULL;
149 L = tostate(l);
150 g = &((LG *)L)->g;
151 L->next = NULL;
152 L->tt = LUA_TTHREAD;
153 g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT);
154 L->marked = luaC_white(g);
155 set2bits(L->marked, FIXEDBIT, SFIXEDBIT);
156 preinit_state(L, g);
157 g->frealloc = f;
158 g->ud = ud;
159 g->mainthread = L;
160 g->uvhead.u.l.prev = &g->uvhead;
161 g->uvhead.u.l.next = &g->uvhead;
162 g->GCthreshold = 0; /* mark it as unfinished state */
163 g->strt.size = 0;
164 g->strt.nuse = 0;
165 g->strt.hash = NULL;
166 setnilvalue(registry(L));
167 luaZ_initbuffer(L, &g->buff);
168 g->panic = NULL;
169 g->gcstate = GCSpause;
170 g->rootgc = obj2gco(L);
171 g->sweepstrgc = 0;
172 g->sweepgc = &g->rootgc;
173 g->gray = NULL;
174 g->grayagain = NULL;
175 g->weak = NULL;
176 g->tmudata = NULL;
177 g->totalbytes = sizeof(LG);
178 g->gcpause = LUAI_GCPAUSE;
179 g->gcstepmul = LUAI_GCMUL;
180 g->gcdept = 0;
181 for (i=0; i<NUM_TAGS; i++) g->mt[i] = NULL;
182 if (luaD_rawrunprotected(L, f_luaopen, NULL) != 0) {
183 /* memory allocation error: free partial state */
184 close_state(L);
185 L = NULL;
186 }
187 else
188 luai_userstateopen(L);
189 return L;
190}
191
192
193static void callallgcTM (lua_State *L, void *ud) {
194 UNUSED(ud);
195 luaC_callGCTM(L); /* call GC metamethods for all udata */
196}
197
198
199LUA_API void lua_close (lua_State *L) {
200 L = G(L)->mainthread; /* only the main thread can be closed */
201 lua_lock(L);
202 luaF_close(L, L->stack); /* close all upvalues for this thread */
203 luaC_separateudata(L, 1); /* separate udata that have GC metamethods */
204 L->errfunc = 0; /* no error function during GC metamethods */
205 do { /* repeat until no more errors */
206 L->ci = L->base_ci;
207 L->base = L->top = L->ci->base;
208 L->nCcalls = L->baseCcalls = 0;
209 } while (luaD_rawrunprotected(L, callallgcTM, NULL) != 0);
210 lua_assert(G(L)->tmudata == NULL);
211 luai_userstateclose(L);
212 close_state(L);
213}
214
diff --git a/apps/plugins/lua/lstate.h b/apps/plugins/lua/lstate.h
new file mode 100644
index 0000000000..94a6249461
--- /dev/null
+++ b/apps/plugins/lua/lstate.h
@@ -0,0 +1,169 @@
1/*
2** $Id$
3** Global State
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lstate_h
8#define lstate_h
9
10#include "lua.h"
11
12#include "lobject.h"
13#include "ltm.h"
14#include "lzio.h"
15
16
17
18struct lua_longjmp; /* defined in ldo.c */
19
20
21/* table of globals */
22#define gt(L) (&L->l_gt)
23
24/* registry */
25#define registry(L) (&G(L)->l_registry)
26
27
28/* extra stack space to handle TM calls and some other extras */
29#define EXTRA_STACK 5
30
31
32#define BASIC_CI_SIZE 8
33
34#define BASIC_STACK_SIZE (2*LUA_MINSTACK)
35
36
37
38typedef struct stringtable {
39 GCObject **hash;
40 lu_int32 nuse; /* number of elements */
41 int size;
42} stringtable;
43
44
45/*
46** informations about a call
47*/
48typedef struct CallInfo {
49 StkId base; /* base for this function */
50 StkId func; /* function index in the stack */
51 StkId top; /* top for this function */
52 const Instruction *savedpc;
53 int nresults; /* expected number of results from this function */
54 int tailcalls; /* number of tail calls lost under this entry */
55} CallInfo;
56
57
58
59#define curr_func(L) (clvalue(L->ci->func))
60#define ci_func(ci) (clvalue((ci)->func))
61#define f_isLua(ci) (!ci_func(ci)->c.isC)
62#define isLua(ci) (ttisfunction((ci)->func) && f_isLua(ci))
63
64
65/*
66** `global state', shared by all threads of this state
67*/
68typedef struct global_State {
69 stringtable strt; /* hash table for strings */
70 lua_Alloc frealloc; /* function to reallocate memory */
71 void *ud; /* auxiliary data to `frealloc' */
72 lu_byte currentwhite;
73 lu_byte gcstate; /* state of garbage collector */
74 int sweepstrgc; /* position of sweep in `strt' */
75 GCObject *rootgc; /* list of all collectable objects */
76 GCObject **sweepgc; /* position of sweep in `rootgc' */
77 GCObject *gray; /* list of gray objects */
78 GCObject *grayagain; /* list of objects to be traversed atomically */
79 GCObject *weak; /* list of weak tables (to be cleared) */
80 GCObject *tmudata; /* last element of list of userdata to be GC */
81 Mbuffer buff; /* temporary buffer for string concatentation */
82 lu_mem GCthreshold;
83 lu_mem totalbytes; /* number of bytes currently allocated */
84 lu_mem estimate; /* an estimate of number of bytes actually in use */
85 lu_mem gcdept; /* how much GC is `behind schedule' */
86 int gcpause; /* size of pause between successive GCs */
87 int gcstepmul; /* GC `granularity' */
88 lua_CFunction panic; /* to be called in unprotected errors */
89 TValue l_registry;
90 struct lua_State *mainthread;
91 UpVal uvhead; /* head of double-linked list of all open upvalues */
92 struct Table *mt[NUM_TAGS]; /* metatables for basic types */
93 TString *tmname[TM_N]; /* array with tag-method names */
94} global_State;
95
96
97/*
98** `per thread' state
99*/
100struct lua_State {
101 CommonHeader;
102 lu_byte status;
103 StkId top; /* first free slot in the stack */
104 StkId base; /* base of current function */
105 global_State *l_G;
106 CallInfo *ci; /* call info for current function */
107 const Instruction *savedpc; /* `savedpc' of current function */
108 StkId stack_last; /* last free slot in the stack */
109 StkId stack; /* stack base */
110 CallInfo *end_ci; /* points after end of ci array*/
111 CallInfo *base_ci; /* array of CallInfo's */
112 int stacksize;
113 int size_ci; /* size of array `base_ci' */
114 unsigned short nCcalls; /* number of nested C calls */
115 unsigned short baseCcalls; /* nested C calls when resuming coroutine */
116 lu_byte hookmask;
117 lu_byte allowhook;
118 int basehookcount;
119 int hookcount;
120 lua_Hook hook;
121 TValue l_gt; /* table of globals */
122 TValue env; /* temporary place for environments */
123 GCObject *openupval; /* list of open upvalues in this stack */
124 GCObject *gclist;
125 struct lua_longjmp *errorJmp; /* current error recover point */
126 ptrdiff_t errfunc; /* current error handling function (stack index) */
127};
128
129
130#define G(L) (L->l_G)
131
132
133/*
134** Union of all collectable objects
135*/
136union GCObject {
137 GCheader gch;
138 union TString ts;
139 union Udata u;
140 union Closure cl;
141 struct Table h;
142 struct Proto p;
143 struct UpVal uv;
144 struct lua_State th; /* thread */
145};
146
147
148/* macros to convert a GCObject into a specific value */
149#define rawgco2ts(o) check_exp((o)->gch.tt == LUA_TSTRING, &((o)->ts))
150#define gco2ts(o) (&rawgco2ts(o)->tsv)
151#define rawgco2u(o) check_exp((o)->gch.tt == LUA_TUSERDATA, &((o)->u))
152#define gco2u(o) (&rawgco2u(o)->uv)
153#define gco2cl(o) check_exp((o)->gch.tt == LUA_TFUNCTION, &((o)->cl))
154#define gco2h(o) check_exp((o)->gch.tt == LUA_TTABLE, &((o)->h))
155#define gco2p(o) check_exp((o)->gch.tt == LUA_TPROTO, &((o)->p))
156#define gco2uv(o) check_exp((o)->gch.tt == LUA_TUPVAL, &((o)->uv))
157#define ngcotouv(o) \
158 check_exp((o) == NULL || (o)->gch.tt == LUA_TUPVAL, &((o)->uv))
159#define gco2th(o) check_exp((o)->gch.tt == LUA_TTHREAD, &((o)->th))
160
161/* macro to convert any Lua object into a GCObject */
162#define obj2gco(v) (cast(GCObject *, (v)))
163
164
165LUAI_FUNC lua_State *luaE_newthread (lua_State *L);
166LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
167
168#endif
169
diff --git a/apps/plugins/lua/lstring.c b/apps/plugins/lua/lstring.c
new file mode 100644
index 0000000000..49113151cc
--- /dev/null
+++ b/apps/plugins/lua/lstring.c
@@ -0,0 +1,111 @@
1/*
2** $Id: lstring.c,v 2.8.1.1 2007/12/27 13:02:25 roberto Exp $
3** String table (keeps all strings handled by Lua)
4** See Copyright Notice in lua.h
5*/
6
7
8#include <string.h>
9
10#define lstring_c
11#define LUA_CORE
12
13#include "lua.h"
14
15#include "lmem.h"
16#include "lobject.h"
17#include "lstate.h"
18#include "lstring.h"
19
20
21
22void luaS_resize (lua_State *L, int newsize) {
23 GCObject **newhash;
24 stringtable *tb;
25 int i;
26 if (G(L)->gcstate == GCSsweepstring)
27 return; /* cannot resize during GC traverse */
28 newhash = luaM_newvector(L, newsize, GCObject *);
29 tb = &G(L)->strt;
30 for (i=0; i<newsize; i++) newhash[i] = NULL;
31 /* rehash */
32 for (i=0; i<tb->size; i++) {
33 GCObject *p = tb->hash[i];
34 while (p) { /* for each node in the list */
35 GCObject *next = p->gch.next; /* save next */
36 unsigned int h = gco2ts(p)->hash;
37 int h1 = lmod(h, newsize); /* new position */
38 lua_assert(cast_int(h%newsize) == lmod(h, newsize));
39 p->gch.next = newhash[h1]; /* chain it */
40 newhash[h1] = p;
41 p = next;
42 }
43 }
44 luaM_freearray(L, tb->hash, tb->size, TString *);
45 tb->size = newsize;
46 tb->hash = newhash;
47}
48
49
50static TString *newlstr (lua_State *L, const char *str, size_t l,
51 unsigned int h) {
52 TString *ts;
53 stringtable *tb;
54 if (l+1 > (MAX_SIZET - sizeof(TString))/sizeof(char))
55 luaM_toobig(L);
56 ts = cast(TString *, luaM_malloc(L, (l+1)*sizeof(char)+sizeof(TString)));
57 ts->tsv.len = l;
58 ts->tsv.hash = h;
59 ts->tsv.marked = luaC_white(G(L));
60 ts->tsv.tt = LUA_TSTRING;
61 ts->tsv.reserved = 0;
62 memcpy(ts+1, str, l*sizeof(char));
63 ((char *)(ts+1))[l] = '\0'; /* ending 0 */
64 tb = &G(L)->strt;
65 h = lmod(h, tb->size);
66 ts->tsv.next = tb->hash[h]; /* chain new entry */
67 tb->hash[h] = obj2gco(ts);
68 tb->nuse++;
69 if (tb->nuse > cast(lu_int32, tb->size) && tb->size <= MAX_INT/2)
70 luaS_resize(L, tb->size*2); /* too crowded */
71 return ts;
72}
73
74
75TString *luaS_newlstr (lua_State *L, const char *str, size_t l) {
76 GCObject *o;
77 unsigned int h = cast(unsigned int, l); /* seed */
78 size_t step = (l>>5)+1; /* if string is too long, don't hash all its chars */
79 size_t l1;
80 for (l1=l; l1>=step; l1-=step) /* compute hash */
81 h = h ^ ((h<<5)+(h>>2)+cast(unsigned char, str[l1-1]));
82 for (o = G(L)->strt.hash[lmod(h, G(L)->strt.size)];
83 o != NULL;
84 o = o->gch.next) {
85 TString *ts = rawgco2ts(o);
86 if (ts->tsv.len == l && (memcmp(str, getstr(ts), l) == 0)) {
87 /* string may be dead */
88 if (isdead(G(L), o)) changewhite(o);
89 return ts;
90 }
91 }
92 return newlstr(L, str, l, h); /* not found */
93}
94
95
96Udata *luaS_newudata (lua_State *L, size_t s, Table *e) {
97 Udata *u;
98 if (s > MAX_SIZET - sizeof(Udata))
99 luaM_toobig(L);
100 u = cast(Udata *, luaM_malloc(L, s + sizeof(Udata)));
101 u->uv.marked = luaC_white(G(L)); /* is not finalized */
102 u->uv.tt = LUA_TUSERDATA;
103 u->uv.len = s;
104 u->uv.metatable = NULL;
105 u->uv.env = e;
106 /* chain it on udata list (after main thread) */
107 u->uv.next = G(L)->mainthread->next;
108 G(L)->mainthread->next = obj2gco(u);
109 return u;
110}
111
diff --git a/apps/plugins/lua/lstring.h b/apps/plugins/lua/lstring.h
new file mode 100644
index 0000000000..c88e4c12a9
--- /dev/null
+++ b/apps/plugins/lua/lstring.h
@@ -0,0 +1,31 @@
1/*
2** $Id$
3** String table (keep all strings handled by Lua)
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lstring_h
8#define lstring_h
9
10
11#include "lgc.h"
12#include "lobject.h"
13#include "lstate.h"
14
15
16#define sizestring(s) (sizeof(union TString)+((s)->len+1)*sizeof(char))
17
18#define sizeudata(u) (sizeof(union Udata)+(u)->len)
19
20#define luaS_new(L, s) (luaS_newlstr(L, s, strlen(s)))
21#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \
22 (sizeof(s)/sizeof(char))-1))
23
24#define luaS_fix(s) l_setbit((s)->tsv.marked, FIXEDBIT)
25
26LUAI_FUNC void luaS_resize (lua_State *L, int newsize);
27LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, Table *e);
28LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l);
29
30
31#endif
diff --git a/apps/plugins/lua/lstrlib.c b/apps/plugins/lua/lstrlib.c
new file mode 100644
index 0000000000..3d6103692f
--- /dev/null
+++ b/apps/plugins/lua/lstrlib.c
@@ -0,0 +1,869 @@
1/*
2** $Id: lstrlib.c,v 1.132.1.4 2008/07/11 17:27:21 roberto Exp $
3** Standard library for string operations and pattern-matching
4** See Copyright Notice in lua.h
5*/
6
7
8#include <ctype.h>
9#include <stddef.h>
10#include <stdio.h>
11#include <stdlib.h>
12#include <string.h>
13
14#define lstrlib_c
15#define LUA_LIB
16
17#include "lua.h"
18
19#include "lauxlib.h"
20#include "lualib.h"
21
22
23/* macro to `unsign' a character */
24#define uchar(c) ((unsigned char)(c))
25
26
27
28static int str_len (lua_State *L) {
29 size_t l;
30 luaL_checklstring(L, 1, &l);
31 lua_pushinteger(L, l);
32 return 1;
33}
34
35
36static ptrdiff_t posrelat (ptrdiff_t pos, size_t len) {
37 /* relative string position: negative means back from end */
38 if (pos < 0) pos += (ptrdiff_t)len + 1;
39 return (pos >= 0) ? pos : 0;
40}
41
42
43static int str_sub (lua_State *L) {
44 size_t l;
45 const char *s = luaL_checklstring(L, 1, &l);
46 ptrdiff_t start = posrelat(luaL_checkinteger(L, 2), l);
47 ptrdiff_t end = posrelat(luaL_optinteger(L, 3, -1), l);
48 if (start < 1) start = 1;
49 if (end > (ptrdiff_t)l) end = (ptrdiff_t)l;
50 if (start <= end)
51 lua_pushlstring(L, s+start-1, end-start+1);
52 else lua_pushliteral(L, "");
53 return 1;
54}
55
56
57static int str_reverse (lua_State *L) {
58 size_t l;
59 luaL_Buffer b;
60 const char *s = luaL_checklstring(L, 1, &l);
61 luaL_buffinit(L, &b);
62 while (l--) luaL_addchar(&b, s[l]);
63 luaL_pushresult(&b);
64 return 1;
65}
66
67
68static int str_lower (lua_State *L) {
69 size_t l;
70 size_t i;
71 luaL_Buffer b;
72 const char *s = luaL_checklstring(L, 1, &l);
73 luaL_buffinit(L, &b);
74 for (i=0; i<l; i++)
75 luaL_addchar(&b, tolower(uchar(s[i])));
76 luaL_pushresult(&b);
77 return 1;
78}
79
80
81static int str_upper (lua_State *L) {
82 size_t l;
83 size_t i;
84 luaL_Buffer b;
85 const char *s = luaL_checklstring(L, 1, &l);
86 luaL_buffinit(L, &b);
87 for (i=0; i<l; i++)
88 luaL_addchar(&b, toupper(uchar(s[i])));
89 luaL_pushresult(&b);
90 return 1;
91}
92
93static int str_rep (lua_State *L) {
94 size_t l;
95 luaL_Buffer b;
96 const char *s = luaL_checklstring(L, 1, &l);
97 int n = luaL_checkint(L, 2);
98 luaL_buffinit(L, &b);
99 while (n-- > 0)
100 luaL_addlstring(&b, s, l);
101 luaL_pushresult(&b);
102 return 1;
103}
104
105
106static int str_byte (lua_State *L) {
107 size_t l;
108 const char *s = luaL_checklstring(L, 1, &l);
109 ptrdiff_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
110 ptrdiff_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
111 int n, i;
112 if (posi <= 0) posi = 1;
113 if ((size_t)pose > l) pose = l;
114 if (posi > pose) return 0; /* empty interval; return no values */
115 n = (int)(pose - posi + 1);
116 if (posi + n <= pose) /* overflow? */
117 luaL_error(L, "string slice too long");
118 luaL_checkstack(L, n, "string slice too long");
119 for (i=0; i<n; i++)
120 lua_pushinteger(L, uchar(s[posi+i-1]));
121 return n;
122}
123
124
125static int str_char (lua_State *L) {
126 int n = lua_gettop(L); /* number of arguments */
127 int i;
128 luaL_Buffer b;
129 luaL_buffinit(L, &b);
130 for (i=1; i<=n; i++) {
131 int c = luaL_checkint(L, i);
132 luaL_argcheck(L, uchar(c) == c, i, "invalid value");
133 luaL_addchar(&b, uchar(c));
134 }
135 luaL_pushresult(&b);
136 return 1;
137}
138
139
140static int writer (lua_State *L, const void* b, size_t size, void* B) {
141 (void)L;
142 luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
143 return 0;
144}
145
146
147static int str_dump (lua_State *L) {
148 luaL_Buffer b;
149 luaL_checktype(L, 1, LUA_TFUNCTION);
150 lua_settop(L, 1);
151 luaL_buffinit(L,&b);
152 if (lua_dump(L, writer, &b) != 0)
153 luaL_error(L, "unable to dump given function");
154 luaL_pushresult(&b);
155 return 1;
156}
157
158
159
160/*
161** {======================================================
162** PATTERN MATCHING
163** =======================================================
164*/
165
166
167#define CAP_UNFINISHED (-1)
168#define CAP_POSITION (-2)
169
170typedef struct MatchState {
171 const char *src_init; /* init of source string */
172 const char *src_end; /* end (`\0') of source string */
173 lua_State *L;
174 int level; /* total number of captures (finished or unfinished) */
175 struct {
176 const char *init;
177 ptrdiff_t len;
178 } capture[LUA_MAXCAPTURES];
179} MatchState;
180
181
182#define L_ESC '%'
183#define SPECIALS "^$*+?.([%-"
184
185
186static int check_capture (MatchState *ms, int l) {
187 l -= '1';
188 if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
189 return luaL_error(ms->L, "invalid capture index");
190 return l;
191}
192
193
194static int capture_to_close (MatchState *ms) {
195 int level = ms->level;
196 for (level--; level>=0; level--)
197 if (ms->capture[level].len == CAP_UNFINISHED) return level;
198 return luaL_error(ms->L, "invalid pattern capture");
199}
200
201
202static const char *classend (MatchState *ms, const char *p) {
203 switch (*p++) {
204 case L_ESC: {
205 if (*p == '\0')
206 luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
207 return p+1;
208 }
209 case '[': {
210 if (*p == '^') p++;
211 do { /* look for a `]' */
212 if (*p == '\0')
213 luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
214 if (*(p++) == L_ESC && *p != '\0')
215 p++; /* skip escapes (e.g. `%]') */
216 } while (*p != ']');
217 return p+1;
218 }
219 default: {
220 return p;
221 }
222 }
223}
224
225
226static int match_class (int c, int cl) {
227 int res;
228 switch (tolower(cl)) {
229 case 'a' : res = isalpha(c); break;
230 case 'c' : res = iscntrl(c); break;
231 case 'd' : res = isdigit(c); break;
232 case 'l' : res = islower(c); break;
233 case 'p' : res = ispunct(c); break;
234 case 's' : res = isspace(c); break;
235 case 'u' : res = isupper(c); break;
236 case 'w' : res = isalnum(c); break;
237 case 'x' : res = isxdigit(c); break;
238 case 'z' : res = (c == 0); break;
239 default: return (cl == c);
240 }
241 return (islower(cl) ? res : !res);
242}
243
244
245static int matchbracketclass (int c, const char *p, const char *ec) {
246 int sig = 1;
247 if (*(p+1) == '^') {
248 sig = 0;
249 p++; /* skip the `^' */
250 }
251 while (++p < ec) {
252 if (*p == L_ESC) {
253 p++;
254 if (match_class(c, uchar(*p)))
255 return sig;
256 }
257 else if ((*(p+1) == '-') && (p+2 < ec)) {
258 p+=2;
259 if (uchar(*(p-2)) <= c && c <= uchar(*p))
260 return sig;
261 }
262 else if (uchar(*p) == c) return sig;
263 }
264 return !sig;
265}
266
267
268static int singlematch (int c, const char *p, const char *ep) {
269 switch (*p) {
270 case '.': return 1; /* matches any char */
271 case L_ESC: return match_class(c, uchar(*(p+1)));
272 case '[': return matchbracketclass(c, p, ep-1);
273 default: return (uchar(*p) == c);
274 }
275}
276
277
278static const char *match (MatchState *ms, const char *s, const char *p);
279
280
281static const char *matchbalance (MatchState *ms, const char *s,
282 const char *p) {
283 if (*p == 0 || *(p+1) == 0)
284 luaL_error(ms->L, "unbalanced pattern");
285 if (*s != *p) return NULL;
286 else {
287 int b = *p;
288 int e = *(p+1);
289 int cont = 1;
290 while (++s < ms->src_end) {
291 if (*s == e) {
292 if (--cont == 0) return s+1;
293 }
294 else if (*s == b) cont++;
295 }
296 }
297 return NULL; /* string ends out of balance */
298}
299
300
301static const char *max_expand (MatchState *ms, const char *s,
302 const char *p, const char *ep) {
303 ptrdiff_t i = 0; /* counts maximum expand for item */
304 while ((s+i)<ms->src_end && singlematch(uchar(*(s+i)), p, ep))
305 i++;
306 /* keeps trying to match with the maximum repetitions */
307 while (i>=0) {
308 const char *res = match(ms, (s+i), ep+1);
309 if (res) return res;
310 i--; /* else didn't match; reduce 1 repetition to try again */
311 }
312 return NULL;
313}
314
315
316static const char *min_expand (MatchState *ms, const char *s,
317 const char *p, const char *ep) {
318 for (;;) {
319 const char *res = match(ms, s, ep+1);
320 if (res != NULL)
321 return res;
322 else if (s<ms->src_end && singlematch(uchar(*s), p, ep))
323 s++; /* try with one more repetition */
324 else return NULL;
325 }
326}
327
328
329static const char *start_capture (MatchState *ms, const char *s,
330 const char *p, int what) {
331 const char *res;
332 int level = ms->level;
333 if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
334 ms->capture[level].init = s;
335 ms->capture[level].len = what;
336 ms->level = level+1;
337 if ((res=match(ms, s, p)) == NULL) /* match failed? */
338 ms->level--; /* undo capture */
339 return res;
340}
341
342
343static const char *end_capture (MatchState *ms, const char *s,
344 const char *p) {
345 int l = capture_to_close(ms);
346 const char *res;
347 ms->capture[l].len = s - ms->capture[l].init; /* close capture */
348 if ((res = match(ms, s, p)) == NULL) /* match failed? */
349 ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
350 return res;
351}
352
353
354static const char *match_capture (MatchState *ms, const char *s, int l) {
355 size_t len;
356 l = check_capture(ms, l);
357 len = ms->capture[l].len;
358 if ((size_t)(ms->src_end-s) >= len &&
359 memcmp(ms->capture[l].init, s, len) == 0)
360 return s+len;
361 else return NULL;
362}
363
364
365static const char *match (MatchState *ms, const char *s, const char *p) {
366 init: /* using goto's to optimize tail recursion */
367 switch (*p) {
368 case '(': { /* start capture */
369 if (*(p+1) == ')') /* position capture? */
370 return start_capture(ms, s, p+2, CAP_POSITION);
371 else
372 return start_capture(ms, s, p+1, CAP_UNFINISHED);
373 }
374 case ')': { /* end capture */
375 return end_capture(ms, s, p+1);
376 }
377 case L_ESC: {
378 switch (*(p+1)) {
379 case 'b': { /* balanced string? */
380 s = matchbalance(ms, s, p+2);
381 if (s == NULL) return NULL;
382 p+=4; goto init; /* else return match(ms, s, p+4); */
383 }
384 case 'f': { /* frontier? */
385 const char *ep; char previous;
386 p += 2;
387 if (*p != '[')
388 luaL_error(ms->L, "missing " LUA_QL("[") " after "
389 LUA_QL("%%f") " in pattern");
390 ep = classend(ms, p); /* points to what is next */
391 previous = (s == ms->src_init) ? '\0' : *(s-1);
392 if (matchbracketclass(uchar(previous), p, ep-1) ||
393 !matchbracketclass(uchar(*s), p, ep-1)) return NULL;
394 p=ep; goto init; /* else return match(ms, s, ep); */
395 }
396 default: {
397 if (isdigit(uchar(*(p+1)))) { /* capture results (%0-%9)? */
398 s = match_capture(ms, s, uchar(*(p+1)));
399 if (s == NULL) return NULL;
400 p+=2; goto init; /* else return match(ms, s, p+2) */
401 }
402 goto dflt; /* case default */
403 }
404 }
405 }
406 case '\0': { /* end of pattern */
407 return s; /* match succeeded */
408 }
409 case '$': {
410 if (*(p+1) == '\0') /* is the `$' the last char in pattern? */
411 return (s == ms->src_end) ? s : NULL; /* check end of string */
412 else goto dflt;
413 }
414 default: dflt: { /* it is a pattern item */
415 const char *ep = classend(ms, p); /* points to what is next */
416 int m = s<ms->src_end && singlematch(uchar(*s), p, ep);
417 switch (*ep) {
418 case '?': { /* optional */
419 const char *res;
420 if (m && ((res=match(ms, s+1, ep+1)) != NULL))
421 return res;
422 p=ep+1; goto init; /* else return match(ms, s, ep+1); */
423 }
424 case '*': { /* 0 or more repetitions */
425 return max_expand(ms, s, p, ep);
426 }
427 case '+': { /* 1 or more repetitions */
428 return (m ? max_expand(ms, s+1, p, ep) : NULL);
429 }
430 case '-': { /* 0 or more repetitions (minimum) */
431 return min_expand(ms, s, p, ep);
432 }
433 default: {
434 if (!m) return NULL;
435 s++; p=ep; goto init; /* else return match(ms, s+1, ep); */
436 }
437 }
438 }
439 }
440}
441
442
443
444static const char *lmemfind (const char *s1, size_t l1,
445 const char *s2, size_t l2) {
446 if (l2 == 0) return s1; /* empty strings are everywhere */
447 else if (l2 > l1) return NULL; /* avoids a negative `l1' */
448 else {
449 const char *init; /* to search for a `*s2' inside `s1' */
450 l2--; /* 1st char will be checked by `memchr' */
451 l1 = l1-l2; /* `s2' cannot be found after that */
452 while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
453 init++; /* 1st char is already checked */
454 if (memcmp(init, s2+1, l2) == 0)
455 return init-1;
456 else { /* correct `l1' and `s1' to try again */
457 l1 -= init-s1;
458 s1 = init;
459 }
460 }
461 return NULL; /* not found */
462 }
463}
464
465
466static void push_onecapture (MatchState *ms, int i, const char *s,
467 const char *e) {
468 if (i >= ms->level) {
469 if (i == 0) /* ms->level == 0, too */
470 lua_pushlstring(ms->L, s, e - s); /* add whole match */
471 else
472 luaL_error(ms->L, "invalid capture index");
473 }
474 else {
475 ptrdiff_t l = ms->capture[i].len;
476 if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
477 if (l == CAP_POSITION)
478 lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
479 else
480 lua_pushlstring(ms->L, ms->capture[i].init, l);
481 }
482}
483
484
485static int push_captures (MatchState *ms, const char *s, const char *e) {
486 int i;
487 int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
488 luaL_checkstack(ms->L, nlevels, "too many captures");
489 for (i = 0; i < nlevels; i++)
490 push_onecapture(ms, i, s, e);
491 return nlevels; /* number of strings pushed */
492}
493
494
495static int str_find_aux (lua_State *L, int find) {
496 size_t l1, l2;
497 const char *s = luaL_checklstring(L, 1, &l1);
498 const char *p = luaL_checklstring(L, 2, &l2);
499 ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
500 if (init < 0) init = 0;
501 else if ((size_t)(init) > l1) init = (ptrdiff_t)l1;
502 if (find && (lua_toboolean(L, 4) || /* explicit request? */
503 strpbrk(p, SPECIALS) == NULL)) { /* or no special characters? */
504 /* do a plain search */
505 const char *s2 = lmemfind(s+init, l1-init, p, l2);
506 if (s2) {
507 lua_pushinteger(L, s2-s+1);
508 lua_pushinteger(L, s2-s+l2);
509 return 2;
510 }
511 }
512 else {
513 MatchState ms;
514 int anchor = (*p == '^') ? (p++, 1) : 0;
515 const char *s1=s+init;
516 ms.L = L;
517 ms.src_init = s;
518 ms.src_end = s+l1;
519 do {
520 const char *res;
521 ms.level = 0;
522 if ((res=match(&ms, s1, p)) != NULL) {
523 if (find) {
524 lua_pushinteger(L, s1-s+1); /* start */
525 lua_pushinteger(L, res-s); /* end */
526 return push_captures(&ms, NULL, 0) + 2;
527 }
528 else
529 return push_captures(&ms, s1, res);
530 }
531 } while (s1++ < ms.src_end && !anchor);
532 }
533 lua_pushnil(L); /* not found */
534 return 1;
535}
536
537
538static int str_find (lua_State *L) {
539 return str_find_aux(L, 1);
540}
541
542
543static int str_match (lua_State *L) {
544 return str_find_aux(L, 0);
545}
546
547
548static int gmatch_aux (lua_State *L) {
549 MatchState ms;
550 size_t ls;
551 const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
552 const char *p = lua_tostring(L, lua_upvalueindex(2));
553 const char *src;
554 ms.L = L;
555 ms.src_init = s;
556 ms.src_end = s+ls;
557 for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
558 src <= ms.src_end;
559 src++) {
560 const char *e;
561 ms.level = 0;
562 if ((e = match(&ms, src, p)) != NULL) {
563 lua_Integer newstart = e-s;
564 if (e == src) newstart++; /* empty match? go at least one position */
565 lua_pushinteger(L, newstart);
566 lua_replace(L, lua_upvalueindex(3));
567 return push_captures(&ms, src, e);
568 }
569 }
570 return 0; /* not found */
571}
572
573
574static int gmatch (lua_State *L) {
575 luaL_checkstring(L, 1);
576 luaL_checkstring(L, 2);
577 lua_settop(L, 2);
578 lua_pushinteger(L, 0);
579 lua_pushcclosure(L, gmatch_aux, 3);
580 return 1;
581}
582
583
584static int gfind_nodef (lua_State *L) {
585 return luaL_error(L, LUA_QL("string.gfind") " was renamed to "
586 LUA_QL("string.gmatch"));
587}
588
589
590static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
591 const char *e) {
592 size_t l, i;
593 const char *news = lua_tolstring(ms->L, 3, &l);
594 for (i = 0; i < l; i++) {
595 if (news[i] != L_ESC)
596 luaL_addchar(b, news[i]);
597 else {
598 i++; /* skip ESC */
599 if (!isdigit(uchar(news[i])))
600 luaL_addchar(b, news[i]);
601 else if (news[i] == '0')
602 luaL_addlstring(b, s, e - s);
603 else {
604 push_onecapture(ms, news[i] - '1', s, e);
605 luaL_addvalue(b); /* add capture to accumulated result */
606 }
607 }
608 }
609}
610
611
612static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
613 const char *e) {
614 lua_State *L = ms->L;
615 switch (lua_type(L, 3)) {
616 case LUA_TNUMBER:
617 case LUA_TSTRING: {
618 add_s(ms, b, s, e);
619 return;
620 }
621 case LUA_TFUNCTION: {
622 int n;
623 lua_pushvalue(L, 3);
624 n = push_captures(ms, s, e);
625 lua_call(L, n, 1);
626 break;
627 }
628 case LUA_TTABLE: {
629 push_onecapture(ms, 0, s, e);
630 lua_gettable(L, 3);
631 break;
632 }
633 }
634 if (!lua_toboolean(L, -1)) { /* nil or false? */
635 lua_pop(L, 1);
636 lua_pushlstring(L, s, e - s); /* keep original text */
637 }
638 else if (!lua_isstring(L, -1))
639 luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
640 luaL_addvalue(b); /* add result to accumulator */
641}
642
643
644static int str_gsub (lua_State *L) {
645 size_t srcl;
646 const char *src = luaL_checklstring(L, 1, &srcl);
647 const char *p = luaL_checkstring(L, 2);
648 int tr = lua_type(L, 3);
649 int max_s = luaL_optint(L, 4, srcl+1);
650 int anchor = (*p == '^') ? (p++, 1) : 0;
651 int n = 0;
652 MatchState ms;
653 luaL_Buffer b;
654 luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
655 tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
656 "string/function/table expected");
657 luaL_buffinit(L, &b);
658 ms.L = L;
659 ms.src_init = src;
660 ms.src_end = src+srcl;
661 while (n < max_s) {
662 const char *e;
663 ms.level = 0;
664 e = match(&ms, src, p);
665 if (e) {
666 n++;
667 add_value(&ms, &b, src, e);
668 }
669 if (e && e>src) /* non empty match? */
670 src = e; /* skip it */
671 else if (src < ms.src_end)
672 luaL_addchar(&b, *src++);
673 else break;
674 if (anchor) break;
675 }
676 luaL_addlstring(&b, src, ms.src_end-src);
677 luaL_pushresult(&b);
678 lua_pushinteger(L, n); /* number of substitutions */
679 return 2;
680}
681
682/* }====================================================== */
683
684
685/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
686#define MAX_ITEM 512
687/* valid flags in a format specification */
688#define FLAGS "-+ #0"
689/*
690** maximum size of each format specification (such as '%-099.99d')
691** (+10 accounts for %99.99x plus margin of error)
692*/
693#define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
694
695
696static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
697 size_t l;
698 const char *s = luaL_checklstring(L, arg, &l);
699 luaL_addchar(b, '"');
700 while (l--) {
701 switch (*s) {
702 case '"': case '\\': case '\n': {
703 luaL_addchar(b, '\\');
704 luaL_addchar(b, *s);
705 break;
706 }
707 case '\r': {
708 luaL_addlstring(b, "\\r", 2);
709 break;
710 }
711 case '\0': {
712 luaL_addlstring(b, "\\000", 4);
713 break;
714 }
715 default: {
716 luaL_addchar(b, *s);
717 break;
718 }
719 }
720 s++;
721 }
722 luaL_addchar(b, '"');
723}
724
725static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
726 const char *p = strfrmt;
727 while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
728 if ((size_t)(p - strfrmt) >= sizeof(FLAGS))
729 luaL_error(L, "invalid format (repeated flags)");
730 if (isdigit(uchar(*p))) p++; /* skip width */
731 if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
732 if (*p == '.') {
733 p++;
734 if (isdigit(uchar(*p))) p++; /* skip precision */
735 if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
736 }
737 if (isdigit(uchar(*p)))
738 luaL_error(L, "invalid format (width or precision too long)");
739 *(form++) = '%';
740 strncpy(form, strfrmt, p - strfrmt + 1);
741 form += p - strfrmt + 1;
742 *form = '\0';
743 return p;
744}
745
746
747static void addintlen (char *form) {
748 size_t l = strlen(form);
749 char spec = form[l - 1];
750 strcpy(form + l - 1, LUA_INTFRMLEN);
751 form[l + sizeof(LUA_INTFRMLEN) - 2] = spec;
752 form[l + sizeof(LUA_INTFRMLEN) - 1] = '\0';
753}
754
755
756static int str_format (lua_State *L) {
757 int arg = 1;
758 size_t sfl;
759 const char *strfrmt = luaL_checklstring(L, arg, &sfl);
760 const char *strfrmt_end = strfrmt+sfl;
761 luaL_Buffer b;
762 luaL_buffinit(L, &b);
763 while (strfrmt < strfrmt_end) {
764 if (*strfrmt != L_ESC)
765 luaL_addchar(&b, *strfrmt++);
766 else if (*++strfrmt == L_ESC)
767 luaL_addchar(&b, *strfrmt++); /* %% */
768 else { /* format item */
769 char form[MAX_FORMAT]; /* to store the format (`%...') */
770 char buff[MAX_ITEM]; /* to store the formatted item */
771 arg++;
772 strfrmt = scanformat(L, strfrmt, form);
773 switch (*strfrmt++) {
774 case 'c': {
775 snprintf(buff, MAX_ITEM, form, (int)luaL_checknumber(L, arg));
776 break;
777 }
778 case 'd': case 'i': {
779 addintlen(form);
780 snprintf(buff, MAX_ITEM, form, (LUA_INTFRM_T)luaL_checknumber(L, arg));
781 break;
782 }
783 case 'o': case 'u': case 'x': case 'X': {
784 addintlen(form);
785 snprintf(buff, MAX_ITEM, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg));
786 break;
787 }
788 case 'e': case 'E': case 'f':
789 case 'g': case 'G': {
790 snprintf(buff, MAX_ITEM, form, (double)luaL_checknumber(L, arg));
791 break;
792 }
793 case 'q': {
794 addquoted(L, &b, arg);
795 continue; /* skip the 'addsize' at the end */
796 }
797 case 's': {
798 size_t l;
799 const char *s = luaL_checklstring(L, arg, &l);
800 if (!strchr(form, '.') && l >= 100) {
801 /* no precision and string is too long to be formatted;
802 keep original string */
803 lua_pushvalue(L, arg);
804 luaL_addvalue(&b);
805 continue; /* skip the `addsize' at the end */
806 }
807 else {
808 snprintf(buff, MAX_ITEM, form, s);
809 break;
810 }
811 }
812 default: { /* also treat cases `pnLlh' */
813 return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
814 LUA_QL("format"), *(strfrmt - 1));
815 }
816 }
817 luaL_addlstring(&b, buff, strlen(buff));
818 }
819 }
820 luaL_pushresult(&b);
821 return 1;
822}
823
824
825static const luaL_Reg strlib[] = {
826 {"byte", str_byte},
827 {"char", str_char},
828 {"dump", str_dump},
829 {"find", str_find},
830 {"format", str_format},
831 {"gfind", gfind_nodef},
832 {"gmatch", gmatch},
833 {"gsub", str_gsub},
834 {"len", str_len},
835 {"lower", str_lower},
836 {"match", str_match},
837 {"rep", str_rep},
838 {"reverse", str_reverse},
839 {"sub", str_sub},
840 {"upper", str_upper},
841 {NULL, NULL}
842};
843
844
845static void createmetatable (lua_State *L) {
846 lua_createtable(L, 0, 1); /* create metatable for strings */
847 lua_pushliteral(L, ""); /* dummy string */
848 lua_pushvalue(L, -2);
849 lua_setmetatable(L, -2); /* set string metatable */
850 lua_pop(L, 1); /* pop dummy string */
851 lua_pushvalue(L, -2); /* string library... */
852 lua_setfield(L, -2, "__index"); /* ...is the __index metamethod */
853 lua_pop(L, 1); /* pop metatable */
854}
855
856
857/*
858** Open string library
859*/
860LUALIB_API int luaopen_string (lua_State *L) {
861 luaL_register(L, LUA_STRLIBNAME, strlib);
862#if defined(LUA_COMPAT_GFIND)
863 lua_getfield(L, -1, "gmatch");
864 lua_setfield(L, -2, "gfind");
865#endif
866 createmetatable(L);
867 return 1;
868}
869
diff --git a/apps/plugins/lua/ltable.c b/apps/plugins/lua/ltable.c
new file mode 100644
index 0000000000..ec84f4fabc
--- /dev/null
+++ b/apps/plugins/lua/ltable.c
@@ -0,0 +1,588 @@
1/*
2** $Id: ltable.c,v 2.32.1.2 2007/12/28 15:32:23 roberto Exp $
3** Lua tables (hash)
4** See Copyright Notice in lua.h
5*/
6
7
8/*
9** Implementation of tables (aka arrays, objects, or hash tables).
10** Tables keep its elements in two parts: an array part and a hash part.
11** Non-negative integer keys are all candidates to be kept in the array
12** part. The actual size of the array is the largest `n' such that at
13** least half the slots between 0 and n are in use.
14** Hash uses a mix of chained scatter table with Brent's variation.
15** A main invariant of these tables is that, if an element is not
16** in its main position (i.e. the `original' position that its hash gives
17** to it), then the colliding element is in its own main position.
18** Hence even when the load factor reaches 100%, performance remains good.
19*/
20
21#include <math.h>
22#include <string.h>
23
24#define ltable_c
25#define LUA_CORE
26
27#include "lua.h"
28
29#include "ldebug.h"
30#include "ldo.h"
31#include "lgc.h"
32#include "lmem.h"
33#include "lobject.h"
34#include "lstate.h"
35#include "ltable.h"
36
37
38/*
39** max size of array part is 2^MAXBITS
40*/
41#if LUAI_BITSINT > 26
42#define MAXBITS 26
43#else
44#define MAXBITS (LUAI_BITSINT-2)
45#endif
46
47#define MAXASIZE (1 << MAXBITS)
48
49
50#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))
51
52#define hashstr(t,str) hashpow2(t, (str)->tsv.hash)
53#define hashboolean(t,p) hashpow2(t, p)
54
55
56/*
57** for some types, it is better to avoid modulus by power of 2, as
58** they tend to have many 2 factors.
59*/
60#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))
61
62
63#define hashpointer(t,p) hashmod(t, IntPoint(p))
64
65
66/*
67** number of ints inside a lua_Number
68*/
69#define numints cast_int(sizeof(lua_Number)/sizeof(int))
70
71
72
73#define dummynode (&dummynode_)
74
75static const Node dummynode_ = {
76 {{NULL}, LUA_TNIL}, /* value */
77 {{{NULL}, LUA_TNIL, NULL}} /* key */
78};
79
80
81/*
82** hash for lua_Numbers
83*/
84static Node *hashnum (const Table *t, lua_Number n) {
85 unsigned int a[numints];
86 int i;
87 if (luai_numeq(n, 0)) /* avoid problems with -0 */
88 return gnode(t, 0);
89 memcpy(a, &n, sizeof(a));
90 for (i = 1; i < numints; i++) a[0] += a[i];
91 return hashmod(t, a[0]);
92}
93
94
95
96/*
97** returns the `main' position of an element in a table (that is, the index
98** of its hash value)
99*/
100static Node *mainposition (const Table *t, const TValue *key) {
101 switch (ttype(key)) {
102 case LUA_TNUMBER:
103 return hashnum(t, nvalue(key));
104 case LUA_TSTRING:
105 return hashstr(t, rawtsvalue(key));
106 case LUA_TBOOLEAN:
107 return hashboolean(t, bvalue(key));
108 case LUA_TLIGHTUSERDATA:
109 return hashpointer(t, pvalue(key));
110 default:
111 return hashpointer(t, gcvalue(key));
112 }
113}
114
115
116/*
117** returns the index for `key' if `key' is an appropriate key to live in
118** the array part of the table, -1 otherwise.
119*/
120static int arrayindex (const TValue *key) {
121 if (ttisnumber(key)) {
122 lua_Number n = nvalue(key);
123 int k;
124 lua_number2int(k, n);
125 if (luai_numeq(cast_num(k), n))
126 return k;
127 }
128 return -1; /* `key' did not match some condition */
129}
130
131
132/*
133** returns the index of a `key' for table traversals. First goes all
134** elements in the array part, then elements in the hash part. The
135** beginning of a traversal is signalled by -1.
136*/
137static int findindex (lua_State *L, Table *t, StkId key) {
138 int i;
139 if (ttisnil(key)) return -1; /* first iteration */
140 i = arrayindex(key);
141 if (0 < i && i <= t->sizearray) /* is `key' inside array part? */
142 return i-1; /* yes; that's the index (corrected to C) */
143 else {
144 Node *n = mainposition(t, key);
145 do { /* check whether `key' is somewhere in the chain */
146 /* key may be dead already, but it is ok to use it in `next' */
147 if (luaO_rawequalObj(key2tval(n), key) ||
148 (ttype(gkey(n)) == LUA_TDEADKEY && iscollectable(key) &&
149 gcvalue(gkey(n)) == gcvalue(key))) {
150 i = cast_int(n - gnode(t, 0)); /* key index in hash table */
151 /* hash elements are numbered after array ones */
152 return i + t->sizearray;
153 }
154 else n = gnext(n);
155 } while (n);
156 luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */
157 return 0; /* to avoid warnings */
158 }
159}
160
161
162int luaH_next (lua_State *L, Table *t, StkId key) {
163 int i = findindex(L, t, key); /* find original element */
164 for (i++; i < t->sizearray; i++) { /* try first array part */
165 if (!ttisnil(&t->array[i])) { /* a non-nil value? */
166 setnvalue(key, cast_num(i+1));
167 setobj2s(L, key+1, &t->array[i]);
168 return 1;
169 }
170 }
171 for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */
172 if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */
173 setobj2s(L, key, key2tval(gnode(t, i)));
174 setobj2s(L, key+1, gval(gnode(t, i)));
175 return 1;
176 }
177 }
178 return 0; /* no more elements */
179}
180
181
182/*
183** {=============================================================
184** Rehash
185** ==============================================================
186*/
187
188
189static int computesizes (int nums[], int *narray) {
190 int i;
191 int twotoi; /* 2^i */
192 int a = 0; /* number of elements smaller than 2^i */
193 int na = 0; /* number of elements to go to array part */
194 int n = 0; /* optimal size for array part */
195 for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) {
196 if (nums[i] > 0) {
197 a += nums[i];
198 if (a > twotoi/2) { /* more than half elements present? */
199 n = twotoi; /* optimal size (till now) */
200 na = a; /* all elements smaller than n will go to array part */
201 }
202 }
203 if (a == *narray) break; /* all elements already counted */
204 }
205 *narray = n;
206 lua_assert(*narray/2 <= na && na <= *narray);
207 return na;
208}
209
210
211static int countint (const TValue *key, int *nums) {
212 int k = arrayindex(key);
213 if (0 < k && k <= MAXASIZE) { /* is `key' an appropriate array index? */
214 nums[ceillog2(k)]++; /* count as such */
215 return 1;
216 }
217 else
218 return 0;
219}
220
221
222static int numusearray (const Table *t, int *nums) {
223 int lg;
224 int ttlg; /* 2^lg */
225 int ause = 0; /* summation of `nums' */
226 int i = 1; /* count to traverse all array keys */
227 for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { /* for each slice */
228 int lc = 0; /* counter */
229 int lim = ttlg;
230 if (lim > t->sizearray) {
231 lim = t->sizearray; /* adjust upper limit */
232 if (i > lim)
233 break; /* no more elements to count */
234 }
235 /* count elements in range (2^(lg-1), 2^lg] */
236 for (; i <= lim; i++) {
237 if (!ttisnil(&t->array[i-1]))
238 lc++;
239 }
240 nums[lg] += lc;
241 ause += lc;
242 }
243 return ause;
244}
245
246
247static int numusehash (const Table *t, int *nums, int *pnasize) {
248 int totaluse = 0; /* total number of elements */
249 int ause = 0; /* summation of `nums' */
250 int i = sizenode(t);
251 while (i--) {
252 Node *n = &t->node[i];
253 if (!ttisnil(gval(n))) {
254 ause += countint(key2tval(n), nums);
255 totaluse++;
256 }
257 }
258 *pnasize += ause;
259 return totaluse;
260}
261
262
263static void setarrayvector (lua_State *L, Table *t, int size) {
264 int i;
265 luaM_reallocvector(L, t->array, t->sizearray, size, TValue);
266 for (i=t->sizearray; i<size; i++)
267 setnilvalue(&t->array[i]);
268 t->sizearray = size;
269}
270
271
272static void setnodevector (lua_State *L, Table *t, int size) {
273 int lsize;
274 if (size == 0) { /* no elements to hash part? */
275 t->node = cast(Node *, dummynode); /* use common `dummynode' */
276 lsize = 0;
277 }
278 else {
279 int i;
280 lsize = ceillog2(size);
281 if (lsize > MAXBITS)
282 luaG_runerror(L, "table overflow");
283 size = twoto(lsize);
284 t->node = luaM_newvector(L, size, Node);
285 for (i=0; i<size; i++) {
286 Node *n = gnode(t, i);
287 gnext(n) = NULL;
288 setnilvalue(gkey(n));
289 setnilvalue(gval(n));
290 }
291 }
292 t->lsizenode = cast_byte(lsize);
293 t->lastfree = gnode(t, size); /* all positions are free */
294}
295
296
297static void resize (lua_State *L, Table *t, int nasize, int nhsize) {
298 int i;
299 int oldasize = t->sizearray;
300 int oldhsize = t->lsizenode;
301 Node *nold = t->node; /* save old hash ... */
302 if (nasize > oldasize) /* array part must grow? */
303 setarrayvector(L, t, nasize);
304 /* create new hash part with appropriate size */
305 setnodevector(L, t, nhsize);
306 if (nasize < oldasize) { /* array part must shrink? */
307 t->sizearray = nasize;
308 /* re-insert elements from vanishing slice */
309 for (i=nasize; i<oldasize; i++) {
310 if (!ttisnil(&t->array[i]))
311 setobjt2t(L, luaH_setnum(L, t, i+1), &t->array[i]);
312 }
313 /* shrink array */
314 luaM_reallocvector(L, t->array, oldasize, nasize, TValue);
315 }
316 /* re-insert elements from hash part */
317 for (i = twoto(oldhsize) - 1; i >= 0; i--) {
318 Node *old = nold+i;
319 if (!ttisnil(gval(old)))
320 setobjt2t(L, luaH_set(L, t, key2tval(old)), gval(old));
321 }
322 if (nold != dummynode)
323 luaM_freearray(L, nold, twoto(oldhsize), Node); /* free old array */
324}
325
326
327void luaH_resizearray (lua_State *L, Table *t, int nasize) {
328 int nsize = (t->node == dummynode) ? 0 : sizenode(t);
329 resize(L, t, nasize, nsize);
330}
331
332
333static void rehash (lua_State *L, Table *t, const TValue *ek) {
334 int nasize, na;
335 int nums[MAXBITS+1]; /* nums[i] = number of keys between 2^(i-1) and 2^i */
336 int i;
337 int totaluse;
338 for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */
339 nasize = numusearray(t, nums); /* count keys in array part */
340 totaluse = nasize; /* all those keys are integer keys */
341 totaluse += numusehash(t, nums, &nasize); /* count keys in hash part */
342 /* count extra key */
343 nasize += countint(ek, nums);
344 totaluse++;
345 /* compute new size for array part */
346 na = computesizes(nums, &nasize);
347 /* resize the table to new computed sizes */
348 resize(L, t, nasize, totaluse - na);
349}
350
351
352
353/*
354** }=============================================================
355*/
356
357
358Table *luaH_new (lua_State *L, int narray, int nhash) {
359 Table *t = luaM_new(L, Table);
360 luaC_link(L, obj2gco(t), LUA_TTABLE);
361 t->metatable = NULL;
362 t->flags = cast_byte(~0);
363 /* temporary values (kept only if some malloc fails) */
364 t->array = NULL;
365 t->sizearray = 0;
366 t->lsizenode = 0;
367 t->node = cast(Node *, dummynode);
368 setarrayvector(L, t, narray);
369 setnodevector(L, t, nhash);
370 return t;
371}
372
373
374void luaH_free (lua_State *L, Table *t) {
375 if (t->node != dummynode)
376 luaM_freearray(L, t->node, sizenode(t), Node);
377 luaM_freearray(L, t->array, t->sizearray, TValue);
378 luaM_free(L, t);
379}
380
381
382static Node *getfreepos (Table *t) {
383 while (t->lastfree-- > t->node) {
384 if (ttisnil(gkey(t->lastfree)))
385 return t->lastfree;
386 }
387 return NULL; /* could not find a free place */
388}
389
390
391
392/*
393** inserts a new key into a hash table; first, check whether key's main
394** position is free. If not, check whether colliding node is in its main
395** position or not: if it is not, move colliding node to an empty place and
396** put new key in its main position; otherwise (colliding node is in its main
397** position), new key goes to an empty position.
398*/
399static TValue *newkey (lua_State *L, Table *t, const TValue *key) {
400 Node *mp = mainposition(t, key);
401 if (!ttisnil(gval(mp)) || mp == dummynode) {
402 Node *othern;
403 Node *n = getfreepos(t); /* get a free place */
404 if (n == NULL) { /* cannot find a free place? */
405 rehash(L, t, key); /* grow table */
406 return luaH_set(L, t, key); /* re-insert key into grown table */
407 }
408 lua_assert(n != dummynode);
409 othern = mainposition(t, key2tval(mp));
410 if (othern != mp) { /* is colliding node out of its main position? */
411 /* yes; move colliding node into free position */
412 while (gnext(othern) != mp) othern = gnext(othern); /* find previous */
413 gnext(othern) = n; /* redo the chain with `n' in place of `mp' */
414 *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */
415 gnext(mp) = NULL; /* now `mp' is free */
416 setnilvalue(gval(mp));
417 }
418 else { /* colliding node is in its own main position */
419 /* new node will go into free position */
420 gnext(n) = gnext(mp); /* chain new position */
421 gnext(mp) = n;
422 mp = n;
423 }
424 }
425 gkey(mp)->value = key->value; gkey(mp)->tt = key->tt;
426 luaC_barriert(L, t, key);
427 lua_assert(ttisnil(gval(mp)));
428 return gval(mp);
429}
430
431
432/*
433** search function for integers
434*/
435const TValue *luaH_getnum (Table *t, int key) {
436 /* (1 <= key && key <= t->sizearray) */
437 if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray))
438 return &t->array[key-1];
439 else {
440 lua_Number nk = cast_num(key);
441 Node *n = hashnum(t, nk);
442 do { /* check whether `key' is somewhere in the chain */
443 if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk))
444 return gval(n); /* that's it */
445 else n = gnext(n);
446 } while (n);
447 return luaO_nilobject;
448 }
449}
450
451
452/*
453** search function for strings
454*/
455const TValue *luaH_getstr (Table *t, TString *key) {
456 Node *n = hashstr(t, key);
457 do { /* check whether `key' is somewhere in the chain */
458 if (ttisstring(gkey(n)) && rawtsvalue(gkey(n)) == key)
459 return gval(n); /* that's it */
460 else n = gnext(n);
461 } while (n);
462 return luaO_nilobject;
463}
464
465
466/*
467** main search function
468*/
469const TValue *luaH_get (Table *t, const TValue *key) {
470 switch (ttype(key)) {
471 case LUA_TNIL: return luaO_nilobject;
472 case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key));
473 case LUA_TNUMBER: {
474 int k;
475 lua_Number n = nvalue(key);
476 lua_number2int(k, n);
477 if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */
478 return luaH_getnum(t, k); /* use specialized version */
479 /* else go through */
480 }
481 default: {
482 Node *n = mainposition(t, key);
483 do { /* check whether `key' is somewhere in the chain */
484 if (luaO_rawequalObj(key2tval(n), key))
485 return gval(n); /* that's it */
486 else n = gnext(n);
487 } while (n);
488 return luaO_nilobject;
489 }
490 }
491}
492
493
494TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
495 const TValue *p = luaH_get(t, key);
496 t->flags = 0;
497 if (p != luaO_nilobject)
498 return cast(TValue *, p);
499 else {
500 if (ttisnil(key)) luaG_runerror(L, "table index is nil");
501 else if (ttisnumber(key) && luai_numisnan(nvalue(key)))
502 luaG_runerror(L, "table index is NaN");
503 return newkey(L, t, key);
504 }
505}
506
507
508TValue *luaH_setnum (lua_State *L, Table *t, int key) {
509 const TValue *p = luaH_getnum(t, key);
510 if (p != luaO_nilobject)
511 return cast(TValue *, p);
512 else {
513 TValue k;
514 setnvalue(&k, cast_num(key));
515 return newkey(L, t, &k);
516 }
517}
518
519
520TValue *luaH_setstr (lua_State *L, Table *t, TString *key) {
521 const TValue *p = luaH_getstr(t, key);
522 if (p != luaO_nilobject)
523 return cast(TValue *, p);
524 else {
525 TValue k;
526 setsvalue(L, &k, key);
527 return newkey(L, t, &k);
528 }
529}
530
531
532static int unbound_search (Table *t, unsigned int j) {
533 unsigned int i = j; /* i is zero or a present index */
534 j++;
535 /* find `i' and `j' such that i is present and j is not */
536 while (!ttisnil(luaH_getnum(t, j))) {
537 i = j;
538 j *= 2;
539 if (j > cast(unsigned int, MAX_INT)) { /* overflow? */
540 /* table was built with bad purposes: resort to linear search */
541 i = 1;
542 while (!ttisnil(luaH_getnum(t, i))) i++;
543 return i - 1;
544 }
545 }
546 /* now do a binary search between them */
547 while (j - i > 1) {
548 unsigned int m = (i+j)/2;
549 if (ttisnil(luaH_getnum(t, m))) j = m;
550 else i = m;
551 }
552 return i;
553}
554
555
556/*
557** Try to find a boundary in table `t'. A `boundary' is an integer index
558** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
559*/
560int luaH_getn (Table *t) {
561 unsigned int j = t->sizearray;
562 if (j > 0 && ttisnil(&t->array[j - 1])) {
563 /* there is a boundary in the array part: (binary) search for it */
564 unsigned int i = 0;
565 while (j - i > 1) {
566 unsigned int m = (i+j)/2;
567 if (ttisnil(&t->array[m - 1])) j = m;
568 else i = m;
569 }
570 return i;
571 }
572 /* else must find a boundary in hash part */
573 else if (t->node == dummynode) /* hash part is empty? */
574 return j; /* that is easy... */
575 else return unbound_search(t, j);
576}
577
578
579
580#if defined(LUA_DEBUG)
581
582Node *luaH_mainposition (const Table *t, const TValue *key) {
583 return mainposition(t, key);
584}
585
586int luaH_isdummy (Node *n) { return n == dummynode; }
587
588#endif
diff --git a/apps/plugins/lua/ltable.h b/apps/plugins/lua/ltable.h
new file mode 100644
index 0000000000..aa28914871
--- /dev/null
+++ b/apps/plugins/lua/ltable.h
@@ -0,0 +1,40 @@
1/*
2** $Id$
3** Lua tables (hash)
4** See Copyright Notice in lua.h
5*/
6
7#ifndef ltable_h
8#define ltable_h
9
10#include "lobject.h"
11
12
13#define gnode(t,i) (&(t)->node[i])
14#define gkey(n) (&(n)->i_key.nk)
15#define gval(n) (&(n)->i_val)
16#define gnext(n) ((n)->i_key.nk.next)
17
18#define key2tval(n) (&(n)->i_key.tvk)
19
20
21LUAI_FUNC const TValue *luaH_getnum (Table *t, int key);
22LUAI_FUNC TValue *luaH_setnum (lua_State *L, Table *t, int key);
23LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key);
24LUAI_FUNC TValue *luaH_setstr (lua_State *L, Table *t, TString *key);
25LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key);
26LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key);
27LUAI_FUNC Table *luaH_new (lua_State *L, int narray, int lnhash);
28LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, int nasize);
29LUAI_FUNC void luaH_free (lua_State *L, Table *t);
30LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key);
31LUAI_FUNC int luaH_getn (Table *t);
32
33
34#if defined(LUA_DEBUG)
35LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key);
36LUAI_FUNC int luaH_isdummy (Node *n);
37#endif
38
39
40#endif
diff --git a/apps/plugins/lua/ltablib.c b/apps/plugins/lua/ltablib.c
new file mode 100644
index 0000000000..b6d9cb4ac7
--- /dev/null
+++ b/apps/plugins/lua/ltablib.c
@@ -0,0 +1,287 @@
1/*
2** $Id: ltablib.c,v 1.38.1.3 2008/02/14 16:46:58 roberto Exp $
3** Library for Table Manipulation
4** See Copyright Notice in lua.h
5*/
6
7
8#include <stddef.h>
9
10#define ltablib_c
11#define LUA_LIB
12
13#include "lua.h"
14
15#include "lauxlib.h"
16#include "lualib.h"
17
18
19#define aux_getn(L,n) (luaL_checktype(L, n, LUA_TTABLE), luaL_getn(L, n))
20
21
22static int foreachi (lua_State *L) {
23 int i;
24 int n = aux_getn(L, 1);
25 luaL_checktype(L, 2, LUA_TFUNCTION);
26 for (i=1; i <= n; i++) {
27 lua_pushvalue(L, 2); /* function */
28 lua_pushinteger(L, i); /* 1st argument */
29 lua_rawgeti(L, 1, i); /* 2nd argument */
30 lua_call(L, 2, 1);
31 if (!lua_isnil(L, -1))
32 return 1;
33 lua_pop(L, 1); /* remove nil result */
34 }
35 return 0;
36}
37
38
39static int foreach (lua_State *L) {
40 luaL_checktype(L, 1, LUA_TTABLE);
41 luaL_checktype(L, 2, LUA_TFUNCTION);
42 lua_pushnil(L); /* first key */
43 while (lua_next(L, 1)) {
44 lua_pushvalue(L, 2); /* function */
45 lua_pushvalue(L, -3); /* key */
46 lua_pushvalue(L, -3); /* value */
47 lua_call(L, 2, 1);
48 if (!lua_isnil(L, -1))
49 return 1;
50 lua_pop(L, 2); /* remove value and result */
51 }
52 return 0;
53}
54
55
56static int maxn (lua_State *L) {
57 lua_Number max = 0;
58 luaL_checktype(L, 1, LUA_TTABLE);
59 lua_pushnil(L); /* first key */
60 while (lua_next(L, 1)) {
61 lua_pop(L, 1); /* remove value */
62 if (lua_type(L, -1) == LUA_TNUMBER) {
63 lua_Number v = lua_tonumber(L, -1);
64 if (v > max) max = v;
65 }
66 }
67 lua_pushnumber(L, max);
68 return 1;
69}
70
71
72static int getn (lua_State *L) {
73 lua_pushinteger(L, aux_getn(L, 1));
74 return 1;
75}
76
77
78static int setn (lua_State *L) {
79 luaL_checktype(L, 1, LUA_TTABLE);
80#ifndef luaL_setn
81 luaL_setn(L, 1, luaL_checkint(L, 2));
82#else
83 luaL_error(L, LUA_QL("setn") " is obsolete");
84#endif
85 lua_pushvalue(L, 1);
86 return 1;
87}
88
89
90static int tinsert (lua_State *L) {
91 int e = aux_getn(L, 1) + 1; /* first empty element */
92 int pos; /* where to insert new element */
93 switch (lua_gettop(L)) {
94 case 2: { /* called with only 2 arguments */
95 pos = e; /* insert new element at the end */
96 break;
97 }
98 case 3: {
99 int i;
100 pos = luaL_checkint(L, 2); /* 2nd argument is the position */
101 if (pos > e) e = pos; /* `grow' array if necessary */
102 for (i = e; i > pos; i--) { /* move up elements */
103 lua_rawgeti(L, 1, i-1);
104 lua_rawseti(L, 1, i); /* t[i] = t[i-1] */
105 }
106 break;
107 }
108 default: {
109 return luaL_error(L, "wrong number of arguments to " LUA_QL("insert"));
110 }
111 }
112 luaL_setn(L, 1, e); /* new size */
113 lua_rawseti(L, 1, pos); /* t[pos] = v */
114 return 0;
115}
116
117
118static int tremove (lua_State *L) {
119 int e = aux_getn(L, 1);
120 int pos = luaL_optint(L, 2, e);
121 if (!(1 <= pos && pos <= e)) /* position is outside bounds? */
122 return 0; /* nothing to remove */
123 luaL_setn(L, 1, e - 1); /* t.n = n-1 */
124 lua_rawgeti(L, 1, pos); /* result = t[pos] */
125 for ( ;pos<e; pos++) {
126 lua_rawgeti(L, 1, pos+1);
127 lua_rawseti(L, 1, pos); /* t[pos] = t[pos+1] */
128 }
129 lua_pushnil(L);
130 lua_rawseti(L, 1, e); /* t[e] = nil */
131 return 1;
132}
133
134
135static void addfield (lua_State *L, luaL_Buffer *b, int i) {
136 lua_rawgeti(L, 1, i);
137 if (!lua_isstring(L, -1))
138 luaL_error(L, "invalid value (%s) at index %d in table for "
139 LUA_QL("concat"), luaL_typename(L, -1), i);
140 luaL_addvalue(b);
141}
142
143
144static int tconcat (lua_State *L) {
145 luaL_Buffer b;
146 size_t lsep;
147 int i, last;
148 const char *sep = luaL_optlstring(L, 2, "", &lsep);
149 luaL_checktype(L, 1, LUA_TTABLE);
150 i = luaL_optint(L, 3, 1);
151 last = luaL_opt(L, luaL_checkint, 4, luaL_getn(L, 1));
152 luaL_buffinit(L, &b);
153 for (; i < last; i++) {
154 addfield(L, &b, i);
155 luaL_addlstring(&b, sep, lsep);
156 }
157 if (i == last) /* add last value (if interval was not empty) */
158 addfield(L, &b, i);
159 luaL_pushresult(&b);
160 return 1;
161}
162
163
164
165/*
166** {======================================================
167** Quicksort
168** (based on `Algorithms in MODULA-3', Robert Sedgewick;
169** Addison-Wesley, 1993.)
170*/
171
172
173static void set2 (lua_State *L, int i, int j) {
174 lua_rawseti(L, 1, i);
175 lua_rawseti(L, 1, j);
176}
177
178static int sort_comp (lua_State *L, int a, int b) {
179 if (!lua_isnil(L, 2)) { /* function? */
180 int res;
181 lua_pushvalue(L, 2);
182 lua_pushvalue(L, a-1); /* -1 to compensate function */
183 lua_pushvalue(L, b-2); /* -2 to compensate function and `a' */
184 lua_call(L, 2, 1);
185 res = lua_toboolean(L, -1);
186 lua_pop(L, 1);
187 return res;
188 }
189 else /* a < b? */
190 return lua_lessthan(L, a, b);
191}
192
193static void auxsort (lua_State *L, int l, int u) {
194 while (l < u) { /* for tail recursion */
195 int i, j;
196 /* sort elements a[l], a[(l+u)/2] and a[u] */
197 lua_rawgeti(L, 1, l);
198 lua_rawgeti(L, 1, u);
199 if (sort_comp(L, -1, -2)) /* a[u] < a[l]? */
200 set2(L, l, u); /* swap a[l] - a[u] */
201 else
202 lua_pop(L, 2);
203 if (u-l == 1) break; /* only 2 elements */
204 i = (l+u)/2;
205 lua_rawgeti(L, 1, i);
206 lua_rawgeti(L, 1, l);
207 if (sort_comp(L, -2, -1)) /* a[i]<a[l]? */
208 set2(L, i, l);
209 else {
210 lua_pop(L, 1); /* remove a[l] */
211 lua_rawgeti(L, 1, u);
212 if (sort_comp(L, -1, -2)) /* a[u]<a[i]? */
213 set2(L, i, u);
214 else
215 lua_pop(L, 2);
216 }
217 if (u-l == 2) break; /* only 3 elements */
218 lua_rawgeti(L, 1, i); /* Pivot */
219 lua_pushvalue(L, -1);
220 lua_rawgeti(L, 1, u-1);
221 set2(L, i, u-1);
222 /* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */
223 i = l; j = u-1;
224 for (;;) { /* invariant: a[l..i] <= P <= a[j..u] */
225 /* repeat ++i until a[i] >= P */
226 while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) {
227 if (i>u) luaL_error(L, "invalid order function for sorting");
228 lua_pop(L, 1); /* remove a[i] */
229 }
230 /* repeat --j until a[j] <= P */
231 while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) {
232 if (j<l) luaL_error(L, "invalid order function for sorting");
233 lua_pop(L, 1); /* remove a[j] */
234 }
235 if (j<i) {
236 lua_pop(L, 3); /* pop pivot, a[i], a[j] */
237 break;
238 }
239 set2(L, i, j);
240 }
241 lua_rawgeti(L, 1, u-1);
242 lua_rawgeti(L, 1, i);
243 set2(L, u-1, i); /* swap pivot (a[u-1]) with a[i] */
244 /* a[l..i-1] <= a[i] == P <= a[i+1..u] */
245 /* adjust so that smaller half is in [j..i] and larger one in [l..u] */
246 if (i-l < u-i) {
247 j=l; i=i-1; l=i+2;
248 }
249 else {
250 j=i+1; i=u; u=j-2;
251 }
252 auxsort(L, j, i); /* call recursively the smaller one */
253 } /* repeat the routine for the larger one */
254}
255
256static int sort (lua_State *L) {
257 int n = aux_getn(L, 1);
258 luaL_checkstack(L, 40, ""); /* assume array is smaller than 2^40 */
259 if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */
260 luaL_checktype(L, 2, LUA_TFUNCTION);
261 lua_settop(L, 2); /* make sure there is two arguments */
262 auxsort(L, 1, n);
263 return 0;
264}
265
266/* }====================================================== */
267
268
269static const luaL_Reg tab_funcs[] = {
270 {"concat", tconcat},
271 {"foreach", foreach},
272 {"foreachi", foreachi},
273 {"getn", getn},
274 {"maxn", maxn},
275 {"insert", tinsert},
276 {"remove", tremove},
277 {"setn", setn},
278 {"sort", sort},
279 {NULL, NULL}
280};
281
282
283LUALIB_API int luaopen_table (lua_State *L) {
284 luaL_register(L, LUA_TABLIBNAME, tab_funcs);
285 return 1;
286}
287
diff --git a/apps/plugins/lua/ltm.c b/apps/plugins/lua/ltm.c
new file mode 100644
index 0000000000..c27f0f6fab
--- /dev/null
+++ b/apps/plugins/lua/ltm.c
@@ -0,0 +1,75 @@
1/*
2** $Id: ltm.c,v 2.8.1.1 2007/12/27 13:02:25 roberto Exp $
3** Tag methods
4** See Copyright Notice in lua.h
5*/
6
7
8#include <string.h>
9
10#define ltm_c
11#define LUA_CORE
12
13#include "lua.h"
14
15#include "lobject.h"
16#include "lstate.h"
17#include "lstring.h"
18#include "ltable.h"
19#include "ltm.h"
20
21
22
23const char *const luaT_typenames[] = {
24 "nil", "boolean", "userdata", "number",
25 "string", "table", "function", "userdata", "thread",
26 "proto", "upval"
27};
28
29
30void luaT_init (lua_State *L) {
31 static const char *const luaT_eventname[] = { /* ORDER TM */
32 "__index", "__newindex",
33 "__gc", "__mode", "__eq",
34 "__add", "__sub", "__mul", "__div", "__mod",
35 "__pow", "__unm", "__len", "__lt", "__le",
36 "__concat", "__call"
37 };
38 int i;
39 for (i=0; i<TM_N; i++) {
40 G(L)->tmname[i] = luaS_new(L, luaT_eventname[i]);
41 luaS_fix(G(L)->tmname[i]); /* never collect these names */
42 }
43}
44
45
46/*
47** function to be used with macro "fasttm": optimized for absence of
48** tag methods
49*/
50const TValue *luaT_gettm (Table *events, TMS event, TString *ename) {
51 const TValue *tm = luaH_getstr(events, ename);
52 lua_assert(event <= TM_EQ);
53 if (ttisnil(tm)) { /* no tag method? */
54 events->flags |= cast_byte(1u<<event); /* cache this fact */
55 return NULL;
56 }
57 else return tm;
58}
59
60
61const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) {
62 Table *mt;
63 switch (ttype(o)) {
64 case LUA_TTABLE:
65 mt = hvalue(o)->metatable;
66 break;
67 case LUA_TUSERDATA:
68 mt = uvalue(o)->metatable;
69 break;
70 default:
71 mt = G(L)->mt[ttype(o)];
72 }
73 return (mt ? luaH_getstr(mt, G(L)->tmname[event]) : luaO_nilobject);
74}
75
diff --git a/apps/plugins/lua/ltm.h b/apps/plugins/lua/ltm.h
new file mode 100644
index 0000000000..1b89683ef3
--- /dev/null
+++ b/apps/plugins/lua/ltm.h
@@ -0,0 +1,54 @@
1/*
2** $Id$
3** Tag methods
4** See Copyright Notice in lua.h
5*/
6
7#ifndef ltm_h
8#define ltm_h
9
10
11#include "lobject.h"
12
13
14/*
15* WARNING: if you change the order of this enumeration,
16* grep "ORDER TM"
17*/
18typedef enum {
19 TM_INDEX,
20 TM_NEWINDEX,
21 TM_GC,
22 TM_MODE,
23 TM_EQ, /* last tag method with `fast' access */
24 TM_ADD,
25 TM_SUB,
26 TM_MUL,
27 TM_DIV,
28 TM_MOD,
29 TM_POW,
30 TM_UNM,
31 TM_LEN,
32 TM_LT,
33 TM_LE,
34 TM_CONCAT,
35 TM_CALL,
36 TM_N /* number of elements in the enum */
37} TMS;
38
39
40
41#define gfasttm(g,et,e) ((et) == NULL ? NULL : \
42 ((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e]))
43
44#define fasttm(l,et,e) gfasttm(G(l), et, e)
45
46LUAI_DATA const char *const luaT_typenames[];
47
48
49LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename);
50LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o,
51 TMS event);
52LUAI_FUNC void luaT_init (lua_State *L);
53
54#endif
diff --git a/apps/plugins/lua/lua.h b/apps/plugins/lua/lua.h
new file mode 100644
index 0000000000..a0c57dc60b
--- /dev/null
+++ b/apps/plugins/lua/lua.h
@@ -0,0 +1,388 @@
1/*
2** $Id$
3** Lua - An Extensible Extension Language
4** Lua.org, PUC-Rio, Brazil (http://www.lua.org)
5** See Copyright Notice at the end of this file
6*/
7
8
9#ifndef lua_h
10#define lua_h
11
12#include <stdarg.h>
13#include <stddef.h>
14
15
16#include "luaconf.h"
17
18
19#define LUA_VERSION "Lua 5.1"
20#define LUA_RELEASE "Lua 5.1.4"
21#define LUA_VERSION_NUM 501
22#define LUA_COPYRIGHT "Copyright (C) 1994-2008 Lua.org, PUC-Rio"
23#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo & W. Celes"
24
25
26/* mark for precompiled code (`<esc>Lua') */
27#define LUA_SIGNATURE "\033Lua"
28
29/* option for multiple returns in `lua_pcall' and `lua_call' */
30#define LUA_MULTRET (-1)
31
32
33/*
34** pseudo-indices
35*/
36#define LUA_REGISTRYINDEX (-10000)
37#define LUA_ENVIRONINDEX (-10001)
38#define LUA_GLOBALSINDEX (-10002)
39#define lua_upvalueindex(i) (LUA_GLOBALSINDEX-(i))
40
41
42/* thread status; 0 is OK */
43#define LUA_YIELD 1
44#define LUA_ERRRUN 2
45#define LUA_ERRSYNTAX 3
46#define LUA_ERRMEM 4
47#define LUA_ERRERR 5
48
49
50typedef struct lua_State lua_State;
51
52typedef int (*lua_CFunction) (lua_State *L);
53
54
55/*
56** functions that read/write blocks when loading/dumping Lua chunks
57*/
58typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz);
59
60typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud);
61
62
63/*
64** prototype for memory-allocation functions
65*/
66typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize);
67
68
69/*
70** basic types
71*/
72#define LUA_TNONE (-1)
73
74#define LUA_TNIL 0
75#define LUA_TBOOLEAN 1
76#define LUA_TLIGHTUSERDATA 2
77#define LUA_TNUMBER 3
78#define LUA_TSTRING 4
79#define LUA_TTABLE 5
80#define LUA_TFUNCTION 6
81#define LUA_TUSERDATA 7
82#define LUA_TTHREAD 8
83
84
85
86/* minimum Lua stack available to a C function */
87#define LUA_MINSTACK 20
88
89
90/*
91** generic extra include file
92*/
93#if defined(LUA_USER_H)
94#include LUA_USER_H
95#endif
96
97
98/* type of numbers in Lua */
99typedef LUA_NUMBER lua_Number;
100
101
102/* type for integer functions */
103typedef LUA_INTEGER lua_Integer;
104
105
106
107/*
108** state manipulation
109*/
110LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud);
111LUA_API void (lua_close) (lua_State *L);
112LUA_API lua_State *(lua_newthread) (lua_State *L);
113
114LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf);
115
116
117/*
118** basic stack manipulation
119*/
120LUA_API int (lua_gettop) (lua_State *L);
121LUA_API void (lua_settop) (lua_State *L, int idx);
122LUA_API void (lua_pushvalue) (lua_State *L, int idx);
123LUA_API void (lua_remove) (lua_State *L, int idx);
124LUA_API void (lua_insert) (lua_State *L, int idx);
125LUA_API void (lua_replace) (lua_State *L, int idx);
126LUA_API int (lua_checkstack) (lua_State *L, int sz);
127
128LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n);
129
130
131/*
132** access functions (stack -> C)
133*/
134
135LUA_API int (lua_isnumber) (lua_State *L, int idx);
136LUA_API int (lua_isstring) (lua_State *L, int idx);
137LUA_API int (lua_iscfunction) (lua_State *L, int idx);
138LUA_API int (lua_isuserdata) (lua_State *L, int idx);
139LUA_API int (lua_type) (lua_State *L, int idx);
140LUA_API const char *(lua_typename) (lua_State *L, int tp);
141
142LUA_API int (lua_equal) (lua_State *L, int idx1, int idx2);
143LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2);
144LUA_API int (lua_lessthan) (lua_State *L, int idx1, int idx2);
145
146LUA_API lua_Number (lua_tonumber) (lua_State *L, int idx);
147LUA_API lua_Integer (lua_tointeger) (lua_State *L, int idx);
148LUA_API int (lua_toboolean) (lua_State *L, int idx);
149LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len);
150LUA_API size_t (lua_objlen) (lua_State *L, int idx);
151LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx);
152LUA_API void *(lua_touserdata) (lua_State *L, int idx);
153LUA_API lua_State *(lua_tothread) (lua_State *L, int idx);
154LUA_API const void *(lua_topointer) (lua_State *L, int idx);
155
156
157/*
158** push functions (C -> stack)
159*/
160LUA_API void (lua_pushnil) (lua_State *L);
161LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n);
162LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n);
163LUA_API void (lua_pushlstring) (lua_State *L, const char *s, size_t l);
164LUA_API void (lua_pushstring) (lua_State *L, const char *s);
165LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt,
166 va_list argp);
167LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...);
168LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n);
169LUA_API void (lua_pushboolean) (lua_State *L, int b);
170LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p);
171LUA_API int (lua_pushthread) (lua_State *L);
172
173
174/*
175** get functions (Lua -> stack)
176*/
177LUA_API void (lua_gettable) (lua_State *L, int idx);
178LUA_API void (lua_getfield) (lua_State *L, int idx, const char *k);
179LUA_API void (lua_rawget) (lua_State *L, int idx);
180LUA_API void (lua_rawgeti) (lua_State *L, int idx, int n);
181LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec);
182LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz);
183LUA_API int (lua_getmetatable) (lua_State *L, int objindex);
184LUA_API void (lua_getfenv) (lua_State *L, int idx);
185
186
187/*
188** set functions (stack -> Lua)
189*/
190LUA_API void (lua_settable) (lua_State *L, int idx);
191LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k);
192LUA_API void (lua_rawset) (lua_State *L, int idx);
193LUA_API void (lua_rawseti) (lua_State *L, int idx, int n);
194LUA_API int (lua_setmetatable) (lua_State *L, int objindex);
195LUA_API int (lua_setfenv) (lua_State *L, int idx);
196
197
198/*
199** `load' and `call' functions (load and run Lua code)
200*/
201LUA_API void (lua_call) (lua_State *L, int nargs, int nresults);
202LUA_API int (lua_pcall) (lua_State *L, int nargs, int nresults, int errfunc);
203LUA_API int (lua_cpcall) (lua_State *L, lua_CFunction func, void *ud);
204LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt,
205 const char *chunkname);
206
207LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data);
208
209
210/*
211** coroutine functions
212*/
213LUA_API int (lua_yield) (lua_State *L, int nresults);
214LUA_API int (lua_resume) (lua_State *L, int narg);
215LUA_API int (lua_status) (lua_State *L);
216
217/*
218** garbage-collection function and options
219*/
220
221#define LUA_GCSTOP 0
222#define LUA_GCRESTART 1
223#define LUA_GCCOLLECT 2
224#define LUA_GCCOUNT 3
225#define LUA_GCCOUNTB 4
226#define LUA_GCSTEP 5
227#define LUA_GCSETPAUSE 6
228#define LUA_GCSETSTEPMUL 7
229
230LUA_API int (lua_gc) (lua_State *L, int what, int data);
231
232
233/*
234** miscellaneous functions
235*/
236
237LUA_API int (lua_error) (lua_State *L);
238
239LUA_API int (lua_next) (lua_State *L, int idx);
240
241LUA_API void (lua_concat) (lua_State *L, int n);
242
243LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud);
244LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);
245
246
247
248/*
249** ===============================================================
250** some useful macros
251** ===============================================================
252*/
253
254#define lua_pop(L,n) lua_settop(L, -(n)-1)
255
256#define lua_newtable(L) lua_createtable(L, 0, 0)
257
258#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))
259
260#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0)
261
262#define lua_strlen(L,i) lua_objlen(L, (i))
263
264#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION)
265#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE)
266#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA)
267#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL)
268#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN)
269#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD)
270#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE)
271#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0)
272
273#define lua_pushliteral(L, s) \
274 lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1)
275
276#define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, (s))
277#define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, (s))
278
279#define lua_tostring(L,i) lua_tolstring(L, (i), NULL)
280
281
282
283/*
284** compatibility macros and functions
285*/
286
287#define lua_open() luaL_newstate()
288
289#define lua_getregistry(L) lua_pushvalue(L, LUA_REGISTRYINDEX)
290
291#define lua_getgccount(L) lua_gc(L, LUA_GCCOUNT, 0)
292
293#define lua_Chunkreader lua_Reader
294#define lua_Chunkwriter lua_Writer
295
296
297/* hack */
298LUA_API void lua_setlevel (lua_State *from, lua_State *to);
299
300
301/*
302** {======================================================================
303** Debug API
304** =======================================================================
305*/
306
307
308/*
309** Event codes
310*/
311#define LUA_HOOKCALL 0
312#define LUA_HOOKRET 1
313#define LUA_HOOKLINE 2
314#define LUA_HOOKCOUNT 3
315#define LUA_HOOKTAILRET 4
316
317
318/*
319** Event masks
320*/
321#define LUA_MASKCALL (1 << LUA_HOOKCALL)
322#define LUA_MASKRET (1 << LUA_HOOKRET)
323#define LUA_MASKLINE (1 << LUA_HOOKLINE)
324#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT)
325
326typedef struct lua_Debug lua_Debug; /* activation record */
327
328
329/* Functions to be called by the debuger in specific events */
330typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
331
332
333LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar);
334LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
335LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
336LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);
337LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n);
338LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n);
339
340LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count);
341LUA_API lua_Hook lua_gethook (lua_State *L);
342LUA_API int lua_gethookmask (lua_State *L);
343LUA_API int lua_gethookcount (lua_State *L);
344
345
346struct lua_Debug {
347 int event;
348 const char *name; /* (n) */
349 const char *namewhat; /* (n) `global', `local', `field', `method' */
350 const char *what; /* (S) `Lua', `C', `main', `tail' */
351 const char *source; /* (S) */
352 int currentline; /* (l) */
353 int nups; /* (u) number of upvalues */
354 int linedefined; /* (S) */
355 int lastlinedefined; /* (S) */
356 char short_src[LUA_IDSIZE]; /* (S) */
357 /* private part */
358 int i_ci; /* active function */
359};
360
361/* }====================================================================== */
362
363
364/******************************************************************************
365* Copyright (C) 1994-2008 Lua.org, PUC-Rio. All rights reserved.
366*
367* Permission is hereby granted, free of charge, to any person obtaining
368* a copy of this software and associated documentation files (the
369* "Software"), to deal in the Software without restriction, including
370* without limitation the rights to use, copy, modify, merge, publish,
371* distribute, sublicense, and/or sell copies of the Software, and to
372* permit persons to whom the Software is furnished to do so, subject to
373* the following conditions:
374*
375* The above copyright notice and this permission notice shall be
376* included in all copies or substantial portions of the Software.
377*
378* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
379* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
380* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
381* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
382* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
383* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
384* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
385******************************************************************************/
386
387
388#endif
diff --git a/apps/plugins/lua/lua.make b/apps/plugins/lua/lua.make
new file mode 100644
index 0000000000..6688f2d3d8
--- /dev/null
+++ b/apps/plugins/lua/lua.make
@@ -0,0 +1,46 @@
1# __________ __ ___.
2# Open \______ \ ____ ____ | | _\_ |__ _______ ___
3# Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
4# Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
5# Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
6# \/ \/ \/ \/ \/
7# $Id$
8#
9
10LUA_SRCDIR := $(APPSDIR)/plugins/lua
11LUA_BUILDDIR := $(BUILDDIR)/apps/plugins/lua
12
13LUA_SRC := $(call preprocess, $(LUA_SRCDIR)/SOURCES)
14LUA_OBJ := $(call c2obj, $(LUA_SRC))
15
16OTHER_SRC += $(LUA_SRC)
17
18ifndef SIMVER
19ifneq (,$(strip $(foreach tgt,RECORDER ONDIO,$(findstring $(tgt),$(TARGET)))))
20 ### lowmem targets
21 ROCKS += $(LUA_BUILDDIR)/lua.ovl
22 LUA_OUTLDS = $(LUA_BUILDDIR)/lua.link
23 LUA_OVLFLAGS = -T$(LUA_OUTLDS) -Wl,--gc-sections -Wl,-Map,$(basename $@).map
24else
25 ### all other targets
26 ROCKS += $(LUA_BUILDDIR)/lua.rock
27endif
28else
29 ### simulator
30 ROCKS += $(LUA_BUILDDIR)/lua.rock
31endif
32
33$(LUA_BUILDDIR)/lua.rock: $(LUA_OBJ)
34
35$(LUA_BUILDDIR)/lua.refmap: $(LUA_OBJ)
36
37$(LUA_OUTLDS): $(PLUGIN_LDS) $(LUA_BUILDDIR)/lua.refmap
38 $(call PRINTS,PP $(@F))$(call preprocess2file,$<,$@,-DOVERLAY_OFFSET=$(shell \
39 $(TOOLSDIR)/ovl_offset.pl $(LUA_BUILDDIR)/lua.refmap))
40
41$(LUA_BUILDDIR)/lua.ovl: $(LUA_OBJ) $(LUA_OUTLDS)
42 $(SILENT)$(CC) $(PLUGINFLAGS) -o $(basename $@).elf \
43 $(filter %.o, $^) \
44 $(filter %.a, $+) \
45 -lgcc $(LUA_OVLFLAGS)
46 $(call PRINTS,LD $(@F))$(OC) -O binary $(basename $@).elf $@
diff --git a/apps/plugins/lua/luaconf.h b/apps/plugins/lua/luaconf.h
new file mode 100644
index 0000000000..478ea14530
--- /dev/null
+++ b/apps/plugins/lua/luaconf.h
@@ -0,0 +1,763 @@
1/*
2** $Id$
3** Configuration file for Lua
4** See Copyright Notice in lua.h
5*/
6
7
8#ifndef lconfig_h
9#define lconfig_h
10
11#include <limits.h>
12#include <stddef.h>
13
14
15/*
16** ==================================================================
17** Search for "@@" to find all configurable definitions.
18** ===================================================================
19*/
20
21
22/*
23@@ LUA_ANSI controls the use of non-ansi features.
24** CHANGE it (define it) if you want Lua to avoid the use of any
25** non-ansi feature or library.
26*/
27#if defined(__STRICT_ANSI__)
28#define LUA_ANSI
29#endif
30
31
32#if !defined(LUA_ANSI) && defined(_WIN32)
33#define LUA_WIN
34#endif
35
36#if defined(LUA_USE_LINUX)
37#define LUA_USE_POSIX
38#define LUA_USE_DLOPEN /* needs an extra library: -ldl */
39#define LUA_USE_READLINE /* needs some extra libraries */
40#endif
41
42#if defined(LUA_USE_MACOSX)
43#define LUA_USE_POSIX
44#define LUA_DL_DYLD /* does not need extra library */
45#endif
46
47
48
49/*
50@@ LUA_USE_POSIX includes all functionallity listed as X/Open System
51@* Interfaces Extension (XSI).
52** CHANGE it (define it) if your system is XSI compatible.
53*/
54#if defined(LUA_USE_POSIX)
55#define LUA_USE_MKSTEMP
56#define LUA_USE_ISATTY
57#define LUA_USE_POPEN
58#define LUA_USE_ULONGJMP
59#endif
60
61
62/*
63@@ LUA_PATH and LUA_CPATH are the names of the environment variables that
64@* Lua check to set its paths.
65@@ LUA_INIT is the name of the environment variable that Lua
66@* checks for initialization code.
67** CHANGE them if you want different names.
68*/
69#define LUA_PATH "LUA_PATH"
70#define LUA_CPATH "LUA_CPATH"
71#define LUA_INIT "LUA_INIT"
72
73
74/*
75@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for
76@* Lua libraries.
77@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for
78@* C libraries.
79** CHANGE them if your machine has a non-conventional directory
80** hierarchy or if you want to install your libraries in
81** non-conventional directories.
82*/
83#if defined(_WIN32)
84/*
85** In Windows, any exclamation mark ('!') in the path is replaced by the
86** path of the directory of the executable file of the current process.
87*/
88#define LUA_LDIR "!\\lua\\"
89#define LUA_CDIR "!\\"
90#define LUA_PATH_DEFAULT \
91 ".\\?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \
92 LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua"
93#define LUA_CPATH_DEFAULT \
94 ".\\?.dll;" LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll"
95
96#else
97#define LUA_ROOT "/usr/local/"
98#define LUA_LDIR LUA_ROOT "share/lua/5.1/"
99#define LUA_CDIR LUA_ROOT "lib/lua/5.1/"
100#define LUA_PATH_DEFAULT \
101 "./?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \
102 LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua"
103#define LUA_CPATH_DEFAULT \
104 "./?.so;" LUA_CDIR"?.so;" LUA_CDIR"loadall.so"
105#endif
106
107
108/*
109@@ LUA_DIRSEP is the directory separator (for submodules).
110** CHANGE it if your machine does not use "/" as the directory separator
111** and is not Windows. (On Windows Lua automatically uses "\".)
112*/
113#if defined(_WIN32)
114#define LUA_DIRSEP "\\"
115#else
116#define LUA_DIRSEP "/"
117#endif
118
119
120/*
121@@ LUA_PATHSEP is the character that separates templates in a path.
122@@ LUA_PATH_MARK is the string that marks the substitution points in a
123@* template.
124@@ LUA_EXECDIR in a Windows path is replaced by the executable's
125@* directory.
126@@ LUA_IGMARK is a mark to ignore all before it when bulding the
127@* luaopen_ function name.
128** CHANGE them if for some reason your system cannot use those
129** characters. (E.g., if one of those characters is a common character
130** in file/directory names.) Probably you do not need to change them.
131*/
132#define LUA_PATHSEP ";"
133#define LUA_PATH_MARK "?"
134#define LUA_EXECDIR "!"
135#define LUA_IGMARK "-"
136
137
138/*
139@@ LUA_INTEGER is the integral type used by lua_pushinteger/lua_tointeger.
140** CHANGE that if ptrdiff_t is not adequate on your machine. (On most
141** machines, ptrdiff_t gives a good choice between int or long.)
142*/
143#define LUA_INTEGER ptrdiff_t
144
145
146/*
147@@ LUA_API is a mark for all core API functions.
148@@ LUALIB_API is a mark for all standard library functions.
149** CHANGE them if you need to define those functions in some special way.
150** For instance, if you want to create one Windows DLL with the core and
151** the libraries, you may want to use the following definition (define
152** LUA_BUILD_AS_DLL to get it).
153*/
154#if defined(LUA_BUILD_AS_DLL)
155
156#if defined(LUA_CORE) || defined(LUA_LIB)
157#define LUA_API __declspec(dllexport)
158#else
159#define LUA_API __declspec(dllimport)
160#endif
161
162#else
163
164#define LUA_API extern
165
166#endif
167
168/* more often than not the libs go together with the core */
169#define LUALIB_API LUA_API
170
171
172/*
173@@ LUAI_FUNC is a mark for all extern functions that are not to be
174@* exported to outside modules.
175@@ LUAI_DATA is a mark for all extern (const) variables that are not to
176@* be exported to outside modules.
177** CHANGE them if you need to mark them in some special way. Elf/gcc
178** (versions 3.2 and later) mark them as "hidden" to optimize access
179** when Lua is compiled as a shared library.
180*/
181#if defined(luaall_c)
182#define LUAI_FUNC static
183#define LUAI_DATA /* empty */
184
185#elif defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \
186 defined(__ELF__)
187#define LUAI_FUNC __attribute__((visibility("hidden"))) extern
188#define LUAI_DATA LUAI_FUNC
189
190#else
191#define LUAI_FUNC extern
192#define LUAI_DATA extern
193#endif
194
195
196
197/*
198@@ LUA_QL describes how error messages quote program elements.
199** CHANGE it if you want a different appearance.
200*/
201#define LUA_QL(x) "'" x "'"
202#define LUA_QS LUA_QL("%s")
203
204
205/*
206@@ LUA_IDSIZE gives the maximum size for the description of the source
207@* of a function in debug information.
208** CHANGE it if you want a different size.
209*/
210#define LUA_IDSIZE 60
211
212
213/*
214** {==================================================================
215** Stand-alone configuration
216** ===================================================================
217*/
218
219#if defined(lua_c) || defined(luaall_c)
220
221/*
222@@ lua_stdin_is_tty detects whether the standard input is a 'tty' (that
223@* is, whether we're running lua interactively).
224** CHANGE it if you have a better definition for non-POSIX/non-Windows
225** systems.
226*/
227#if defined(LUA_USE_ISATTY)
228#include <unistd.h>
229#define lua_stdin_is_tty() isatty(0)
230#elif defined(LUA_WIN)
231#include <io.h>
232#include <stdio.h>
233#define lua_stdin_is_tty() _isatty(_fileno(stdin))
234#else
235#define lua_stdin_is_tty() 1 /* assume stdin is a tty */
236#endif
237
238
239/*
240@@ LUA_PROMPT is the default prompt used by stand-alone Lua.
241@@ LUA_PROMPT2 is the default continuation prompt used by stand-alone Lua.
242** CHANGE them if you want different prompts. (You can also change the
243** prompts dynamically, assigning to globals _PROMPT/_PROMPT2.)
244*/
245#define LUA_PROMPT "> "
246#define LUA_PROMPT2 ">> "
247
248
249/*
250@@ LUA_PROGNAME is the default name for the stand-alone Lua program.
251** CHANGE it if your stand-alone interpreter has a different name and
252** your system is not able to detect that name automatically.
253*/
254#define LUA_PROGNAME "lua"
255
256
257/*
258@@ LUA_MAXINPUT is the maximum length for an input line in the
259@* stand-alone interpreter.
260** CHANGE it if you need longer lines.
261*/
262#define LUA_MAXINPUT 512
263
264
265/*
266@@ lua_readline defines how to show a prompt and then read a line from
267@* the standard input.
268@@ lua_saveline defines how to "save" a read line in a "history".
269@@ lua_freeline defines how to free a line read by lua_readline.
270** CHANGE them if you want to improve this functionality (e.g., by using
271** GNU readline and history facilities).
272*/
273#if defined(LUA_USE_READLINE)
274#include <stdio.h>
275#include <readline/readline.h>
276#include <readline/history.h>
277#define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL)
278#define lua_saveline(L,idx) \
279 if (lua_strlen(L,idx) > 0) /* non-empty line? */ \
280 add_history(lua_tostring(L, idx)); /* add it to history */
281#define lua_freeline(L,b) ((void)L, free(b))
282#else
283#define lua_readline(L,b,p) \
284 ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \
285 fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */
286#define lua_saveline(L,idx) { (void)L; (void)idx; }
287#define lua_freeline(L,b) { (void)L; (void)b; }
288#endif
289
290#endif
291
292/* }================================================================== */
293
294
295/*
296@@ LUAI_GCPAUSE defines the default pause between garbage-collector cycles
297@* as a percentage.
298** CHANGE it if you want the GC to run faster or slower (higher values
299** mean larger pauses which mean slower collection.) You can also change
300** this value dynamically.
301*/
302#define LUAI_GCPAUSE 200 /* 200% (wait memory to double before next GC) */
303
304
305/*
306@@ LUAI_GCMUL defines the default speed of garbage collection relative to
307@* memory allocation as a percentage.
308** CHANGE it if you want to change the granularity of the garbage
309** collection. (Higher values mean coarser collections. 0 represents
310** infinity, where each step performs a full collection.) You can also
311** change this value dynamically.
312*/
313#define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */
314
315
316
317/*
318@@ LUA_COMPAT_GETN controls compatibility with old getn behavior.
319** CHANGE it (define it) if you want exact compatibility with the
320** behavior of setn/getn in Lua 5.0.
321*/
322#undef LUA_COMPAT_GETN
323
324/*
325@@ LUA_COMPAT_LOADLIB controls compatibility about global loadlib.
326** CHANGE it to undefined as soon as you do not need a global 'loadlib'
327** function (the function is still available as 'package.loadlib').
328*/
329#undef LUA_COMPAT_LOADLIB
330
331/*
332@@ LUA_COMPAT_VARARG controls compatibility with old vararg feature.
333** CHANGE it to undefined as soon as your programs use only '...' to
334** access vararg parameters (instead of the old 'arg' table).
335*/
336#undef LUA_COMPAT_VARARG
337
338/*
339@@ LUA_COMPAT_MOD controls compatibility with old math.mod function.
340** CHANGE it to undefined as soon as your programs use 'math.fmod' or
341** the new '%' operator instead of 'math.mod'.
342*/
343#undef LUA_COMPAT_MOD
344
345/*
346@@ LUA_COMPAT_LSTR controls compatibility with old long string nesting
347@* facility.
348** CHANGE it to 2 if you want the old behaviour, or undefine it to turn
349** off the advisory error when nesting [[...]].
350*/
351#undef LUA_COMPAT_LSTR
352
353/*
354@@ LUA_COMPAT_GFIND controls compatibility with old 'string.gfind' name.
355** CHANGE it to undefined as soon as you rename 'string.gfind' to
356** 'string.gmatch'.
357*/
358#undef LUA_COMPAT_GFIND
359
360/*
361@@ LUA_COMPAT_OPENLIB controls compatibility with old 'luaL_openlib'
362@* behavior.
363** CHANGE it to undefined as soon as you replace to 'luaL_registry'
364** your uses of 'luaL_openlib'
365*/
366#undef LUA_COMPAT_OPENLIB
367
368
369
370/*
371@@ luai_apicheck is the assert macro used by the Lua-C API.
372** CHANGE luai_apicheck if you want Lua to perform some checks in the
373** parameters it gets from API calls. This may slow down the interpreter
374** a bit, but may be quite useful when debugging C code that interfaces
375** with Lua. A useful redefinition is to use assert.h.
376*/
377#if defined(LUA_USE_APICHECK)
378#include <assert.h>
379#define luai_apicheck(L,o) { (void)L; assert(o); }
380#else
381#define luai_apicheck(L,o) { (void)L; }
382#endif
383
384
385/*
386@@ LUAI_BITSINT defines the number of bits in an int.
387** CHANGE here if Lua cannot automatically detect the number of bits of
388** your machine. Probably you do not need to change this.
389*/
390/* avoid overflows in comparison */
391#if INT_MAX-20 < 32760
392#define LUAI_BITSINT 16
393#elif INT_MAX > 2147483640L
394/* int has at least 32 bits */
395#define LUAI_BITSINT 32
396#else
397#error "you must define LUA_BITSINT with number of bits in an integer"
398#endif
399
400
401/*
402@@ LUAI_UINT32 is an unsigned integer with at least 32 bits.
403@@ LUAI_INT32 is an signed integer with at least 32 bits.
404@@ LUAI_UMEM is an unsigned integer big enough to count the total
405@* memory used by Lua.
406@@ LUAI_MEM is a signed integer big enough to count the total memory
407@* used by Lua.
408** CHANGE here if for some weird reason the default definitions are not
409** good enough for your machine. (The definitions in the 'else'
410** part always works, but may waste space on machines with 64-bit
411** longs.) Probably you do not need to change this.
412*/
413#if LUAI_BITSINT >= 32
414#define LUAI_UINT32 unsigned int
415#define LUAI_INT32 int
416#define LUAI_MAXINT32 INT_MAX
417#define LUAI_UMEM size_t
418#define LUAI_MEM ptrdiff_t
419#else
420/* 16-bit ints */
421#define LUAI_UINT32 unsigned long
422#define LUAI_INT32 long
423#define LUAI_MAXINT32 LONG_MAX
424#define LUAI_UMEM unsigned long
425#define LUAI_MEM long
426#endif
427
428
429/*
430@@ LUAI_MAXCALLS limits the number of nested calls.
431** CHANGE it if you need really deep recursive calls. This limit is
432** arbitrary; its only purpose is to stop infinite recursion before
433** exhausting memory.
434*/
435#define LUAI_MAXCALLS 20000
436
437
438/*
439@@ LUAI_MAXCSTACK limits the number of Lua stack slots that a C function
440@* can use.
441** CHANGE it if you need lots of (Lua) stack space for your C
442** functions. This limit is arbitrary; its only purpose is to stop C
443** functions to consume unlimited stack space. (must be smaller than
444** -LUA_REGISTRYINDEX)
445*/
446#define LUAI_MAXCSTACK 8000
447
448
449
450/*
451** {==================================================================
452** CHANGE (to smaller values) the following definitions if your system
453** has a small C stack. (Or you may want to change them to larger
454** values if your system has a large C stack and these limits are
455** too rigid for you.) Some of these constants control the size of
456** stack-allocated arrays used by the compiler or the interpreter, while
457** others limit the maximum number of recursive calls that the compiler
458** or the interpreter can perform. Values too large may cause a C stack
459** overflow for some forms of deep constructs.
460** ===================================================================
461*/
462
463
464/*
465@@ LUAI_MAXCCALLS is the maximum depth for nested C calls (short) and
466@* syntactical nested non-terminals in a program.
467*/
468#define LUAI_MAXCCALLS 200
469
470
471/*
472@@ LUAI_MAXVARS is the maximum number of local variables per function
473@* (must be smaller than 250).
474*/
475#define LUAI_MAXVARS 200
476
477
478/*
479@@ LUAI_MAXUPVALUES is the maximum number of upvalues per function
480@* (must be smaller than 250).
481*/
482#define LUAI_MAXUPVALUES 60
483
484
485/*
486@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system.
487*/
488#define LUAL_BUFFERSIZE 1024
489
490/* }================================================================== */
491
492
493
494
495/*
496** {==================================================================
497@@ LUA_NUMBER is the type of numbers in Lua.
498** CHANGE the following definitions only if you want to build Lua
499** with a number type different from double. You may also need to
500** change lua_number2int & lua_number2integer.
501** ===================================================================
502*/
503
504#undef LUA_NUMBER_DOUBLE
505#define LUA_NUMBER long
506
507/*
508@@ LUAI_UACNUMBER is the result of an 'usual argument conversion'
509@* over a number.
510*/
511#define LUAI_UACNUMBER long
512
513
514/*
515@@ LUA_NUMBER_SCAN is the format for reading numbers.
516@@ LUA_NUMBER_FMT is the format for writing numbers.
517@@ lua_number2str converts a number to a string.
518@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion.
519@@ lua_str2number converts a string to a number.
520*/
521#define LUA_NUMBER_SCAN "%ld"
522#define LUA_NUMBER_FMT "%ld"
523#define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */
524#define lua_number2str(s,n) snprintf((s), 32, LUA_NUMBER_FMT, (n))
525#define lua_str2number(s,p) strtol((s), (p), 10)
526
527
528/*
529@@ The luai_num* macros define the primitive operations over numbers.
530*/
531#if defined(LUA_CORE)
532#include <math.h>
533#define luai_numadd(a,b) ((a)+(b))
534#define luai_numsub(a,b) ((a)-(b))
535#define luai_nummul(a,b) ((a)*(b))
536#define luai_numdiv(a,b) ((a)/(b))
537#define luai_nummod(a,b) ((a) - floor((a)/(b))*(b))
538#define luai_numpow(a,b) (pow(a,b))
539#define luai_numunm(a) (-(a))
540#define luai_numeq(a,b) ((a)==(b))
541#define luai_numlt(a,b) ((a)<(b))
542#define luai_numle(a,b) ((a)<=(b))
543#define luai_numisnan(a) (!luai_numeq((a), (a)))
544#endif
545
546
547/*
548@@ lua_number2int is a macro to convert lua_Number to int.
549@@ lua_number2integer is a macro to convert lua_Number to lua_Integer.
550** CHANGE them if you know a faster way to convert a lua_Number to
551** int (with any rounding method and without throwing errors) in your
552** system. In Pentium machines, a naive typecast from double to int
553** in C is extremely slow, so any alternative is worth trying.
554*/
555
556/* On a Pentium, resort to a trick */
557#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) && !defined(__SSE2__) && \
558 (defined(__i386) || defined (_M_IX86) || defined(__i386__))
559
560/* On a Microsoft compiler, use assembler */
561#if defined(_MSC_VER)
562
563#define lua_number2int(i,d) __asm fld d __asm fistp i
564#define lua_number2integer(i,n) lua_number2int(i, n)
565
566/* the next trick should work on any Pentium, but sometimes clashes
567 with a DirectX idiosyncrasy */
568#else
569
570union luai_Cast { double l_d; long l_l; };
571#define lua_number2int(i,d) \
572 { volatile union luai_Cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; }
573#define lua_number2integer(i,n) lua_number2int(i, n)
574
575#endif
576
577
578/* this option always works, but may be slow */
579#else
580#define lua_number2int(i,d) ((i)=(int)(d))
581#define lua_number2integer(i,d) ((i)=(lua_Integer)(d))
582
583#endif
584
585/* }================================================================== */
586
587
588/*
589@@ LUAI_USER_ALIGNMENT_T is a type that requires maximum alignment.
590** CHANGE it if your system requires alignments larger than double. (For
591** instance, if your system supports long doubles and they must be
592** aligned in 16-byte boundaries, then you should add long double in the
593** union.) Probably you do not need to change this.
594*/
595#define LUAI_USER_ALIGNMENT_T union { void *s; long l; }
596
597
598/*
599@@ LUAI_THROW/LUAI_TRY define how Lua does exception handling.
600** CHANGE them if you prefer to use longjmp/setjmp even with C++
601** or if want/don't to use _longjmp/_setjmp instead of regular
602** longjmp/setjmp. By default, Lua handles errors with exceptions when
603** compiling as C++ code, with _longjmp/_setjmp when asked to use them,
604** and with longjmp/setjmp otherwise.
605*/
606#if defined(__cplusplus)
607/* C++ exceptions */
608#define LUAI_THROW(L,c) throw(c)
609#define LUAI_TRY(L,c,a) try { a } catch(...) \
610 { if ((c)->status == 0) (c)->status = -1; }
611#define luai_jmpbuf int /* dummy variable */
612
613#elif defined(LUA_USE_ULONGJMP)
614/* in Unix, try _longjmp/_setjmp (more efficient) */
615#define LUAI_THROW(L,c) _longjmp((c)->b, 1)
616#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a }
617#define luai_jmpbuf jmp_buf
618
619#else
620/* default handling with long jumps */
621#define LUAI_THROW(L,c) longjmp((c)->b, 1)
622#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }
623#define luai_jmpbuf jmp_buf
624
625#endif
626
627
628/*
629@@ LUA_MAXCAPTURES is the maximum number of captures that a pattern
630@* can do during pattern-matching.
631** CHANGE it if you need more captures. This limit is arbitrary.
632*/
633#define LUA_MAXCAPTURES 32
634
635
636/*
637@@ lua_tmpnam is the function that the OS library uses to create a
638@* temporary name.
639@@ LUA_TMPNAMBUFSIZE is the maximum size of a name created by lua_tmpnam.
640** CHANGE them if you have an alternative to tmpnam (which is considered
641** insecure) or if you want the original tmpnam anyway. By default, Lua
642** uses tmpnam except when POSIX is available, where it uses mkstemp.
643*/
644#if defined(loslib_c) || defined(luaall_c)
645
646#if defined(LUA_USE_MKSTEMP)
647#include <unistd.h>
648#define LUA_TMPNAMBUFSIZE 32
649#define lua_tmpnam(b,e) { \
650 strcpy(b, "/tmp/lua_XXXXXX"); \
651 e = mkstemp(b); \
652 if (e != -1) close(e); \
653 e = (e == -1); }
654
655#else
656#define LUA_TMPNAMBUFSIZE L_tmpnam
657#define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); }
658#endif
659
660#endif
661
662
663/*
664@@ lua_popen spawns a new process connected to the current one through
665@* the file streams.
666** CHANGE it if you have a way to implement it in your system.
667*/
668#if defined(LUA_USE_POPEN)
669
670#define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m))
671#define lua_pclose(L,file) ((void)L, (pclose(file) != -1))
672
673#elif defined(LUA_WIN)
674
675#define lua_popen(L,c,m) ((void)L, _popen(c,m))
676#define lua_pclose(L,file) ((void)L, (_pclose(file) != -1))
677
678#else
679
680#define lua_popen(L,c,m) ((void)((void)c, m), \
681 luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0)
682#define lua_pclose(L,file) ((void)((void)L, file), 0)
683
684#endif
685
686/*
687@@ LUA_DL_* define which dynamic-library system Lua should use.
688** CHANGE here if Lua has problems choosing the appropriate
689** dynamic-library system for your platform (either Windows' DLL, Mac's
690** dyld, or Unix's dlopen). If your system is some kind of Unix, there
691** is a good chance that it has dlopen, so LUA_DL_DLOPEN will work for
692** it. To use dlopen you also need to adapt the src/Makefile (probably
693** adding -ldl to the linker options), so Lua does not select it
694** automatically. (When you change the makefile to add -ldl, you must
695** also add -DLUA_USE_DLOPEN.)
696** If you do not want any kind of dynamic library, undefine all these
697** options.
698** By default, _WIN32 gets LUA_DL_DLL and MAC OS X gets LUA_DL_DYLD.
699*/
700#if defined(LUA_USE_DLOPEN)
701#define LUA_DL_DLOPEN
702#endif
703
704#if defined(LUA_WIN)
705#define LUA_DL_DLL
706#endif
707
708
709/*
710@@ LUAI_EXTRASPACE allows you to add user-specific data in a lua_State
711@* (the data goes just *before* the lua_State pointer).
712** CHANGE (define) this if you really need that. This value must be
713** a multiple of the maximum alignment required for your machine.
714*/
715#define LUAI_EXTRASPACE 0
716
717
718/*
719@@ luai_userstate* allow user-specific actions on threads.
720** CHANGE them if you defined LUAI_EXTRASPACE and need to do something
721** extra when a thread is created/deleted/resumed/yielded.
722*/
723#define luai_userstateopen(L) ((void)L)
724#define luai_userstateclose(L) ((void)L)
725#define luai_userstatethread(L,L1) ((void)L)
726#define luai_userstatefree(L) ((void)L)
727#define luai_userstateresume(L,n) ((void)L)
728#define luai_userstateyield(L,n) ((void)L)
729
730
731/*
732@@ LUA_INTFRMLEN is the length modifier for integer conversions
733@* in 'string.format'.
734@@ LUA_INTFRM_T is the integer type correspoding to the previous length
735@* modifier.
736** CHANGE them if your system supports long long or does not support long.
737*/
738
739#if defined(LUA_USELONGLONG)
740
741#define LUA_INTFRMLEN "ll"
742#define LUA_INTFRM_T long long
743
744#else
745
746#define LUA_INTFRMLEN "l"
747#define LUA_INTFRM_T long
748
749#endif
750
751
752
753/* =================================================================== */
754
755/*
756** Local configuration. You can use this space to add your redefinitions
757** without modifying the main part of the file.
758*/
759
760#include "rockconf.h"
761
762#endif
763
diff --git a/apps/plugins/lua/lualib.h b/apps/plugins/lua/lualib.h
new file mode 100644
index 0000000000..33d4e314c2
--- /dev/null
+++ b/apps/plugins/lua/lualib.h
@@ -0,0 +1,53 @@
1/*
2** $Id$
3** Lua standard libraries
4** See Copyright Notice in lua.h
5*/
6
7
8#ifndef lualib_h
9#define lualib_h
10
11#include "lua.h"
12
13
14/* Key to file-handle type */
15#define LUA_FILEHANDLE "FILE*"
16
17
18#define LUA_COLIBNAME "coroutine"
19LUALIB_API int (luaopen_base) (lua_State *L);
20
21#define LUA_TABLIBNAME "table"
22LUALIB_API int (luaopen_table) (lua_State *L);
23
24#define LUA_IOLIBNAME "io"
25LUALIB_API int (luaopen_io) (lua_State *L);
26
27#define LUA_OSLIBNAME "os"
28LUALIB_API int (luaopen_os) (lua_State *L);
29
30#define LUA_STRLIBNAME "string"
31LUALIB_API int (luaopen_string) (lua_State *L);
32
33#define LUA_MATHLIBNAME "math"
34LUALIB_API int (luaopen_math) (lua_State *L);
35
36#define LUA_DBLIBNAME "debug"
37LUALIB_API int (luaopen_debug) (lua_State *L);
38
39#define LUA_LOADLIBNAME "package"
40LUALIB_API int (luaopen_package) (lua_State *L);
41
42
43/* open all previous libraries */
44LUALIB_API void (luaL_openlibs) (lua_State *L);
45
46
47
48#ifndef lua_assert
49#define lua_assert(x) ((void)0)
50#endif
51
52
53#endif
diff --git a/apps/plugins/lua/lundump.c b/apps/plugins/lua/lundump.c
new file mode 100644
index 0000000000..8010a45795
--- /dev/null
+++ b/apps/plugins/lua/lundump.c
@@ -0,0 +1,227 @@
1/*
2** $Id: lundump.c,v 2.7.1.4 2008/04/04 19:51:41 roberto Exp $
3** load precompiled Lua chunks
4** See Copyright Notice in lua.h
5*/
6
7#include <string.h>
8
9#define lundump_c
10#define LUA_CORE
11
12#include "lua.h"
13
14#include "ldebug.h"
15#include "ldo.h"
16#include "lfunc.h"
17#include "lmem.h"
18#include "lobject.h"
19#include "lstring.h"
20#include "lundump.h"
21#include "lzio.h"
22
23typedef struct {
24 lua_State* L;
25 ZIO* Z;
26 Mbuffer* b;
27 const char* name;
28} LoadState;
29
30#ifdef LUAC_TRUST_BINARIES
31#define IF(c,s)
32#define error(S,s)
33#else
34#define IF(c,s) if (c) error(S,s)
35
36static void error(LoadState* S, const char* why)
37{
38 luaO_pushfstring(S->L,"%s: %s in precompiled chunk",S->name,why);
39 luaD_throw(S->L,LUA_ERRSYNTAX);
40}
41#endif
42
43#define LoadMem(S,b,n,size) LoadBlock(S,b,(n)*(size))
44#define LoadByte(S) (lu_byte)LoadChar(S)
45#define LoadVar(S,x) LoadMem(S,&x,1,sizeof(x))
46#define LoadVector(S,b,n,size) LoadMem(S,b,n,size)
47
48static void LoadBlock(LoadState* S, void* b, size_t size)
49{
50 size_t r=luaZ_read(S->Z,b,size);
51 IF (r!=0, "unexpected end");
52}
53
54static int LoadChar(LoadState* S)
55{
56 char x;
57 LoadVar(S,x);
58 return x;
59}
60
61static int LoadInt(LoadState* S)
62{
63 int x;
64 LoadVar(S,x);
65 IF (x<0, "bad integer");
66 return x;
67}
68
69static lua_Number LoadNumber(LoadState* S)
70{
71 lua_Number x;
72 LoadVar(S,x);
73 return x;
74}
75
76static TString* LoadString(LoadState* S)
77{
78 size_t size;
79 LoadVar(S,size);
80 if (size==0)
81 return NULL;
82 else
83 {
84 char* s=luaZ_openspace(S->L,S->b,size);
85 LoadBlock(S,s,size);
86 return luaS_newlstr(S->L,s,size-1); /* remove trailing '\0' */
87 }
88}
89
90static void LoadCode(LoadState* S, Proto* f)
91{
92 int n=LoadInt(S);
93 f->code=luaM_newvector(S->L,n,Instruction);
94 f->sizecode=n;
95 LoadVector(S,f->code,n,sizeof(Instruction));
96}
97
98static Proto* LoadFunction(LoadState* S, TString* p);
99
100static void LoadConstants(LoadState* S, Proto* f)
101{
102 int i,n;
103 n=LoadInt(S);
104 f->k=luaM_newvector(S->L,n,TValue);
105 f->sizek=n;
106 for (i=0; i<n; i++) setnilvalue(&f->k[i]);
107 for (i=0; i<n; i++)
108 {
109 TValue* o=&f->k[i];
110 int t=LoadChar(S);
111 switch (t)
112 {
113 case LUA_TNIL:
114 setnilvalue(o);
115 break;
116 case LUA_TBOOLEAN:
117 setbvalue(o,LoadChar(S)!=0);
118 break;
119 case LUA_TNUMBER:
120 setnvalue(o,LoadNumber(S));
121 break;
122 case LUA_TSTRING:
123 setsvalue2n(S->L,o,LoadString(S));
124 break;
125 default:
126 error(S,"bad constant");
127 break;
128 }
129 }
130 n=LoadInt(S);
131 f->p=luaM_newvector(S->L,n,Proto*);
132 f->sizep=n;
133 for (i=0; i<n; i++) f->p[i]=NULL;
134 for (i=0; i<n; i++) f->p[i]=LoadFunction(S,f->source);
135}
136
137static void LoadDebug(LoadState* S, Proto* f)
138{
139 int i,n;
140 n=LoadInt(S);
141 f->lineinfo=luaM_newvector(S->L,n,int);
142 f->sizelineinfo=n;
143 LoadVector(S,f->lineinfo,n,sizeof(int));
144 n=LoadInt(S);
145 f->locvars=luaM_newvector(S->L,n,LocVar);
146 f->sizelocvars=n;
147 for (i=0; i<n; i++) f->locvars[i].varname=NULL;
148 for (i=0; i<n; i++)
149 {
150 f->locvars[i].varname=LoadString(S);
151 f->locvars[i].startpc=LoadInt(S);
152 f->locvars[i].endpc=LoadInt(S);
153 }
154 n=LoadInt(S);
155 f->upvalues=luaM_newvector(S->L,n,TString*);
156 f->sizeupvalues=n;
157 for (i=0; i<n; i++) f->upvalues[i]=NULL;
158 for (i=0; i<n; i++) f->upvalues[i]=LoadString(S);
159}
160
161static Proto* LoadFunction(LoadState* S, TString* p)
162{
163 Proto* f;
164 if (++S->L->nCcalls > LUAI_MAXCCALLS) error(S,"code too deep");
165 f=luaF_newproto(S->L);
166 setptvalue2s(S->L,S->L->top,f); incr_top(S->L);
167 f->source=LoadString(S); if (f->source==NULL) f->source=p;
168 f->linedefined=LoadInt(S);
169 f->lastlinedefined=LoadInt(S);
170 f->nups=LoadByte(S);
171 f->numparams=LoadByte(S);
172 f->is_vararg=LoadByte(S);
173 f->maxstacksize=LoadByte(S);
174 LoadCode(S,f);
175 LoadConstants(S,f);
176 LoadDebug(S,f);
177 IF (!luaG_checkcode(f), "bad code");
178 S->L->top--;
179 S->L->nCcalls--;
180 return f;
181}
182
183static void LoadHeader(LoadState* S)
184{
185 char h[LUAC_HEADERSIZE];
186 char s[LUAC_HEADERSIZE];
187 luaU_header(h);
188 LoadBlock(S,s,LUAC_HEADERSIZE);
189 IF (memcmp(h,s,LUAC_HEADERSIZE)!=0, "bad header");
190}
191
192/*
193** load precompiled chunk
194*/
195Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name)
196{
197 LoadState S;
198 if (*name=='@' || *name=='=')
199 S.name=name+1;
200 else if (*name==LUA_SIGNATURE[0])
201 S.name="binary string";
202 else
203 S.name=name;
204 S.L=L;
205 S.Z=Z;
206 S.b=buff;
207 LoadHeader(&S);
208 return LoadFunction(&S,luaS_newliteral(L,"=?"));
209}
210
211/*
212* make header
213*/
214void luaU_header (char* h)
215{
216 int x=1;
217 memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-1);
218 h+=sizeof(LUA_SIGNATURE)-1;
219 *h++=(char)LUAC_VERSION;
220 *h++=(char)LUAC_FORMAT;
221 *h++=(char)*(char*)&x; /* endianness */
222 *h++=(char)sizeof(int);
223 *h++=(char)sizeof(size_t);
224 *h++=(char)sizeof(Instruction);
225 *h++=(char)sizeof(lua_Number);
226 *h++=(char)(((lua_Number)0.5)==0); /* is lua_Number integral? */
227}
diff --git a/apps/plugins/lua/lundump.h b/apps/plugins/lua/lundump.h
new file mode 100644
index 0000000000..f791a4f173
--- /dev/null
+++ b/apps/plugins/lua/lundump.h
@@ -0,0 +1,36 @@
1/*
2** $Id$
3** load precompiled Lua chunks
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lundump_h
8#define lundump_h
9
10#include "lobject.h"
11#include "lzio.h"
12
13/* load one chunk; from lundump.c */
14LUAI_FUNC Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name);
15
16/* make header; from lundump.c */
17LUAI_FUNC void luaU_header (char* h);
18
19/* dump one chunk; from ldump.c */
20LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip);
21
22#ifdef luac_c
23/* print one chunk; from print.c */
24LUAI_FUNC void luaU_print (const Proto* f, int full);
25#endif
26
27/* for header of binary files -- this is Lua 5.1 */
28#define LUAC_VERSION 0x51
29
30/* for header of binary files -- this is the official format */
31#define LUAC_FORMAT 0
32
33/* size of header of binary files */
34#define LUAC_HEADERSIZE 12
35
36#endif
diff --git a/apps/plugins/lua/lvm.c b/apps/plugins/lua/lvm.c
new file mode 100644
index 0000000000..ee3256ab94
--- /dev/null
+++ b/apps/plugins/lua/lvm.c
@@ -0,0 +1,763 @@
1/*
2** $Id: lvm.c,v 2.63.1.3 2007/12/28 15:32:23 roberto Exp $
3** Lua virtual machine
4** See Copyright Notice in lua.h
5*/
6
7
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11
12#define lvm_c
13#define LUA_CORE
14
15#include "lua.h"
16
17#include "ldebug.h"
18#include "ldo.h"
19#include "lfunc.h"
20#include "lgc.h"
21#include "lobject.h"
22#include "lopcodes.h"
23#include "lstate.h"
24#include "lstring.h"
25#include "ltable.h"
26#include "ltm.h"
27#include "lvm.h"
28
29
30
31/* limit for table tag-method chains (to avoid loops) */
32#define MAXTAGLOOP 100
33
34
35const TValue *luaV_tonumber (const TValue *obj, TValue *n) {
36 lua_Number num;
37 if (ttisnumber(obj)) return obj;
38 if (ttisstring(obj) && luaO_str2d(svalue(obj), &num)) {
39 setnvalue(n, num);
40 return n;
41 }
42 else
43 return NULL;
44}
45
46
47int luaV_tostring (lua_State *L, StkId obj) {
48 if (!ttisnumber(obj))
49 return 0;
50 else {
51 char s[LUAI_MAXNUMBER2STR];
52 lua_Number n = nvalue(obj);
53 lua_number2str(s, n);
54 setsvalue2s(L, obj, luaS_new(L, s));
55 return 1;
56 }
57}
58
59
60static void traceexec (lua_State *L, const Instruction *pc) {
61 lu_byte mask = L->hookmask;
62 const Instruction *oldpc = L->savedpc;
63 L->savedpc = pc;
64 if ((mask & LUA_MASKCOUNT) && L->hookcount == 0) {
65 resethookcount(L);
66 luaD_callhook(L, LUA_HOOKCOUNT, -1);
67 }
68 if (mask & LUA_MASKLINE) {
69 Proto *p = ci_func(L->ci)->l.p;
70 int npc = pcRel(pc, p);
71 int newline = getline(p, npc);
72 /* call linehook when enter a new function, when jump back (loop),
73 or when enter a new line */
74 if (npc == 0 || pc <= oldpc || newline != getline(p, pcRel(oldpc, p)))
75 luaD_callhook(L, LUA_HOOKLINE, newline);
76 }
77}
78
79
80static void callTMres (lua_State *L, StkId res, const TValue *f,
81 const TValue *p1, const TValue *p2) {
82 ptrdiff_t result = savestack(L, res);
83 setobj2s(L, L->top, f); /* push function */
84 setobj2s(L, L->top+1, p1); /* 1st argument */
85 setobj2s(L, L->top+2, p2); /* 2nd argument */
86 luaD_checkstack(L, 3);
87 L->top += 3;
88 luaD_call(L, L->top - 3, 1);
89 res = restorestack(L, result);
90 L->top--;
91 setobjs2s(L, res, L->top);
92}
93
94
95
96static void callTM (lua_State *L, const TValue *f, const TValue *p1,
97 const TValue *p2, const TValue *p3) {
98 setobj2s(L, L->top, f); /* push function */
99 setobj2s(L, L->top+1, p1); /* 1st argument */
100 setobj2s(L, L->top+2, p2); /* 2nd argument */
101 setobj2s(L, L->top+3, p3); /* 3th argument */
102 luaD_checkstack(L, 4);
103 L->top += 4;
104 luaD_call(L, L->top - 4, 0);
105}
106
107
108void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) {
109 int loop;
110 for (loop = 0; loop < MAXTAGLOOP; loop++) {
111 const TValue *tm;
112 if (ttistable(t)) { /* `t' is a table? */
113 Table *h = hvalue(t);
114 const TValue *res = luaH_get(h, key); /* do a primitive get */
115 if (!ttisnil(res) || /* result is no nil? */
116 (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */
117 setobj2s(L, val, res);
118 return;
119 }
120 /* else will try the tag method */
121 }
122 else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX)))
123 luaG_typeerror(L, t, "index");
124 if (ttisfunction(tm)) {
125 callTMres(L, val, tm, t, key);
126 return;
127 }
128 t = tm; /* else repeat with `tm' */
129 }
130 luaG_runerror(L, "loop in gettable");
131}
132
133
134void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) {
135 int loop;
136 for (loop = 0; loop < MAXTAGLOOP; loop++) {
137 const TValue *tm;
138 if (ttistable(t)) { /* `t' is a table? */
139 Table *h = hvalue(t);
140 TValue *oldval = luaH_set(L, h, key); /* do a primitive set */
141 if (!ttisnil(oldval) || /* result is no nil? */
142 (tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL) { /* or no TM? */
143 setobj2t(L, oldval, val);
144 luaC_barriert(L, h, val);
145 return;
146 }
147 /* else will try the tag method */
148 }
149 else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX)))
150 luaG_typeerror(L, t, "index");
151 if (ttisfunction(tm)) {
152 callTM(L, tm, t, key, val);
153 return;
154 }
155 t = tm; /* else repeat with `tm' */
156 }
157 luaG_runerror(L, "loop in settable");
158}
159
160
161static int call_binTM (lua_State *L, const TValue *p1, const TValue *p2,
162 StkId res, TMS event) {
163 const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */
164 if (ttisnil(tm))
165 tm = luaT_gettmbyobj(L, p2, event); /* try second operand */
166 if (ttisnil(tm)) return 0;
167 callTMres(L, res, tm, p1, p2);
168 return 1;
169}
170
171
172static const TValue *get_compTM (lua_State *L, Table *mt1, Table *mt2,
173 TMS event) {
174 const TValue *tm1 = fasttm(L, mt1, event);
175 const TValue *tm2;
176 if (tm1 == NULL) return NULL; /* no metamethod */
177 if (mt1 == mt2) return tm1; /* same metatables => same metamethods */
178 tm2 = fasttm(L, mt2, event);
179 if (tm2 == NULL) return NULL; /* no metamethod */
180 if (luaO_rawequalObj(tm1, tm2)) /* same metamethods? */
181 return tm1;
182 return NULL;
183}
184
185
186static int call_orderTM (lua_State *L, const TValue *p1, const TValue *p2,
187 TMS event) {
188 const TValue *tm1 = luaT_gettmbyobj(L, p1, event);
189 const TValue *tm2;
190 if (ttisnil(tm1)) return -1; /* no metamethod? */
191 tm2 = luaT_gettmbyobj(L, p2, event);
192 if (!luaO_rawequalObj(tm1, tm2)) /* different metamethods? */
193 return -1;
194 callTMres(L, L->top, tm1, p1, p2);
195 return !l_isfalse(L->top);
196}
197
198
199static int l_strcmp (const TString *ls, const TString *rs) {
200 const char *l = getstr(ls);
201 size_t ll = ls->tsv.len;
202 const char *r = getstr(rs);
203 size_t lr = rs->tsv.len;
204 for (;;) {
205 int temp = strcoll(l, r);
206 if (temp != 0) return temp;
207 else { /* strings are equal up to a `\0' */
208 size_t len = strlen(l); /* index of first `\0' in both strings */
209 if (len == lr) /* r is finished? */
210 return (len == ll) ? 0 : 1;
211 else if (len == ll) /* l is finished? */
212 return -1; /* l is smaller than r (because r is not finished) */
213 /* both strings longer than `len'; go on comparing (after the `\0') */
214 len++;
215 l += len; ll -= len; r += len; lr -= len;
216 }
217 }
218}
219
220
221int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {
222 int res;
223 if (ttype(l) != ttype(r))
224 return luaG_ordererror(L, l, r);
225 else if (ttisnumber(l))
226 return luai_numlt(nvalue(l), nvalue(r));
227 else if (ttisstring(l))
228 return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0;
229 else if ((res = call_orderTM(L, l, r, TM_LT)) != -1)
230 return res;
231 return luaG_ordererror(L, l, r);
232}
233
234
235static int lessequal (lua_State *L, const TValue *l, const TValue *r) {
236 int res;
237 if (ttype(l) != ttype(r))
238 return luaG_ordererror(L, l, r);
239 else if (ttisnumber(l))
240 return luai_numle(nvalue(l), nvalue(r));
241 else if (ttisstring(l))
242 return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0;
243 else if ((res = call_orderTM(L, l, r, TM_LE)) != -1) /* first try `le' */
244 return res;
245 else if ((res = call_orderTM(L, r, l, TM_LT)) != -1) /* else try `lt' */
246 return !res;
247 return luaG_ordererror(L, l, r);
248}
249
250
251int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2) {
252 const TValue *tm;
253 lua_assert(ttype(t1) == ttype(t2));
254 switch (ttype(t1)) {
255 case LUA_TNIL: return 1;
256 case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2));
257 case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */
258 case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);
259 case LUA_TUSERDATA: {
260 if (uvalue(t1) == uvalue(t2)) return 1;
261 tm = get_compTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable,
262 TM_EQ);
263 break; /* will try TM */
264 }
265 case LUA_TTABLE: {
266 if (hvalue(t1) == hvalue(t2)) return 1;
267 tm = get_compTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ);
268 break; /* will try TM */
269 }
270 default: return gcvalue(t1) == gcvalue(t2);
271 }
272 if (tm == NULL) return 0; /* no TM? */
273 callTMres(L, L->top, tm, t1, t2); /* call TM */
274 return !l_isfalse(L->top);
275}
276
277
278void luaV_concat (lua_State *L, int total, int last) {
279 do {
280 StkId top = L->base + last + 1;
281 int n = 2; /* number of elements handled in this pass (at least 2) */
282 if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1)) {
283 if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT))
284 luaG_concaterror(L, top-2, top-1);
285 } else if (tsvalue(top-1)->len == 0) /* second op is empty? */
286 (void)tostring(L, top - 2); /* result is first op (as string) */
287 else {
288 /* at least two string values; get as many as possible */
289 size_t tl = tsvalue(top-1)->len;
290 char *buffer;
291 int i;
292 /* collect total length */
293 for (n = 1; n < total && tostring(L, top-n-1); n++) {
294 size_t l = tsvalue(top-n-1)->len;
295 if (l >= MAX_SIZET - tl) luaG_runerror(L, "string length overflow");
296 tl += l;
297 }
298 buffer = luaZ_openspace(L, &G(L)->buff, tl);
299 tl = 0;
300 for (i=n; i>0; i--) { /* concat all strings */
301 size_t l = tsvalue(top-i)->len;
302 memcpy(buffer+tl, svalue(top-i), l);
303 tl += l;
304 }
305 setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl));
306 }
307 total -= n-1; /* got `n' strings to create 1 new */
308 last -= n-1;
309 } while (total > 1); /* repeat until only 1 result left */
310}
311
312
313static void Arith (lua_State *L, StkId ra, const TValue *rb,
314 const TValue *rc, TMS op) {
315 TValue tempb, tempc;
316 const TValue *b, *c;
317 if ((b = luaV_tonumber(rb, &tempb)) != NULL &&
318 (c = luaV_tonumber(rc, &tempc)) != NULL) {
319 lua_Number nb = nvalue(b), nc = nvalue(c);
320 switch (op) {
321 case TM_ADD: setnvalue(ra, luai_numadd(nb, nc)); break;
322 case TM_SUB: setnvalue(ra, luai_numsub(nb, nc)); break;
323 case TM_MUL: setnvalue(ra, luai_nummul(nb, nc)); break;
324 case TM_DIV: setnvalue(ra, luai_numdiv(nb, nc)); break;
325 case TM_MOD: setnvalue(ra, luai_nummod(nb, nc)); break;
326 case TM_POW: setnvalue(ra, luai_numpow(nb, nc)); break;
327 case TM_UNM: setnvalue(ra, luai_numunm(nb)); break;
328 default: lua_assert(0); break;
329 }
330 }
331 else if (!call_binTM(L, rb, rc, ra, op))
332 luaG_aritherror(L, rb, rc);
333}
334
335
336
337/*
338** some macros for common tasks in `luaV_execute'
339*/
340
341#define runtime_check(L, c) { if (!(c)) break; }
342
343#define RA(i) (base+GETARG_A(i))
344/* to be used after possible stack reallocation */
345#define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i))
346#define RC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i))
347#define RKB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \
348 ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i))
349#define RKC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \
350 ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i))
351#define KBx(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, k+GETARG_Bx(i))
352
353
354#define dojump(L,pc,i) {(pc) += (i); luai_threadyield(L);}
355
356
357#define Protect(x) { L->savedpc = pc; {x;}; base = L->base; }
358
359
360#define arith_op(op,tm) { \
361 TValue *rb = RKB(i); \
362 TValue *rc = RKC(i); \
363 if (ttisnumber(rb) && ttisnumber(rc)) { \
364 lua_Number nb = nvalue(rb), nc = nvalue(rc); \
365 setnvalue(ra, op(nb, nc)); \
366 } \
367 else \
368 Protect(Arith(L, ra, rb, rc, tm)); \
369 }
370
371
372
373void luaV_execute (lua_State *L, int nexeccalls) {
374 LClosure *cl;
375 StkId base;
376 TValue *k;
377 const Instruction *pc;
378 reentry: /* entry point */
379 lua_assert(isLua(L->ci));
380 pc = L->savedpc;
381 cl = &clvalue(L->ci->func)->l;
382 base = L->base;
383 k = cl->p->k;
384 /* main loop of interpreter */
385 for (;;) {
386 const Instruction i = *pc++;
387 StkId ra;
388 if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
389 (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
390 traceexec(L, pc);
391 if (L->status == LUA_YIELD) { /* did hook yield? */
392 L->savedpc = pc - 1;
393 return;
394 }
395 base = L->base;
396 }
397 /* warning!! several calls may realloc the stack and invalidate `ra' */
398 ra = RA(i);
399 lua_assert(base == L->base && L->base == L->ci->base);
400 lua_assert(base <= L->top && L->top <= L->stack + L->stacksize);
401 lua_assert(L->top == L->ci->top || luaG_checkopenop(i));
402 switch (GET_OPCODE(i)) {
403 case OP_MOVE: {
404 setobjs2s(L, ra, RB(i));
405 continue;
406 }
407 case OP_LOADK: {
408 setobj2s(L, ra, KBx(i));
409 continue;
410 }
411 case OP_LOADBOOL: {
412 setbvalue(ra, GETARG_B(i));
413 if (GETARG_C(i)) pc++; /* skip next instruction (if C) */
414 continue;
415 }
416 case OP_LOADNIL: {
417 TValue *rb = RB(i);
418 do {
419 setnilvalue(rb--);
420 } while (rb >= ra);
421 continue;
422 }
423 case OP_GETUPVAL: {
424 int b = GETARG_B(i);
425 setobj2s(L, ra, cl->upvals[b]->v);
426 continue;
427 }
428 case OP_GETGLOBAL: {
429 TValue g;
430 TValue *rb = KBx(i);
431 sethvalue(L, &g, cl->env);
432 lua_assert(ttisstring(rb));
433 Protect(luaV_gettable(L, &g, rb, ra));
434 continue;
435 }
436 case OP_GETTABLE: {
437 Protect(luaV_gettable(L, RB(i), RKC(i), ra));
438 continue;
439 }
440 case OP_SETGLOBAL: {
441 TValue g;
442 sethvalue(L, &g, cl->env);
443 lua_assert(ttisstring(KBx(i)));
444 Protect(luaV_settable(L, &g, KBx(i), ra));
445 continue;
446 }
447 case OP_SETUPVAL: {
448 UpVal *uv = cl->upvals[GETARG_B(i)];
449 setobj(L, uv->v, ra);
450 luaC_barrier(L, uv, ra);
451 continue;
452 }
453 case OP_SETTABLE: {
454 Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
455 continue;
456 }
457 case OP_NEWTABLE: {
458 int b = GETARG_B(i);
459 int c = GETARG_C(i);
460 sethvalue(L, ra, luaH_new(L, luaO_fb2int(b), luaO_fb2int(c)));
461 Protect(luaC_checkGC(L));
462 continue;
463 }
464 case OP_SELF: {
465 StkId rb = RB(i);
466 setobjs2s(L, ra+1, rb);
467 Protect(luaV_gettable(L, rb, RKC(i), ra));
468 continue;
469 }
470 case OP_ADD: {
471 arith_op(luai_numadd, TM_ADD);
472 continue;
473 }
474 case OP_SUB: {
475 arith_op(luai_numsub, TM_SUB);
476 continue;
477 }
478 case OP_MUL: {
479 arith_op(luai_nummul, TM_MUL);
480 continue;
481 }
482 case OP_DIV: {
483 arith_op(luai_numdiv, TM_DIV);
484 continue;
485 }
486 case OP_MOD: {
487 arith_op(luai_nummod, TM_MOD);
488 continue;
489 }
490 case OP_POW: {
491 arith_op(luai_numpow, TM_POW);
492 continue;
493 }
494 case OP_UNM: {
495 TValue *rb = RB(i);
496 if (ttisnumber(rb)) {
497 lua_Number nb = nvalue(rb);
498 setnvalue(ra, luai_numunm(nb));
499 }
500 else {
501 Protect(Arith(L, ra, rb, rb, TM_UNM));
502 }
503 continue;
504 }
505 case OP_NOT: {
506 int res = l_isfalse(RB(i)); /* next assignment may change this value */
507 setbvalue(ra, res);
508 continue;
509 }
510 case OP_LEN: {
511 const TValue *rb = RB(i);
512 switch (ttype(rb)) {
513 case LUA_TTABLE: {
514 setnvalue(ra, cast_num(luaH_getn(hvalue(rb))));
515 break;
516 }
517 case LUA_TSTRING: {
518 setnvalue(ra, cast_num(tsvalue(rb)->len));
519 break;
520 }
521 default: { /* try metamethod */
522 Protect(
523 if (!call_binTM(L, rb, luaO_nilobject, ra, TM_LEN))
524 luaG_typeerror(L, rb, "get length of");
525 )
526 }
527 }
528 continue;
529 }
530 case OP_CONCAT: {
531 int b = GETARG_B(i);
532 int c = GETARG_C(i);
533 Protect(luaV_concat(L, c-b+1, c); luaC_checkGC(L));
534 setobjs2s(L, RA(i), base+b);
535 continue;
536 }
537 case OP_JMP: {
538 dojump(L, pc, GETARG_sBx(i));
539 continue;
540 }
541 case OP_EQ: {
542 TValue *rb = RKB(i);
543 TValue *rc = RKC(i);
544 Protect(
545 if (equalobj(L, rb, rc) == GETARG_A(i))
546 dojump(L, pc, GETARG_sBx(*pc));
547 )
548 pc++;
549 continue;
550 }
551 case OP_LT: {
552 Protect(
553 if (luaV_lessthan(L, RKB(i), RKC(i)) == GETARG_A(i))
554 dojump(L, pc, GETARG_sBx(*pc));
555 )
556 pc++;
557 continue;
558 }
559 case OP_LE: {
560 Protect(
561 if (lessequal(L, RKB(i), RKC(i)) == GETARG_A(i))
562 dojump(L, pc, GETARG_sBx(*pc));
563 )
564 pc++;
565 continue;
566 }
567 case OP_TEST: {
568 if (l_isfalse(ra) != GETARG_C(i))
569 dojump(L, pc, GETARG_sBx(*pc));
570 pc++;
571 continue;
572 }
573 case OP_TESTSET: {
574 TValue *rb = RB(i);
575 if (l_isfalse(rb) != GETARG_C(i)) {
576 setobjs2s(L, ra, rb);
577 dojump(L, pc, GETARG_sBx(*pc));
578 }
579 pc++;
580 continue;
581 }
582 case OP_CALL: {
583 int b = GETARG_B(i);
584 int nresults = GETARG_C(i) - 1;
585 if (b != 0) L->top = ra+b; /* else previous instruction set top */
586 L->savedpc = pc;
587 switch (luaD_precall(L, ra, nresults)) {
588 case PCRLUA: {
589 nexeccalls++;
590 goto reentry; /* restart luaV_execute over new Lua function */
591 }
592 case PCRC: {
593 /* it was a C function (`precall' called it); adjust results */
594 if (nresults >= 0) L->top = L->ci->top;
595 base = L->base;
596 continue;
597 }
598 default: {
599 return; /* yield */
600 }
601 }
602 }
603 case OP_TAILCALL: {
604 int b = GETARG_B(i);
605 if (b != 0) L->top = ra+b; /* else previous instruction set top */
606 L->savedpc = pc;
607 lua_assert(GETARG_C(i) - 1 == LUA_MULTRET);
608 switch (luaD_precall(L, ra, LUA_MULTRET)) {
609 case PCRLUA: {
610 /* tail call: put new frame in place of previous one */
611 CallInfo *ci = L->ci - 1; /* previous frame */
612 int aux;
613 StkId func = ci->func;
614 StkId pfunc = (ci+1)->func; /* previous function index */
615 if (L->openupval) luaF_close(L, ci->base);
616 L->base = ci->base = ci->func + ((ci+1)->base - pfunc);
617 for (aux = 0; pfunc+aux < L->top; aux++) /* move frame down */
618 setobjs2s(L, func+aux, pfunc+aux);
619 ci->top = L->top = func+aux; /* correct top */
620 lua_assert(L->top == L->base + clvalue(func)->l.p->maxstacksize);
621 ci->savedpc = L->savedpc;
622 ci->tailcalls++; /* one more call lost */
623 L->ci--; /* remove new frame */
624 goto reentry;
625 }
626 case PCRC: { /* it was a C function (`precall' called it) */
627 base = L->base;
628 continue;
629 }
630 default: {
631 return; /* yield */
632 }
633 }
634 }
635 case OP_RETURN: {
636 int b = GETARG_B(i);
637 if (b != 0) L->top = ra+b-1;
638 if (L->openupval) luaF_close(L, base);
639 L->savedpc = pc;
640 b = luaD_poscall(L, ra);
641 if (--nexeccalls == 0) /* was previous function running `here'? */
642 return; /* no: return */
643 else { /* yes: continue its execution */
644 if (b) L->top = L->ci->top;
645 lua_assert(isLua(L->ci));
646 lua_assert(GET_OPCODE(*((L->ci)->savedpc - 1)) == OP_CALL);
647 goto reentry;
648 }
649 }
650 case OP_FORLOOP: {
651 lua_Number step = nvalue(ra+2);
652 lua_Number idx = luai_numadd(nvalue(ra), step); /* increment index */
653 lua_Number limit = nvalue(ra+1);
654 if (luai_numlt(0, step) ? luai_numle(idx, limit)
655 : luai_numle(limit, idx)) {
656 dojump(L, pc, GETARG_sBx(i)); /* jump back */
657 setnvalue(ra, idx); /* update internal index... */
658 setnvalue(ra+3, idx); /* ...and external index */
659 }
660 continue;
661 }
662 case OP_FORPREP: {
663 const TValue *init = ra;
664 const TValue *plimit = ra+1;
665 const TValue *pstep = ra+2;
666 L->savedpc = pc; /* next steps may throw errors */
667 if (!tonumber(init, ra))
668 luaG_runerror(L, LUA_QL("for") " initial value must be a number");
669 else if (!tonumber(plimit, ra+1))
670 luaG_runerror(L, LUA_QL("for") " limit must be a number");
671 else if (!tonumber(pstep, ra+2))
672 luaG_runerror(L, LUA_QL("for") " step must be a number");
673 setnvalue(ra, luai_numsub(nvalue(ra), nvalue(pstep)));
674 dojump(L, pc, GETARG_sBx(i));
675 continue;
676 }
677 case OP_TFORLOOP: {
678 StkId cb = ra + 3; /* call base */
679 setobjs2s(L, cb+2, ra+2);
680 setobjs2s(L, cb+1, ra+1);
681 setobjs2s(L, cb, ra);
682 L->top = cb+3; /* func. + 2 args (state and index) */
683 Protect(luaD_call(L, cb, GETARG_C(i)));
684 L->top = L->ci->top;
685 cb = RA(i) + 3; /* previous call may change the stack */
686 if (!ttisnil(cb)) { /* continue loop? */
687 setobjs2s(L, cb-1, cb); /* save control variable */
688 dojump(L, pc, GETARG_sBx(*pc)); /* jump back */
689 }
690 pc++;
691 continue;
692 }
693 case OP_SETLIST: {
694 int n = GETARG_B(i);
695 int c = GETARG_C(i);
696 int last;
697 Table *h;
698 if (n == 0) {
699 n = cast_int(L->top - ra) - 1;
700 L->top = L->ci->top;
701 }
702 if (c == 0) c = cast_int(*pc++);
703 runtime_check(L, ttistable(ra));
704 h = hvalue(ra);
705 last = ((c-1)*LFIELDS_PER_FLUSH) + n;
706 if (last > h->sizearray) /* needs more space? */
707 luaH_resizearray(L, h, last); /* pre-alloc it at once */
708 for (; n > 0; n--) {
709 TValue *val = ra+n;
710 setobj2t(L, luaH_setnum(L, h, last--), val);
711 luaC_barriert(L, h, val);
712 }
713 continue;
714 }
715 case OP_CLOSE: {
716 luaF_close(L, ra);
717 continue;
718 }
719 case OP_CLOSURE: {
720 Proto *p;
721 Closure *ncl;
722 int nup, j;
723 p = cl->p->p[GETARG_Bx(i)];
724 nup = p->nups;
725 ncl = luaF_newLclosure(L, nup, cl->env);
726 ncl->l.p = p;
727 for (j=0; j<nup; j++, pc++) {
728 if (GET_OPCODE(*pc) == OP_GETUPVAL)
729 ncl->l.upvals[j] = cl->upvals[GETARG_B(*pc)];
730 else {
731 lua_assert(GET_OPCODE(*pc) == OP_MOVE);
732 ncl->l.upvals[j] = luaF_findupval(L, base + GETARG_B(*pc));
733 }
734 }
735 setclvalue(L, ra, ncl);
736 Protect(luaC_checkGC(L));
737 continue;
738 }
739 case OP_VARARG: {
740 int b = GETARG_B(i) - 1;
741 int j;
742 CallInfo *ci = L->ci;
743 int n = cast_int(ci->base - ci->func) - cl->p->numparams - 1;
744 if (b == LUA_MULTRET) {
745 Protect(luaD_checkstack(L, n));
746 ra = RA(i); /* previous call may change the stack */
747 b = n;
748 L->top = ra + n;
749 }
750 for (j = 0; j < b; j++) {
751 if (j < n) {
752 setobjs2s(L, ra + j, ci->base - n + j);
753 }
754 else {
755 setnilvalue(ra + j);
756 }
757 }
758 continue;
759 }
760 }
761 }
762}
763
diff --git a/apps/plugins/lua/lvm.h b/apps/plugins/lua/lvm.h
new file mode 100644
index 0000000000..dff2a139f7
--- /dev/null
+++ b/apps/plugins/lua/lvm.h
@@ -0,0 +1,36 @@
1/*
2** $Id$
3** Lua virtual machine
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lvm_h
8#define lvm_h
9
10
11#include "ldo.h"
12#include "lobject.h"
13#include "ltm.h"
14
15
16#define tostring(L,o) ((ttype(o) == LUA_TSTRING) || (luaV_tostring(L, o)))
17
18#define tonumber(o,n) (ttype(o) == LUA_TNUMBER || \
19 (((o) = luaV_tonumber(o,n)) != NULL))
20
21#define equalobj(L,o1,o2) \
22 (ttype(o1) == ttype(o2) && luaV_equalval(L, o1, o2))
23
24
25LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);
26LUAI_FUNC int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2);
27LUAI_FUNC const TValue *luaV_tonumber (const TValue *obj, TValue *n);
28LUAI_FUNC int luaV_tostring (lua_State *L, StkId obj);
29LUAI_FUNC void luaV_gettable (lua_State *L, const TValue *t, TValue *key,
30 StkId val);
31LUAI_FUNC void luaV_settable (lua_State *L, const TValue *t, TValue *key,
32 StkId val);
33LUAI_FUNC void luaV_execute (lua_State *L, int nexeccalls);
34LUAI_FUNC void luaV_concat (lua_State *L, int total, int last);
35
36#endif
diff --git a/apps/plugins/lua/lzio.c b/apps/plugins/lua/lzio.c
new file mode 100644
index 0000000000..293edd59b0
--- /dev/null
+++ b/apps/plugins/lua/lzio.c
@@ -0,0 +1,82 @@
1/*
2** $Id: lzio.c,v 1.31.1.1 2007/12/27 13:02:25 roberto Exp $
3** a generic input stream interface
4** See Copyright Notice in lua.h
5*/
6
7
8#include <string.h>
9
10#define lzio_c
11#define LUA_CORE
12
13#include "lua.h"
14
15#include "llimits.h"
16#include "lmem.h"
17#include "lstate.h"
18#include "lzio.h"
19
20
21int luaZ_fill (ZIO *z) {
22 size_t size;
23 lua_State *L = z->L;
24 const char *buff;
25 lua_unlock(L);
26 buff = z->reader(L, z->data, &size);
27 lua_lock(L);
28 if (buff == NULL || size == 0) return EOZ;
29 z->n = size - 1;
30 z->p = buff;
31 return char2int(*(z->p++));
32}
33
34
35int luaZ_lookahead (ZIO *z) {
36 if (z->n == 0) {
37 if (luaZ_fill(z) == EOZ)
38 return EOZ;
39 else {
40 z->n++; /* luaZ_fill removed first byte; put back it */
41 z->p--;
42 }
43 }
44 return char2int(*z->p);
45}
46
47
48void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
49 z->L = L;
50 z->reader = reader;
51 z->data = data;
52 z->n = 0;
53 z->p = NULL;
54}
55
56
57/* --------------------------------------------------------------- read --- */
58size_t luaZ_read (ZIO *z, void *b, size_t n) {
59 while (n) {
60 size_t m;
61 if (luaZ_lookahead(z) == EOZ)
62 return n; /* return number of missing bytes */
63 m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
64 memcpy(b, z->p, m);
65 z->n -= m;
66 z->p += m;
67 b = (char *)b + m;
68 n -= m;
69 }
70 return 0;
71}
72
73/* ------------------------------------------------------------------------ */
74char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n) {
75 if (n > buff->buffsize) {
76 if (n < LUA_MINBUFFER) n = LUA_MINBUFFER;
77 luaZ_resizebuffer(L, buff, n);
78 }
79 return buff->buffer;
80}
81
82
diff --git a/apps/plugins/lua/lzio.h b/apps/plugins/lua/lzio.h
new file mode 100644
index 0000000000..9aa9e4b537
--- /dev/null
+++ b/apps/plugins/lua/lzio.h
@@ -0,0 +1,67 @@
1/*
2** $Id$
3** Buffered streams
4** See Copyright Notice in lua.h
5*/
6
7
8#ifndef lzio_h
9#define lzio_h
10
11#include "lua.h"
12
13#include "lmem.h"
14
15
16#define EOZ (-1) /* end of stream */
17
18typedef struct Zio ZIO;
19
20#define char2int(c) cast(int, cast(unsigned char, (c)))
21
22#define zgetc(z) (((z)->n--)>0 ? char2int(*(z)->p++) : luaZ_fill(z))
23
24typedef struct Mbuffer {
25 char *buffer;
26 size_t n;
27 size_t buffsize;
28} Mbuffer;
29
30#define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0)
31
32#define luaZ_buffer(buff) ((buff)->buffer)
33#define luaZ_sizebuffer(buff) ((buff)->buffsize)
34#define luaZ_bufflen(buff) ((buff)->n)
35
36#define luaZ_resetbuffer(buff) ((buff)->n = 0)
37
38
39#define luaZ_resizebuffer(L, buff, size) \
40 (luaM_reallocvector(L, (buff)->buffer, (buff)->buffsize, size, char), \
41 (buff)->buffsize = size)
42
43#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0)
44
45
46LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n);
47LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader,
48 void *data);
49LUAI_FUNC size_t luaZ_read (ZIO* z, void* b, size_t n); /* read next n bytes */
50LUAI_FUNC int luaZ_lookahead (ZIO *z);
51
52
53
54/* --------- Private Part ------------------ */
55
56struct Zio {
57 size_t n; /* bytes still unread */
58 const char *p; /* current position in buffer */
59 lua_Reader reader;
60 void* data; /* additional data */
61 lua_State *L; /* Lua state (for reader) */
62};
63
64
65LUAI_FUNC int luaZ_fill (ZIO *z);
66
67#endif
diff --git a/apps/plugins/lua/malloc.c b/apps/plugins/lua/malloc.c
new file mode 100644
index 0000000000..6dc00c4f9a
--- /dev/null
+++ b/apps/plugins/lua/malloc.c
@@ -0,0 +1,5061 @@
1/*
2 This is a version (aka dlmalloc) of malloc/free/realloc written by
3 Doug Lea and released to the public domain, as explained at
4 http://creativecommons.org/licenses/publicdomain. Send questions,
5 comments, complaints, performance data, etc to dl@cs.oswego.edu
6
7* Version 2.8.3 Thu Sep 22 11:16:15 2005 Doug Lea (dl at gee)
8
9 Note: There may be an updated version of this malloc obtainable at
10 ftp://gee.cs.oswego.edu/pub/misc/malloc.c
11 Check before installing!
12
13* Quickstart
14
15 This library is all in one file to simplify the most common usage:
16 ftp it, compile it (-O3), and link it into another program. All of
17 the compile-time options default to reasonable values for use on
18 most platforms. You might later want to step through various
19 compile-time and dynamic tuning options.
20
21 For convenience, an include file for code using this malloc is at:
22 ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.3.h
23 You don't really need this .h file unless you call functions not
24 defined in your system include files. The .h file contains only the
25 excerpts from this file needed for using this malloc on ANSI C/C++
26 systems, so long as you haven't changed compile-time options about
27 naming and tuning parameters. If you do, then you can create your
28 own malloc.h that does include all settings by cutting at the point
29 indicated below. Note that you may already by default be using a C
30 library containing a malloc that is based on some version of this
31 malloc (for example in linux). You might still want to use the one
32 in this file to customize settings or to avoid overheads associated
33 with library versions.
34
35* Vital statistics:
36
37 Supported pointer/size_t representation: 4 or 8 bytes
38 size_t MUST be an unsigned type of the same width as
39 pointers. (If you are using an ancient system that declares
40 size_t as a signed type, or need it to be a different width
41 than pointers, you can use a previous release of this malloc
42 (e.g. 2.7.2) supporting these.)
43
44 Alignment: 8 bytes (default)
45 This suffices for nearly all current machines and C compilers.
46 However, you can define MALLOC_ALIGNMENT to be wider than this
47 if necessary (up to 128bytes), at the expense of using more space.
48
49 Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes)
50 8 or 16 bytes (if 8byte sizes)
51 Each malloced chunk has a hidden word of overhead holding size
52 and status information, and additional cross-check word
53 if FOOTERS is defined.
54
55 Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead)
56 8-byte ptrs: 32 bytes (including overhead)
57
58 Even a request for zero bytes (i.e., malloc(0)) returns a
59 pointer to something of the minimum allocatable size.
60 The maximum overhead wastage (i.e., number of extra bytes
61 allocated than were requested in malloc) is less than or equal
62 to the minimum size, except for requests >= mmap_threshold that
63 are serviced via mmap(), where the worst case wastage is about
64 32 bytes plus the remainder from a system page (the minimal
65 mmap unit); typically 4096 or 8192 bytes.
66
67 Security: static-safe; optionally more or less
68 The "security" of malloc refers to the ability of malicious
69 code to accentuate the effects of errors (for example, freeing
70 space that is not currently malloc'ed or overwriting past the
71 ends of chunks) in code that calls malloc. This malloc
72 guarantees not to modify any memory locations below the base of
73 heap, i.e., static variables, even in the presence of usage
74 errors. The routines additionally detect most improper frees
75 and reallocs. All this holds as long as the static bookkeeping
76 for malloc itself is not corrupted by some other means. This
77 is only one aspect of security -- these checks do not, and
78 cannot, detect all possible programming errors.
79
80 If FOOTERS is defined nonzero, then each allocated chunk
81 carries an additional check word to verify that it was malloced
82 from its space. These check words are the same within each
83 execution of a program using malloc, but differ across
84 executions, so externally crafted fake chunks cannot be
85 freed. This improves security by rejecting frees/reallocs that
86 could corrupt heap memory, in addition to the checks preventing
87 writes to statics that are always on. This may further improve
88 security at the expense of time and space overhead. (Note that
89 FOOTERS may also be worth using with MSPACES.)
90
91 By default detected errors cause the program to abort (calling
92 "abort()"). You can override this to instead proceed past
93 errors by defining PROCEED_ON_ERROR. In this case, a bad free
94 has no effect, and a malloc that encounters a bad address
95 caused by user overwrites will ignore the bad address by
96 dropping pointers and indices to all known memory. This may
97 be appropriate for programs that should continue if at all
98 possible in the face of programming errors, although they may
99 run out of memory because dropped memory is never reclaimed.
100
101 If you don't like either of these options, you can define
102 CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything
103 else. And if if you are sure that your program using malloc has
104 no errors or vulnerabilities, you can define INSECURE to 1,
105 which might (or might not) provide a small performance improvement.
106
107 Thread-safety: NOT thread-safe unless USE_LOCKS defined
108 When USE_LOCKS is defined, each public call to malloc, free,
109 etc is surrounded with either a pthread mutex or a win32
110 spinlock (depending on WIN32). This is not especially fast, and
111 can be a major bottleneck. It is designed only to provide
112 minimal protection in concurrent environments, and to provide a
113 basis for extensions. If you are using malloc in a concurrent
114 program, consider instead using ptmalloc, which is derived from
115 a version of this malloc. (See http://www.malloc.de).
116
117 System requirements: Any combination of MORECORE and/or MMAP/MUNMAP
118 This malloc can use unix sbrk or any emulation (invoked using
119 the CALL_MORECORE macro) and/or mmap/munmap or any emulation
120 (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system
121 memory. On most unix systems, it tends to work best if both
122 MORECORE and MMAP are enabled. On Win32, it uses emulations
123 based on VirtualAlloc. It also uses common C library functions
124 like memset.
125
126 Compliance: I believe it is compliant with the Single Unix Specification
127 (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably
128 others as well.
129
130* Overview of algorithms
131
132 This is not the fastest, most space-conserving, most portable, or
133 most tunable malloc ever written. However it is among the fastest
134 while also being among the most space-conserving, portable and
135 tunable. Consistent balance across these factors results in a good
136 general-purpose allocator for malloc-intensive programs.
137
138 In most ways, this malloc is a best-fit allocator. Generally, it
139 chooses the best-fitting existing chunk for a request, with ties
140 broken in approximately least-recently-used order. (This strategy
141 normally maintains low fragmentation.) However, for requests less
142 than 256bytes, it deviates from best-fit when there is not an
143 exactly fitting available chunk by preferring to use space adjacent
144 to that used for the previous small request, as well as by breaking
145 ties in approximately most-recently-used order. (These enhance
146 locality of series of small allocations.) And for very large requests
147 (>= 256Kb by default), it relies on system memory mapping
148 facilities, if supported. (This helps avoid carrying around and
149 possibly fragmenting memory used only for large chunks.)
150
151 All operations (except malloc_stats and mallinfo) have execution
152 times that are bounded by a constant factor of the number of bits in
153 a size_t, not counting any clearing in calloc or copying in realloc,
154 or actions surrounding MORECORE and MMAP that have times
155 proportional to the number of non-contiguous regions returned by
156 system allocation routines, which is often just 1.
157
158 The implementation is not very modular and seriously overuses
159 macros. Perhaps someday all C compilers will do as good a job
160 inlining modular code as can now be done by brute-force expansion,
161 but now, enough of them seem not to.
162
163 Some compilers issue a lot of warnings about code that is
164 dead/unreachable only on some platforms, and also about intentional
165 uses of negation on unsigned types. All known cases of each can be
166 ignored.
167
168 For a longer but out of date high-level description, see
169 http://gee.cs.oswego.edu/dl/html/malloc.html
170
171* MSPACES
172 If MSPACES is defined, then in addition to malloc, free, etc.,
173 this file also defines mspace_malloc, mspace_free, etc. These
174 are versions of malloc routines that take an "mspace" argument
175 obtained using create_mspace, to control all internal bookkeeping.
176 If ONLY_MSPACES is defined, only these versions are compiled.
177 So if you would like to use this allocator for only some allocations,
178 and your system malloc for others, you can compile with
179 ONLY_MSPACES and then do something like...
180 static mspace mymspace = create_mspace(0,0); // for example
181 #define mymalloc(bytes) mspace_malloc(mymspace, bytes)
182
183 (Note: If you only need one instance of an mspace, you can instead
184 use "USE_DL_PREFIX" to relabel the global malloc.)
185
186 You can similarly create thread-local allocators by storing
187 mspaces as thread-locals. For example:
188 static __thread mspace tlms = 0;
189 void* tlmalloc(size_t bytes) {
190 if (tlms == 0) tlms = create_mspace(0, 0);
191 return mspace_malloc(tlms, bytes);
192 }
193 void tlfree(void* mem) { mspace_free(tlms, mem); }
194
195 Unless FOOTERS is defined, each mspace is completely independent.
196 You cannot allocate from one and free to another (although
197 conformance is only weakly checked, so usage errors are not always
198 caught). If FOOTERS is defined, then each chunk carries around a tag
199 indicating its originating mspace, and frees are directed to their
200 originating spaces.
201
202 ------------------------- Compile-time options ---------------------------
203
204Be careful in setting #define values for numerical constants of type
205size_t. On some systems, literal values are not automatically extended
206to size_t precision unless they are explicitly casted.
207
208WIN32 default: defined if _WIN32 defined
209 Defining WIN32 sets up defaults for MS environment and compilers.
210 Otherwise defaults are for unix.
211
212MALLOC_ALIGNMENT default: (size_t)8
213 Controls the minimum alignment for malloc'ed chunks. It must be a
214 power of two and at least 8, even on machines for which smaller
215 alignments would suffice. It may be defined as larger than this
216 though. Note however that code and data structures are optimized for
217 the case of 8-byte alignment.
218
219MSPACES default: 0 (false)
220 If true, compile in support for independent allocation spaces.
221 This is only supported if HAVE_MMAP is true.
222
223ONLY_MSPACES default: 0 (false)
224 If true, only compile in mspace versions, not regular versions.
225
226USE_LOCKS default: 0 (false)
227 Causes each call to each public routine to be surrounded with
228 pthread or WIN32 mutex lock/unlock. (If set true, this can be
229 overridden on a per-mspace basis for mspace versions.)
230
231FOOTERS default: 0
232 If true, provide extra checking and dispatching by placing
233 information in the footers of allocated chunks. This adds
234 space and time overhead.
235
236INSECURE default: 0
237 If true, omit checks for usage errors and heap space overwrites.
238
239USE_DL_PREFIX default: NOT defined
240 Causes compiler to prefix all public routines with the string 'dl'.
241 This can be useful when you only want to use this malloc in one part
242 of a program, using your regular system malloc elsewhere.
243
244ABORT default: defined as abort()
245 Defines how to abort on failed checks. On most systems, a failed
246 check cannot die with an "assert" or even print an informative
247 message, because the underlying print routines in turn call malloc,
248 which will fail again. Generally, the best policy is to simply call
249 abort(). It's not very useful to do more than this because many
250 errors due to overwriting will show up as address faults (null, odd
251 addresses etc) rather than malloc-triggered checks, so will also
252 abort. Also, most compilers know that abort() does not return, so
253 can better optimize code conditionally calling it.
254
255PROCEED_ON_ERROR default: defined as 0 (false)
256 Controls whether detected bad addresses cause them to bypassed
257 rather than aborting. If set, detected bad arguments to free and
258 realloc are ignored. And all bookkeeping information is zeroed out
259 upon a detected overwrite of freed heap space, thus losing the
260 ability to ever return it from malloc again, but enabling the
261 application to proceed. If PROCEED_ON_ERROR is defined, the
262 static variable malloc_corruption_error_count is compiled in
263 and can be examined to see if errors have occurred. This option
264 generates slower code than the default abort policy.
265
266DEBUG default: NOT defined
267 The DEBUG setting is mainly intended for people trying to modify
268 this code or diagnose problems when porting to new platforms.
269 However, it may also be able to better isolate user errors than just
270 using runtime checks. The assertions in the check routines spell
271 out in more detail the assumptions and invariants underlying the
272 algorithms. The checking is fairly extensive, and will slow down
273 execution noticeably. Calling malloc_stats or mallinfo with DEBUG
274 set will attempt to check every non-mmapped allocated and free chunk
275 in the course of computing the summaries.
276
277ABORT_ON_ASSERT_FAILURE default: defined as 1 (true)
278 Debugging assertion failures can be nearly impossible if your
279 version of the assert macro causes malloc to be called, which will
280 lead to a cascade of further failures, blowing the runtime stack.
281 ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),
282 which will usually make debugging easier.
283
284MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32
285 The action to take before "return 0" when malloc fails to be able to
286 return memory because there is none available.
287
288HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES
289 True if this system supports sbrk or an emulation of it.
290
291MORECORE default: sbrk
292 The name of the sbrk-style system routine to call to obtain more
293 memory. See below for guidance on writing custom MORECORE
294 functions. The type of the argument to sbrk/MORECORE varies across
295 systems. It cannot be size_t, because it supports negative
296 arguments, so it is normally the signed type of the same width as
297 size_t (sometimes declared as "intptr_t"). It doesn't much matter
298 though. Internally, we only call it with arguments less than half
299 the max value of a size_t, which should work across all reasonable
300 possibilities, although sometimes generating compiler warnings. See
301 near the end of this file for guidelines for creating a custom
302 version of MORECORE.
303
304MORECORE_CONTIGUOUS default: 1 (true)
305 If true, take advantage of fact that consecutive calls to MORECORE
306 with positive arguments always return contiguous increasing
307 addresses. This is true of unix sbrk. It does not hurt too much to
308 set it true anyway, since malloc copes with non-contiguities.
309 Setting it false when definitely non-contiguous saves time
310 and possibly wasted space it would take to discover this though.
311
312MORECORE_CANNOT_TRIM default: NOT defined
313 True if MORECORE cannot release space back to the system when given
314 negative arguments. This is generally necessary only if you are
315 using a hand-crafted MORECORE function that cannot handle negative
316 arguments.
317
318HAVE_MMAP default: 1 (true)
319 True if this system supports mmap or an emulation of it. If so, and
320 HAVE_MORECORE is not true, MMAP is used for all system
321 allocation. If set and HAVE_MORECORE is true as well, MMAP is
322 primarily used to directly allocate very large blocks. It is also
323 used as a backup strategy in cases where MORECORE fails to provide
324 space from system. Note: A single call to MUNMAP is assumed to be
325 able to unmap memory that may have be allocated using multiple calls
326 to MMAP, so long as they are adjacent.
327
328HAVE_MREMAP default: 1 on linux, else 0
329 If true realloc() uses mremap() to re-allocate large blocks and
330 extend or shrink allocation spaces.
331
332MMAP_CLEARS default: 1 on unix
333 True if mmap clears memory so calloc doesn't need to. This is true
334 for standard unix mmap using /dev/zero.
335
336USE_BUILTIN_FFS default: 0 (i.e., not used)
337 Causes malloc to use the builtin ffs() function to compute indices.
338 Some compilers may recognize and intrinsify ffs to be faster than the
339 supplied C version. Also, the case of x86 using gcc is special-cased
340 to an asm instruction, so is already as fast as it can be, and so
341 this setting has no effect. (On most x86s, the asm version is only
342 slightly faster than the C version.)
343
344malloc_getpagesize default: derive from system includes, or 4096.
345 The system page size. To the extent possible, this malloc manages
346 memory from the system in page-size units. This may be (and
347 usually is) a function rather than a constant. This is ignored
348 if WIN32, where page size is determined using getSystemInfo during
349 initialization.
350
351USE_DEV_RANDOM default: 0 (i.e., not used)
352 Causes malloc to use /dev/random to initialize secure magic seed for
353 stamping footers. Otherwise, the current time is used.
354
355NO_MALLINFO default: 0
356 If defined, don't compile "mallinfo". This can be a simple way
357 of dealing with mismatches between system declarations and
358 those in this file.
359
360MALLINFO_FIELD_TYPE default: size_t
361 The type of the fields in the mallinfo struct. This was originally
362 defined as "int" in SVID etc, but is more usefully defined as
363 size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set
364
365REALLOC_ZERO_BYTES_FREES default: not defined
366 This should be set if a call to realloc with zero bytes should
367 be the same as a call to free. Some people think it should. Otherwise,
368 since this malloc returns a unique pointer for malloc(0), so does
369 realloc(p, 0).
370
371LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H
372LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H
373LACKS_STDLIB_H default: NOT defined unless on WIN32
374 Define these if your system does not have these header files.
375 You might need to manually insert some of the declarations they provide.
376
377DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS,
378 system_info.dwAllocationGranularity in WIN32,
379 otherwise 64K.
380 Also settable using mallopt(M_GRANULARITY, x)
381 The unit for allocating and deallocating memory from the system. On
382 most systems with contiguous MORECORE, there is no reason to
383 make this more than a page. However, systems with MMAP tend to
384 either require or encourage larger granularities. You can increase
385 this value to prevent system allocation functions to be called so
386 often, especially if they are slow. The value must be at least one
387 page and must be a power of two. Setting to 0 causes initialization
388 to either page size or win32 region size. (Note: In previous
389 versions of malloc, the equivalent of this option was called
390 "TOP_PAD")
391
392DEFAULT_TRIM_THRESHOLD default: 2MB
393 Also settable using mallopt(M_TRIM_THRESHOLD, x)
394 The maximum amount of unused top-most memory to keep before
395 releasing via malloc_trim in free(). Automatic trimming is mainly
396 useful in long-lived programs using contiguous MORECORE. Because
397 trimming via sbrk can be slow on some systems, and can sometimes be
398 wasteful (in cases where programs immediately afterward allocate
399 more large chunks) the value should be high enough so that your
400 overall system performance would improve by releasing this much
401 memory. As a rough guide, you might set to a value close to the
402 average size of a process (program) running on your system.
403 Releasing this much memory would allow such a process to run in
404 memory. Generally, it is worth tuning trim thresholds when a
405 program undergoes phases where several large chunks are allocated
406 and released in ways that can reuse each other's storage, perhaps
407 mixed with phases where there are no such chunks at all. The trim
408 value must be greater than page size to have any useful effect. To
409 disable trimming completely, you can set to MAX_SIZE_T. Note that the trick
410 some people use of mallocing a huge space and then freeing it at
411 program startup, in an attempt to reserve system memory, doesn't
412 have the intended effect under automatic trimming, since that memory
413 will immediately be returned to the system.
414
415DEFAULT_MMAP_THRESHOLD default: 256K
416 Also settable using mallopt(M_MMAP_THRESHOLD, x)
417 The request size threshold for using MMAP to directly service a
418 request. Requests of at least this size that cannot be allocated
419 using already-existing space will be serviced via mmap. (If enough
420 normal freed space already exists it is used instead.) Using mmap
421 segregates relatively large chunks of memory so that they can be
422 individually obtained and released from the host system. A request
423 serviced through mmap is never reused by any other request (at least
424 not directly; the system may just so happen to remap successive
425 requests to the same locations). Segregating space in this way has
426 the benefits that: Mmapped space can always be individually released
427 back to the system, which helps keep the system level memory demands
428 of a long-lived program low. Also, mapped memory doesn't become
429 `locked' between other chunks, as can happen with normally allocated
430 chunks, which means that even trimming via malloc_trim would not
431 release them. However, it has the disadvantage that the space
432 cannot be reclaimed, consolidated, and then used to service later
433 requests, as happens with normal chunks. The advantages of mmap
434 nearly always outweigh disadvantages for "large" chunks, but the
435 value of "large" may vary across systems. The default is an
436 empirically derived value that works well in most systems. You can
437 disable mmap by setting to MAX_SIZE_T.
438
439*/
440
441#ifndef WIN32
442#ifdef _WIN32
443#define WIN32 1
444#endif /* _WIN32 */
445#endif /* WIN32 */
446#ifdef WIN32
447#define WIN32_LEAN_AND_MEAN
448#include <windows.h>
449#define HAVE_MMAP 1
450#define HAVE_MORECORE 0
451#define LACKS_UNISTD_H
452#define LACKS_SYS_PARAM_H
453#define LACKS_SYS_MMAN_H
454#define LACKS_STRING_H
455#define LACKS_STRINGS_H
456#define LACKS_SYS_TYPES_H
457#define LACKS_ERRNO_H
458#define MALLOC_FAILURE_ACTION
459#define MMAP_CLEARS 0 /* WINCE and some others apparently don't clear */
460#endif /* WIN32 */
461
462#if defined(DARWIN) || defined(_DARWIN)
463/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */
464#ifndef HAVE_MORECORE
465#define HAVE_MORECORE 0
466#define HAVE_MMAP 1
467#endif /* HAVE_MORECORE */
468#endif /* DARWIN */
469
470#ifndef LACKS_SYS_TYPES_H
471#include <sys/types.h> /* For size_t */
472#endif /* LACKS_SYS_TYPES_H */
473
474/* The maximum possible size_t value has all bits set */
475#define MAX_SIZE_T (~(size_t)0)
476
477#ifndef ONLY_MSPACES
478#define ONLY_MSPACES 0
479#endif /* ONLY_MSPACES */
480#ifndef MSPACES
481#if ONLY_MSPACES
482#define MSPACES 1
483#else /* ONLY_MSPACES */
484#define MSPACES 0
485#endif /* ONLY_MSPACES */
486#endif /* MSPACES */
487#ifndef MALLOC_ALIGNMENT
488#define MALLOC_ALIGNMENT ((size_t)8U)
489#endif /* MALLOC_ALIGNMENT */
490#ifndef FOOTERS
491#define FOOTERS 0
492#endif /* FOOTERS */
493#ifndef ABORT
494#define ABORT abort()
495#endif /* ABORT */
496#ifndef ABORT_ON_ASSERT_FAILURE
497#define ABORT_ON_ASSERT_FAILURE 1
498#endif /* ABORT_ON_ASSERT_FAILURE */
499#ifndef PROCEED_ON_ERROR
500#define PROCEED_ON_ERROR 0
501#endif /* PROCEED_ON_ERROR */
502#ifndef USE_LOCKS
503#define USE_LOCKS 0
504#endif /* USE_LOCKS */
505#ifndef INSECURE
506#define INSECURE 0
507#endif /* INSECURE */
508#ifndef HAVE_MMAP
509#define HAVE_MMAP 1
510#endif /* HAVE_MMAP */
511#ifndef MMAP_CLEARS
512#define MMAP_CLEARS 1
513#endif /* MMAP_CLEARS */
514#ifndef HAVE_MREMAP
515#ifdef linux
516#define HAVE_MREMAP 1
517#else /* linux */
518#define HAVE_MREMAP 0
519#endif /* linux */
520#endif /* HAVE_MREMAP */
521#ifndef MALLOC_FAILURE_ACTION
522#define MALLOC_FAILURE_ACTION errno = ENOMEM;
523#endif /* MALLOC_FAILURE_ACTION */
524#ifndef HAVE_MORECORE
525#if ONLY_MSPACES
526#define HAVE_MORECORE 0
527#else /* ONLY_MSPACES */
528#define HAVE_MORECORE 1
529#endif /* ONLY_MSPACES */
530#endif /* HAVE_MORECORE */
531#if !HAVE_MORECORE
532#define MORECORE_CONTIGUOUS 0
533#else /* !HAVE_MORECORE */
534#ifndef MORECORE
535#define MORECORE sbrk
536#endif /* MORECORE */
537#ifndef MORECORE_CONTIGUOUS
538#define MORECORE_CONTIGUOUS 1
539#endif /* MORECORE_CONTIGUOUS */
540#endif /* HAVE_MORECORE */
541#ifndef DEFAULT_GRANULARITY
542#if MORECORE_CONTIGUOUS
543#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */
544#else /* MORECORE_CONTIGUOUS */
545#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)
546#endif /* MORECORE_CONTIGUOUS */
547#endif /* DEFAULT_GRANULARITY */
548#ifndef DEFAULT_TRIM_THRESHOLD
549#ifndef MORECORE_CANNOT_TRIM
550#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)
551#else /* MORECORE_CANNOT_TRIM */
552#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T
553#endif /* MORECORE_CANNOT_TRIM */
554#endif /* DEFAULT_TRIM_THRESHOLD */
555#ifndef DEFAULT_MMAP_THRESHOLD
556#if HAVE_MMAP
557#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)
558#else /* HAVE_MMAP */
559#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
560#endif /* HAVE_MMAP */
561#endif /* DEFAULT_MMAP_THRESHOLD */
562#ifndef USE_BUILTIN_FFS
563#define USE_BUILTIN_FFS 0
564#endif /* USE_BUILTIN_FFS */
565#ifndef USE_DEV_RANDOM
566#define USE_DEV_RANDOM 0
567#endif /* USE_DEV_RANDOM */
568#ifndef NO_MALLINFO
569#define NO_MALLINFO 0
570#endif /* NO_MALLINFO */
571#ifndef MALLINFO_FIELD_TYPE
572#define MALLINFO_FIELD_TYPE size_t
573#endif /* MALLINFO_FIELD_TYPE */
574
575/*
576 mallopt tuning options. SVID/XPG defines four standard parameter
577 numbers for mallopt, normally defined in malloc.h. None of these
578 are used in this malloc, so setting them has no effect. But this
579 malloc does support the following options.
580*/
581
582#define M_TRIM_THRESHOLD (-1)
583#define M_GRANULARITY (-2)
584#define M_MMAP_THRESHOLD (-3)
585
586/* ------------------------ Mallinfo declarations ------------------------ */
587
588#if !NO_MALLINFO
589/*
590 This version of malloc supports the standard SVID/XPG mallinfo
591 routine that returns a struct containing usage properties and
592 statistics. It should work on any system that has a
593 /usr/include/malloc.h defining struct mallinfo. The main
594 declaration needed is the mallinfo struct that is returned (by-copy)
595 by mallinfo(). The malloinfo struct contains a bunch of fields that
596 are not even meaningful in this version of malloc. These fields are
597 are instead filled by mallinfo() with other numbers that might be of
598 interest.
599
600 HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
601 /usr/include/malloc.h file that includes a declaration of struct
602 mallinfo. If so, it is included; else a compliant version is
603 declared below. These must be precisely the same for mallinfo() to
604 work. The original SVID version of this struct, defined on most
605 systems with mallinfo, declares all fields as ints. But some others
606 define as unsigned long. If your system defines the fields using a
607 type of different width than listed here, you MUST #include your
608 system version and #define HAVE_USR_INCLUDE_MALLOC_H.
609*/
610
611/* #define HAVE_USR_INCLUDE_MALLOC_H */
612
613#ifdef HAVE_USR_INCLUDE_MALLOC_H
614#include "/usr/include/malloc.h"
615#else /* HAVE_USR_INCLUDE_MALLOC_H */
616
617struct mallinfo {
618 MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */
619 MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */
620 MALLINFO_FIELD_TYPE smblks; /* always 0 */
621 MALLINFO_FIELD_TYPE hblks; /* always 0 */
622 MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */
623 MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */
624 MALLINFO_FIELD_TYPE fsmblks; /* always 0 */
625 MALLINFO_FIELD_TYPE uordblks; /* total allocated space */
626 MALLINFO_FIELD_TYPE fordblks; /* total free space */
627 MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */
628};
629
630#endif /* HAVE_USR_INCLUDE_MALLOC_H */
631#endif /* NO_MALLINFO */
632
633#ifdef __cplusplus
634extern "C" {
635#endif /* __cplusplus */
636
637#if !ONLY_MSPACES
638
639/* ------------------- Declarations of public routines ------------------- */
640
641#ifndef USE_DL_PREFIX
642#define dlcalloc calloc
643#define dlfree free
644#define dlmalloc malloc
645#define dlmemalign memalign
646#define dlrealloc realloc
647#define dlvalloc valloc
648#define dlpvalloc pvalloc
649#define dlmallinfo mallinfo
650#define dlmallopt mallopt
651#define dlmalloc_trim malloc_trim
652#define dlmalloc_stats malloc_stats
653#define dlmalloc_usable_size malloc_usable_size
654#define dlmalloc_footprint malloc_footprint
655#define dlmalloc_max_footprint malloc_max_footprint
656#define dlindependent_calloc independent_calloc
657#define dlindependent_comalloc independent_comalloc
658#endif /* USE_DL_PREFIX */
659
660
661/*
662 malloc(size_t n)
663 Returns a pointer to a newly allocated chunk of at least n bytes, or
664 null if no space is available, in which case errno is set to ENOMEM
665 on ANSI C systems.
666
667 If n is zero, malloc returns a minimum-sized chunk. (The minimum
668 size is 16 bytes on most 32bit systems, and 32 bytes on 64bit
669 systems.) Note that size_t is an unsigned type, so calls with
670 arguments that would be negative if signed are interpreted as
671 requests for huge amounts of space, which will often fail. The
672 maximum supported value of n differs across systems, but is in all
673 cases less than the maximum representable value of a size_t.
674*/
675void* dlmalloc(size_t);
676
677/*
678 free(void* p)
679 Releases the chunk of memory pointed to by p, that had been previously
680 allocated using malloc or a related routine such as realloc.
681 It has no effect if p is null. If p was not malloced or already
682 freed, free(p) will by default cause the current program to abort.
683*/
684void dlfree(void*);
685
686/*
687 calloc(size_t n_elements, size_t element_size);
688 Returns a pointer to n_elements * element_size bytes, with all locations
689 set to zero.
690*/
691void* dlcalloc(size_t, size_t);
692
693/*
694 realloc(void* p, size_t n)
695 Returns a pointer to a chunk of size n that contains the same data
696 as does chunk p up to the minimum of (n, p's size) bytes, or null
697 if no space is available.
698
699 The returned pointer may or may not be the same as p. The algorithm
700 prefers extending p in most cases when possible, otherwise it
701 employs the equivalent of a malloc-copy-free sequence.
702
703 If p is null, realloc is equivalent to malloc.
704
705 If space is not available, realloc returns null, errno is set (if on
706 ANSI) and p is NOT freed.
707
708 if n is for fewer bytes than already held by p, the newly unused
709 space is lopped off and freed if possible. realloc with a size
710 argument of zero (re)allocates a minimum-sized chunk.
711
712 The old unix realloc convention of allowing the last-free'd chunk
713 to be used as an argument to realloc is not supported.
714*/
715
716void* dlrealloc(void*, size_t);
717
718/*
719 memalign(size_t alignment, size_t n);
720 Returns a pointer to a newly allocated chunk of n bytes, aligned
721 in accord with the alignment argument.
722
723 The alignment argument should be a power of two. If the argument is
724 not a power of two, the nearest greater power is used.
725 8-byte alignment is guaranteed by normal malloc calls, so don't
726 bother calling memalign with an argument of 8 or less.
727
728 Overreliance on memalign is a sure way to fragment space.
729*/
730void* dlmemalign(size_t, size_t);
731
732/*
733 valloc(size_t n);
734 Equivalent to memalign(pagesize, n), where pagesize is the page
735 size of the system. If the pagesize is unknown, 4096 is used.
736*/
737void* dlvalloc(size_t);
738
739/*
740 mallopt(int parameter_number, int parameter_value)
741 Sets tunable parameters The format is to provide a
742 (parameter-number, parameter-value) pair. mallopt then sets the
743 corresponding parameter to the argument value if it can (i.e., so
744 long as the value is meaningful), and returns 1 if successful else
745 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
746 normally defined in malloc.h. None of these are use in this malloc,
747 so setting them has no effect. But this malloc also supports other
748 options in mallopt. See below for details. Briefly, supported
749 parameters are as follows (listed defaults are for "typical"
750 configurations).
751
752 Symbol param # default allowed param values
753 M_TRIM_THRESHOLD -1 2*1024*1024 any (MAX_SIZE_T disables)
754 M_GRANULARITY -2 page size any power of 2 >= page size
755 M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support)
756*/
757int dlmallopt(int, int);
758
759/*
760 malloc_footprint();
761 Returns the number of bytes obtained from the system. The total
762 number of bytes allocated by malloc, realloc etc., is less than this
763 value. Unlike mallinfo, this function returns only a precomputed
764 result, so can be called frequently to monitor memory consumption.
765 Even if locks are otherwise defined, this function does not use them,
766 so results might not be up to date.
767*/
768size_t dlmalloc_footprint(void);
769
770/*
771 malloc_max_footprint();
772 Returns the maximum number of bytes obtained from the system. This
773 value will be greater than current footprint if deallocated space
774 has been reclaimed by the system. The peak number of bytes allocated
775 by malloc, realloc etc., is less than this value. Unlike mallinfo,
776 this function returns only a precomputed result, so can be called
777 frequently to monitor memory consumption. Even if locks are
778 otherwise defined, this function does not use them, so results might
779 not be up to date.
780*/
781size_t dlmalloc_max_footprint(void);
782
783#if !NO_MALLINFO
784/*
785 mallinfo()
786 Returns (by copy) a struct containing various summary statistics:
787
788 arena: current total non-mmapped bytes allocated from system
789 ordblks: the number of free chunks
790 smblks: always zero.
791 hblks: current number of mmapped regions
792 hblkhd: total bytes held in mmapped regions
793 usmblks: the maximum total allocated space. This will be greater
794 than current total if trimming has occurred.
795 fsmblks: always zero
796 uordblks: current total allocated space (normal or mmapped)
797 fordblks: total free space
798 keepcost: the maximum number of bytes that could ideally be released
799 back to system via malloc_trim. ("ideally" means that
800 it ignores page restrictions etc.)
801
802 Because these fields are ints, but internal bookkeeping may
803 be kept as longs, the reported values may wrap around zero and
804 thus be inaccurate.
805*/
806struct mallinfo dlmallinfo(void);
807#endif /* NO_MALLINFO */
808
809/*
810 independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);
811
812 independent_calloc is similar to calloc, but instead of returning a
813 single cleared space, it returns an array of pointers to n_elements
814 independent elements that can hold contents of size elem_size, each
815 of which starts out cleared, and can be independently freed,
816 realloc'ed etc. The elements are guaranteed to be adjacently
817 allocated (this is not guaranteed to occur with multiple callocs or
818 mallocs), which may also improve cache locality in some
819 applications.
820
821 The "chunks" argument is optional (i.e., may be null, which is
822 probably the most typical usage). If it is null, the returned array
823 is itself dynamically allocated and should also be freed when it is
824 no longer needed. Otherwise, the chunks array must be of at least
825 n_elements in length. It is filled in with the pointers to the
826 chunks.
827
828 In either case, independent_calloc returns this pointer array, or
829 null if the allocation failed. If n_elements is zero and "chunks"
830 is null, it returns a chunk representing an array with zero elements
831 (which should be freed if not wanted).
832
833 Each element must be individually freed when it is no longer
834 needed. If you'd like to instead be able to free all at once, you
835 should instead use regular calloc and assign pointers into this
836 space to represent elements. (In this case though, you cannot
837 independently free elements.)
838
839 independent_calloc simplifies and speeds up implementations of many
840 kinds of pools. It may also be useful when constructing large data
841 structures that initially have a fixed number of fixed-sized nodes,
842 but the number is not known at compile time, and some of the nodes
843 may later need to be freed. For example:
844
845 struct Node { int item; struct Node* next; };
846
847 struct Node* build_list() {
848 struct Node** pool;
849 int n = read_number_of_nodes_needed();
850 if (n <= 0) return 0;
851 pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
852 if (pool == 0) die();
853 // organize into a linked list...
854 struct Node* first = pool[0];
855 for (i = 0; i < n-1; ++i)
856 pool[i]->next = pool[i+1];
857 free(pool); // Can now free the array (or not, if it is needed later)
858 return first;
859 }
860*/
861void** dlindependent_calloc(size_t, size_t, void**);
862
863/*
864 independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
865
866 independent_comalloc allocates, all at once, a set of n_elements
867 chunks with sizes indicated in the "sizes" array. It returns
868 an array of pointers to these elements, each of which can be
869 independently freed, realloc'ed etc. The elements are guaranteed to
870 be adjacently allocated (this is not guaranteed to occur with
871 multiple callocs or mallocs), which may also improve cache locality
872 in some applications.
873
874 The "chunks" argument is optional (i.e., may be null). If it is null
875 the returned array is itself dynamically allocated and should also
876 be freed when it is no longer needed. Otherwise, the chunks array
877 must be of at least n_elements in length. It is filled in with the
878 pointers to the chunks.
879
880 In either case, independent_comalloc returns this pointer array, or
881 null if the allocation failed. If n_elements is zero and chunks is
882 null, it returns a chunk representing an array with zero elements
883 (which should be freed if not wanted).
884
885 Each element must be individually freed when it is no longer
886 needed. If you'd like to instead be able to free all at once, you
887 should instead use a single regular malloc, and assign pointers at
888 particular offsets in the aggregate space. (In this case though, you
889 cannot independently free elements.)
890
891 independent_comallac differs from independent_calloc in that each
892 element may have a different size, and also that it does not
893 automatically clear elements.
894
895 independent_comalloc can be used to speed up allocation in cases
896 where several structs or objects must always be allocated at the
897 same time. For example:
898
899 struct Head { ... }
900 struct Foot { ... }
901
902 void send_message(char* msg) {
903 int msglen = strlen(msg);
904 size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
905 void* chunks[3];
906 if (independent_comalloc(3, sizes, chunks) == 0)
907 die();
908 struct Head* head = (struct Head*)(chunks[0]);
909 char* body = (char*)(chunks[1]);
910 struct Foot* foot = (struct Foot*)(chunks[2]);
911 // ...
912 }
913
914 In general though, independent_comalloc is worth using only for
915 larger values of n_elements. For small values, you probably won't
916 detect enough difference from series of malloc calls to bother.
917
918 Overuse of independent_comalloc can increase overall memory usage,
919 since it cannot reuse existing noncontiguous small chunks that
920 might be available for some of the elements.
921*/
922void** dlindependent_comalloc(size_t, size_t*, void**);
923
924
925/*
926 pvalloc(size_t n);
927 Equivalent to valloc(minimum-page-that-holds(n)), that is,
928 round up n to nearest pagesize.
929 */
930void* dlpvalloc(size_t);
931
932/*
933 malloc_trim(size_t pad);
934
935 If possible, gives memory back to the system (via negative arguments
936 to sbrk) if there is unused memory at the `high' end of the malloc
937 pool or in unused MMAP segments. You can call this after freeing
938 large blocks of memory to potentially reduce the system-level memory
939 requirements of a program. However, it cannot guarantee to reduce
940 memory. Under some allocation patterns, some large free blocks of
941 memory will be locked between two used chunks, so they cannot be
942 given back to the system.
943
944 The `pad' argument to malloc_trim represents the amount of free
945 trailing space to leave untrimmed. If this argument is zero, only
946 the minimum amount of memory to maintain internal data structures
947 will be left. Non-zero arguments can be supplied to maintain enough
948 trailing space to service future expected allocations without having
949 to re-obtain memory from the system.
950
951 Malloc_trim returns 1 if it actually released any memory, else 0.
952*/
953int dlmalloc_trim(size_t);
954
955/*
956 malloc_usable_size(void* p);
957
958 Returns the number of bytes you can actually use in
959 an allocated chunk, which may be more than you requested (although
960 often not) due to alignment and minimum size constraints.
961 You can use this many bytes without worrying about
962 overwriting other allocated objects. This is not a particularly great
963 programming practice. malloc_usable_size can be more useful in
964 debugging and assertions, for example:
965
966 p = malloc(n);
967 assert(malloc_usable_size(p) >= 256);
968*/
969size_t dlmalloc_usable_size(void*);
970
971/*
972 malloc_stats();
973 Prints on stderr the amount of space obtained from the system (both
974 via sbrk and mmap), the maximum amount (which may be more than
975 current if malloc_trim and/or munmap got called), and the current
976 number of bytes allocated via malloc (or realloc, etc) but not yet
977 freed. Note that this is the number of bytes allocated, not the
978 number requested. It will be larger than the number requested
979 because of alignment and bookkeeping overhead. Because it includes
980 alignment wastage as being in use, this figure may be greater than
981 zero even when no user-level chunks are allocated.
982
983 The reported current and maximum system memory can be inaccurate if
984 a program makes other calls to system memory allocation functions
985 (normally sbrk) outside of malloc.
986
987 malloc_stats prints only the most commonly interesting statistics.
988 More information can be obtained by calling mallinfo.
989*/
990void dlmalloc_stats(void);
991
992#endif /* ONLY_MSPACES */
993
994#if MSPACES
995
996/*
997 mspace is an opaque type representing an independent
998 region of space that supports mspace_malloc, etc.
999*/
1000typedef void* mspace;
1001
1002/*
1003 create_mspace creates and returns a new independent space with the
1004 given initial capacity, or, if 0, the default granularity size. It
1005 returns null if there is no system memory available to create the
1006 space. If argument locked is non-zero, the space uses a separate
1007 lock to control access. The capacity of the space will grow
1008 dynamically as needed to service mspace_malloc requests. You can
1009 control the sizes of incremental increases of this space by
1010 compiling with a different DEFAULT_GRANULARITY or dynamically
1011 setting with mallopt(M_GRANULARITY, value).
1012*/
1013mspace create_mspace(size_t capacity, int locked);
1014
1015/*
1016 destroy_mspace destroys the given space, and attempts to return all
1017 of its memory back to the system, returning the total number of
1018 bytes freed. After destruction, the results of access to all memory
1019 used by the space become undefined.
1020*/
1021size_t destroy_mspace(mspace msp);
1022
1023/*
1024 create_mspace_with_base uses the memory supplied as the initial base
1025 of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this
1026 space is used for bookkeeping, so the capacity must be at least this
1027 large. (Otherwise 0 is returned.) When this initial space is
1028 exhausted, additional memory will be obtained from the system.
1029 Destroying this space will deallocate all additionally allocated
1030 space (if possible) but not the initial base.
1031*/
1032mspace create_mspace_with_base(void* base, size_t capacity, int locked);
1033
1034/*
1035 mspace_malloc behaves as malloc, but operates within
1036 the given space.
1037*/
1038void* mspace_malloc(mspace msp, size_t bytes);
1039
1040/*
1041 mspace_free behaves as free, but operates within
1042 the given space.
1043
1044 If compiled with FOOTERS==1, mspace_free is not actually needed.
1045 free may be called instead of mspace_free because freed chunks from
1046 any space are handled by their originating spaces.
1047*/
1048void mspace_free(mspace msp, void* mem);
1049
1050/*
1051 mspace_realloc behaves as realloc, but operates within
1052 the given space.
1053
1054 If compiled with FOOTERS==1, mspace_realloc is not actually
1055 needed. realloc may be called instead of mspace_realloc because
1056 realloced chunks from any space are handled by their originating
1057 spaces.
1058*/
1059void* mspace_realloc(mspace msp, void* mem, size_t newsize);
1060
1061/*
1062 mspace_calloc behaves as calloc, but operates within
1063 the given space.
1064*/
1065void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);
1066
1067/*
1068 mspace_memalign behaves as memalign, but operates within
1069 the given space.
1070*/
1071void* mspace_memalign(mspace msp, size_t alignment, size_t bytes);
1072
1073/*
1074 mspace_independent_calloc behaves as independent_calloc, but
1075 operates within the given space.
1076*/
1077void** mspace_independent_calloc(mspace msp, size_t n_elements,
1078 size_t elem_size, void* chunks[]);
1079
1080/*
1081 mspace_independent_comalloc behaves as independent_comalloc, but
1082 operates within the given space.
1083*/
1084void** mspace_independent_comalloc(mspace msp, size_t n_elements,
1085 size_t sizes[], void* chunks[]);
1086
1087/*
1088 mspace_footprint() returns the number of bytes obtained from the
1089 system for this space.
1090*/
1091size_t mspace_footprint(mspace msp);
1092
1093/*
1094 mspace_max_footprint() returns the peak number of bytes obtained from the
1095 system for this space.
1096*/
1097size_t mspace_max_footprint(mspace msp);
1098
1099
1100#if !NO_MALLINFO
1101/*
1102 mspace_mallinfo behaves as mallinfo, but reports properties of
1103 the given space.
1104*/
1105struct mallinfo mspace_mallinfo(mspace msp);
1106#endif /* NO_MALLINFO */
1107
1108/*
1109 mspace_malloc_stats behaves as malloc_stats, but reports
1110 properties of the given space.
1111*/
1112void mspace_malloc_stats(mspace msp);
1113
1114/*
1115 mspace_trim behaves as malloc_trim, but
1116 operates within the given space.
1117*/
1118int mspace_trim(mspace msp, size_t pad);
1119
1120/*
1121 An alias for mallopt.
1122*/
1123int mspace_mallopt(int, int);
1124
1125#endif /* MSPACES */
1126
1127#ifdef __cplusplus
1128}; /* end of extern "C" */
1129#endif /* __cplusplus */
1130
1131/*
1132 ========================================================================
1133 To make a fully customizable malloc.h header file, cut everything
1134 above this line, put into file malloc.h, edit to suit, and #include it
1135 on the next line, as well as in programs that use this malloc.
1136 ========================================================================
1137*/
1138
1139// #include "malloc.h"
1140
1141/*------------------------------ internal #includes ---------------------- */
1142
1143#ifdef WIN32
1144#pragma warning( disable : 4146 ) /* no "unsigned" warnings */
1145#endif /* WIN32 */
1146
1147#include <stdio.h> /* for printing in malloc_stats */
1148
1149#ifndef LACKS_ERRNO_H
1150#include <errno.h> /* for MALLOC_FAILURE_ACTION */
1151#endif /* LACKS_ERRNO_H */
1152#if FOOTERS
1153#include <time.h> /* for magic initialization */
1154#endif /* FOOTERS */
1155#ifndef LACKS_STDLIB_H
1156#include <stdlib.h> /* for abort() */
1157#endif /* LACKS_STDLIB_H */
1158#ifdef DEBUG
1159#if ABORT_ON_ASSERT_FAILURE
1160#define assert(x) if(!(x)) ABORT
1161#else /* ABORT_ON_ASSERT_FAILURE */
1162#include <assert.h>
1163#endif /* ABORT_ON_ASSERT_FAILURE */
1164#else /* DEBUG */
1165#define assert(x)
1166#endif /* DEBUG */
1167#ifndef LACKS_STRING_H
1168#include <string.h> /* for memset etc */
1169#endif /* LACKS_STRING_H */
1170#if USE_BUILTIN_FFS
1171#ifndef LACKS_STRINGS_H
1172#include <strings.h> /* for ffs */
1173#endif /* LACKS_STRINGS_H */
1174#endif /* USE_BUILTIN_FFS */
1175#if HAVE_MMAP
1176#ifndef LACKS_SYS_MMAN_H
1177#include <sys/mman.h> /* for mmap */
1178#endif /* LACKS_SYS_MMAN_H */
1179#ifndef LACKS_FCNTL_H
1180#include <fcntl.h>
1181#endif /* LACKS_FCNTL_H */
1182#endif /* HAVE_MMAP */
1183#if HAVE_MORECORE
1184#ifndef LACKS_UNISTD_H
1185#include <unistd.h> /* for sbrk */
1186#else /* LACKS_UNISTD_H */
1187#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
1188extern void* sbrk(ptrdiff_t);
1189#endif /* FreeBSD etc */
1190#endif /* LACKS_UNISTD_H */
1191#endif /* HAVE_MMAP */
1192
1193#ifndef WIN32
1194#ifndef malloc_getpagesize
1195# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
1196# ifndef _SC_PAGE_SIZE
1197# define _SC_PAGE_SIZE _SC_PAGESIZE
1198# endif
1199# endif
1200# ifdef _SC_PAGE_SIZE
1201# define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
1202# else
1203# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
1204 extern size_t getpagesize();
1205# define malloc_getpagesize getpagesize()
1206# else
1207# ifdef WIN32 /* use supplied emulation of getpagesize */
1208# define malloc_getpagesize getpagesize()
1209# else
1210# ifndef LACKS_SYS_PARAM_H
1211# include <sys/param.h>
1212# endif
1213# ifdef EXEC_PAGESIZE
1214# define malloc_getpagesize EXEC_PAGESIZE
1215# else
1216# ifdef NBPG
1217# ifndef CLSIZE
1218# define malloc_getpagesize NBPG
1219# else
1220# define malloc_getpagesize (NBPG * CLSIZE)
1221# endif
1222# else
1223# ifdef NBPC
1224# define malloc_getpagesize NBPC
1225# else
1226# ifdef PAGESIZE
1227# define malloc_getpagesize PAGESIZE
1228# else /* just guess */
1229# define malloc_getpagesize ((size_t)4096U)
1230# endif
1231# endif
1232# endif
1233# endif
1234# endif
1235# endif
1236# endif
1237#endif
1238#endif
1239
1240/* ------------------- size_t and alignment properties -------------------- */
1241
1242/* The byte and bit size of a size_t */
1243#define SIZE_T_SIZE (sizeof(size_t))
1244#define SIZE_T_BITSIZE (sizeof(size_t) << 3)
1245
1246/* Some constants coerced to size_t */
1247/* Annoying but necessary to avoid errors on some plaftorms */
1248#define SIZE_T_ZERO ((size_t)0)
1249#define SIZE_T_ONE ((size_t)1)
1250#define SIZE_T_TWO ((size_t)2)
1251#define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1)
1252#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2)
1253#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES)
1254#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U)
1255
1256/* The bit mask value corresponding to MALLOC_ALIGNMENT */
1257#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE)
1258
1259/* True if address a has acceptable alignment */
1260#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0)
1261
1262/* the number of bytes to offset an address to align it */
1263#define align_offset(A)\
1264 ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\
1265 ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK))
1266
1267/* -------------------------- MMAP preliminaries ------------------------- */
1268
1269/*
1270 If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and
1271 checks to fail so compiler optimizer can delete code rather than
1272 using so many "#if"s.
1273*/
1274
1275
1276/* MORECORE and MMAP must return MFAIL on failure */
1277#define MFAIL ((void*)(MAX_SIZE_T))
1278#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */
1279
1280#if !HAVE_MMAP
1281#define IS_MMAPPED_BIT (SIZE_T_ZERO)
1282#define USE_MMAP_BIT (SIZE_T_ZERO)
1283#define CALL_MMAP(s) MFAIL
1284#define CALL_MUNMAP(a, s) (-1)
1285#define DIRECT_MMAP(s) MFAIL
1286
1287#else /* HAVE_MMAP */
1288#define IS_MMAPPED_BIT (SIZE_T_ONE)
1289#define USE_MMAP_BIT (SIZE_T_ONE)
1290
1291#ifndef WIN32
1292#define CALL_MUNMAP(a, s) munmap((a), (s))
1293#define MMAP_PROT (PROT_READ|PROT_WRITE)
1294#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1295#define MAP_ANONYMOUS MAP_ANON
1296#endif /* MAP_ANON */
1297#ifdef MAP_ANONYMOUS
1298#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS)
1299#define CALL_MMAP(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0)
1300#else /* MAP_ANONYMOUS */
1301/*
1302 Nearly all versions of mmap support MAP_ANONYMOUS, so the following
1303 is unlikely to be needed, but is supplied just in case.
1304*/
1305#define MMAP_FLAGS (MAP_PRIVATE)
1306static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
1307#define CALL_MMAP(s) ((dev_zero_fd < 0) ? \
1308 (dev_zero_fd = open("/dev/zero", O_RDWR), \
1309 mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \
1310 mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0))
1311#endif /* MAP_ANONYMOUS */
1312
1313#define DIRECT_MMAP(s) CALL_MMAP(s)
1314#else /* WIN32 */
1315
1316/* Win32 MMAP via VirtualAlloc */
1317static void* win32mmap(size_t size) {
1318 void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
1319 return (ptr != 0)? ptr: MFAIL;
1320}
1321
1322/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */
1323static void* win32direct_mmap(size_t size) {
1324 void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN,
1325 PAGE_READWRITE);
1326 return (ptr != 0)? ptr: MFAIL;
1327}
1328
1329/* This function supports releasing coalesed segments */
1330static int win32munmap(void* ptr, size_t size) {
1331 MEMORY_BASIC_INFORMATION minfo;
1332 char* cptr = ptr;
1333 while (size) {
1334 if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0)
1335 return -1;
1336 if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr ||
1337 minfo.State != MEM_COMMIT || minfo.RegionSize > size)
1338 return -1;
1339 if (VirtualFree(cptr, 0, MEM_RELEASE) == 0)
1340 return -1;
1341 cptr += minfo.RegionSize;
1342 size -= minfo.RegionSize;
1343 }
1344 return 0;
1345}
1346
1347#define CALL_MMAP(s) win32mmap(s)
1348#define CALL_MUNMAP(a, s) win32munmap((a), (s))
1349#define DIRECT_MMAP(s) win32direct_mmap(s)
1350#endif /* WIN32 */
1351#endif /* HAVE_MMAP */
1352
1353#if HAVE_MMAP && HAVE_MREMAP
1354#define CALL_MREMAP(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv))
1355#else /* HAVE_MMAP && HAVE_MREMAP */
1356#define CALL_MREMAP(addr, osz, nsz, mv) MFAIL
1357#endif /* HAVE_MMAP && HAVE_MREMAP */
1358
1359#if HAVE_MORECORE
1360#define CALL_MORECORE(S) MORECORE(S)
1361#else /* HAVE_MORECORE */
1362#define CALL_MORECORE(S) MFAIL
1363#endif /* HAVE_MORECORE */
1364
1365/* mstate bit set if continguous morecore disabled or failed */
1366#define USE_NONCONTIGUOUS_BIT (4U)
1367
1368/* segment bit set in create_mspace_with_base */
1369#define EXTERN_BIT (8U)
1370
1371
1372/* --------------------------- Lock preliminaries ------------------------ */
1373
1374#if USE_LOCKS
1375
1376/*
1377 When locks are defined, there are up to two global locks:
1378
1379 * If HAVE_MORECORE, morecore_mutex protects sequences of calls to
1380 MORECORE. In many cases sys_alloc requires two calls, that should
1381 not be interleaved with calls by other threads. This does not
1382 protect against direct calls to MORECORE by other threads not
1383 using this lock, so there is still code to cope the best we can on
1384 interference.
1385
1386 * magic_init_mutex ensures that mparams.magic and other
1387 unique mparams values are initialized only once.
1388*/
1389
1390#ifndef WIN32
1391/* By default use posix locks */
1392#include <pthread.h>
1393#define MLOCK_T pthread_mutex_t
1394#define INITIAL_LOCK(l) pthread_mutex_init(l, NULL)
1395#define ACQUIRE_LOCK(l) pthread_mutex_lock(l)
1396#define RELEASE_LOCK(l) pthread_mutex_unlock(l)
1397
1398#if HAVE_MORECORE
1399static MLOCK_T morecore_mutex = PTHREAD_MUTEX_INITIALIZER;
1400#endif /* HAVE_MORECORE */
1401
1402static MLOCK_T magic_init_mutex = PTHREAD_MUTEX_INITIALIZER;
1403
1404#else /* WIN32 */
1405/*
1406 Because lock-protected regions have bounded times, and there
1407 are no recursive lock calls, we can use simple spinlocks.
1408*/
1409
1410#define MLOCK_T long
1411static int win32_acquire_lock (MLOCK_T *sl) {
1412 for (;;) {
1413#ifdef InterlockedCompareExchangePointer
1414 if (!InterlockedCompareExchange(sl, 1, 0))
1415 return 0;
1416#else /* Use older void* version */
1417 if (!InterlockedCompareExchange((void**)sl, (void*)1, (void*)0))
1418 return 0;
1419#endif /* InterlockedCompareExchangePointer */
1420 Sleep (0);
1421 }
1422}
1423
1424static void win32_release_lock (MLOCK_T *sl) {
1425 InterlockedExchange (sl, 0);
1426}
1427
1428#define INITIAL_LOCK(l) *(l)=0
1429#define ACQUIRE_LOCK(l) win32_acquire_lock(l)
1430#define RELEASE_LOCK(l) win32_release_lock(l)
1431#if HAVE_MORECORE
1432static MLOCK_T morecore_mutex;
1433#endif /* HAVE_MORECORE */
1434static MLOCK_T magic_init_mutex;
1435#endif /* WIN32 */
1436
1437#define USE_LOCK_BIT (2U)
1438#else /* USE_LOCKS */
1439#define USE_LOCK_BIT (0U)
1440#define INITIAL_LOCK(l)
1441#endif /* USE_LOCKS */
1442
1443#if USE_LOCKS && HAVE_MORECORE
1444#define ACQUIRE_MORECORE_LOCK() ACQUIRE_LOCK(&morecore_mutex);
1445#define RELEASE_MORECORE_LOCK() RELEASE_LOCK(&morecore_mutex);
1446#else /* USE_LOCKS && HAVE_MORECORE */
1447#define ACQUIRE_MORECORE_LOCK()
1448#define RELEASE_MORECORE_LOCK()
1449#endif /* USE_LOCKS && HAVE_MORECORE */
1450
1451#if USE_LOCKS
1452#define ACQUIRE_MAGIC_INIT_LOCK() ACQUIRE_LOCK(&magic_init_mutex);
1453#define RELEASE_MAGIC_INIT_LOCK() RELEASE_LOCK(&magic_init_mutex);
1454#else /* USE_LOCKS */
1455#define ACQUIRE_MAGIC_INIT_LOCK()
1456#define RELEASE_MAGIC_INIT_LOCK()
1457#endif /* USE_LOCKS */
1458
1459
1460/* ----------------------- Chunk representations ------------------------ */
1461
1462/*
1463 (The following includes lightly edited explanations by Colin Plumb.)
1464
1465 The malloc_chunk declaration below is misleading (but accurate and
1466 necessary). It declares a "view" into memory allowing access to
1467 necessary fields at known offsets from a given base.
1468
1469 Chunks of memory are maintained using a `boundary tag' method as
1470 originally described by Knuth. (See the paper by Paul Wilson
1471 ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such
1472 techniques.) Sizes of free chunks are stored both in the front of
1473 each chunk and at the end. This makes consolidating fragmented
1474 chunks into bigger chunks fast. The head fields also hold bits
1475 representing whether chunks are free or in use.
1476
1477 Here are some pictures to make it clearer. They are "exploded" to
1478 show that the state of a chunk can be thought of as extending from
1479 the high 31 bits of the head field of its header through the
1480 prev_foot and PINUSE_BIT bit of the following chunk header.
1481
1482 A chunk that's in use looks like:
1483
1484 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1485 | Size of previous chunk (if P = 1) |
1486 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1487 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
1488 | Size of this chunk 1| +-+
1489 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1490 | |
1491 +- -+
1492 | |
1493 +- -+
1494 | :
1495 +- size - sizeof(size_t) available payload bytes -+
1496 : |
1497 chunk-> +- -+
1498 | |
1499 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1500 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1|
1501 | Size of next chunk (may or may not be in use) | +-+
1502 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1503
1504 And if it's free, it looks like this:
1505
1506 chunk-> +- -+
1507 | User payload (must be in use, or we would have merged!) |
1508 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1509 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
1510 | Size of this chunk 0| +-+
1511 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1512 | Next pointer |
1513 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1514 | Prev pointer |
1515 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1516 | :
1517 +- size - sizeof(struct chunk) unused bytes -+
1518 : |
1519 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1520 | Size of this chunk |
1521 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1522 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|
1523 | Size of next chunk (must be in use, or we would have merged)| +-+
1524 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1525 | :
1526 +- User payload -+
1527 : |
1528 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1529 |0|
1530 +-+
1531 Note that since we always merge adjacent free chunks, the chunks
1532 adjacent to a free chunk must be in use.
1533
1534 Given a pointer to a chunk (which can be derived trivially from the
1535 payload pointer) we can, in O(1) time, find out whether the adjacent
1536 chunks are free, and if so, unlink them from the lists that they
1537 are on and merge them with the current chunk.
1538
1539 Chunks always begin on even word boundaries, so the mem portion
1540 (which is returned to the user) is also on an even word boundary, and
1541 thus at least double-word aligned.
1542
1543 The P (PINUSE_BIT) bit, stored in the unused low-order bit of the
1544 chunk size (which is always a multiple of two words), is an in-use
1545 bit for the *previous* chunk. If that bit is *clear*, then the
1546 word before the current chunk size contains the previous chunk
1547 size, and can be used to find the front of the previous chunk.
1548 The very first chunk allocated always has this bit set, preventing
1549 access to non-existent (or non-owned) memory. If pinuse is set for
1550 any given chunk, then you CANNOT determine the size of the
1551 previous chunk, and might even get a memory addressing fault when
1552 trying to do so.
1553
1554 The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of
1555 the chunk size redundantly records whether the current chunk is
1556 inuse. This redundancy enables usage checks within free and realloc,
1557 and reduces indirection when freeing and consolidating chunks.
1558
1559 Each freshly allocated chunk must have both cinuse and pinuse set.
1560 That is, each allocated chunk borders either a previously allocated
1561 and still in-use chunk, or the base of its memory arena. This is
1562 ensured by making all allocations from the the `lowest' part of any
1563 found chunk. Further, no free chunk physically borders another one,
1564 so each free chunk is known to be preceded and followed by either
1565 inuse chunks or the ends of memory.
1566
1567 Note that the `foot' of the current chunk is actually represented
1568 as the prev_foot of the NEXT chunk. This makes it easier to
1569 deal with alignments etc but can be very confusing when trying
1570 to extend or adapt this code.
1571
1572 The exceptions to all this are
1573
1574 1. The special chunk `top' is the top-most available chunk (i.e.,
1575 the one bordering the end of available memory). It is treated
1576 specially. Top is never included in any bin, is used only if
1577 no other chunk is available, and is released back to the
1578 system if it is very large (see M_TRIM_THRESHOLD). In effect,
1579 the top chunk is treated as larger (and thus less well
1580 fitting) than any other available chunk. The top chunk
1581 doesn't update its trailing size field since there is no next
1582 contiguous chunk that would have to index off it. However,
1583 space is still allocated for it (TOP_FOOT_SIZE) to enable
1584 separation or merging when space is extended.
1585
1586 3. Chunks allocated via mmap, which have the lowest-order bit
1587 (IS_MMAPPED_BIT) set in their prev_foot fields, and do not set
1588 PINUSE_BIT in their head fields. Because they are allocated
1589 one-by-one, each must carry its own prev_foot field, which is
1590 also used to hold the offset this chunk has within its mmapped
1591 region, which is needed to preserve alignment. Each mmapped
1592 chunk is trailed by the first two fields of a fake next-chunk
1593 for sake of usage checks.
1594
1595*/
1596
1597struct malloc_chunk {
1598 size_t prev_foot; /* Size of previous chunk (if free). */
1599 size_t head; /* Size and inuse bits. */
1600 struct malloc_chunk* fd; /* double links -- used only if free. */
1601 struct malloc_chunk* bk;
1602};
1603
1604typedef struct malloc_chunk mchunk;
1605typedef struct malloc_chunk* mchunkptr;
1606typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */
1607typedef unsigned int bindex_t; /* Described below */
1608typedef unsigned int binmap_t; /* Described below */
1609typedef unsigned int flag_t; /* The type of various bit flag sets */
1610
1611/* ------------------- Chunks sizes and alignments ----------------------- */
1612
1613#define MCHUNK_SIZE (sizeof(mchunk))
1614
1615#if FOOTERS
1616#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
1617#else /* FOOTERS */
1618#define CHUNK_OVERHEAD (SIZE_T_SIZE)
1619#endif /* FOOTERS */
1620
1621/* MMapped chunks need a second word of overhead ... */
1622#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
1623/* ... and additional padding for fake next-chunk at foot */
1624#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES)
1625
1626/* The smallest size we can malloc is an aligned minimal chunk */
1627#define MIN_CHUNK_SIZE\
1628 ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
1629
1630/* conversion from malloc headers to user pointers, and back */
1631#define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES))
1632#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES))
1633/* chunk associated with aligned address A */
1634#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A)))
1635
1636/* Bounds on request (not chunk) sizes. */
1637#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2)
1638#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE)
1639
1640/* pad request bytes into a usable size */
1641#define pad_request(req) \
1642 (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
1643
1644/* pad request, checking for minimum (but not maximum) */
1645#define request2size(req) \
1646 (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req))
1647
1648
1649/* ------------------ Operations on head and foot fields ----------------- */
1650
1651/*
1652 The head field of a chunk is or'ed with PINUSE_BIT when previous
1653 adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in
1654 use. If the chunk was obtained with mmap, the prev_foot field has
1655 IS_MMAPPED_BIT set, otherwise holding the offset of the base of the
1656 mmapped region to the base of the chunk.
1657*/
1658
1659#define PINUSE_BIT (SIZE_T_ONE)
1660#define CINUSE_BIT (SIZE_T_TWO)
1661#define INUSE_BITS (PINUSE_BIT|CINUSE_BIT)
1662
1663/* Head value for fenceposts */
1664#define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE)
1665
1666/* extraction of fields from head words */
1667#define cinuse(p) ((p)->head & CINUSE_BIT)
1668#define pinuse(p) ((p)->head & PINUSE_BIT)
1669#define chunksize(p) ((p)->head & ~(INUSE_BITS))
1670
1671#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT)
1672#define clear_cinuse(p) ((p)->head &= ~CINUSE_BIT)
1673
1674/* Treat space at ptr +/- offset as a chunk */
1675#define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
1676#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s)))
1677
1678/* Ptr to next or previous physical malloc_chunk. */
1679#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~INUSE_BITS)))
1680#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) ))
1681
1682/* extract next chunk's pinuse bit */
1683#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT)
1684
1685/* Get/set size at footer */
1686#define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot)
1687#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s))
1688
1689/* Set size, pinuse bit, and foot */
1690#define set_size_and_pinuse_of_free_chunk(p, s)\
1691 ((p)->head = (s|PINUSE_BIT), set_foot(p, s))
1692
1693/* Set size, pinuse bit, foot, and clear next pinuse */
1694#define set_free_with_pinuse(p, s, n)\
1695 (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s))
1696
1697#define is_mmapped(p)\
1698 (!((p)->head & PINUSE_BIT) && ((p)->prev_foot & IS_MMAPPED_BIT))
1699
1700/* Get the internal overhead associated with chunk p */
1701#define overhead_for(p)\
1702 (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD)
1703
1704/* Return true if malloced space is not necessarily cleared */
1705#if MMAP_CLEARS
1706#define calloc_must_clear(p) (!is_mmapped(p))
1707#else /* MMAP_CLEARS */
1708#define calloc_must_clear(p) (1)
1709#endif /* MMAP_CLEARS */
1710
1711/* ---------------------- Overlaid data structures ----------------------- */
1712
1713/*
1714 When chunks are not in use, they are treated as nodes of either
1715 lists or trees.
1716
1717 "Small" chunks are stored in circular doubly-linked lists, and look
1718 like this:
1719
1720 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1721 | Size of previous chunk |
1722 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1723 `head:' | Size of chunk, in bytes |P|
1724 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1725 | Forward pointer to next chunk in list |
1726 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1727 | Back pointer to previous chunk in list |
1728 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1729 | Unused space (may be 0 bytes long) .
1730 . .
1731 . |
1732nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1733 `foot:' | Size of chunk, in bytes |
1734 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1735
1736 Larger chunks are kept in a form of bitwise digital trees (aka
1737 tries) keyed on chunksizes. Because malloc_tree_chunks are only for
1738 free chunks greater than 256 bytes, their size doesn't impose any
1739 constraints on user chunk sizes. Each node looks like:
1740
1741 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1742 | Size of previous chunk |
1743 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1744 `head:' | Size of chunk, in bytes |P|
1745 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1746 | Forward pointer to next chunk of same size |
1747 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1748 | Back pointer to previous chunk of same size |
1749 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1750 | Pointer to left child (child[0]) |
1751 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1752 | Pointer to right child (child[1]) |
1753 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1754 | Pointer to parent |
1755 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1756 | bin index of this chunk |
1757 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1758 | Unused space .
1759 . |
1760nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1761 `foot:' | Size of chunk, in bytes |
1762 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1763
1764 Each tree holding treenodes is a tree of unique chunk sizes. Chunks
1765 of the same size are arranged in a circularly-linked list, with only
1766 the oldest chunk (the next to be used, in our FIFO ordering)
1767 actually in the tree. (Tree members are distinguished by a non-null
1768 parent pointer.) If a chunk with the same size an an existing node
1769 is inserted, it is linked off the existing node using pointers that
1770 work in the same way as fd/bk pointers of small chunks.
1771
1772 Each tree contains a power of 2 sized range of chunk sizes (the
1773 smallest is 0x100 <= x < 0x180), which is is divided in half at each
1774 tree level, with the chunks in the smaller half of the range (0x100
1775 <= x < 0x140 for the top nose) in the left subtree and the larger
1776 half (0x140 <= x < 0x180) in the right subtree. This is, of course,
1777 done by inspecting individual bits.
1778
1779 Using these rules, each node's left subtree contains all smaller
1780 sizes than its right subtree. However, the node at the root of each
1781 subtree has no particular ordering relationship to either. (The
1782 dividing line between the subtree sizes is based on trie relation.)
1783 If we remove the last chunk of a given size from the interior of the
1784 tree, we need to replace it with a leaf node. The tree ordering
1785 rules permit a node to be replaced by any leaf below it.
1786
1787 The smallest chunk in a tree (a common operation in a best-fit
1788 allocator) can be found by walking a path to the leftmost leaf in
1789 the tree. Unlike a usual binary tree, where we follow left child
1790 pointers until we reach a null, here we follow the right child
1791 pointer any time the left one is null, until we reach a leaf with
1792 both child pointers null. The smallest chunk in the tree will be
1793 somewhere along that path.
1794
1795 The worst case number of steps to add, find, or remove a node is
1796 bounded by the number of bits differentiating chunks within
1797 bins. Under current bin calculations, this ranges from 6 up to 21
1798 (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case
1799 is of course much better.
1800*/
1801
1802struct malloc_tree_chunk {
1803 /* The first four fields must be compatible with malloc_chunk */
1804 size_t prev_foot;
1805 size_t head;
1806 struct malloc_tree_chunk* fd;
1807 struct malloc_tree_chunk* bk;
1808
1809 struct malloc_tree_chunk* child[2];
1810 struct malloc_tree_chunk* parent;
1811 bindex_t index;
1812};
1813
1814typedef struct malloc_tree_chunk tchunk;
1815typedef struct malloc_tree_chunk* tchunkptr;
1816typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */
1817
1818/* A little helper macro for trees */
1819#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1])
1820
1821/* ----------------------------- Segments -------------------------------- */
1822
1823/*
1824 Each malloc space may include non-contiguous segments, held in a
1825 list headed by an embedded malloc_segment record representing the
1826 top-most space. Segments also include flags holding properties of
1827 the space. Large chunks that are directly allocated by mmap are not
1828 included in this list. They are instead independently created and
1829 destroyed without otherwise keeping track of them.
1830
1831 Segment management mainly comes into play for spaces allocated by
1832 MMAP. Any call to MMAP might or might not return memory that is
1833 adjacent to an existing segment. MORECORE normally contiguously
1834 extends the current space, so this space is almost always adjacent,
1835 which is simpler and faster to deal with. (This is why MORECORE is
1836 used preferentially to MMAP when both are available -- see
1837 sys_alloc.) When allocating using MMAP, we don't use any of the
1838 hinting mechanisms (inconsistently) supported in various
1839 implementations of unix mmap, or distinguish reserving from
1840 committing memory. Instead, we just ask for space, and exploit
1841 contiguity when we get it. It is probably possible to do
1842 better than this on some systems, but no general scheme seems
1843 to be significantly better.
1844
1845 Management entails a simpler variant of the consolidation scheme
1846 used for chunks to reduce fragmentation -- new adjacent memory is
1847 normally prepended or appended to an existing segment. However,
1848 there are limitations compared to chunk consolidation that mostly
1849 reflect the fact that segment processing is relatively infrequent
1850 (occurring only when getting memory from system) and that we
1851 don't expect to have huge numbers of segments:
1852
1853 * Segments are not indexed, so traversal requires linear scans. (It
1854 would be possible to index these, but is not worth the extra
1855 overhead and complexity for most programs on most platforms.)
1856 * New segments are only appended to old ones when holding top-most
1857 memory; if they cannot be prepended to others, they are held in
1858 different segments.
1859
1860 Except for the top-most segment of an mstate, each segment record
1861 is kept at the tail of its segment. Segments are added by pushing
1862 segment records onto the list headed by &mstate.seg for the
1863 containing mstate.
1864
1865 Segment flags control allocation/merge/deallocation policies:
1866 * If EXTERN_BIT set, then we did not allocate this segment,
1867 and so should not try to deallocate or merge with others.
1868 (This currently holds only for the initial segment passed
1869 into create_mspace_with_base.)
1870 * If IS_MMAPPED_BIT set, the segment may be merged with
1871 other surrounding mmapped segments and trimmed/de-allocated
1872 using munmap.
1873 * If neither bit is set, then the segment was obtained using
1874 MORECORE so can be merged with surrounding MORECORE'd segments
1875 and deallocated/trimmed using MORECORE with negative arguments.
1876*/
1877
1878struct malloc_segment {
1879 char* base; /* base address */
1880 size_t size; /* allocated size */
1881 struct malloc_segment* next; /* ptr to next segment */
1882 flag_t sflags; /* mmap and extern flag */
1883};
1884
1885#define is_mmapped_segment(S) ((S)->sflags & IS_MMAPPED_BIT)
1886#define is_extern_segment(S) ((S)->sflags & EXTERN_BIT)
1887
1888typedef struct malloc_segment msegment;
1889typedef struct malloc_segment* msegmentptr;
1890
1891/* ---------------------------- malloc_state ----------------------------- */
1892
1893/*
1894 A malloc_state holds all of the bookkeeping for a space.
1895 The main fields are:
1896
1897 Top
1898 The topmost chunk of the currently active segment. Its size is
1899 cached in topsize. The actual size of topmost space is
1900 topsize+TOP_FOOT_SIZE, which includes space reserved for adding
1901 fenceposts and segment records if necessary when getting more
1902 space from the system. The size at which to autotrim top is
1903 cached from mparams in trim_check, except that it is disabled if
1904 an autotrim fails.
1905
1906 Designated victim (dv)
1907 This is the preferred chunk for servicing small requests that
1908 don't have exact fits. It is normally the chunk split off most
1909 recently to service another small request. Its size is cached in
1910 dvsize. The link fields of this chunk are not maintained since it
1911 is not kept in a bin.
1912
1913 SmallBins
1914 An array of bin headers for free chunks. These bins hold chunks
1915 with sizes less than MIN_LARGE_SIZE bytes. Each bin contains
1916 chunks of all the same size, spaced 8 bytes apart. To simplify
1917 use in double-linked lists, each bin header acts as a malloc_chunk
1918 pointing to the real first node, if it exists (else pointing to
1919 itself). This avoids special-casing for headers. But to avoid
1920 waste, we allocate only the fd/bk pointers of bins, and then use
1921 repositioning tricks to treat these as the fields of a chunk.
1922
1923 TreeBins
1924 Treebins are pointers to the roots of trees holding a range of
1925 sizes. There are 2 equally spaced treebins for each power of two
1926 from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything
1927 larger.
1928
1929 Bin maps
1930 There is one bit map for small bins ("smallmap") and one for
1931 treebins ("treemap). Each bin sets its bit when non-empty, and
1932 clears the bit when empty. Bit operations are then used to avoid
1933 bin-by-bin searching -- nearly all "search" is done without ever
1934 looking at bins that won't be selected. The bit maps
1935 conservatively use 32 bits per map word, even if on 64bit system.
1936 For a good description of some of the bit-based techniques used
1937 here, see Henry S. Warren Jr's book "Hacker's Delight" (and
1938 supplement at http://hackersdelight.org/). Many of these are
1939 intended to reduce the branchiness of paths through malloc etc, as
1940 well as to reduce the number of memory locations read or written.
1941
1942 Segments
1943 A list of segments headed by an embedded malloc_segment record
1944 representing the initial space.
1945
1946 Address check support
1947 The least_addr field is the least address ever obtained from
1948 MORECORE or MMAP. Attempted frees and reallocs of any address less
1949 than this are trapped (unless INSECURE is defined).
1950
1951 Magic tag
1952 A cross-check field that should always hold same value as mparams.magic.
1953
1954 Flags
1955 Bits recording whether to use MMAP, locks, or contiguous MORECORE
1956
1957 Statistics
1958 Each space keeps track of current and maximum system memory
1959 obtained via MORECORE or MMAP.
1960
1961 Locking
1962 If USE_LOCKS is defined, the "mutex" lock is acquired and released
1963 around every public call using this mspace.
1964*/
1965
1966/* Bin types, widths and sizes */
1967#define NSMALLBINS (32U)
1968#define NTREEBINS (32U)
1969#define SMALLBIN_SHIFT (3U)
1970#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT)
1971#define TREEBIN_SHIFT (8U)
1972#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT)
1973#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE)
1974#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)
1975
1976struct malloc_state {
1977 binmap_t smallmap;
1978 binmap_t treemap;
1979 size_t dvsize;
1980 size_t topsize;
1981 char* least_addr;
1982 mchunkptr dv;
1983 mchunkptr top;
1984 size_t trim_check;
1985 size_t magic;
1986 mchunkptr smallbins[(NSMALLBINS+1)*2];
1987 tbinptr treebins[NTREEBINS];
1988 size_t footprint;
1989 size_t max_footprint;
1990 flag_t mflags;
1991#if USE_LOCKS
1992 MLOCK_T mutex; /* locate lock among fields that rarely change */
1993#endif /* USE_LOCKS */
1994 msegment seg;
1995};
1996
1997typedef struct malloc_state* mstate;
1998
1999/* ------------- Global malloc_state and malloc_params ------------------- */
2000
2001/*
2002 malloc_params holds global properties, including those that can be
2003 dynamically set using mallopt. There is a single instance, mparams,
2004 initialized in init_mparams.
2005*/
2006
2007struct malloc_params {
2008 size_t magic;
2009 size_t page_size;
2010 size_t granularity;
2011 size_t mmap_threshold;
2012 size_t trim_threshold;
2013 flag_t default_mflags;
2014};
2015
2016static struct malloc_params mparams;
2017
2018/* The global malloc_state used for all non-"mspace" calls */
2019static struct malloc_state _gm_;
2020#define gm (&_gm_)
2021#define is_global(M) ((M) == &_gm_)
2022#define is_initialized(M) ((M)->top != 0)
2023
2024/* -------------------------- system alloc setup ------------------------- */
2025
2026/* Operations on mflags */
2027
2028#define use_lock(M) ((M)->mflags & USE_LOCK_BIT)
2029#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT)
2030#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT)
2031
2032#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT)
2033#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT)
2034#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT)
2035
2036#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT)
2037#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT)
2038
2039#define set_lock(M,L)\
2040 ((M)->mflags = (L)?\
2041 ((M)->mflags | USE_LOCK_BIT) :\
2042 ((M)->mflags & ~USE_LOCK_BIT))
2043
2044/* page-align a size */
2045#define page_align(S)\
2046 (((S) + (mparams.page_size)) & ~(mparams.page_size - SIZE_T_ONE))
2047
2048/* granularity-align a size */
2049#define granularity_align(S)\
2050 (((S) + (mparams.granularity)) & ~(mparams.granularity - SIZE_T_ONE))
2051
2052#define is_page_aligned(S)\
2053 (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0)
2054#define is_granularity_aligned(S)\
2055 (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0)
2056
2057/* True if segment S holds address A */
2058#define segment_holds(S, A)\
2059 ((char*)(A) >= S->base && (char*)(A) < S->base + S->size)
2060
2061/* Return segment holding given address */
2062static msegmentptr segment_holding(mstate m, char* addr) {
2063 msegmentptr sp = &m->seg;
2064 for (;;) {
2065 if (addr >= sp->base && addr < sp->base + sp->size)
2066 return sp;
2067 if ((sp = sp->next) == 0)
2068 return 0;
2069 }
2070}
2071
2072/* Return true if segment contains a segment link */
2073static int has_segment_link(mstate m, msegmentptr ss) {
2074 msegmentptr sp = &m->seg;
2075 for (;;) {
2076 if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size)
2077 return 1;
2078 if ((sp = sp->next) == 0)
2079 return 0;
2080 }
2081}
2082
2083#ifndef MORECORE_CANNOT_TRIM
2084#define should_trim(M,s) ((s) > (M)->trim_check)
2085#else /* MORECORE_CANNOT_TRIM */
2086#define should_trim(M,s) (0)
2087#endif /* MORECORE_CANNOT_TRIM */
2088
2089/*
2090 TOP_FOOT_SIZE is padding at the end of a segment, including space
2091 that may be needed to place segment records and fenceposts when new
2092 noncontiguous segments are added.
2093*/
2094#define TOP_FOOT_SIZE\
2095 (align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE)
2096
2097
2098/* ------------------------------- Hooks -------------------------------- */
2099
2100/*
2101 PREACTION should be defined to return 0 on success, and nonzero on
2102 failure. If you are not using locking, you can redefine these to do
2103 anything you like.
2104*/
2105
2106#if USE_LOCKS
2107
2108/* Ensure locks are initialized */
2109#define GLOBALLY_INITIALIZE() (mparams.page_size == 0 && init_mparams())
2110
2111#define PREACTION(M) ((GLOBALLY_INITIALIZE() || use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0)
2112#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); }
2113#else /* USE_LOCKS */
2114
2115#ifndef PREACTION
2116#define PREACTION(M) (0)
2117#endif /* PREACTION */
2118
2119#ifndef POSTACTION
2120#define POSTACTION(M)
2121#endif /* POSTACTION */
2122
2123#endif /* USE_LOCKS */
2124
2125/*
2126 CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses.
2127 USAGE_ERROR_ACTION is triggered on detected bad frees and
2128 reallocs. The argument p is an address that might have triggered the
2129 fault. It is ignored by the two predefined actions, but might be
2130 useful in custom actions that try to help diagnose errors.
2131*/
2132
2133#if PROCEED_ON_ERROR
2134
2135/* A count of the number of corruption errors causing resets */
2136int malloc_corruption_error_count;
2137
2138/* default corruption action */
2139static void reset_on_error(mstate m);
2140
2141#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m)
2142#define USAGE_ERROR_ACTION(m, p)
2143
2144#else /* PROCEED_ON_ERROR */
2145
2146#ifndef CORRUPTION_ERROR_ACTION
2147#define CORRUPTION_ERROR_ACTION(m) ABORT
2148#endif /* CORRUPTION_ERROR_ACTION */
2149
2150#ifndef USAGE_ERROR_ACTION
2151#define USAGE_ERROR_ACTION(m,p) ABORT
2152#endif /* USAGE_ERROR_ACTION */
2153
2154#endif /* PROCEED_ON_ERROR */
2155
2156/* -------------------------- Debugging setup ---------------------------- */
2157
2158#if ! DEBUG
2159
2160#define check_free_chunk(M,P)
2161#define check_inuse_chunk(M,P)
2162#define check_malloced_chunk(M,P,N)
2163#define check_mmapped_chunk(M,P)
2164#define check_malloc_state(M)
2165#define check_top_chunk(M,P)
2166
2167#else /* DEBUG */
2168#define check_free_chunk(M,P) do_check_free_chunk(M,P)
2169#define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P)
2170#define check_top_chunk(M,P) do_check_top_chunk(M,P)
2171#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N)
2172#define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P)
2173#define check_malloc_state(M) do_check_malloc_state(M)
2174
2175static void do_check_any_chunk(mstate m, mchunkptr p);
2176static void do_check_top_chunk(mstate m, mchunkptr p);
2177static void do_check_mmapped_chunk(mstate m, mchunkptr p);
2178static void do_check_inuse_chunk(mstate m, mchunkptr p);
2179static void do_check_free_chunk(mstate m, mchunkptr p);
2180static void do_check_malloced_chunk(mstate m, void* mem, size_t s);
2181static void do_check_tree(mstate m, tchunkptr t);
2182static void do_check_treebin(mstate m, bindex_t i);
2183static void do_check_smallbin(mstate m, bindex_t i);
2184static void do_check_malloc_state(mstate m);
2185static int bin_find(mstate m, mchunkptr x);
2186static size_t traverse_and_check(mstate m);
2187#endif /* DEBUG */
2188
2189/* ---------------------------- Indexing Bins ---------------------------- */
2190
2191#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS)
2192#define small_index(s) ((s) >> SMALLBIN_SHIFT)
2193#define small_index2size(i) ((i) << SMALLBIN_SHIFT)
2194#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE))
2195
2196/* addressing by index. See above about smallbin repositioning */
2197#define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1])))
2198#define treebin_at(M,i) (&((M)->treebins[i]))
2199
2200/* assign tree index for size S to variable I */
2201#if defined(__GNUC__) && defined(i386)
2202#define compute_tree_index(S, I)\
2203{\
2204 size_t X = S >> TREEBIN_SHIFT;\
2205 if (X == 0)\
2206 I = 0;\
2207 else if (X > 0xFFFF)\
2208 I = NTREEBINS-1;\
2209 else {\
2210 unsigned int K;\
2211 __asm__("bsrl %1,%0\n\t" : "=r" (K) : "rm" (X));\
2212 I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
2213 }\
2214}
2215#else /* GNUC */
2216#define compute_tree_index(S, I)\
2217{\
2218 size_t X = S >> TREEBIN_SHIFT;\
2219 if (X == 0)\
2220 I = 0;\
2221 else if (X > 0xFFFF)\
2222 I = NTREEBINS-1;\
2223 else {\
2224 unsigned int Y = (unsigned int)X;\
2225 unsigned int N = ((Y - 0x100) >> 16) & 8;\
2226 unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\
2227 N += K;\
2228 N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\
2229 K = 14 - N + ((Y <<= K) >> 15);\
2230 I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\
2231 }\
2232}
2233#endif /* GNUC */
2234
2235/* Bit representing maximum resolved size in a treebin at i */
2236#define bit_for_tree_index(i) \
2237 (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2)
2238
2239/* Shift placing maximum resolved bit in a treebin at i as sign bit */
2240#define leftshift_for_tree_index(i) \
2241 ((i == NTREEBINS-1)? 0 : \
2242 ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2)))
2243
2244/* The size of the smallest chunk held in bin with index i */
2245#define minsize_for_tree_index(i) \
2246 ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \
2247 (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1)))
2248
2249
2250/* ------------------------ Operations on bin maps ----------------------- */
2251
2252/* bit corresponding to given index */
2253#define idx2bit(i) ((binmap_t)(1) << (i))
2254
2255/* Mark/Clear bits with given index */
2256#define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i))
2257#define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i))
2258#define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i))
2259
2260#define mark_treemap(M,i) ((M)->treemap |= idx2bit(i))
2261#define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i))
2262#define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i))
2263
2264/* index corresponding to given bit */
2265
2266#if defined(__GNUC__) && defined(i386)
2267#define compute_bit2idx(X, I)\
2268{\
2269 unsigned int J;\
2270 __asm__("bsfl %1,%0\n\t" : "=r" (J) : "rm" (X));\
2271 I = (bindex_t)J;\
2272}
2273
2274#else /* GNUC */
2275#if USE_BUILTIN_FFS
2276#define compute_bit2idx(X, I) I = ffs(X)-1
2277
2278#else /* USE_BUILTIN_FFS */
2279#define compute_bit2idx(X, I)\
2280{\
2281 unsigned int Y = X - 1;\
2282 unsigned int K = Y >> (16-4) & 16;\
2283 unsigned int N = K; Y >>= K;\
2284 N += K = Y >> (8-3) & 8; Y >>= K;\
2285 N += K = Y >> (4-2) & 4; Y >>= K;\
2286 N += K = Y >> (2-1) & 2; Y >>= K;\
2287 N += K = Y >> (1-0) & 1; Y >>= K;\
2288 I = (bindex_t)(N + Y);\
2289}
2290#endif /* USE_BUILTIN_FFS */
2291#endif /* GNUC */
2292
2293/* isolate the least set bit of a bitmap */
2294#define least_bit(x) ((x) & -(x))
2295
2296/* mask with all bits to left of least bit of x on */
2297#define left_bits(x) ((x<<1) | -(x<<1))
2298
2299/* mask with all bits to left of or equal to least bit of x on */
2300#define same_or_left_bits(x) ((x) | -(x))
2301
2302
2303/* ----------------------- Runtime Check Support ------------------------- */
2304
2305/*
2306 For security, the main invariant is that malloc/free/etc never
2307 writes to a static address other than malloc_state, unless static
2308 malloc_state itself has been corrupted, which cannot occur via
2309 malloc (because of these checks). In essence this means that we
2310 believe all pointers, sizes, maps etc held in malloc_state, but
2311 check all of those linked or offsetted from other embedded data
2312 structures. These checks are interspersed with main code in a way
2313 that tends to minimize their run-time cost.
2314
2315 When FOOTERS is defined, in addition to range checking, we also
2316 verify footer fields of inuse chunks, which can be used guarantee
2317 that the mstate controlling malloc/free is intact. This is a
2318 streamlined version of the approach described by William Robertson
2319 et al in "Run-time Detection of Heap-based Overflows" LISA'03
2320 http://www.usenix.org/events/lisa03/tech/robertson.html The footer
2321 of an inuse chunk holds the xor of its mstate and a random seed,
2322 that is checked upon calls to free() and realloc(). This is
2323 (probablistically) unguessable from outside the program, but can be
2324 computed by any code successfully malloc'ing any chunk, so does not
2325 itself provide protection against code that has already broken
2326 security through some other means. Unlike Robertson et al, we
2327 always dynamically check addresses of all offset chunks (previous,
2328 next, etc). This turns out to be cheaper than relying on hashes.
2329*/
2330
2331#if !INSECURE
2332/* Check if address a is at least as high as any from MORECORE or MMAP */
2333#define ok_address(M, a) ((char*)(a) >= (M)->least_addr)
2334/* Check if address of next chunk n is higher than base chunk p */
2335#define ok_next(p, n) ((char*)(p) < (char*)(n))
2336/* Check if p has its cinuse bit on */
2337#define ok_cinuse(p) cinuse(p)
2338/* Check if p has its pinuse bit on */
2339#define ok_pinuse(p) pinuse(p)
2340
2341#else /* !INSECURE */
2342#define ok_address(M, a) (1)
2343#define ok_next(b, n) (1)
2344#define ok_cinuse(p) (1)
2345#define ok_pinuse(p) (1)
2346#endif /* !INSECURE */
2347
2348#if (FOOTERS && !INSECURE)
2349/* Check if (alleged) mstate m has expected magic field */
2350#define ok_magic(M) ((M)->magic == mparams.magic)
2351#else /* (FOOTERS && !INSECURE) */
2352#define ok_magic(M) (1)
2353#endif /* (FOOTERS && !INSECURE) */
2354
2355
2356/* In gcc, use __builtin_expect to minimize impact of checks */
2357#if !INSECURE
2358#if defined(__GNUC__) && __GNUC__ >= 3
2359#define RTCHECK(e) __builtin_expect(e, 1)
2360#else /* GNUC */
2361#define RTCHECK(e) (e)
2362#endif /* GNUC */
2363#else /* !INSECURE */
2364#define RTCHECK(e) (1)
2365#endif /* !INSECURE */
2366
2367/* macros to set up inuse chunks with or without footers */
2368
2369#if !FOOTERS
2370
2371#define mark_inuse_foot(M,p,s)
2372
2373/* Set cinuse bit and pinuse bit of next chunk */
2374#define set_inuse(M,p,s)\
2375 ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
2376 ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
2377
2378/* Set cinuse and pinuse of this chunk and pinuse of next chunk */
2379#define set_inuse_and_pinuse(M,p,s)\
2380 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
2381 ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
2382
2383/* Set size, cinuse and pinuse bit of this chunk */
2384#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
2385 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT))
2386
2387#else /* FOOTERS */
2388
2389/* Set foot of inuse chunk to be xor of mstate and seed */
2390#define mark_inuse_foot(M,p,s)\
2391 (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic))
2392
2393#define get_mstate_for(p)\
2394 ((mstate)(((mchunkptr)((char*)(p) +\
2395 (chunksize(p))))->prev_foot ^ mparams.magic))
2396
2397#define set_inuse(M,p,s)\
2398 ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
2399 (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \
2400 mark_inuse_foot(M,p,s))
2401
2402#define set_inuse_and_pinuse(M,p,s)\
2403 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
2404 (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\
2405 mark_inuse_foot(M,p,s))
2406
2407#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
2408 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
2409 mark_inuse_foot(M, p, s))
2410
2411#endif /* !FOOTERS */
2412
2413/* ---------------------------- setting mparams -------------------------- */
2414
2415/* Initialize mparams */
2416static int init_mparams(void) {
2417 if (mparams.page_size == 0) {
2418 size_t s;
2419
2420 mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
2421 mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD;
2422#if MORECORE_CONTIGUOUS
2423 mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT;
2424#else /* MORECORE_CONTIGUOUS */
2425 mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT;
2426#endif /* MORECORE_CONTIGUOUS */
2427
2428#if (FOOTERS && !INSECURE)
2429 {
2430#if USE_DEV_RANDOM
2431 int fd;
2432 unsigned char buf[sizeof(size_t)];
2433 /* Try to use /dev/urandom, else fall back on using time */
2434 if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 &&
2435 read(fd, buf, sizeof(buf)) == sizeof(buf)) {
2436 s = *((size_t *) buf);
2437 close(fd);
2438 }
2439 else
2440#endif /* USE_DEV_RANDOM */
2441 s = (size_t)(time(0) ^ (size_t)0x55555555U);
2442
2443 s |= (size_t)8U; /* ensure nonzero */
2444 s &= ~(size_t)7U; /* improve chances of fault for bad values */
2445
2446 }
2447#else /* (FOOTERS && !INSECURE) */
2448 s = (size_t)0x58585858U;
2449#endif /* (FOOTERS && !INSECURE) */
2450 ACQUIRE_MAGIC_INIT_LOCK();
2451 if (mparams.magic == 0) {
2452 mparams.magic = s;
2453 /* Set up lock for main malloc area */
2454 INITIAL_LOCK(&gm->mutex);
2455 gm->mflags = mparams.default_mflags;
2456 }
2457 RELEASE_MAGIC_INIT_LOCK();
2458
2459#ifndef WIN32
2460 mparams.page_size = malloc_getpagesize;
2461 mparams.granularity = ((DEFAULT_GRANULARITY != 0)?
2462 DEFAULT_GRANULARITY : mparams.page_size);
2463#else /* WIN32 */
2464 {
2465 SYSTEM_INFO system_info;
2466 GetSystemInfo(&system_info);
2467 mparams.page_size = system_info.dwPageSize;
2468 mparams.granularity = system_info.dwAllocationGranularity;
2469 }
2470#endif /* WIN32 */
2471
2472 /* Sanity-check configuration:
2473 size_t must be unsigned and as wide as pointer type.
2474 ints must be at least 4 bytes.
2475 alignment must be at least 8.
2476 Alignment, min chunk size, and page size must all be powers of 2.
2477 */
2478 if ((sizeof(size_t) != sizeof(char*)) ||
2479 (MAX_SIZE_T < MIN_CHUNK_SIZE) ||
2480 (sizeof(int) < 4) ||
2481 (MALLOC_ALIGNMENT < (size_t)8U) ||
2482 ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) ||
2483 ((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) ||
2484 ((mparams.granularity & (mparams.granularity-SIZE_T_ONE)) != 0) ||
2485 ((mparams.page_size & (mparams.page_size-SIZE_T_ONE)) != 0))
2486 ABORT;
2487 }
2488 return 0;
2489}
2490
2491/* support for mallopt */
2492static int change_mparam(int param_number, int value) {
2493 size_t val = (size_t)value;
2494 init_mparams();
2495 switch(param_number) {
2496 case M_TRIM_THRESHOLD:
2497 mparams.trim_threshold = val;
2498 return 1;
2499 case M_GRANULARITY:
2500 if (val >= mparams.page_size && ((val & (val-1)) == 0)) {
2501 mparams.granularity = val;
2502 return 1;
2503 }
2504 else
2505 return 0;
2506 case M_MMAP_THRESHOLD:
2507 mparams.mmap_threshold = val;
2508 return 1;
2509 default:
2510 return 0;
2511 }
2512}
2513
2514#if DEBUG
2515/* ------------------------- Debugging Support --------------------------- */
2516
2517/* Check properties of any chunk, whether free, inuse, mmapped etc */
2518static void do_check_any_chunk(mstate m, mchunkptr p) {
2519 assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
2520 assert(ok_address(m, p));
2521}
2522
2523/* Check properties of top chunk */
2524static void do_check_top_chunk(mstate m, mchunkptr p) {
2525 msegmentptr sp = segment_holding(m, (char*)p);
2526 size_t sz = chunksize(p);
2527 assert(sp != 0);
2528 assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
2529 assert(ok_address(m, p));
2530 assert(sz == m->topsize);
2531 assert(sz > 0);
2532 assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE);
2533 assert(pinuse(p));
2534 assert(!next_pinuse(p));
2535}
2536
2537/* Check properties of (inuse) mmapped chunks */
2538static void do_check_mmapped_chunk(mstate m, mchunkptr p) {
2539 size_t sz = chunksize(p);
2540 size_t len = (sz + (p->prev_foot & ~IS_MMAPPED_BIT) + MMAP_FOOT_PAD);
2541 assert(is_mmapped(p));
2542 assert(use_mmap(m));
2543 assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
2544 assert(ok_address(m, p));
2545 assert(!is_small(sz));
2546 assert((len & (mparams.page_size-SIZE_T_ONE)) == 0);
2547 assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD);
2548 assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0);
2549}
2550
2551/* Check properties of inuse chunks */
2552static void do_check_inuse_chunk(mstate m, mchunkptr p) {
2553 do_check_any_chunk(m, p);
2554 assert(cinuse(p));
2555 assert(next_pinuse(p));
2556 /* If not pinuse and not mmapped, previous chunk has OK offset */
2557 assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p);
2558 if (is_mmapped(p))
2559 do_check_mmapped_chunk(m, p);
2560}
2561
2562/* Check properties of free chunks */
2563static void do_check_free_chunk(mstate m, mchunkptr p) {
2564 size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT);
2565 mchunkptr next = chunk_plus_offset(p, sz);
2566 do_check_any_chunk(m, p);
2567 assert(!cinuse(p));
2568 assert(!next_pinuse(p));
2569 assert (!is_mmapped(p));
2570 if (p != m->dv && p != m->top) {
2571 if (sz >= MIN_CHUNK_SIZE) {
2572 assert((sz & CHUNK_ALIGN_MASK) == 0);
2573 assert(is_aligned(chunk2mem(p)));
2574 assert(next->prev_foot == sz);
2575 assert(pinuse(p));
2576 assert (next == m->top || cinuse(next));
2577 assert(p->fd->bk == p);
2578 assert(p->bk->fd == p);
2579 }
2580 else /* markers are always of size SIZE_T_SIZE */
2581 assert(sz == SIZE_T_SIZE);
2582 }
2583}
2584
2585/* Check properties of malloced chunks at the point they are malloced */
2586static void do_check_malloced_chunk(mstate m, void* mem, size_t s) {
2587 if (mem != 0) {
2588 mchunkptr p = mem2chunk(mem);
2589 size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT);
2590 do_check_inuse_chunk(m, p);
2591 assert((sz & CHUNK_ALIGN_MASK) == 0);
2592 assert(sz >= MIN_CHUNK_SIZE);
2593 assert(sz >= s);
2594 /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */
2595 assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE));
2596 }
2597}
2598
2599/* Check a tree and its subtrees. */
2600static void do_check_tree(mstate m, tchunkptr t) {
2601 tchunkptr head = 0;
2602 tchunkptr u = t;
2603 bindex_t tindex = t->index;
2604 size_t tsize = chunksize(t);
2605 bindex_t idx;
2606 compute_tree_index(tsize, idx);
2607 assert(tindex == idx);
2608 assert(tsize >= MIN_LARGE_SIZE);
2609 assert(tsize >= minsize_for_tree_index(idx));
2610 assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1))));
2611
2612 do { /* traverse through chain of same-sized nodes */
2613 do_check_any_chunk(m, ((mchunkptr)u));
2614 assert(u->index == tindex);
2615 assert(chunksize(u) == tsize);
2616 assert(!cinuse(u));
2617 assert(!next_pinuse(u));
2618 assert(u->fd->bk == u);
2619 assert(u->bk->fd == u);
2620 if (u->parent == 0) {
2621 assert(u->child[0] == 0);
2622 assert(u->child[1] == 0);
2623 }
2624 else {
2625 assert(head == 0); /* only one node on chain has parent */
2626 head = u;
2627 assert(u->parent != u);
2628 assert (u->parent->child[0] == u ||
2629 u->parent->child[1] == u ||
2630 *((tbinptr*)(u->parent)) == u);
2631 if (u->child[0] != 0) {
2632 assert(u->child[0]->parent == u);
2633 assert(u->child[0] != u);
2634 do_check_tree(m, u->child[0]);
2635 }
2636 if (u->child[1] != 0) {
2637 assert(u->child[1]->parent == u);
2638 assert(u->child[1] != u);
2639 do_check_tree(m, u->child[1]);
2640 }
2641 if (u->child[0] != 0 && u->child[1] != 0) {
2642 assert(chunksize(u->child[0]) < chunksize(u->child[1]));
2643 }
2644 }
2645 u = u->fd;
2646 } while (u != t);
2647 assert(head != 0);
2648}
2649
2650/* Check all the chunks in a treebin. */
2651static void do_check_treebin(mstate m, bindex_t i) {
2652 tbinptr* tb = treebin_at(m, i);
2653 tchunkptr t = *tb;
2654 int empty = (m->treemap & (1U << i)) == 0;
2655 if (t == 0)
2656 assert(empty);
2657 if (!empty)
2658 do_check_tree(m, t);
2659}
2660
2661/* Check all the chunks in a smallbin. */
2662static void do_check_smallbin(mstate m, bindex_t i) {
2663 sbinptr b = smallbin_at(m, i);
2664 mchunkptr p = b->bk;
2665 unsigned int empty = (m->smallmap & (1U << i)) == 0;
2666 if (p == b)
2667 assert(empty);
2668 if (!empty) {
2669 for (; p != b; p = p->bk) {
2670 size_t size = chunksize(p);
2671 mchunkptr q;
2672 /* each chunk claims to be free */
2673 do_check_free_chunk(m, p);
2674 /* chunk belongs in bin */
2675 assert(small_index(size) == i);
2676 assert(p->bk == b || chunksize(p->bk) == chunksize(p));
2677 /* chunk is followed by an inuse chunk */
2678 q = next_chunk(p);
2679 if (q->head != FENCEPOST_HEAD)
2680 do_check_inuse_chunk(m, q);
2681 }
2682 }
2683}
2684
2685/* Find x in a bin. Used in other check functions. */
2686static int bin_find(mstate m, mchunkptr x) {
2687 size_t size = chunksize(x);
2688 if (is_small(size)) {
2689 bindex_t sidx = small_index(size);
2690 sbinptr b = smallbin_at(m, sidx);
2691 if (smallmap_is_marked(m, sidx)) {
2692 mchunkptr p = b;
2693 do {
2694 if (p == x)
2695 return 1;
2696 } while ((p = p->fd) != b);
2697 }
2698 }
2699 else {
2700 bindex_t tidx;
2701 compute_tree_index(size, tidx);
2702 if (treemap_is_marked(m, tidx)) {
2703 tchunkptr t = *treebin_at(m, tidx);
2704 size_t sizebits = size << leftshift_for_tree_index(tidx);
2705 while (t != 0 && chunksize(t) != size) {
2706 t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
2707 sizebits <<= 1;
2708 }
2709 if (t != 0) {
2710 tchunkptr u = t;
2711 do {
2712 if (u == (tchunkptr)x)
2713 return 1;
2714 } while ((u = u->fd) != t);
2715 }
2716 }
2717 }
2718 return 0;
2719}
2720
2721/* Traverse each chunk and check it; return total */
2722static size_t traverse_and_check(mstate m) {
2723 size_t sum = 0;
2724 if (is_initialized(m)) {
2725 msegmentptr s = &m->seg;
2726 sum += m->topsize + TOP_FOOT_SIZE;
2727 while (s != 0) {
2728 mchunkptr q = align_as_chunk(s->base);
2729 mchunkptr lastq = 0;
2730 assert(pinuse(q));
2731 while (segment_holds(s, q) &&
2732 q != m->top && q->head != FENCEPOST_HEAD) {
2733 sum += chunksize(q);
2734 if (cinuse(q)) {
2735 assert(!bin_find(m, q));
2736 do_check_inuse_chunk(m, q);
2737 }
2738 else {
2739 assert(q == m->dv || bin_find(m, q));
2740 assert(lastq == 0 || cinuse(lastq)); /* Not 2 consecutive free */
2741 do_check_free_chunk(m, q);
2742 }
2743 lastq = q;
2744 q = next_chunk(q);
2745 }
2746 s = s->next;
2747 }
2748 }
2749 return sum;
2750}
2751
2752/* Check all properties of malloc_state. */
2753static void do_check_malloc_state(mstate m) {
2754 bindex_t i;
2755 size_t total;
2756 /* check bins */
2757 for (i = 0; i < NSMALLBINS; ++i)
2758 do_check_smallbin(m, i);
2759 for (i = 0; i < NTREEBINS; ++i)
2760 do_check_treebin(m, i);
2761
2762 if (m->dvsize != 0) { /* check dv chunk */
2763 do_check_any_chunk(m, m->dv);
2764 assert(m->dvsize == chunksize(m->dv));
2765 assert(m->dvsize >= MIN_CHUNK_SIZE);
2766 assert(bin_find(m, m->dv) == 0);
2767 }
2768
2769 if (m->top != 0) { /* check top chunk */
2770 do_check_top_chunk(m, m->top);
2771 assert(m->topsize == chunksize(m->top));
2772 assert(m->topsize > 0);
2773 assert(bin_find(m, m->top) == 0);
2774 }
2775
2776 total = traverse_and_check(m);
2777 assert(total <= m->footprint);
2778 assert(m->footprint <= m->max_footprint);
2779}
2780#endif /* DEBUG */
2781
2782/* ----------------------------- statistics ------------------------------ */
2783
2784#if !NO_MALLINFO
2785static struct mallinfo internal_mallinfo(mstate m) {
2786 struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
2787 if (!PREACTION(m)) {
2788 check_malloc_state(m);
2789 if (is_initialized(m)) {
2790 size_t nfree = SIZE_T_ONE; /* top always free */
2791 size_t mfree = m->topsize + TOP_FOOT_SIZE;
2792 size_t sum = mfree;
2793 msegmentptr s = &m->seg;
2794 while (s != 0) {
2795 mchunkptr q = align_as_chunk(s->base);
2796 while (segment_holds(s, q) &&
2797 q != m->top && q->head != FENCEPOST_HEAD) {
2798 size_t sz = chunksize(q);
2799 sum += sz;
2800 if (!cinuse(q)) {
2801 mfree += sz;
2802 ++nfree;
2803 }
2804 q = next_chunk(q);
2805 }
2806 s = s->next;
2807 }
2808
2809 nm.arena = sum;
2810 nm.ordblks = nfree;
2811 nm.hblkhd = m->footprint - sum;
2812 nm.usmblks = m->max_footprint;
2813 nm.uordblks = m->footprint - mfree;
2814 nm.fordblks = mfree;
2815 nm.keepcost = m->topsize;
2816 }
2817
2818 POSTACTION(m);
2819 }
2820 return nm;
2821}
2822#endif /* !NO_MALLINFO */
2823
2824static void internal_malloc_stats(mstate m) {
2825 if (!PREACTION(m)) {
2826 size_t maxfp = 0;
2827 size_t fp = 0;
2828 size_t used = 0;
2829 check_malloc_state(m);
2830 if (is_initialized(m)) {
2831 msegmentptr s = &m->seg;
2832 maxfp = m->max_footprint;
2833 fp = m->footprint;
2834 used = fp - (m->topsize + TOP_FOOT_SIZE);
2835
2836 while (s != 0) {
2837 mchunkptr q = align_as_chunk(s->base);
2838 while (segment_holds(s, q) &&
2839 q != m->top && q->head != FENCEPOST_HEAD) {
2840 if (!cinuse(q))
2841 used -= chunksize(q);
2842 q = next_chunk(q);
2843 }
2844 s = s->next;
2845 }
2846 }
2847
2848 DEBUGF("max system bytes = %10lu\n", (unsigned long)(maxfp));
2849 DEBUGF("system bytes = %10lu\n", (unsigned long)(fp));
2850 DEBUGF("in use bytes = %10lu\n", (unsigned long)(used));
2851
2852 POSTACTION(m);
2853 }
2854}
2855
2856/* ----------------------- Operations on smallbins ----------------------- */
2857
2858/*
2859 Various forms of linking and unlinking are defined as macros. Even
2860 the ones for trees, which are very long but have very short typical
2861 paths. This is ugly but reduces reliance on inlining support of
2862 compilers.
2863*/
2864
2865/* Link a free chunk into a smallbin */
2866#define insert_small_chunk(M, P, S) {\
2867 bindex_t I = small_index(S);\
2868 mchunkptr B = smallbin_at(M, I);\
2869 mchunkptr F = B;\
2870 assert(S >= MIN_CHUNK_SIZE);\
2871 if (!smallmap_is_marked(M, I))\
2872 mark_smallmap(M, I);\
2873 else if (RTCHECK(ok_address(M, B->fd)))\
2874 F = B->fd;\
2875 else {\
2876 CORRUPTION_ERROR_ACTION(M);\
2877 }\
2878 B->fd = P;\
2879 F->bk = P;\
2880 P->fd = F;\
2881 P->bk = B;\
2882}
2883
2884/* Unlink a chunk from a smallbin */
2885#define unlink_small_chunk(M, P, S) {\
2886 mchunkptr F = P->fd;\
2887 mchunkptr B = P->bk;\
2888 bindex_t I = small_index(S);\
2889 assert(P != B);\
2890 assert(P != F);\
2891 assert(chunksize(P) == small_index2size(I));\
2892 if (F == B)\
2893 clear_smallmap(M, I);\
2894 else if (RTCHECK((F == smallbin_at(M,I) || ok_address(M, F)) &&\
2895 (B == smallbin_at(M,I) || ok_address(M, B)))) {\
2896 F->bk = B;\
2897 B->fd = F;\
2898 }\
2899 else {\
2900 CORRUPTION_ERROR_ACTION(M);\
2901 }\
2902}
2903
2904/* Unlink the first chunk from a smallbin */
2905#define unlink_first_small_chunk(M, B, P, I) {\
2906 mchunkptr F = P->fd;\
2907 assert(P != B);\
2908 assert(P != F);\
2909 assert(chunksize(P) == small_index2size(I));\
2910 if (B == F)\
2911 clear_smallmap(M, I);\
2912 else if (RTCHECK(ok_address(M, F))) {\
2913 B->fd = F;\
2914 F->bk = B;\
2915 }\
2916 else {\
2917 CORRUPTION_ERROR_ACTION(M);\
2918 }\
2919}
2920
2921/* Replace dv node, binning the old one */
2922/* Used only when dvsize known to be small */
2923#define replace_dv(M, P, S) {\
2924 size_t DVS = M->dvsize;\
2925 if (DVS != 0) {\
2926 mchunkptr DV = M->dv;\
2927 assert(is_small(DVS));\
2928 insert_small_chunk(M, DV, DVS);\
2929 }\
2930 M->dvsize = S;\
2931 M->dv = P;\
2932}
2933
2934/* ------------------------- Operations on trees ------------------------- */
2935
2936/* Insert chunk into tree */
2937#define insert_large_chunk(M, X, S) {\
2938 tbinptr* H;\
2939 bindex_t I;\
2940 compute_tree_index(S, I);\
2941 H = treebin_at(M, I);\
2942 X->index = I;\
2943 X->child[0] = X->child[1] = 0;\
2944 if (!treemap_is_marked(M, I)) {\
2945 mark_treemap(M, I);\
2946 *H = X;\
2947 X->parent = (tchunkptr)H;\
2948 X->fd = X->bk = X;\
2949 }\
2950 else {\
2951 tchunkptr T = *H;\
2952 size_t K = S << leftshift_for_tree_index(I);\
2953 for (;;) {\
2954 if (chunksize(T) != S) {\
2955 tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\
2956 K <<= 1;\
2957 if (*C != 0)\
2958 T = *C;\
2959 else if (RTCHECK(ok_address(M, C))) {\
2960 *C = X;\
2961 X->parent = T;\
2962 X->fd = X->bk = X;\
2963 break;\
2964 }\
2965 else {\
2966 CORRUPTION_ERROR_ACTION(M);\
2967 break;\
2968 }\
2969 }\
2970 else {\
2971 tchunkptr F = T->fd;\
2972 if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\
2973 T->fd = F->bk = X;\
2974 X->fd = F;\
2975 X->bk = T;\
2976 X->parent = 0;\
2977 break;\
2978 }\
2979 else {\
2980 CORRUPTION_ERROR_ACTION(M);\
2981 break;\
2982 }\
2983 }\
2984 }\
2985 }\
2986}
2987
2988/*
2989 Unlink steps:
2990
2991 1. If x is a chained node, unlink it from its same-sized fd/bk links
2992 and choose its bk node as its replacement.
2993 2. If x was the last node of its size, but not a leaf node, it must
2994 be replaced with a leaf node (not merely one with an open left or
2995 right), to make sure that lefts and rights of descendents
2996 correspond properly to bit masks. We use the rightmost descendent
2997 of x. We could use any other leaf, but this is easy to locate and
2998 tends to counteract removal of leftmosts elsewhere, and so keeps
2999 paths shorter than minimally guaranteed. This doesn't loop much
3000 because on average a node in a tree is near the bottom.
3001 3. If x is the base of a chain (i.e., has parent links) relink
3002 x's parent and children to x's replacement (or null if none).
3003*/
3004
3005#define unlink_large_chunk(M, X) {\
3006 tchunkptr XP = X->parent;\
3007 tchunkptr R;\
3008 if (X->bk != X) {\
3009 tchunkptr F = X->fd;\
3010 R = X->bk;\
3011 if (RTCHECK(ok_address(M, F))) {\
3012 F->bk = R;\
3013 R->fd = F;\
3014 }\
3015 else {\
3016 CORRUPTION_ERROR_ACTION(M);\
3017 }\
3018 }\
3019 else {\
3020 tchunkptr* RP;\
3021 if (((R = *(RP = &(X->child[1]))) != 0) ||\
3022 ((R = *(RP = &(X->child[0]))) != 0)) {\
3023 tchunkptr* CP;\
3024 while ((*(CP = &(R->child[1])) != 0) ||\
3025 (*(CP = &(R->child[0])) != 0)) {\
3026 R = *(RP = CP);\
3027 }\
3028 if (RTCHECK(ok_address(M, RP)))\
3029 *RP = 0;\
3030 else {\
3031 CORRUPTION_ERROR_ACTION(M);\
3032 }\
3033 }\
3034 }\
3035 if (XP != 0) {\
3036 tbinptr* H = treebin_at(M, X->index);\
3037 if (X == *H) {\
3038 if ((*H = R) == 0) \
3039 clear_treemap(M, X->index);\
3040 }\
3041 else if (RTCHECK(ok_address(M, XP))) {\
3042 if (XP->child[0] == X) \
3043 XP->child[0] = R;\
3044 else \
3045 XP->child[1] = R;\
3046 }\
3047 else\
3048 CORRUPTION_ERROR_ACTION(M);\
3049 if (R != 0) {\
3050 if (RTCHECK(ok_address(M, R))) {\
3051 tchunkptr C0, C1;\
3052 R->parent = XP;\
3053 if ((C0 = X->child[0]) != 0) {\
3054 if (RTCHECK(ok_address(M, C0))) {\
3055 R->child[0] = C0;\
3056 C0->parent = R;\
3057 }\
3058 else\
3059 CORRUPTION_ERROR_ACTION(M);\
3060 }\
3061 if ((C1 = X->child[1]) != 0) {\
3062 if (RTCHECK(ok_address(M, C1))) {\
3063 R->child[1] = C1;\
3064 C1->parent = R;\
3065 }\
3066 else\
3067 CORRUPTION_ERROR_ACTION(M);\
3068 }\
3069 }\
3070 else\
3071 CORRUPTION_ERROR_ACTION(M);\
3072 }\
3073 }\
3074}
3075
3076/* Relays to large vs small bin operations */
3077
3078#define insert_chunk(M, P, S)\
3079 if (is_small(S)) insert_small_chunk(M, P, S)\
3080 else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); }
3081
3082#define unlink_chunk(M, P, S)\
3083 if (is_small(S)) unlink_small_chunk(M, P, S)\
3084 else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); }
3085
3086
3087/* Relays to internal calls to malloc/free from realloc, memalign etc */
3088
3089#if ONLY_MSPACES
3090#define internal_malloc(m, b) mspace_malloc(m, b)
3091#define internal_free(m, mem) mspace_free(m,mem);
3092#else /* ONLY_MSPACES */
3093#if MSPACES
3094#define internal_malloc(m, b)\
3095 (m == gm)? dlmalloc(b) : mspace_malloc(m, b)
3096#define internal_free(m, mem)\
3097 if (m == gm) dlfree(mem); else mspace_free(m,mem);
3098#else /* MSPACES */
3099#define internal_malloc(m, b) dlmalloc(b)
3100#define internal_free(m, mem) dlfree(mem)
3101#endif /* MSPACES */
3102#endif /* ONLY_MSPACES */
3103
3104/* ----------------------- Direct-mmapping chunks ----------------------- */
3105
3106/*
3107 Directly mmapped chunks are set up with an offset to the start of
3108 the mmapped region stored in the prev_foot field of the chunk. This
3109 allows reconstruction of the required argument to MUNMAP when freed,
3110 and also allows adjustment of the returned chunk to meet alignment
3111 requirements (especially in memalign). There is also enough space
3112 allocated to hold a fake next chunk of size SIZE_T_SIZE to maintain
3113 the PINUSE bit so frees can be checked.
3114*/
3115
3116/* Malloc using mmap */
3117static void* mmap_alloc(mstate m, size_t nb) {
3118 size_t mmsize = granularity_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
3119 if (mmsize > nb) { /* Check for wrap around 0 */
3120 char* mm = (char*)(DIRECT_MMAP(mmsize));
3121 if (mm != CMFAIL) {
3122 size_t offset = align_offset(chunk2mem(mm));
3123 size_t psize = mmsize - offset - MMAP_FOOT_PAD;
3124 mchunkptr p = (mchunkptr)(mm + offset);
3125 p->prev_foot = offset | IS_MMAPPED_BIT;
3126 (p)->head = (psize|CINUSE_BIT);
3127 mark_inuse_foot(m, p, psize);
3128 chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;
3129 chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0;
3130
3131 if (mm < m->least_addr)
3132 m->least_addr = mm;
3133 if ((m->footprint += mmsize) > m->max_footprint)
3134 m->max_footprint = m->footprint;
3135 assert(is_aligned(chunk2mem(p)));
3136 check_mmapped_chunk(m, p);
3137 return chunk2mem(p);
3138 }
3139 }
3140 return 0;
3141}
3142
3143/* Realloc using mmap */
3144static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb) {
3145 size_t oldsize = chunksize(oldp);
3146 if (is_small(nb)) /* Can't shrink mmap regions below small size */
3147 return 0;
3148 /* Keep old chunk if big enough but not too big */
3149 if (oldsize >= nb + SIZE_T_SIZE &&
3150 (oldsize - nb) <= (mparams.granularity << 1))
3151 return oldp;
3152 else {
3153 size_t offset = oldp->prev_foot & ~IS_MMAPPED_BIT;
3154 size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD;
3155 size_t newmmsize = granularity_align(nb + SIX_SIZE_T_SIZES +
3156 CHUNK_ALIGN_MASK);
3157 char* cp = (char*)CALL_MREMAP((char*)oldp - offset,
3158 oldmmsize, newmmsize, 1);
3159 if (cp != CMFAIL) {
3160 mchunkptr newp = (mchunkptr)(cp + offset);
3161 size_t psize = newmmsize - offset - MMAP_FOOT_PAD;
3162 newp->head = (psize|CINUSE_BIT);
3163 mark_inuse_foot(m, newp, psize);
3164 chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD;
3165 chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0;
3166
3167 if (cp < m->least_addr)
3168 m->least_addr = cp;
3169 if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint)
3170 m->max_footprint = m->footprint;
3171 check_mmapped_chunk(m, newp);
3172 return newp;
3173 }
3174 }
3175 return 0;
3176}
3177
3178/* -------------------------- mspace management -------------------------- */
3179
3180/* Initialize top chunk and its size */
3181static void init_top(mstate m, mchunkptr p, size_t psize) {
3182 /* Ensure alignment */
3183 size_t offset = align_offset(chunk2mem(p));
3184 p = (mchunkptr)((char*)p + offset);
3185 psize -= offset;
3186
3187 m->top = p;
3188 m->topsize = psize;
3189 p->head = psize | PINUSE_BIT;
3190 /* set size of fake trailing chunk holding overhead space only once */
3191 chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE;
3192 m->trim_check = mparams.trim_threshold; /* reset on each update */
3193}
3194
3195/* Initialize bins for a new mstate that is otherwise zeroed out */
3196static void init_bins(mstate m) {
3197 /* Establish circular links for smallbins */
3198 bindex_t i;
3199 for (i = 0; i < NSMALLBINS; ++i) {
3200 sbinptr bin = smallbin_at(m,i);
3201 bin->fd = bin->bk = bin;
3202 }
3203}
3204
3205#if PROCEED_ON_ERROR
3206
3207/* default corruption action */
3208static void reset_on_error(mstate m) {
3209 int i;
3210 ++malloc_corruption_error_count;
3211 /* Reinitialize fields to forget about all memory */
3212 m->smallbins = m->treebins = 0;
3213 m->dvsize = m->topsize = 0;
3214 m->seg.base = 0;
3215 m->seg.size = 0;
3216 m->seg.next = 0;
3217 m->top = m->dv = 0;
3218 for (i = 0; i < NTREEBINS; ++i)
3219 *treebin_at(m, i) = 0;
3220 init_bins(m);
3221}
3222#endif /* PROCEED_ON_ERROR */
3223
3224/* Allocate chunk and prepend remainder with chunk in successor base. */
3225static void* prepend_alloc(mstate m, char* newbase, char* oldbase,
3226 size_t nb) {
3227 mchunkptr p = align_as_chunk(newbase);
3228 mchunkptr oldfirst = align_as_chunk(oldbase);
3229 size_t psize = (char*)oldfirst - (char*)p;
3230 mchunkptr q = chunk_plus_offset(p, nb);
3231 size_t qsize = psize - nb;
3232 set_size_and_pinuse_of_inuse_chunk(m, p, nb);
3233
3234 assert((char*)oldfirst > (char*)q);
3235 assert(pinuse(oldfirst));
3236 assert(qsize >= MIN_CHUNK_SIZE);
3237
3238 /* consolidate remainder with first chunk of old base */
3239 if (oldfirst == m->top) {
3240 size_t tsize = m->topsize += qsize;
3241 m->top = q;
3242 q->head = tsize | PINUSE_BIT;
3243 check_top_chunk(m, q);
3244 }
3245 else if (oldfirst == m->dv) {
3246 size_t dsize = m->dvsize += qsize;
3247 m->dv = q;
3248 set_size_and_pinuse_of_free_chunk(q, dsize);
3249 }
3250 else {
3251 if (!cinuse(oldfirst)) {
3252 size_t nsize = chunksize(oldfirst);
3253 unlink_chunk(m, oldfirst, nsize);
3254 oldfirst = chunk_plus_offset(oldfirst, nsize);
3255 qsize += nsize;
3256 }
3257 set_free_with_pinuse(q, qsize, oldfirst);
3258 insert_chunk(m, q, qsize);
3259 check_free_chunk(m, q);
3260 }
3261
3262 check_malloced_chunk(m, chunk2mem(p), nb);
3263 return chunk2mem(p);
3264}
3265
3266
3267/* Add a segment to hold a new noncontiguous region */
3268static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) {
3269 /* Determine locations and sizes of segment, fenceposts, old top */
3270 char* old_top = (char*)m->top;
3271 msegmentptr oldsp = segment_holding(m, old_top);
3272 char* old_end = oldsp->base + oldsp->size;
3273 size_t ssize = pad_request(sizeof(struct malloc_segment));
3274 char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
3275 size_t offset = align_offset(chunk2mem(rawsp));
3276 char* asp = rawsp + offset;
3277 char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp;
3278 mchunkptr sp = (mchunkptr)csp;
3279 msegmentptr ss = (msegmentptr)(chunk2mem(sp));
3280 mchunkptr tnext = chunk_plus_offset(sp, ssize);
3281 mchunkptr p = tnext;
3282 int nfences = 0;
3283
3284 /* reset top to new space */
3285 init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
3286
3287 /* Set up segment record */
3288 assert(is_aligned(ss));
3289 set_size_and_pinuse_of_inuse_chunk(m, sp, ssize);
3290 *ss = m->seg; /* Push current record */
3291 m->seg.base = tbase;
3292 m->seg.size = tsize;
3293 m->seg.sflags = mmapped;
3294 m->seg.next = ss;
3295
3296 /* Insert trailing fenceposts */
3297 for (;;) {
3298 mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE);
3299 p->head = FENCEPOST_HEAD;
3300 ++nfences;
3301 if ((char*)(&(nextp->head)) < old_end)
3302 p = nextp;
3303 else
3304 break;
3305 }
3306 assert(nfences >= 2);
3307
3308 /* Insert the rest of old top into a bin as an ordinary free chunk */
3309 if (csp != old_top) {
3310 mchunkptr q = (mchunkptr)old_top;
3311 size_t psize = csp - old_top;
3312 mchunkptr tn = chunk_plus_offset(q, psize);
3313 set_free_with_pinuse(q, psize, tn);
3314 insert_chunk(m, q, psize);
3315 }
3316
3317 check_top_chunk(m, m->top);
3318}
3319
3320/* -------------------------- System allocation -------------------------- */
3321
3322/* Get memory from system using MORECORE or MMAP */
3323static void* sys_alloc(mstate m, size_t nb) {
3324 char* tbase = CMFAIL;
3325 size_t tsize = 0;
3326 flag_t mmap_flag = 0;
3327
3328 init_mparams();
3329
3330 /* Directly map large chunks */
3331 if (use_mmap(m) && nb >= mparams.mmap_threshold) {
3332 void* mem = mmap_alloc(m, nb);
3333 if (mem != 0)
3334 return mem;
3335 }
3336
3337 /*
3338 Try getting memory in any of three ways (in most-preferred to
3339 least-preferred order):
3340 1. A call to MORECORE that can normally contiguously extend memory.
3341 (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or
3342 or main space is mmapped or a previous contiguous call failed)
3343 2. A call to MMAP new space (disabled if not HAVE_MMAP).
3344 Note that under the default settings, if MORECORE is unable to
3345 fulfill a request, and HAVE_MMAP is true, then mmap is
3346 used as a noncontiguous system allocator. This is a useful backup
3347 strategy for systems with holes in address spaces -- in this case
3348 sbrk cannot contiguously expand the heap, but mmap may be able to
3349 find space.
3350 3. A call to MORECORE that cannot usually contiguously extend memory.
3351 (disabled if not HAVE_MORECORE)
3352 */
3353
3354 if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) {
3355 char* br = CMFAIL;
3356 msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top);
3357 size_t asize = 0;
3358 ACQUIRE_MORECORE_LOCK();
3359
3360 if (ss == 0) { /* First time through or recovery */
3361 char* base = (char*)CALL_MORECORE(0);
3362 if (base != CMFAIL) {
3363 asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE);
3364 /* Adjust to end on a page boundary */
3365 if (!is_page_aligned(base))
3366 asize += (page_align((size_t)base) - (size_t)base);
3367 /* Can't call MORECORE if size is negative when treated as signed */
3368 if (asize < HALF_MAX_SIZE_T &&
3369 (br = (char*)(CALL_MORECORE(asize))) == base) {
3370 tbase = base;
3371 tsize = asize;
3372 }
3373 }
3374 }
3375 else {
3376 /* Subtract out existing available top space from MORECORE request. */
3377 asize = granularity_align(nb - m->topsize + TOP_FOOT_SIZE + SIZE_T_ONE);
3378 /* Use mem here only if it did continuously extend old space */
3379 if (asize < HALF_MAX_SIZE_T &&
3380 (br = (char*)(CALL_MORECORE(asize))) == ss->base+ss->size) {
3381 tbase = br;
3382 tsize = asize;
3383 }
3384 }
3385
3386 if (tbase == CMFAIL) { /* Cope with partial failure */
3387 if (br != CMFAIL) { /* Try to use/extend the space we did get */
3388 if (asize < HALF_MAX_SIZE_T &&
3389 asize < nb + TOP_FOOT_SIZE + SIZE_T_ONE) {
3390 size_t esize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE - asize);
3391 if (esize < HALF_MAX_SIZE_T) {
3392 char* end = (char*)CALL_MORECORE(esize);
3393 if (end != CMFAIL)
3394 asize += esize;
3395 else { /* Can't use; try to release */
3396 CALL_MORECORE(-asize);
3397 br = CMFAIL;
3398 }
3399 }
3400 }
3401 }
3402 if (br != CMFAIL) { /* Use the space we did get */
3403 tbase = br;
3404 tsize = asize;
3405 }
3406 else
3407 disable_contiguous(m); /* Don't try contiguous path in the future */
3408 }
3409
3410 RELEASE_MORECORE_LOCK();
3411 }
3412
3413 if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */
3414 size_t req = nb + TOP_FOOT_SIZE + SIZE_T_ONE;
3415 size_t rsize = granularity_align(req);
3416 if (rsize > nb) { /* Fail if wraps around zero */
3417 char* mp = (char*)(CALL_MMAP(rsize));
3418 if (mp != CMFAIL) {
3419 tbase = mp;
3420 tsize = rsize;
3421 mmap_flag = IS_MMAPPED_BIT;
3422 }
3423 }
3424 }
3425
3426 if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */
3427 size_t asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE);
3428 if (asize < HALF_MAX_SIZE_T) {
3429 char* br = CMFAIL;
3430 char* end = CMFAIL;
3431 ACQUIRE_MORECORE_LOCK();
3432 br = (char*)(CALL_MORECORE(asize));
3433 end = (char*)(CALL_MORECORE(0));
3434 RELEASE_MORECORE_LOCK();
3435 if (br != CMFAIL && end != CMFAIL && br < end) {
3436 size_t ssize = end - br;
3437 if (ssize > nb + TOP_FOOT_SIZE) {
3438 tbase = br;
3439 tsize = ssize;
3440 }
3441 }
3442 }
3443 }
3444
3445 if (tbase != CMFAIL) {
3446
3447 if ((m->footprint += tsize) > m->max_footprint)
3448 m->max_footprint = m->footprint;
3449
3450 if (!is_initialized(m)) { /* first-time initialization */
3451 m->seg.base = m->least_addr = tbase;
3452 m->seg.size = tsize;
3453 m->seg.sflags = mmap_flag;
3454 m->magic = mparams.magic;
3455 init_bins(m);
3456 if (is_global(m))
3457 init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
3458 else {
3459 /* Offset top by embedded malloc_state */
3460 mchunkptr mn = next_chunk(mem2chunk(m));
3461 init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE);
3462 }
3463 }
3464
3465 else {
3466 /* Try to merge with an existing segment */
3467 msegmentptr sp = &m->seg;
3468 while (sp != 0 && tbase != sp->base + sp->size)
3469 sp = sp->next;
3470 if (sp != 0 &&
3471 !is_extern_segment(sp) &&
3472 (sp->sflags & IS_MMAPPED_BIT) == mmap_flag &&
3473 segment_holds(sp, m->top)) { /* append */
3474 sp->size += tsize;
3475 init_top(m, m->top, m->topsize + tsize);
3476 }
3477 else {
3478 if (tbase < m->least_addr)
3479 m->least_addr = tbase;
3480 sp = &m->seg;
3481 while (sp != 0 && sp->base != tbase + tsize)
3482 sp = sp->next;
3483 if (sp != 0 &&
3484 !is_extern_segment(sp) &&
3485 (sp->sflags & IS_MMAPPED_BIT) == mmap_flag) {
3486 char* oldbase = sp->base;
3487 sp->base = tbase;
3488 sp->size += tsize;
3489 return prepend_alloc(m, tbase, oldbase, nb);
3490 }
3491 else
3492 add_segment(m, tbase, tsize, mmap_flag);
3493 }
3494 }
3495
3496 if (nb < m->topsize) { /* Allocate from new or extended top space */
3497 size_t rsize = m->topsize -= nb;
3498 mchunkptr p = m->top;
3499 mchunkptr r = m->top = chunk_plus_offset(p, nb);
3500 r->head = rsize | PINUSE_BIT;
3501 set_size_and_pinuse_of_inuse_chunk(m, p, nb);
3502 check_top_chunk(m, m->top);
3503 check_malloced_chunk(m, chunk2mem(p), nb);
3504 return chunk2mem(p);
3505 }
3506 }
3507
3508 MALLOC_FAILURE_ACTION;
3509 return 0;
3510}
3511
3512/* ----------------------- system deallocation -------------------------- */
3513
3514/* Unmap and unlink any mmapped segments that don't contain used chunks */
3515static size_t release_unused_segments(mstate m) {
3516 size_t released = 0;
3517 msegmentptr pred = &m->seg;
3518 msegmentptr sp = pred->next;
3519 while (sp != 0) {
3520 char* base = sp->base;
3521 size_t size = sp->size;
3522 msegmentptr next = sp->next;
3523 if (is_mmapped_segment(sp) && !is_extern_segment(sp)) {
3524 mchunkptr p = align_as_chunk(base);
3525 size_t psize = chunksize(p);
3526 /* Can unmap if first chunk holds entire segment and not pinned */
3527 if (!cinuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) {
3528 tchunkptr tp = (tchunkptr)p;
3529 assert(segment_holds(sp, (char*)sp));
3530 if (p == m->dv) {
3531 m->dv = 0;
3532 m->dvsize = 0;
3533 }
3534 else {
3535 unlink_large_chunk(m, tp);
3536 }
3537 if (CALL_MUNMAP(base, size) == 0) {
3538 released += size;
3539 m->footprint -= size;
3540 /* unlink obsoleted record */
3541 sp = pred;
3542 sp->next = next;
3543 }
3544 else { /* back out if cannot unmap */
3545 insert_large_chunk(m, tp, psize);
3546 }
3547 }
3548 }
3549 pred = sp;
3550 sp = next;
3551 }
3552 return released;
3553}
3554
3555static int sys_trim(mstate m, size_t pad) {
3556 size_t released = 0;
3557 if (pad < MAX_REQUEST && is_initialized(m)) {
3558 pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */
3559
3560 if (m->topsize > pad) {
3561 /* Shrink top space in granularity-size units, keeping at least one */
3562 size_t unit = mparams.granularity;
3563 size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit -
3564 SIZE_T_ONE) * unit;
3565 msegmentptr sp = segment_holding(m, (char*)m->top);
3566
3567 if (!is_extern_segment(sp)) {
3568 if (is_mmapped_segment(sp)) {
3569 if (HAVE_MMAP &&
3570 sp->size >= extra &&
3571 !has_segment_link(m, sp)) { /* can't shrink if pinned */
3572// size_t newsize = sp->size - extra;
3573 /* Prefer mremap, fall back to munmap */
3574 if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) ||
3575 (CALL_MUNMAP(sp->base + newsize, extra) == 0)) {
3576 released = extra;
3577 }
3578 }
3579 }
3580 else if (HAVE_MORECORE) {
3581 if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */
3582 extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit;
3583 ACQUIRE_MORECORE_LOCK();
3584 {
3585 /* Make sure end of memory is where we last set it. */
3586 char* old_br = (char*)(CALL_MORECORE(0));
3587 if (old_br == sp->base + sp->size) {
3588 char* rel_br = (char*)(CALL_MORECORE(-extra));
3589 char* new_br = (char*)(CALL_MORECORE(0));
3590 if (rel_br != CMFAIL && new_br < old_br)
3591 released = old_br - new_br;
3592 }
3593 }
3594 RELEASE_MORECORE_LOCK();
3595 }
3596 }
3597
3598 if (released != 0) {
3599 sp->size -= released;
3600 m->footprint -= released;
3601 init_top(m, m->top, m->topsize - released);
3602 check_top_chunk(m, m->top);
3603 }
3604 }
3605
3606 /* Unmap any unused mmapped segments */
3607 if (HAVE_MMAP)
3608 released += release_unused_segments(m);
3609
3610 /* On failure, disable autotrim to avoid repeated failed future calls */
3611 if (released == 0)
3612 m->trim_check = MAX_SIZE_T;
3613 }
3614
3615 return (released != 0)? 1 : 0;
3616}
3617
3618/* ---------------------------- malloc support --------------------------- */
3619
3620/* allocate a large request from the best fitting chunk in a treebin */
3621static void* tmalloc_large(mstate m, size_t nb) {
3622 tchunkptr v = 0;
3623 size_t rsize = -nb; /* Unsigned negation */
3624 tchunkptr t;
3625 bindex_t idx;
3626 compute_tree_index(nb, idx);
3627
3628 if ((t = *treebin_at(m, idx)) != 0) {
3629 /* Traverse tree for this bin looking for node with size == nb */
3630 size_t sizebits = nb << leftshift_for_tree_index(idx);
3631 tchunkptr rst = 0; /* The deepest untaken right subtree */
3632 for (;;) {
3633 tchunkptr rt;
3634 size_t trem = chunksize(t) - nb;
3635 if (trem < rsize) {
3636 v = t;
3637 if ((rsize = trem) == 0)
3638 break;
3639 }
3640 rt = t->child[1];
3641 t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
3642 if (rt != 0 && rt != t)
3643 rst = rt;
3644 if (t == 0) {
3645 t = rst; /* set t to least subtree holding sizes > nb */
3646 break;
3647 }
3648 sizebits <<= 1;
3649 }
3650 }
3651
3652 if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */
3653 binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap;
3654 if (leftbits != 0) {
3655 bindex_t i;
3656 binmap_t leastbit = least_bit(leftbits);
3657 compute_bit2idx(leastbit, i);
3658 t = *treebin_at(m, i);
3659 }
3660 }
3661
3662 while (t != 0) { /* find smallest of tree or subtree */
3663 size_t trem = chunksize(t) - nb;
3664 if (trem < rsize) {
3665 rsize = trem;
3666 v = t;
3667 }
3668 t = leftmost_child(t);
3669 }
3670
3671 /* If dv is a better fit, return 0 so malloc will use it */
3672 if (v != 0 && rsize < (size_t)(m->dvsize - nb)) {
3673 if (RTCHECK(ok_address(m, v))) { /* split */
3674 mchunkptr r = chunk_plus_offset(v, nb);
3675 assert(chunksize(v) == rsize + nb);
3676 if (RTCHECK(ok_next(v, r))) {
3677 unlink_large_chunk(m, v);
3678 if (rsize < MIN_CHUNK_SIZE)
3679 set_inuse_and_pinuse(m, v, (rsize + nb));
3680 else {
3681 set_size_and_pinuse_of_inuse_chunk(m, v, nb);
3682 set_size_and_pinuse_of_free_chunk(r, rsize);
3683 insert_chunk(m, r, rsize);
3684 }
3685 return chunk2mem(v);
3686 }
3687 }
3688 CORRUPTION_ERROR_ACTION(m);
3689 }
3690 return 0;
3691}
3692
3693/* allocate a small request from the best fitting chunk in a treebin */
3694static void* tmalloc_small(mstate m, size_t nb) {
3695 tchunkptr t, v;
3696 size_t rsize;
3697 bindex_t i;
3698 binmap_t leastbit = least_bit(m->treemap);
3699 compute_bit2idx(leastbit, i);
3700
3701 v = t = *treebin_at(m, i);
3702 rsize = chunksize(t) - nb;
3703
3704 while ((t = leftmost_child(t)) != 0) {
3705 size_t trem = chunksize(t) - nb;
3706 if (trem < rsize) {
3707 rsize = trem;
3708 v = t;
3709 }
3710 }
3711
3712 if (RTCHECK(ok_address(m, v))) {
3713 mchunkptr r = chunk_plus_offset(v, nb);
3714 assert(chunksize(v) == rsize + nb);
3715 if (RTCHECK(ok_next(v, r))) {
3716 unlink_large_chunk(m, v);
3717 if (rsize < MIN_CHUNK_SIZE)
3718 set_inuse_and_pinuse(m, v, (rsize + nb));
3719 else {
3720 set_size_and_pinuse_of_inuse_chunk(m, v, nb);
3721 set_size_and_pinuse_of_free_chunk(r, rsize);
3722 replace_dv(m, r, rsize);
3723 }
3724 return chunk2mem(v);
3725 }
3726 }
3727
3728 CORRUPTION_ERROR_ACTION(m);
3729 return 0;
3730}
3731
3732/* --------------------------- realloc support --------------------------- */
3733
3734static void* internal_realloc(mstate m, void* oldmem, size_t bytes) {
3735 if (bytes >= MAX_REQUEST) {
3736 MALLOC_FAILURE_ACTION;
3737 return 0;
3738 }
3739 if (!PREACTION(m)) {
3740 mchunkptr oldp = mem2chunk(oldmem);
3741 size_t oldsize = chunksize(oldp);
3742 mchunkptr next = chunk_plus_offset(oldp, oldsize);
3743 mchunkptr newp = 0;
3744 void* extra = 0;
3745
3746 /* Try to either shrink or extend into top. Else malloc-copy-free */
3747
3748 if (RTCHECK(ok_address(m, oldp) && ok_cinuse(oldp) &&
3749 ok_next(oldp, next) && ok_pinuse(next))) {
3750 size_t nb = request2size(bytes);
3751 if (is_mmapped(oldp))
3752 newp = mmap_resize(m, oldp, nb);
3753 else if (oldsize >= nb) { /* already big enough */
3754 size_t rsize = oldsize - nb;
3755 newp = oldp;
3756 if (rsize >= MIN_CHUNK_SIZE) {
3757 mchunkptr remainder = chunk_plus_offset(newp, nb);
3758 set_inuse(m, newp, nb);
3759 set_inuse(m, remainder, rsize);
3760 extra = chunk2mem(remainder);
3761 }
3762 }
3763 else if (next == m->top && oldsize + m->topsize > nb) {
3764 /* Expand into top */
3765 size_t newsize = oldsize + m->topsize;
3766 size_t newtopsize = newsize - nb;
3767 mchunkptr newtop = chunk_plus_offset(oldp, nb);
3768 set_inuse(m, oldp, nb);
3769 newtop->head = newtopsize |PINUSE_BIT;
3770 m->top = newtop;
3771 m->topsize = newtopsize;
3772 newp = oldp;
3773 }
3774 }
3775 else {
3776 USAGE_ERROR_ACTION(m, oldmem);
3777 POSTACTION(m);
3778 return 0;
3779 }
3780
3781 POSTACTION(m);
3782
3783 if (newp != 0) {
3784 if (extra != 0) {
3785 internal_free(m, extra);
3786 }
3787 check_inuse_chunk(m, newp);
3788 return chunk2mem(newp);
3789 }
3790 else {
3791 void* newmem = internal_malloc(m, bytes);
3792 if (newmem != 0) {
3793 size_t oc = oldsize - overhead_for(oldp);
3794 memcpy(newmem, oldmem, (oc < bytes)? oc : bytes);
3795 internal_free(m, oldmem);
3796 }
3797 return newmem;
3798 }
3799 }
3800 return 0;
3801}
3802
3803/* --------------------------- memalign support -------------------------- */
3804
3805static void* internal_memalign(mstate m, size_t alignment, size_t bytes) {
3806 if (alignment <= MALLOC_ALIGNMENT) /* Can just use malloc */
3807 return internal_malloc(m, bytes);
3808 if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */
3809 alignment = MIN_CHUNK_SIZE;
3810 if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */
3811 size_t a = MALLOC_ALIGNMENT << 1;
3812 while (a < alignment) a <<= 1;
3813 alignment = a;
3814 }
3815
3816 if (bytes >= MAX_REQUEST - alignment) {
3817 if (m != 0) { /* Test isn't needed but avoids compiler warning */
3818 MALLOC_FAILURE_ACTION;
3819 }
3820 }
3821 else {
3822 size_t nb = request2size(bytes);
3823 size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD;
3824 char* mem = (char*)internal_malloc(m, req);
3825 if (mem != 0) {
3826 void* leader = 0;
3827 void* trailer = 0;
3828 mchunkptr p = mem2chunk(mem);
3829
3830 if (PREACTION(m)) return 0;
3831 if ((((size_t)(mem)) % alignment) != 0) { /* misaligned */
3832 /*
3833 Find an aligned spot inside chunk. Since we need to give
3834 back leading space in a chunk of at least MIN_CHUNK_SIZE, if
3835 the first calculation places us at a spot with less than
3836 MIN_CHUNK_SIZE leader, we can move to the next aligned spot.
3837 We've allocated enough total room so that this is always
3838 possible.
3839 */
3840 char* br = (char*)mem2chunk((size_t)(((size_t)(mem +
3841 alignment -
3842 SIZE_T_ONE)) &
3843 -alignment));
3844 char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)?
3845 br : br+alignment;
3846 mchunkptr newp = (mchunkptr)pos;
3847 size_t leadsize = pos - (char*)(p);
3848 size_t newsize = chunksize(p) - leadsize;
3849
3850 if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */
3851 newp->prev_foot = p->prev_foot + leadsize;
3852 newp->head = (newsize|CINUSE_BIT);
3853 }
3854 else { /* Otherwise, give back leader, use the rest */
3855 set_inuse(m, newp, newsize);
3856 set_inuse(m, p, leadsize);
3857 leader = chunk2mem(p);
3858 }
3859 p = newp;
3860 }
3861
3862 /* Give back spare room at the end */
3863 if (!is_mmapped(p)) {
3864 size_t size = chunksize(p);
3865 if (size > nb + MIN_CHUNK_SIZE) {
3866 size_t remainder_size = size - nb;
3867 mchunkptr remainder = chunk_plus_offset(p, nb);
3868 set_inuse(m, p, nb);
3869 set_inuse(m, remainder, remainder_size);
3870 trailer = chunk2mem(remainder);
3871 }
3872 }
3873
3874 assert (chunksize(p) >= nb);
3875 assert((((size_t)(chunk2mem(p))) % alignment) == 0);
3876 check_inuse_chunk(m, p);
3877 POSTACTION(m);
3878 if (leader != 0) {
3879 internal_free(m, leader);
3880 }
3881 if (trailer != 0) {
3882 internal_free(m, trailer);
3883 }
3884 return chunk2mem(p);
3885 }
3886 }
3887 return 0;
3888}
3889
3890/* ------------------------ comalloc/coalloc support --------------------- */
3891
3892static void** ialloc(mstate m,
3893 size_t n_elements,
3894 size_t* sizes,
3895 int opts,
3896 void* chunks[]) {
3897 /*
3898 This provides common support for independent_X routines, handling
3899 all of the combinations that can result.
3900
3901 The opts arg has:
3902 bit 0 set if all elements are same size (using sizes[0])
3903 bit 1 set if elements should be zeroed
3904 */
3905
3906 size_t element_size; /* chunksize of each element, if all same */
3907 size_t contents_size; /* total size of elements */
3908 size_t array_size; /* request size of pointer array */
3909 void* mem; /* malloced aggregate space */
3910 mchunkptr p; /* corresponding chunk */
3911 size_t remainder_size; /* remaining bytes while splitting */
3912 void** marray; /* either "chunks" or malloced ptr array */
3913 mchunkptr array_chunk; /* chunk for malloced ptr array */
3914 flag_t was_enabled; /* to disable mmap */
3915 size_t size;
3916 size_t i;
3917
3918 /* compute array length, if needed */
3919 if (chunks != 0) {
3920 if (n_elements == 0)
3921 return chunks; /* nothing to do */
3922 marray = chunks;
3923 array_size = 0;
3924 }
3925 else {
3926 /* if empty req, must still return chunk representing empty array */
3927 if (n_elements == 0)
3928 return (void**)internal_malloc(m, 0);
3929 marray = 0;
3930 array_size = request2size(n_elements * (sizeof(void*)));
3931 }
3932
3933 /* compute total element size */
3934 if (opts & 0x1) { /* all-same-size */
3935 element_size = request2size(*sizes);
3936 contents_size = n_elements * element_size;
3937 }
3938 else { /* add up all the sizes */
3939 element_size = 0;
3940 contents_size = 0;
3941 for (i = 0; i != n_elements; ++i)
3942 contents_size += request2size(sizes[i]);
3943 }
3944
3945 size = contents_size + array_size;
3946
3947 /*
3948 Allocate the aggregate chunk. First disable direct-mmapping so
3949 malloc won't use it, since we would not be able to later
3950 free/realloc space internal to a segregated mmap region.
3951 */
3952 was_enabled = use_mmap(m);
3953 disable_mmap(m);
3954 mem = internal_malloc(m, size - CHUNK_OVERHEAD);
3955 if (was_enabled)
3956 enable_mmap(m);
3957 if (mem == 0)
3958 return 0;
3959
3960 if (PREACTION(m)) return 0;
3961 p = mem2chunk(mem);
3962 remainder_size = chunksize(p);
3963
3964 assert(!is_mmapped(p));
3965
3966 if (opts & 0x2) { /* optionally clear the elements */
3967 memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size);
3968 }
3969
3970 /* If not provided, allocate the pointer array as final part of chunk */
3971 if (marray == 0) {
3972 size_t array_chunk_size;
3973 array_chunk = chunk_plus_offset(p, contents_size);
3974 array_chunk_size = remainder_size - contents_size;
3975 marray = (void**) (chunk2mem(array_chunk));
3976 set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size);
3977 remainder_size = contents_size;
3978 }
3979
3980 /* split out elements */
3981 for (i = 0; ; ++i) {
3982 marray[i] = chunk2mem(p);
3983 if (i != n_elements-1) {
3984 if (element_size != 0)
3985 size = element_size;
3986 else
3987 size = request2size(sizes[i]);
3988 remainder_size -= size;
3989 set_size_and_pinuse_of_inuse_chunk(m, p, size);
3990 p = chunk_plus_offset(p, size);
3991 }
3992 else { /* the final element absorbs any overallocation slop */
3993 set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size);
3994 break;
3995 }
3996 }
3997
3998#if DEBUG
3999 if (marray != chunks) {
4000 /* final element must have exactly exhausted chunk */
4001 if (element_size != 0) {
4002 assert(remainder_size == element_size);
4003 }
4004 else {
4005 assert(remainder_size == request2size(sizes[i]));
4006 }
4007 check_inuse_chunk(m, mem2chunk(marray));
4008 }
4009 for (i = 0; i != n_elements; ++i)
4010 check_inuse_chunk(m, mem2chunk(marray[i]));
4011
4012#endif /* DEBUG */
4013
4014 POSTACTION(m);
4015 return marray;
4016}
4017
4018
4019/* -------------------------- public routines ---------------------------- */
4020
4021#if !ONLY_MSPACES
4022
4023void* dlmalloc(size_t bytes) {
4024 /*
4025 Basic algorithm:
4026 If a small request (< 256 bytes minus per-chunk overhead):
4027 1. If one exists, use a remainderless chunk in associated smallbin.
4028 (Remainderless means that there are too few excess bytes to
4029 represent as a chunk.)
4030 2. If it is big enough, use the dv chunk, which is normally the
4031 chunk adjacent to the one used for the most recent small request.
4032 3. If one exists, split the smallest available chunk in a bin,
4033 saving remainder in dv.
4034 4. If it is big enough, use the top chunk.
4035 5. If available, get memory from system and use it
4036 Otherwise, for a large request:
4037 1. Find the smallest available binned chunk that fits, and use it
4038 if it is better fitting than dv chunk, splitting if necessary.
4039 2. If better fitting than any binned chunk, use the dv chunk.
4040 3. If it is big enough, use the top chunk.
4041 4. If request size >= mmap threshold, try to directly mmap this chunk.
4042 5. If available, get memory from system and use it
4043
4044 The ugly goto's here ensure that postaction occurs along all paths.
4045 */
4046
4047 if (!PREACTION(gm)) {
4048 void* mem;
4049 size_t nb;
4050 if (bytes <= MAX_SMALL_REQUEST) {
4051 bindex_t idx;
4052 binmap_t smallbits;
4053 nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
4054 idx = small_index(nb);
4055 smallbits = gm->smallmap >> idx;
4056
4057 if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
4058 mchunkptr b, p;
4059 idx += ~smallbits & 1; /* Uses next bin if idx empty */
4060 b = smallbin_at(gm, idx);
4061 p = b->fd;
4062 assert(chunksize(p) == small_index2size(idx));
4063 unlink_first_small_chunk(gm, b, p, idx);
4064 set_inuse_and_pinuse(gm, p, small_index2size(idx));
4065 mem = chunk2mem(p);
4066 check_malloced_chunk(gm, mem, nb);
4067 goto postaction;
4068 }
4069
4070 else if (nb > gm->dvsize) {
4071 if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
4072 mchunkptr b, p, r;
4073 size_t rsize;
4074 bindex_t i;
4075 binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
4076 binmap_t leastbit = least_bit(leftbits);
4077 compute_bit2idx(leastbit, i);
4078 b = smallbin_at(gm, i);
4079 p = b->fd;
4080 assert(chunksize(p) == small_index2size(i));
4081 unlink_first_small_chunk(gm, b, p, i);
4082 rsize = small_index2size(i) - nb;
4083 /* Fit here cannot be remainderless if 4byte sizes */
4084 if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
4085 set_inuse_and_pinuse(gm, p, small_index2size(i));
4086 else {
4087 set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
4088 r = chunk_plus_offset(p, nb);
4089 set_size_and_pinuse_of_free_chunk(r, rsize);
4090 replace_dv(gm, r, rsize);
4091 }
4092 mem = chunk2mem(p);
4093 check_malloced_chunk(gm, mem, nb);
4094 goto postaction;
4095 }
4096
4097 else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) {
4098 check_malloced_chunk(gm, mem, nb);
4099 goto postaction;
4100 }
4101 }
4102 }
4103 else if (bytes >= MAX_REQUEST)
4104 nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
4105 else {
4106 nb = pad_request(bytes);
4107 if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) {
4108 check_malloced_chunk(gm, mem, nb);
4109 goto postaction;
4110 }
4111 }
4112
4113 if (nb <= gm->dvsize) {
4114 size_t rsize = gm->dvsize - nb;
4115 mchunkptr p = gm->dv;
4116 if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
4117 mchunkptr r = gm->dv = chunk_plus_offset(p, nb);
4118 gm->dvsize = rsize;
4119 set_size_and_pinuse_of_free_chunk(r, rsize);
4120 set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
4121 }
4122 else { /* exhaust dv */
4123 size_t dvs = gm->dvsize;
4124 gm->dvsize = 0;
4125 gm->dv = 0;
4126 set_inuse_and_pinuse(gm, p, dvs);
4127 }
4128 mem = chunk2mem(p);
4129 check_malloced_chunk(gm, mem, nb);
4130 goto postaction;
4131 }
4132
4133 else if (nb < gm->topsize) { /* Split top */
4134 size_t rsize = gm->topsize -= nb;
4135 mchunkptr p = gm->top;
4136 mchunkptr r = gm->top = chunk_plus_offset(p, nb);
4137 r->head = rsize | PINUSE_BIT;
4138 set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
4139 mem = chunk2mem(p);
4140 check_top_chunk(gm, gm->top);
4141 check_malloced_chunk(gm, mem, nb);
4142 goto postaction;
4143 }
4144
4145 mem = sys_alloc(gm, nb);
4146
4147 postaction:
4148 POSTACTION(gm);
4149 return mem;
4150 }
4151
4152 return 0;
4153}
4154
4155void dlfree(void* mem) {
4156 /*
4157 Consolidate freed chunks with preceeding or succeeding bordering
4158 free chunks, if they exist, and then place in a bin. Intermixed
4159 with special cases for top, dv, mmapped chunks, and usage errors.
4160 */
4161
4162 if (mem != 0) {
4163 mchunkptr p = mem2chunk(mem);
4164#if FOOTERS
4165 mstate fm = get_mstate_for(p);
4166 if (!ok_magic(fm)) {
4167 USAGE_ERROR_ACTION(fm, p);
4168 return;
4169 }
4170#else /* FOOTERS */
4171#define fm gm
4172#endif /* FOOTERS */
4173 if (!PREACTION(fm)) {
4174 check_inuse_chunk(fm, p);
4175 if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) {
4176 size_t psize = chunksize(p);
4177 mchunkptr next = chunk_plus_offset(p, psize);
4178 if (!pinuse(p)) {
4179 size_t prevsize = p->prev_foot;
4180 if ((prevsize & IS_MMAPPED_BIT) != 0) {
4181 prevsize &= ~IS_MMAPPED_BIT;
4182 psize += prevsize + MMAP_FOOT_PAD;
4183 if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
4184 fm->footprint -= psize;
4185 goto postaction;
4186 }
4187 else {
4188 mchunkptr prev = chunk_minus_offset(p, prevsize);
4189 psize += prevsize;
4190 p = prev;
4191 if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
4192 if (p != fm->dv) {
4193 unlink_chunk(fm, p, prevsize);
4194 }
4195 else if ((next->head & INUSE_BITS) == INUSE_BITS) {
4196 fm->dvsize = psize;
4197 set_free_with_pinuse(p, psize, next);
4198 goto postaction;
4199 }
4200 }
4201 else
4202 goto erroraction;
4203 }
4204 }
4205
4206 if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
4207 if (!cinuse(next)) { /* consolidate forward */
4208 if (next == fm->top) {
4209 size_t tsize = fm->topsize += psize;
4210 fm->top = p;
4211 p->head = tsize | PINUSE_BIT;
4212 if (p == fm->dv) {
4213 fm->dv = 0;
4214 fm->dvsize = 0;
4215 }
4216 if (should_trim(fm, tsize))
4217 sys_trim(fm, 0);
4218 goto postaction;
4219 }
4220 else if (next == fm->dv) {
4221 size_t dsize = fm->dvsize += psize;
4222 fm->dv = p;
4223 set_size_and_pinuse_of_free_chunk(p, dsize);
4224 goto postaction;
4225 }
4226 else {
4227 size_t nsize = chunksize(next);
4228 psize += nsize;
4229 unlink_chunk(fm, next, nsize);
4230 set_size_and_pinuse_of_free_chunk(p, psize);
4231 if (p == fm->dv) {
4232 fm->dvsize = psize;
4233 goto postaction;
4234 }
4235 }
4236 }
4237 else
4238 set_free_with_pinuse(p, psize, next);
4239 insert_chunk(fm, p, psize);
4240 check_free_chunk(fm, p);
4241 goto postaction;
4242 }
4243 }
4244 erroraction:
4245 USAGE_ERROR_ACTION(fm, p);
4246 postaction:
4247 POSTACTION(fm);
4248 }
4249 }
4250#if !FOOTERS
4251#undef fm
4252#endif /* FOOTERS */
4253}
4254
4255void* dlcalloc(size_t n_elements, size_t elem_size) {
4256 void* mem;
4257 size_t req = 0;
4258 if (n_elements != 0) {
4259 req = n_elements * elem_size;
4260 if (((n_elements | elem_size) & ~(size_t)0xffff) &&
4261 (req / n_elements != elem_size))
4262 req = MAX_SIZE_T; /* force downstream failure on overflow */
4263 }
4264 mem = dlmalloc(req);
4265 if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
4266 memset(mem, 0, req);
4267 return mem;
4268}
4269
4270void* dlrealloc(void* oldmem, size_t bytes) {
4271 if (oldmem == 0)
4272 return dlmalloc(bytes);
4273#ifdef REALLOC_ZERO_BYTES_FREES
4274 if (bytes == 0) {
4275 dlfree(oldmem);
4276 return 0;
4277 }
4278#endif /* REALLOC_ZERO_BYTES_FREES */
4279 else {
4280#if ! FOOTERS
4281 mstate m = gm;
4282#else /* FOOTERS */
4283 mstate m = get_mstate_for(mem2chunk(oldmem));
4284 if (!ok_magic(m)) {
4285 USAGE_ERROR_ACTION(m, oldmem);
4286 return 0;
4287 }
4288#endif /* FOOTERS */
4289 return internal_realloc(m, oldmem, bytes);
4290 }
4291}
4292
4293void* dlmemalign(size_t alignment, size_t bytes) {
4294 return internal_memalign(gm, alignment, bytes);
4295}
4296
4297void** dlindependent_calloc(size_t n_elements, size_t elem_size,
4298 void* chunks[]) {
4299 size_t sz = elem_size; /* serves as 1-element array */
4300 return ialloc(gm, n_elements, &sz, 3, chunks);
4301}
4302
4303void** dlindependent_comalloc(size_t n_elements, size_t sizes[],
4304 void* chunks[]) {
4305 return ialloc(gm, n_elements, sizes, 0, chunks);
4306}
4307
4308void* dlvalloc(size_t bytes) {
4309 size_t pagesz;
4310 init_mparams();
4311 pagesz = mparams.page_size;
4312 return dlmemalign(pagesz, bytes);
4313}
4314
4315void* dlpvalloc(size_t bytes) {
4316 size_t pagesz;
4317 init_mparams();
4318 pagesz = mparams.page_size;
4319 return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE));
4320}
4321
4322int dlmalloc_trim(size_t pad) {
4323 int result = 0;
4324 if (!PREACTION(gm)) {
4325 result = sys_trim(gm, pad);
4326 POSTACTION(gm);
4327 }
4328 return result;
4329}
4330
4331size_t dlmalloc_footprint(void) {
4332 return gm->footprint;
4333}
4334
4335size_t dlmalloc_max_footprint(void) {
4336 return gm->max_footprint;
4337}
4338
4339#if !NO_MALLINFO
4340struct mallinfo dlmallinfo(void) {
4341 return internal_mallinfo(gm);
4342}
4343#endif /* NO_MALLINFO */
4344
4345void dlmalloc_stats() {
4346 internal_malloc_stats(gm);
4347}
4348
4349size_t dlmalloc_usable_size(void* mem) {
4350 if (mem != 0) {
4351 mchunkptr p = mem2chunk(mem);
4352 if (cinuse(p))
4353 return chunksize(p) - overhead_for(p);
4354 }
4355 return 0;
4356}
4357
4358int dlmallopt(int param_number, int value) {
4359 return change_mparam(param_number, value);
4360}
4361
4362#endif /* !ONLY_MSPACES */
4363
4364/* ----------------------------- user mspaces ---------------------------- */
4365
4366#if MSPACES
4367
4368static mstate init_user_mstate(char* tbase, size_t tsize) {
4369 size_t msize = pad_request(sizeof(struct malloc_state));
4370 mchunkptr mn;
4371 mchunkptr msp = align_as_chunk(tbase);
4372 mstate m = (mstate)(chunk2mem(msp));
4373 memset(m, 0, msize);
4374 INITIAL_LOCK(&m->mutex);
4375 msp->head = (msize|PINUSE_BIT|CINUSE_BIT);
4376 m->seg.base = m->least_addr = tbase;
4377 m->seg.size = m->footprint = m->max_footprint = tsize;
4378 m->magic = mparams.magic;
4379 m->mflags = mparams.default_mflags;
4380 disable_contiguous(m);
4381 init_bins(m);
4382 mn = next_chunk(mem2chunk(m));
4383 init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE);
4384 check_top_chunk(m, m->top);
4385 return m;
4386}
4387
4388mspace create_mspace(size_t capacity, int locked) {
4389 mstate m = 0;
4390 size_t msize = pad_request(sizeof(struct malloc_state));
4391 init_mparams(); /* Ensure pagesize etc initialized */
4392
4393 if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
4394 size_t rs = ((capacity == 0)? mparams.granularity :
4395 (capacity + TOP_FOOT_SIZE + msize));
4396 size_t tsize = granularity_align(rs);
4397 char* tbase = (char*)(CALL_MMAP(tsize));
4398 if (tbase != CMFAIL) {
4399 m = init_user_mstate(tbase, tsize);
4400 m->seg.sflags = IS_MMAPPED_BIT;
4401 set_lock(m, locked);
4402 }
4403 }
4404 return (mspace)m;
4405}
4406
4407mspace create_mspace_with_base(void* base, size_t capacity, int locked) {
4408 mstate m = 0;
4409 size_t msize = pad_request(sizeof(struct malloc_state));
4410 init_mparams(); /* Ensure pagesize etc initialized */
4411
4412 if (capacity > msize + TOP_FOOT_SIZE &&
4413 capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
4414 m = init_user_mstate((char*)base, capacity);
4415 m->seg.sflags = EXTERN_BIT;
4416 set_lock(m, locked);
4417 }
4418 return (mspace)m;
4419}
4420
4421size_t destroy_mspace(mspace msp) {
4422 size_t freed = 0;
4423 mstate ms = (mstate)msp;
4424 if (ok_magic(ms)) {
4425 msegmentptr sp = &ms->seg;
4426 while (sp != 0) {
4427 char* base = sp->base;
4428 size_t size = sp->size;
4429 flag_t flag = sp->sflags;
4430 sp = sp->next;
4431 if ((flag & IS_MMAPPED_BIT) && !(flag & EXTERN_BIT) &&
4432 CALL_MUNMAP(base, size) == 0)
4433 freed += size;
4434 }
4435 }
4436 else {
4437 USAGE_ERROR_ACTION(ms,ms);
4438 }
4439 return freed;
4440}
4441
4442/*
4443 mspace versions of routines are near-clones of the global
4444 versions. This is not so nice but better than the alternatives.
4445*/
4446
4447
4448void* mspace_malloc(mspace msp, size_t bytes) {
4449 mstate ms = (mstate)msp;
4450 if (!ok_magic(ms)) {
4451 USAGE_ERROR_ACTION(ms,ms);
4452 return 0;
4453 }
4454 if (!PREACTION(ms)) {
4455 void* mem;
4456 size_t nb;
4457 if (bytes <= MAX_SMALL_REQUEST) {
4458 bindex_t idx;
4459 binmap_t smallbits;
4460 nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
4461 idx = small_index(nb);
4462 smallbits = ms->smallmap >> idx;
4463
4464 if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
4465 mchunkptr b, p;
4466 idx += ~smallbits & 1; /* Uses next bin if idx empty */
4467 b = smallbin_at(ms, idx);
4468 p = b->fd;
4469 assert(chunksize(p) == small_index2size(idx));
4470 unlink_first_small_chunk(ms, b, p, idx);
4471 set_inuse_and_pinuse(ms, p, small_index2size(idx));
4472 mem = chunk2mem(p);
4473 check_malloced_chunk(ms, mem, nb);
4474 goto postaction;
4475 }
4476
4477 else if (nb > ms->dvsize) {
4478 if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
4479 mchunkptr b, p, r;
4480 size_t rsize;
4481 bindex_t i;
4482 binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
4483 binmap_t leastbit = least_bit(leftbits);
4484 compute_bit2idx(leastbit, i);
4485 b = smallbin_at(ms, i);
4486 p = b->fd;
4487 assert(chunksize(p) == small_index2size(i));
4488 unlink_first_small_chunk(ms, b, p, i);
4489 rsize = small_index2size(i) - nb;
4490 /* Fit here cannot be remainderless if 4byte sizes */
4491 if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
4492 set_inuse_and_pinuse(ms, p, small_index2size(i));
4493 else {
4494 set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
4495 r = chunk_plus_offset(p, nb);
4496 set_size_and_pinuse_of_free_chunk(r, rsize);
4497 replace_dv(ms, r, rsize);
4498 }
4499 mem = chunk2mem(p);
4500 check_malloced_chunk(ms, mem, nb);
4501 goto postaction;
4502 }
4503
4504 else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) {
4505 check_malloced_chunk(ms, mem, nb);
4506 goto postaction;
4507 }
4508 }
4509 }
4510 else if (bytes >= MAX_REQUEST)
4511 nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
4512 else {
4513 nb = pad_request(bytes);
4514 if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) {
4515 check_malloced_chunk(ms, mem, nb);
4516 goto postaction;
4517 }
4518 }
4519
4520 if (nb <= ms->dvsize) {
4521 size_t rsize = ms->dvsize - nb;
4522 mchunkptr p = ms->dv;
4523 if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
4524 mchunkptr r = ms->dv = chunk_plus_offset(p, nb);
4525 ms->dvsize = rsize;
4526 set_size_and_pinuse_of_free_chunk(r, rsize);
4527 set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
4528 }
4529 else { /* exhaust dv */
4530 size_t dvs = ms->dvsize;
4531 ms->dvsize = 0;
4532 ms->dv = 0;
4533 set_inuse_and_pinuse(ms, p, dvs);
4534 }
4535 mem = chunk2mem(p);
4536 check_malloced_chunk(ms, mem, nb);
4537 goto postaction;
4538 }
4539
4540 else if (nb < ms->topsize) { /* Split top */
4541 size_t rsize = ms->topsize -= nb;
4542 mchunkptr p = ms->top;
4543 mchunkptr r = ms->top = chunk_plus_offset(p, nb);
4544 r->head = rsize | PINUSE_BIT;
4545 set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
4546 mem = chunk2mem(p);
4547 check_top_chunk(ms, ms->top);
4548 check_malloced_chunk(ms, mem, nb);
4549 goto postaction;
4550 }
4551
4552 mem = sys_alloc(ms, nb);
4553
4554 postaction:
4555 POSTACTION(ms);
4556 return mem;
4557 }
4558
4559 return 0;
4560}
4561
4562void mspace_free(mspace msp, void* mem) {
4563 if (mem != 0) {
4564 mchunkptr p = mem2chunk(mem);
4565#if FOOTERS
4566 mstate fm = get_mstate_for(p);
4567#else /* FOOTERS */
4568 mstate fm = (mstate)msp;
4569#endif /* FOOTERS */
4570 if (!ok_magic(fm)) {
4571 USAGE_ERROR_ACTION(fm, p);
4572 return;
4573 }
4574 if (!PREACTION(fm)) {
4575 check_inuse_chunk(fm, p);
4576 if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) {
4577 size_t psize = chunksize(p);
4578 mchunkptr next = chunk_plus_offset(p, psize);
4579 if (!pinuse(p)) {
4580 size_t prevsize = p->prev_foot;
4581 if ((prevsize & IS_MMAPPED_BIT) != 0) {
4582 prevsize &= ~IS_MMAPPED_BIT;
4583 psize += prevsize + MMAP_FOOT_PAD;
4584 if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
4585 fm->footprint -= psize;
4586 goto postaction;
4587 }
4588 else {
4589 mchunkptr prev = chunk_minus_offset(p, prevsize);
4590 psize += prevsize;
4591 p = prev;
4592 if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
4593 if (p != fm->dv) {
4594 unlink_chunk(fm, p, prevsize);
4595 }
4596 else if ((next->head & INUSE_BITS) == INUSE_BITS) {
4597 fm->dvsize = psize;
4598 set_free_with_pinuse(p, psize, next);
4599 goto postaction;
4600 }
4601 }
4602 else
4603 goto erroraction;
4604 }
4605 }
4606
4607 if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
4608 if (!cinuse(next)) { /* consolidate forward */
4609 if (next == fm->top) {
4610 size_t tsize = fm->topsize += psize;
4611 fm->top = p;
4612 p->head = tsize | PINUSE_BIT;
4613 if (p == fm->dv) {
4614 fm->dv = 0;
4615 fm->dvsize = 0;
4616 }
4617 if (should_trim(fm, tsize))
4618 sys_trim(fm, 0);
4619 goto postaction;
4620 }
4621 else if (next == fm->dv) {
4622 size_t dsize = fm->dvsize += psize;
4623 fm->dv = p;
4624 set_size_and_pinuse_of_free_chunk(p, dsize);
4625 goto postaction;
4626 }
4627 else {
4628 size_t nsize = chunksize(next);
4629 psize += nsize;
4630 unlink_chunk(fm, next, nsize);
4631 set_size_and_pinuse_of_free_chunk(p, psize);
4632 if (p == fm->dv) {
4633 fm->dvsize = psize;
4634 goto postaction;
4635 }
4636 }
4637 }
4638 else
4639 set_free_with_pinuse(p, psize, next);
4640 insert_chunk(fm, p, psize);
4641 check_free_chunk(fm, p);
4642 goto postaction;
4643 }
4644 }
4645 erroraction:
4646 USAGE_ERROR_ACTION(fm, p);
4647 postaction:
4648 POSTACTION(fm);
4649 }
4650 }
4651}
4652
4653void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) {
4654 void* mem;
4655 size_t req = 0;
4656 mstate ms = (mstate)msp;
4657 if (!ok_magic(ms)) {
4658 USAGE_ERROR_ACTION(ms,ms);
4659 return 0;
4660 }
4661 if (n_elements != 0) {
4662 req = n_elements * elem_size;
4663 if (((n_elements | elem_size) & ~(size_t)0xffff) &&
4664 (req / n_elements != elem_size))
4665 req = MAX_SIZE_T; /* force downstream failure on overflow */
4666 }
4667 mem = internal_malloc(ms, req);
4668 if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
4669 memset(mem, 0, req);
4670 return mem;
4671}
4672
4673void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) {
4674 if (oldmem == 0)
4675 return mspace_malloc(msp, bytes);
4676#ifdef REALLOC_ZERO_BYTES_FREES
4677 if (bytes == 0) {
4678 mspace_free(msp, oldmem);
4679 return 0;
4680 }
4681#endif /* REALLOC_ZERO_BYTES_FREES */
4682 else {
4683#if FOOTERS
4684 mchunkptr p = mem2chunk(oldmem);
4685 mstate ms = get_mstate_for(p);
4686#else /* FOOTERS */
4687 mstate ms = (mstate)msp;
4688#endif /* FOOTERS */
4689 if (!ok_magic(ms)) {
4690 USAGE_ERROR_ACTION(ms,ms);
4691 return 0;
4692 }
4693 return internal_realloc(ms, oldmem, bytes);
4694 }
4695}
4696
4697void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) {
4698 mstate ms = (mstate)msp;
4699 if (!ok_magic(ms)) {
4700 USAGE_ERROR_ACTION(ms,ms);
4701 return 0;
4702 }
4703 return internal_memalign(ms, alignment, bytes);
4704}
4705
4706void** mspace_independent_calloc(mspace msp, size_t n_elements,
4707 size_t elem_size, void* chunks[]) {
4708 size_t sz = elem_size; /* serves as 1-element array */
4709 mstate ms = (mstate)msp;
4710 if (!ok_magic(ms)) {
4711 USAGE_ERROR_ACTION(ms,ms);
4712 return 0;
4713 }
4714 return ialloc(ms, n_elements, &sz, 3, chunks);
4715}
4716
4717void** mspace_independent_comalloc(mspace msp, size_t n_elements,
4718 size_t sizes[], void* chunks[]) {
4719 mstate ms = (mstate)msp;
4720 if (!ok_magic(ms)) {
4721 USAGE_ERROR_ACTION(ms,ms);
4722 return 0;
4723 }
4724 return ialloc(ms, n_elements, sizes, 0, chunks);
4725}
4726
4727int mspace_trim(mspace msp, size_t pad) {
4728 int result = 0;
4729 mstate ms = (mstate)msp;
4730 if (ok_magic(ms)) {
4731 if (!PREACTION(ms)) {
4732 result = sys_trim(ms, pad);
4733 POSTACTION(ms);
4734 }
4735 }
4736 else {
4737 USAGE_ERROR_ACTION(ms,ms);
4738 }
4739 return result;
4740}
4741
4742void mspace_malloc_stats(mspace msp) {
4743 mstate ms = (mstate)msp;
4744 if (ok_magic(ms)) {
4745 internal_malloc_stats(ms);
4746 }
4747 else {
4748 USAGE_ERROR_ACTION(ms,ms);
4749 }
4750}
4751
4752size_t mspace_footprint(mspace msp) {
4753 size_t result;
4754 mstate ms = (mstate)msp;
4755 if (ok_magic(ms)) {
4756 result = ms->footprint;
4757 }
4758 USAGE_ERROR_ACTION(ms,ms);
4759 return result;
4760}
4761
4762
4763size_t mspace_max_footprint(mspace msp) {
4764 size_t result;
4765 mstate ms = (mstate)msp;
4766 if (ok_magic(ms)) {
4767 result = ms->max_footprint;
4768 }
4769 USAGE_ERROR_ACTION(ms,ms);
4770 return result;
4771}
4772
4773
4774#if !NO_MALLINFO
4775struct mallinfo mspace_mallinfo(mspace msp) {
4776 mstate ms = (mstate)msp;
4777 if (!ok_magic(ms)) {
4778 USAGE_ERROR_ACTION(ms,ms);
4779 }
4780 return internal_mallinfo(ms);
4781}
4782#endif /* NO_MALLINFO */
4783
4784int mspace_mallopt(int param_number, int value) {
4785 return change_mparam(param_number, value);
4786}
4787
4788#endif /* MSPACES */
4789
4790/* -------------------- Alternative MORECORE functions ------------------- */
4791
4792/*
4793 Guidelines for creating a custom version of MORECORE:
4794
4795 * For best performance, MORECORE should allocate in multiples of pagesize.
4796 * MORECORE may allocate more memory than requested. (Or even less,
4797 but this will usually result in a malloc failure.)
4798 * MORECORE must not allocate memory when given argument zero, but
4799 instead return one past the end address of memory from previous
4800 nonzero call.
4801 * For best performance, consecutive calls to MORECORE with positive
4802 arguments should return increasing addresses, indicating that
4803 space has been contiguously extended.
4804 * Even though consecutive calls to MORECORE need not return contiguous
4805 addresses, it must be OK for malloc'ed chunks to span multiple
4806 regions in those cases where they do happen to be contiguous.
4807 * MORECORE need not handle negative arguments -- it may instead
4808 just return MFAIL when given negative arguments.
4809 Negative arguments are always multiples of pagesize. MORECORE
4810 must not misinterpret negative args as large positive unsigned
4811 args. You can suppress all such calls from even occurring by defining
4812 MORECORE_CANNOT_TRIM,
4813
4814 As an example alternative MORECORE, here is a custom allocator
4815 kindly contributed for pre-OSX macOS. It uses virtually but not
4816 necessarily physically contiguous non-paged memory (locked in,
4817 present and won't get swapped out). You can use it by uncommenting
4818 this section, adding some #includes, and setting up the appropriate
4819 defines above:
4820
4821 #define MORECORE osMoreCore
4822
4823 There is also a shutdown routine that should somehow be called for
4824 cleanup upon program exit.
4825
4826 #define MAX_POOL_ENTRIES 100
4827 #define MINIMUM_MORECORE_SIZE (64 * 1024U)
4828 static int next_os_pool;
4829 void *our_os_pools[MAX_POOL_ENTRIES];
4830
4831 void *osMoreCore(int size)
4832 {
4833 void *ptr = 0;
4834 static void *sbrk_top = 0;
4835
4836 if (size > 0)
4837 {
4838 if (size < MINIMUM_MORECORE_SIZE)
4839 size = MINIMUM_MORECORE_SIZE;
4840 if (CurrentExecutionLevel() == kTaskLevel)
4841 ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
4842 if (ptr == 0)
4843 {
4844 return (void *) MFAIL;
4845 }
4846 // save ptrs so they can be freed during cleanup
4847 our_os_pools[next_os_pool] = ptr;
4848 next_os_pool++;
4849 ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
4850 sbrk_top = (char *) ptr + size;
4851 return ptr;
4852 }
4853 else if (size < 0)
4854 {
4855 // we don't currently support shrink behavior
4856 return (void *) MFAIL;
4857 }
4858 else
4859 {
4860 return sbrk_top;
4861 }
4862 }
4863
4864 // cleanup any allocated memory pools
4865 // called as last thing before shutting down driver
4866
4867 void osCleanupMem(void)
4868 {
4869 void **ptr;
4870
4871 for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
4872 if (*ptr)
4873 {
4874 PoolDeallocate(*ptr);
4875 *ptr = 0;
4876 }
4877 }
4878
4879*/
4880
4881
4882/* -----------------------------------------------------------------------
4883History:
4884 V2.8.3 Thu Sep 22 11:16:32 2005 Doug Lea (dl at gee)
4885 * Add max_footprint functions
4886 * Ensure all appropriate literals are size_t
4887 * Fix conditional compilation problem for some #define settings
4888 * Avoid concatenating segments with the one provided
4889 in create_mspace_with_base
4890 * Rename some variables to avoid compiler shadowing warnings
4891 * Use explicit lock initialization.
4892 * Better handling of sbrk interference.
4893 * Simplify and fix segment insertion, trimming and mspace_destroy
4894 * Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x
4895 * Thanks especially to Dennis Flanagan for help on these.
4896
4897 V2.8.2 Sun Jun 12 16:01:10 2005 Doug Lea (dl at gee)
4898 * Fix memalign brace error.
4899
4900 V2.8.1 Wed Jun 8 16:11:46 2005 Doug Lea (dl at gee)
4901 * Fix improper #endif nesting in C++
4902 * Add explicit casts needed for C++
4903
4904 V2.8.0 Mon May 30 14:09:02 2005 Doug Lea (dl at gee)
4905 * Use trees for large bins
4906 * Support mspaces
4907 * Use segments to unify sbrk-based and mmap-based system allocation,
4908 removing need for emulation on most platforms without sbrk.
4909 * Default safety checks
4910 * Optional footer checks. Thanks to William Robertson for the idea.
4911 * Internal code refactoring
4912 * Incorporate suggestions and platform-specific changes.
4913 Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas,
4914 Aaron Bachmann, Emery Berger, and others.
4915 * Speed up non-fastbin processing enough to remove fastbins.
4916 * Remove useless cfree() to avoid conflicts with other apps.
4917 * Remove internal memcpy, memset. Compilers handle builtins better.
4918 * Remove some options that no one ever used and rename others.
4919
4920 V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee)
4921 * Fix malloc_state bitmap array misdeclaration
4922
4923 V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee)
4924 * Allow tuning of FIRST_SORTED_BIN_SIZE
4925 * Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte.
4926 * Better detection and support for non-contiguousness of MORECORE.
4927 Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger
4928 * Bypass most of malloc if no frees. Thanks To Emery Berger.
4929 * Fix freeing of old top non-contiguous chunk im sysmalloc.
4930 * Raised default trim and map thresholds to 256K.
4931 * Fix mmap-related #defines. Thanks to Lubos Lunak.
4932 * Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield.
4933 * Branch-free bin calculation
4934 * Default trim and mmap thresholds now 256K.
4935
4936 V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
4937 * Introduce independent_comalloc and independent_calloc.
4938 Thanks to Michael Pachos for motivation and help.
4939 * Make optional .h file available
4940 * Allow > 2GB requests on 32bit systems.
4941 * new WIN32 sbrk, mmap, munmap, lock code from <Walter@GeNeSys-e.de>.
4942 Thanks also to Andreas Mueller <a.mueller at paradatec.de>,
4943 and Anonymous.
4944 * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for
4945 helping test this.)
4946 * memalign: check alignment arg
4947 * realloc: don't try to shift chunks backwards, since this
4948 leads to more fragmentation in some programs and doesn't
4949 seem to help in any others.
4950 * Collect all cases in malloc requiring system memory into sysmalloc
4951 * Use mmap as backup to sbrk
4952 * Place all internal state in malloc_state
4953 * Introduce fastbins (although similar to 2.5.1)
4954 * Many minor tunings and cosmetic improvements
4955 * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK
4956 * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS
4957 Thanks to Tony E. Bennett <tbennett@nvidia.com> and others.
4958 * Include errno.h to support default failure action.
4959
4960 V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee)
4961 * return null for negative arguments
4962 * Added Several WIN32 cleanups from Martin C. Fong <mcfong at yahoo.com>
4963 * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
4964 (e.g. WIN32 platforms)
4965 * Cleanup header file inclusion for WIN32 platforms
4966 * Cleanup code to avoid Microsoft Visual C++ compiler complaints
4967 * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
4968 memory allocation routines
4969 * Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
4970 * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
4971 usage of 'assert' in non-WIN32 code
4972 * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
4973 avoid infinite loop
4974 * Always call 'fREe()' rather than 'free()'
4975
4976 V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee)
4977 * Fixed ordering problem with boundary-stamping
4978
4979 V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)
4980 * Added pvalloc, as recommended by H.J. Liu
4981 * Added 64bit pointer support mainly from Wolfram Gloger
4982 * Added anonymously donated WIN32 sbrk emulation
4983 * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
4984 * malloc_extend_top: fix mask error that caused wastage after
4985 foreign sbrks
4986 * Add linux mremap support code from HJ Liu
4987
4988 V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)
4989 * Integrated most documentation with the code.
4990 * Add support for mmap, with help from
4991 Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
4992 * Use last_remainder in more cases.
4993 * Pack bins using idea from colin@nyx10.cs.du.edu
4994 * Use ordered bins instead of best-fit threshhold
4995 * Eliminate block-local decls to simplify tracing and debugging.
4996 * Support another case of realloc via move into top
4997 * Fix error occuring when initial sbrk_base not word-aligned.
4998 * Rely on page size for units instead of SBRK_UNIT to
4999 avoid surprises about sbrk alignment conventions.
5000 * Add mallinfo, mallopt. Thanks to Raymond Nijssen
5001 (raymond@es.ele.tue.nl) for the suggestion.
5002 * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
5003 * More precautions for cases where other routines call sbrk,
5004 courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
5005 * Added macros etc., allowing use in linux libc from
5006 H.J. Lu (hjl@gnu.ai.mit.edu)
5007 * Inverted this history list
5008
5009 V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)
5010 * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
5011 * Removed all preallocation code since under current scheme
5012 the work required to undo bad preallocations exceeds
5013 the work saved in good cases for most test programs.
5014 * No longer use return list or unconsolidated bins since
5015 no scheme using them consistently outperforms those that don't
5016 given above changes.
5017 * Use best fit for very large chunks to prevent some worst-cases.
5018 * Added some support for debugging
5019
5020 V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)
5021 * Removed footers when chunks are in use. Thanks to
5022 Paul Wilson (wilson@cs.texas.edu) for the suggestion.
5023
5024 V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)
5025 * Added malloc_trim, with help from Wolfram Gloger
5026 (wmglo@Dent.MED.Uni-Muenchen.DE).
5027
5028 V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)
5029
5030 V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)
5031 * realloc: try to expand in both directions
5032 * malloc: swap order of clean-bin strategy;
5033 * realloc: only conditionally expand backwards
5034 * Try not to scavenge used bins
5035 * Use bin counts as a guide to preallocation
5036 * Occasionally bin return list chunks in first scan
5037 * Add a few optimizations from colin@nyx10.cs.du.edu
5038
5039 V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)
5040 * faster bin computation & slightly different binning
5041 * merged all consolidations to one part of malloc proper
5042 (eliminating old malloc_find_space & malloc_clean_bin)
5043 * Scan 2 returns chunks (not just 1)
5044 * Propagate failure in realloc if malloc returns 0
5045 * Add stuff to allow compilation on non-ANSI compilers
5046 from kpv@research.att.com
5047
5048 V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)
5049 * removed potential for odd address access in prev_chunk
5050 * removed dependency on getpagesize.h
5051 * misc cosmetics and a bit more internal documentation
5052 * anticosmetics: mangled names in macros to evade debugger strangeness
5053 * tested on sparc, hp-700, dec-mips, rs6000
5054 with gcc & native cc (hp, dec only) allowing
5055 Detlefs & Zorn comparison study (in SIGPLAN Notices.)
5056
5057 Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)
5058 * Based loosely on libg++-1.2X malloc. (It retains some of the overall
5059 structure of old version, but most details differ.)
5060
5061*/
diff --git a/apps/plugins/lua/rockaux.c b/apps/plugins/lua/rockaux.c
new file mode 100644
index 0000000000..2213420ce2
--- /dev/null
+++ b/apps/plugins/lua/rockaux.c
@@ -0,0 +1,61 @@
1/***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
9 *
10 * Copyright (C) 2008 Dan Everton (safetydan)
11 * String function implementations taken from dietlibc 0.31 (GPLv2 License)
12 *
13 * This program is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU General Public License
15 * as published by the Free Software Foundation; either version 2
16 * of the License, or (at your option) any later version.
17 *
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
20 *
21 ****************************************************************************/
22
23#include "plugin.h"
24
25#ifndef SIMULATOR
26int errno = 0;
27#endif
28
29char *strerror(int errnum)
30{
31 (void) errnum;
32
33 DEBUGF("strerror()\n");
34
35 return NULL;
36}
37
38long floor(long x)
39{
40 (void) x;
41
42 DEBUGF("floor()\n");
43
44 return 0;
45}
46
47long pow(long x, long y)
48{
49 (void) x;
50 (void) y;
51
52 DEBUGF("pow()\n");
53
54 return 0;
55}
56
57int strcoll(const char * str1, const char * str2)
58{
59 return rb->strcmp(str1, str2);
60}
61
diff --git a/apps/plugins/lua/rockconf.h b/apps/plugins/lua/rockconf.h
new file mode 100644
index 0000000000..7ae2245c3a
--- /dev/null
+++ b/apps/plugins/lua/rockconf.h
@@ -0,0 +1,64 @@
1/***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
9 *
10 * Copyright (C) 2008 Dan Everton (safetydan)
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
16 *
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
19 *
20 ****************************************************************************/
21
22#ifndef _ROCKCONF_H_
23#define _ROCKCONF_H_
24
25#include "plugin.h"
26
27#undef LUAI_THROW
28#undef LUAI_TRY
29#undef luai_jmpbuf
30
31#ifndef SIMULATOR
32#include "../../codecs/lib/setjmp.h"
33#else
34#include <setjmp.h>
35#endif
36
37#include "lib/pluginlib_exit.h"
38
39#define LUAI_THROW(L,c) longjmp((c)->b, 1)
40#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }
41#define luai_jmpbuf jmp_buf
42
43extern char curpath[MAX_PATH];
44void *dlrealloc(void *ptr, size_t size);
45void dlfree(void *ptr);
46long strtol(const char *nptr, char **endptr, int base);
47unsigned long strtoul(const char *str, char **endptr, int base);
48long floor(long x);
49long pow(long x, long y);
50
51/* Simple substitutions */
52#define realloc dlrealloc
53#define free dlfree
54#define memchr rb->memchr
55#define snprintf rb->snprintf
56#define strcat rb->strcat
57#define strchr rb->strchr
58#define strcmp rb->strcmp
59#define strcpy rb->strcpy
60#define strncpy rb->strncpy
61#define strlen rb->strlen
62
63#endif /* _ROCKCONF_H_ */
64
diff --git a/apps/plugins/lua/rocklib.c b/apps/plugins/lua/rocklib.c
new file mode 100644
index 0000000000..60c51f3206
--- /dev/null
+++ b/apps/plugins/lua/rocklib.c
@@ -0,0 +1,364 @@
1/***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
9 *
10 * Copyright (C) 2008 Dan Everton (safetydan)
11 * Copyright (C) 2009 Maurus Cuelenaere
12 *
13 * This program is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU General Public License
15 * as published by the Free Software Foundation; either version 2
16 * of the License, or (at your option) any later version.
17 *
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
20 *
21 ****************************************************************************/
22
23#define lrocklib_c
24#define LUA_LIB
25
26#include "lua.h"
27
28#include "lauxlib.h"
29#include "rocklib.h"
30
31#define RB_WRAP(M) static int rock_##M(lua_State *L)
32
33RB_WRAP(splash)
34{
35 int ticks = luaL_checkint(L, 1);
36 const char *s = luaL_checkstring(L, 2);
37 rb->splash(ticks, s);
38 return 1;
39}
40
41RB_WRAP(lcd_update)
42{
43 (void)L;
44 rb->lcd_update();
45 return 1;
46}
47
48RB_WRAP(lcd_clear_display)
49{
50 (void)L;
51 rb->lcd_clear_display();
52 return 1;
53}
54
55RB_WRAP(lcd_putsxy)
56{
57 int x = luaL_checkint(L, 1);
58 int y = luaL_checkint(L, 2);
59 const char* string = luaL_checkstring(L, 3);
60 rb->lcd_putsxy(x, y, string);
61 return 1;
62}
63
64RB_WRAP(lcd_puts)
65{
66 int x = luaL_checkint(L, 1);
67 int y = luaL_checkint(L, 2);
68 const char* string = luaL_checkstring(L, 3);
69 rb->lcd_puts(x, y, string);
70 return 1;
71}
72
73RB_WRAP(lcd_puts_scroll)
74{
75 int x = luaL_checkint(L, 1);
76 int y = luaL_checkint(L, 2);
77 const char* string = luaL_checkstring(L, 3);
78 rb->lcd_puts_scroll(x, y, string);
79 return 1;
80}
81
82RB_WRAP(lcd_stop_scroll)
83{
84 (void)L;
85 rb->lcd_stop_scroll();
86 return 1;
87}
88
89#ifdef HAVE_LCD_BITMAP
90RB_WRAP(lcd_set_drawmode)
91{
92 int drawmode = luaL_checkint(L, 1);
93 rb->lcd_set_drawmode(drawmode);
94 return 1;
95}
96
97RB_WRAP(lcd_get_drawmode)
98{
99 int result = rb->lcd_get_drawmode();
100 lua_pushinteger(L, result);
101 return 1;
102}
103
104RB_WRAP(lcd_setfont)
105{
106 int font = luaL_checkint(L, 1);
107 rb->lcd_setfont(font);
108 return 1;
109}
110
111RB_WRAP(lcd_drawpixel)
112{
113 int x = luaL_checkint(L, 1);
114 int y = luaL_checkint(L, 2);
115
116 rb->lcd_drawpixel(x, y);
117
118 return 1;
119}
120
121RB_WRAP(lcd_drawline)
122{
123 int x1 = luaL_checkint(L, 1);
124 int y1 = luaL_checkint(L, 2);
125 int x2 = luaL_checkint(L, 3);
126 int y2 = luaL_checkint(L, 4);
127
128 rb->lcd_drawline(x1, y1, x2, y2);
129
130 return 1;
131}
132
133RB_WRAP(lcd_hline)
134{
135 int x1 = luaL_checkint(L, 1);
136 int x2 = luaL_checkint(L, 2);
137 int y = luaL_checkint(L, 3);
138
139 rb->lcd_hline(x1, x2, y);
140
141 return 1;
142}
143
144RB_WRAP(lcd_vline)
145{
146 int x = luaL_checkint(L, 1);
147 int y1 = luaL_checkint(L, 2);
148 int y2 = luaL_checkint(L, 3);
149
150 rb->lcd_vline(x, y1, y2);
151
152 return 1;
153}
154
155RB_WRAP(lcd_drawrect)
156{
157 int x = luaL_checkint(L, 1);
158 int y = luaL_checkint(L, 2);
159 int width = luaL_checkint(L, 3);
160 int height = luaL_checkint(L, 4);
161
162 rb->lcd_drawrect(x, y, width, height);
163
164 return 1;
165}
166
167RB_WRAP(lcd_fillrect)
168{
169 int x = luaL_checkint(L, 1);
170 int y = luaL_checkint(L, 2);
171 int width = luaL_checkint(L, 3);
172 int height = luaL_checkint(L, 4);
173
174 rb->lcd_fillrect(x, y, width, height);
175
176 return 1;
177}
178#endif
179
180RB_WRAP(yield)
181{
182 (void)L;
183 rb->yield();
184 return 1;
185}
186
187RB_WRAP(sleep)
188{
189 int ticks = luaL_checkint(L, 1);
190 rb->sleep(ticks);
191 return 1;
192}
193
194RB_WRAP(current_tick)
195{
196 lua_pushinteger(L, *rb->current_tick);
197 return 1;
198}
199
200RB_WRAP(button_get)
201{
202 bool block = lua_toboolean(L, 1);
203 long result = rb->button_get(block);
204 lua_pushinteger(L, result);
205 return 1;
206}
207
208RB_WRAP(button_get_w_tmo)
209{
210 int ticks = luaL_checkint(L, 1);
211 long result = rb->button_get_w_tmo(ticks);
212 lua_pushinteger(L, result);
213 return 1;
214}
215
216RB_WRAP(button_status)
217{
218 int result = rb->button_status();
219 lua_pushinteger(L, result);
220 return 1;
221}
222
223#ifdef HAVE_BUTTON_DATA
224RB_WRAP(button_get_data)
225{
226 int result = rb->button_get_data();
227 lua_pushinteger(L, result);
228 return 1;
229}
230#endif
231
232#ifdef HAS_BUTTON_HOLD
233RB_WRAP(button_hold)
234{
235 bool result = rb->button_hold();
236 lua_pushboolean(L, result);
237 return 1;
238}
239#endif
240
241RB_WRAP(get_action)
242{
243 int context = luaL_checkint(L, 1);
244 int timeout = luaL_checkint(L, 2);
245 int result = rb->get_action(context, timeout);
246 lua_pushinteger(L, result);
247 return 1;
248}
249
250RB_WRAP(action_userabort)
251{
252 int timeout = luaL_checkint(L, 1);
253 bool result = rb->action_userabort(timeout);
254 lua_pushboolean(L, result);
255 return 1;
256}
257
258RB_WRAP(kbd_input)
259{
260 char* buffer = (char*)luaL_checkstring(L, 1);
261 int buflen = luaL_checkint(L, 2);
262 int result = rb->kbd_input(buffer, buflen);
263 lua_pushinteger(L, result);
264 return 1;
265}
266
267RB_WRAP(backlight_on)
268{
269 (void)L;
270 rb->backlight_on();
271 return 1;
272}
273
274RB_WRAP(backlight_off)
275{
276 (void)L;
277 rb->backlight_off();
278 return 1;
279}
280
281RB_WRAP(backlight_set_timeout)
282{
283 int val = luaL_checkint(L, 1);
284 rb->backlight_set_timeout(val);
285 return 1;
286}
287
288#ifdef HAVE_BACKLIGHT_BRIGHTNESS
289RB_WRAP(backlight_set_brightness)
290{
291 int val = luaL_checkint(L, 1);
292 rb->backlight_set_brightness(val);
293 return 1;
294}
295#endif
296
297
298#define R(NAME) {#NAME, rock_##NAME}
299static const luaL_Reg rocklib[] = {
300 /* Graphics */
301 R(lcd_clear_display),
302 R(lcd_update),
303 R(lcd_puts),
304 R(lcd_putsxy),
305 R(lcd_puts_scroll),
306 R(lcd_stop_scroll),
307 R(splash),
308#ifdef HAVE_LCD_BITMAP
309 R(lcd_set_drawmode),
310 R(lcd_get_drawmode),
311 R(lcd_setfont),
312 R(lcd_drawline),
313 R(lcd_drawpixel),
314 R(lcd_hline),
315 R(lcd_vline),
316 R(lcd_drawrect),
317 R(lcd_fillrect),
318#endif
319
320 /* Kernel */
321 R(sleep),
322 R(yield),
323 R(current_tick),
324
325 /* Buttons */
326 R(button_get),
327 R(button_get_w_tmo),
328 R(button_status),
329#ifdef HAVE_BUTTON_DATA
330 R(button_get_data),
331#endif
332#ifdef HAS_BUTTON_HOLD
333 R(button_hold),
334#endif
335 R(get_action),
336 R(action_userabort),
337 R(kbd_input),
338
339 /* Hardware */
340 R(backlight_on),
341 R(backlight_off),
342 R(backlight_set_timeout),
343#ifdef HAVE_BACKLIGHT_BRIGHTNESS
344 R(backlight_set_brightness),
345#endif
346
347 {NULL, NULL}
348};
349#undef R
350
351#define RB_CONSTANT(x) lua_pushinteger(L, x); lua_setfield(L, -2, #x);
352/*
353 ** Open Rockbox library
354 */
355LUALIB_API int luaopen_rock(lua_State *L)
356{
357 luaL_register(L, LUA_ROCKLIBNAME, rocklib);
358 RB_CONSTANT(HZ);
359 RB_CONSTANT(LCD_WIDTH);
360 RB_CONSTANT(LCD_HEIGHT);
361
362 return 1;
363}
364
diff --git a/apps/plugins/lua/rocklib.h b/apps/plugins/lua/rocklib.h
new file mode 100644
index 0000000000..b5817f2f57
--- /dev/null
+++ b/apps/plugins/lua/rocklib.h
@@ -0,0 +1,29 @@
1/***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
9 *
10 * Copyright (C) 2008 Dan Everton (safetydan)
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
16 *
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
19 *
20 ****************************************************************************/
21
22#ifndef _ROCKLIB_H_
23#define _ROCKLIB_H_
24
25#define LUA_ROCKLIBNAME "rb"
26LUALIB_API int (luaopen_rock) (lua_State *L);
27
28#endif /* _ROCKLIB_H_ */
29
diff --git a/apps/plugins/lua/rocklibc.h b/apps/plugins/lua/rocklibc.h
new file mode 100644
index 0000000000..78b83a6c18
--- /dev/null
+++ b/apps/plugins/lua/rocklibc.h
@@ -0,0 +1,45 @@
1
2/***************************************************************************
3 * __________ __ ___.
4 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
5 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
6 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
7 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
8 * \/ \/ \/ \/ \/
9 * $Id$
10 *
11 * Copyright (C) 2008 Dan Everton (safetydan)
12 *
13 * This program is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU General Public License
15 * as published by the Free Software Foundation; either version 2
16 * of the License, or (at your option) any later version.
17 *
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
20 *
21 ****************************************************************************/
22
23#ifndef _ROCKLIBC_H_
24#define _ROCKLIBC_H_
25
26#include <ctype.h>
27#include "plugin.h"
28
29#ifdef SIMULATOR
30#include <errno.h>
31#else
32extern int errno;
33#define EINVAL 22 /* Invalid argument */
34#define ERANGE 34 /* Math result not representable */
35#endif
36
37#define __likely LIKELY
38#define __unlikely UNLIKELY
39
40/* Simple substitutions */
41#define memcmp rb->memcmp
42#define strlen rb->strlen
43
44#endif /* _ROCKLIBC_H_ */
45
diff --git a/apps/plugins/lua/rocklua.c b/apps/plugins/lua/rocklua.c
new file mode 100644
index 0000000000..4bb89ae29b
--- /dev/null
+++ b/apps/plugins/lua/rocklua.c
@@ -0,0 +1,105 @@
1/***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
9 *
10 * Copyright (C) 2008 Dan Everton (safetydan)
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
16 *
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
19 *
20 ****************************************************************************/
21
22#include "plugin.h"
23#include "lib/pluginlib_exit.h"
24#include "lua.h"
25#include "lauxlib.h"
26#include "lualib.h"
27#include "rocklib.h"
28#include "rockmalloc.h"
29
30PLUGIN_HEADER
31
32static const luaL_Reg lualibs[] = {
33 {"", luaopen_base},
34 {LUA_TABLIBNAME, luaopen_table},
35 {LUA_STRLIBNAME, luaopen_string},
36 {LUA_ROCKLIBNAME, luaopen_rock},
37 {NULL, NULL}
38};
39
40static void rocklua_openlibs(lua_State *L) {
41 const luaL_Reg *lib = lualibs;
42 for (; lib->func; lib++) {
43 lua_pushcfunction(L, lib->func);
44 lua_pushstring(L, lib->name);
45 lua_call(L, 1, 0);
46 }
47}
48
49char curpath[MAX_PATH];
50static void fill_curpath(const char* filename)
51{
52 char* pos = rb->strrchr(filename, '/');
53
54 if(pos != NULL)
55 {
56 int len = (int)(pos - filename);
57
58 if(len > 0)
59 memcpy(curpath, filename, len);
60
61 curpath[len] = '\0';
62 }
63}
64
65
66/***************** Plugin Entry Point *****************/
67enum plugin_status plugin_start(const void* parameter)
68{
69 const char* filename;
70 int status;
71
72 PLUGINLIB_EXIT_INIT
73
74 if (parameter == NULL)
75 {
76 rb->splash(HZ, "Play a .lua file!");
77 return PLUGIN_ERROR;
78 }
79 else
80 {
81 filename = (char*) parameter;
82 fill_curpath(filename);
83
84 lua_State *L = luaL_newstate();
85
86 rocklua_openlibs(L);
87 status = luaL_loadfile(L, filename);
88 if (!status) {
89 rb->lcd_clear_display();
90 status = lua_pcall(L, 0, 0, 0);
91 }
92
93 dlmalloc_stats();
94
95 if (status) {
96 rb->splashf(5 * HZ, "%s", lua_tostring(L, -1));
97 lua_pop(L, 1);
98 }
99
100 lua_close(L);
101 }
102
103 return PLUGIN_OK;
104}
105
diff --git a/apps/plugins/lua/rockmalloc.c b/apps/plugins/lua/rockmalloc.c
new file mode 100644
index 0000000000..14a43396ea
--- /dev/null
+++ b/apps/plugins/lua/rockmalloc.c
@@ -0,0 +1,63 @@
1/***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
9 *
10 * Copyright (C) 2008 Dan Everton (safetydan)
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
16 *
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
19 *
20 ****************************************************************************/
21
22#include "plugin.h"
23#include "rockmalloc.h"
24#include "malloc.c"
25
26void *rocklua_morecore(int size)
27{
28 static char *sbrk_top = NULL;
29 static ssize_t total_size = 0;
30 void *ptr = 0;
31
32 if (size > 0) {
33 size = size + 4 - (size % 4);
34
35 if (sbrk_top == NULL) {
36 sbrk_top = rb->plugin_get_buffer((size_t *) &total_size);
37 }
38
39 if (sbrk_top == NULL || size + 4 > abs(total_size)) {
40 /* Try the audio buffer */
41 sbrk_top = rb->plugin_get_audio_buffer((size_t *) &total_size);
42
43 if(sbrk_top == NULL || size + 4 > abs(total_size)) {
44 printf("malloc failed for %d!\n", size);
45 return (void *) MFAIL;
46 }
47 }
48
49 ptr = sbrk_top + 4;
50 *((unsigned int *) sbrk_top) = size;
51
52 sbrk_top += size + 4;
53 total_size -= size + 4;
54
55 return ptr;
56 } else if (size < 0) {
57 /* we don't currently support shrink behavior */
58 return (void *) MFAIL;
59 } else {
60 return sbrk_top;
61 }
62}
63
diff --git a/apps/plugins/lua/rockmalloc.h b/apps/plugins/lua/rockmalloc.h
new file mode 100644
index 0000000000..46a943f59e
--- /dev/null
+++ b/apps/plugins/lua/rockmalloc.h
@@ -0,0 +1,46 @@
1/***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
9 *
10 * Copyright (C) 2008 Dan Everton (safetydan)
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
16 *
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
19 *
20 ****************************************************************************/
21
22#ifndef _ROCKMALLOC_H_
23#define _ROCKMALLOC_H_
24
25#undef WIN32
26#undef _WIN32
27#define LACKS_UNISTD_H
28#define LACKS_SYS_PARAM_H
29#define LACKS_SYS_MMAN_H
30#define LACKS_STRINGS_H
31#define INSECURE 1
32#define USE_DL_PREFIX 1
33#define MORECORE_CANNOT_TRIM 1
34#define HAVE_MMAP 0
35#define HAVE_MREMAP 0
36#define NO_MALLINFO 1
37#define ABORT ((void) 0)
38#define DEBUG 0
39#define MORECORE rocklua_morecore
40
41void *rocklua_morecore(int size);
42void dlmalloc_stats(void);
43
44#define printf DEBUGF
45
46#endif
diff --git a/apps/plugins/lua/strcspn.c b/apps/plugins/lua/strcspn.c
new file mode 100644
index 0000000000..7af6f693eb
--- /dev/null
+++ b/apps/plugins/lua/strcspn.c
@@ -0,0 +1,16 @@
1#include "rocklibc.h"
2
3size_t strcspn(const char *s, const char *reject)
4{
5 size_t l=0;
6 int a=1,i,al=strlen(reject);
7
8 while((a)&&(*s))
9 {
10 for(i=0;(a)&&(i<al);i++)
11 if (*s==reject[i]) a=0;
12 if (a) l++;
13 s++;
14 }
15 return l;
16}
diff --git a/apps/plugins/lua/strncat.c b/apps/plugins/lua/strncat.c
new file mode 100644
index 0000000000..5b15ff07b1
--- /dev/null
+++ b/apps/plugins/lua/strncat.c
@@ -0,0 +1,21 @@
1#include "rocklibc.h"
2
3/* gcc is broken and has a non-SUSv2 compliant internal prototype.
4 * This causes it to warn about a type mismatch here. Ignore it. */
5char *strncat(char *s, const char *t, size_t n) {
6 char *dest=s;
7 register char *max;
8 s+=strlen(s);
9 if (__unlikely((max=s+n)==s)) goto fini;
10 for (;;) {
11 if (__unlikely(!(*s = *t))) break; if (__unlikely(++s==max)) break; ++t;
12#ifndef WANT_SMALL_STRING_ROUTINES
13 if (__unlikely(!(*s = *t))) break; if (__unlikely(++s==max)) break; ++t;
14 if (__unlikely(!(*s = *t))) break; if (__unlikely(++s==max)) break; ++t;
15 if (__unlikely(!(*s = *t))) break; if (__unlikely(++s==max)) break; ++t;
16#endif
17 }
18 *s=0;
19fini:
20 return dest;
21}
diff --git a/apps/plugins/lua/strpbrk.c b/apps/plugins/lua/strpbrk.c
new file mode 100644
index 0000000000..f416f391ae
--- /dev/null
+++ b/apps/plugins/lua/strpbrk.c
@@ -0,0 +1,10 @@
1#include "rocklibc.h"
2
3char *strpbrk(const char *s, const char *accept) {
4 register int i,l=strlen(accept);
5 for (; *s; s++)
6 for (i=0; i<l; i++)
7 if (*s == accept[i])
8 return (char*)s;
9 return 0;
10}
diff --git a/apps/plugins/lua/strstr.c b/apps/plugins/lua/strstr.c
new file mode 100644
index 0000000000..2db47f4adf
--- /dev/null
+++ b/apps/plugins/lua/strstr.c
@@ -0,0 +1,16 @@
1#include "rocklibc.h"
2
3char *strstr(const char *haystack, const char *needle) {
4 size_t nl=strlen(needle);
5 size_t hl=strlen(haystack);
6 int i;
7 if (!nl) goto found;
8 if (nl>hl) return 0;
9 for (i=hl-nl+1; __likely(i); --i) {
10 if (*haystack==*needle && !memcmp(haystack,needle,nl))
11found:
12 return (char*)haystack;
13 ++haystack;
14 }
15 return 0;
16}
diff --git a/apps/plugins/lua/strtol.c b/apps/plugins/lua/strtol.c
new file mode 100644
index 0000000000..184951b844
--- /dev/null
+++ b/apps/plugins/lua/strtol.c
@@ -0,0 +1,27 @@
1#include "rocklibc.h"
2
3extern unsigned long int strtoul(const char *ptr, char **endptr, int base);
4
5#define ABS_LONG_MIN 2147483648UL
6long int strtol(const char *nptr, char **endptr, int base)
7{
8 int neg=0;
9 unsigned long int v;
10 const char*orig=nptr;
11
12 while(isspace(*nptr)) nptr++;
13
14 if (*nptr == '-' && isalnum(nptr[1])) { neg=-1; ++nptr; }
15 v=strtoul(nptr,endptr,base);
16 if (endptr && *endptr==nptr) *endptr=(char *)orig;
17 if (v>=ABS_LONG_MIN) {
18 if (v==ABS_LONG_MIN && neg) {
19 errno=0;
20 return v;
21 }
22 errno=ERANGE;
23 return (neg?LONG_MIN:LONG_MAX);
24 }
25 return (neg?-v:v);
26}
27
diff --git a/apps/plugins/lua/strtoul.c b/apps/plugins/lua/strtoul.c
new file mode 100644
index 0000000000..74d9b4bb09
--- /dev/null
+++ b/apps/plugins/lua/strtoul.c
@@ -0,0 +1,53 @@
1#include "rocklibc.h"
2
3unsigned long int strtoul(const char *ptr, char **endptr, int base)
4{
5 int neg = 0, overflow = 0;
6 unsigned long int v=0;
7 const char* orig;
8 const char* nptr=ptr;
9
10 while(isspace(*nptr)) ++nptr;
11
12 if (*nptr == '-') { neg=1; nptr++; }
13 else if (*nptr == '+') ++nptr;
14 orig=nptr;
15 if (base==16 && nptr[0]=='0') goto skip0x;
16 if (base) {
17 register unsigned int b=base-2;
18 if (__unlikely(b>34)) { errno=EINVAL; return 0; }
19 } else {
20 if (*nptr=='0') {
21 base=8;
22skip0x:
23 if ((nptr[1]=='x'||nptr[1]=='X') && isxdigit(nptr[2])) {
24 nptr+=2;
25 base=16;
26 }
27 } else
28 base=10;
29 }
30 while(__likely(*nptr)) {
31 register unsigned char c=*nptr;
32 c=(c>='a'?c-'a'+10:c>='A'?c-'A'+10:c<='9'?c-'0':0xff);
33 if (__unlikely(c>=base)) break; /* out of base */
34 {
35 register unsigned long x=(v&0xff)*base+c;
36 register unsigned long w=(v>>8)*base+(x>>8);
37 if (w>(ULONG_MAX>>8)) overflow=1;
38 v=(w<<8)+(x&0xff);
39 }
40 ++nptr;
41 }
42 if (__unlikely(nptr==orig)) { /* no conversion done */
43 nptr=ptr;
44 errno=EINVAL;
45 v=0;
46 }
47 if (endptr) *endptr=(char *)nptr;
48 if (overflow) {
49 errno=ERANGE;
50 return ULONG_MAX;
51 }
52 return (neg?-v:v);
53}
diff --git a/apps/plugins/viewers.config b/apps/plugins/viewers.config
index 939a0a5534..fdb700f69d 100644
--- a/apps/plugins/viewers.config
+++ b/apps/plugins/viewers.config
@@ -55,3 +55,4 @@ cells,games/rocklife,-
55link,viewers/shortcuts_view,- 55link,viewers/shortcuts_view,-
56*,viewers/shortcuts_append,- 56*,viewers/shortcuts_append,-
57*,apps/md5sum,- 57*,apps/md5sum,-
58lua,viewers/lua,-
diff --git a/firmware/include/ctype.h b/firmware/include/ctype.h
index aba91a826b..3a04e29ee0 100644
--- a/firmware/include/ctype.h
+++ b/firmware/include/ctype.h
@@ -37,7 +37,7 @@ int _EXFUN(_toupper, (int __c));
37#define _B 0200 37#define _B 0200
38 38
39#ifdef PLUGIN 39#ifdef PLUGIN
40#define _ctype_ (rb->_ctype_) 40#define _ctype_ (rb->_rbctype_)
41#else 41#else
42extern const unsigned char _ctype_[257]; 42extern const unsigned char _ctype_[257];
43#endif 43#endif