xref: /netbsd-src/external/mit/lua/dist/src/luac.c (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 /*	$NetBSD: luac.c,v 1.10 2018/08/04 17:30:01 alnsn Exp $	*/
2 
3 /*
4 ** Id: luac.c,v 1.76 2018/06/19 01:32:02 lhf Exp
5 ** Lua compiler (saves bytecodes to files; also lists bytecodes)
6 ** See Copyright Notice in lua.h
7 */
8 
9 #define luac_c
10 #define LUA_CORE
11 
12 #include "lprefix.h"
13 
14 #include <ctype.h>
15 #include <errno.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 
20 #include "lua.h"
21 #include "lauxlib.h"
22 
23 #include "lobject.h"
24 #include "lstate.h"
25 #include "lundump.h"
26 
27 static void PrintFunction(const Proto* f, int full);
28 #define luaU_print	PrintFunction
29 
30 #define PROGNAME	"luac"		/* default program name */
31 #define OUTPUT		PROGNAME ".out"	/* default output file */
32 
33 static int listing=0;			/* list bytecodes? */
34 static int dumping=1;			/* dump bytecodes? */
35 static int stripping=0;			/* strip debug information? */
36 static char Output[]={ OUTPUT };	/* default output file name */
37 static const char* output=Output;	/* actual output file name */
38 static const char* progname=PROGNAME;	/* actual program name */
39 
40 static void fatal(const char* message)
41 {
42  fprintf(stderr,"%s: %s\n",progname,message);
43  exit(EXIT_FAILURE);
44 }
45 
46 static void cannot(const char* what)
47 {
48  fprintf(stderr,"%s: cannot %s %s: %s\n",progname,what,output,strerror(errno));
49  exit(EXIT_FAILURE);
50 }
51 
52 static void usage(const char* message)
53 {
54  if (*message=='-')
55   fprintf(stderr,"%s: unrecognized option '%s'\n",progname,message);
56  else
57   fprintf(stderr,"%s: %s\n",progname,message);
58  fprintf(stderr,
59   "usage: %s [options] [filenames]\n"
60   "Available options are:\n"
61   "  -l       list (use -l -l for full listing)\n"
62   "  -o name  output to file 'name' (default is \"%s\")\n"
63   "  -p       parse only\n"
64   "  -s       strip debug information\n"
65   "  -v       show version information\n"
66   "  --       stop handling options\n"
67   "  -        stop handling options and process stdin\n"
68   ,progname,Output);
69  exit(EXIT_FAILURE);
70 }
71 
72 #define IS(s)	(strcmp(argv[i],s)==0)
73 
74 static int doargs(int argc, char* argv[])
75 {
76  int i;
77  int version=0;
78  if (argv[0]!=NULL && *argv[0]!=0) progname=argv[0];
79  for (i=1; i<argc; i++)
80  {
81   if (*argv[i]!='-')			/* end of options; keep it */
82    break;
83   else if (IS("--"))			/* end of options; skip it */
84   {
85    ++i;
86    if (version) ++version;
87    break;
88   }
89   else if (IS("-"))			/* end of options; use stdin */
90    break;
91   else if (IS("-l"))			/* list */
92    ++listing;
93   else if (IS("-o"))			/* output file */
94   {
95    output=argv[++i];
96    if (output==NULL || *output==0 || (*output=='-' && output[1]!=0))
97     usage("'-o' needs argument");
98    if (IS("-")) output=NULL;
99   }
100   else if (IS("-p"))			/* parse only */
101    dumping=0;
102   else if (IS("-s"))			/* strip debug information */
103    stripping=1;
104   else if (IS("-v"))			/* show version */
105    ++version;
106   else					/* unknown option */
107    usage(argv[i]);
108  }
109  if (i==argc && (listing || !dumping))
110  {
111   dumping=0;
112   argv[--i]=Output;
113  }
114  if (version)
115  {
116   printf("%s\n",LUA_COPYRIGHT);
117   if (version==argc-1) exit(EXIT_SUCCESS);
118  }
119  return i;
120 }
121 
122 #define FUNCTION "(function()end)();"
123 
124 static const char* reader(lua_State *L, void *ud, size_t *size)
125 {
126  UNUSED(L);
127  if ((*(int*)ud)--)
128  {
129   *size=sizeof(FUNCTION)-1;
130   return FUNCTION;
131  }
132  else
133  {
134   *size=0;
135   return NULL;
136  }
137 }
138 
139 #define toproto(L,i) getproto(L->top+(i))
140 
141 static const Proto* combine(lua_State* L, int n)
142 {
143  if (n==1)
144   return toproto(L,-1);
145  else
146  {
147   Proto* f;
148   int i=n;
149   if (lua_load(L,reader,&i,"=(" PROGNAME ")",NULL)!=LUA_OK) fatal(lua_tostring(L,-1));
150   f=toproto(L,-1);
151   for (i=0; i<n; i++)
152   {
153    f->p[i]=toproto(L,i-n-1);
154    if (f->p[i]->sizeupvalues>0) f->p[i]->upvalues[0].instack=0;
155   }
156   f->sizelineinfo=0;
157   return f;
158  }
159 }
160 
161 static int writer(lua_State* L, const void* p, size_t size, void* u)
162 {
163  UNUSED(L);
164  return (fwrite(p,size,1,(FILE*)u)!=1) && (size!=0);
165 }
166 
167 static int pmain(lua_State* L)
168 {
169  int argc=(int)lua_tointeger(L,1);
170  char** argv=(char**)lua_touserdata(L,2);
171  const Proto* f;
172  int i;
173  if (!lua_checkstack(L,argc)) fatal("too many input files");
174  for (i=0; i<argc; i++)
175  {
176   const char* filename=IS("-") ? NULL : argv[i];
177   if (luaL_loadfile(L,filename)!=LUA_OK) fatal(lua_tostring(L,-1));
178  }
179  f=combine(L,argc);
180  if (listing) luaU_print(f,listing>1);
181  if (dumping)
182  {
183   FILE* D= (output==NULL) ? stdout : fopen(output,"wb");
184   if (D==NULL) cannot("open");
185   lua_lock(L);
186   luaU_dump(L,f,writer,D,stripping);
187   lua_unlock(L);
188   if (ferror(D)) cannot("write");
189   if (fclose(D)) cannot("close");
190  }
191  return 0;
192 }
193 
194 int main(int argc, char* argv[])
195 {
196  lua_State* L;
197  int i=doargs(argc,argv);
198  argc-=i; argv+=i;
199  if (argc<=0) usage("no input files given");
200  L=luaL_newstate();
201  if (L==NULL) fatal("cannot create state: not enough memory");
202  lua_pushcfunction(L,&pmain);
203  lua_pushinteger(L,argc);
204  lua_pushlightuserdata(L,argv);
205  if (lua_pcall(L,2,0,0)!=LUA_OK) fatal(lua_tostring(L,-1));
206  lua_close(L);
207  return EXIT_SUCCESS;
208 }
209 
210 /*
211 ** Id: luac.c,v 1.76 2018/06/19 01:32:02 lhf Exp
212 ** print bytecodes
213 ** See Copyright Notice in lua.h
214 */
215 
216 #include <ctype.h>
217 #include <stdio.h>
218 
219 #define luac_c
220 #define LUA_CORE
221 
222 #include "ldebug.h"
223 #include "lobject.h"
224 #include "lopcodes.h"
225 
226 #define VOID(p)		((const void*)(p))
227 
228 static void PrintString(const TString* ts)
229 {
230  const char* s=getstr(ts);
231  size_t i,n=tsslen(ts);
232  printf("%c",'"');
233  for (i=0; i<n; i++)
234  {
235   int c=(int)(unsigned char)s[i];
236   switch (c)
237   {
238    case '"':  printf("\\\""); break;
239    case '\\': printf("\\\\"); break;
240    case '\a': printf("\\a"); break;
241    case '\b': printf("\\b"); break;
242    case '\f': printf("\\f"); break;
243    case '\n': printf("\\n"); break;
244    case '\r': printf("\\r"); break;
245    case '\t': printf("\\t"); break;
246    case '\v': printf("\\v"); break;
247    default:	if (isprint(c))
248    			printf("%c",c);
249 		else
250 			printf("\\%03d",c);
251   }
252  }
253  printf("%c",'"');
254 }
255 
256 static void PrintConstant(const Proto* f, int i)
257 {
258  const TValue* o=&f->k[i];
259  switch (ttype(o))
260  {
261   case LUA_TNIL:
262 	printf("nil");
263 	break;
264   case LUA_TBOOLEAN:
265 	printf(bvalue(o) ? "true" : "false");
266 	break;
267   case LUA_TNUMFLT:
268 	{
269 	char buff[100];
270 #ifndef __NetBSD__
271 	sprintf(buff,LUA_NUMBER_FMT,fltvalue(o));
272 #else /* __NetBSD__ */
273 	l_sprintf(buff, sizeof(buff), LUA_NUMBER_FMT,fltvalue(o));
274 #endif /* __NetBSD__ */
275 	printf("%s",buff);
276 	if (buff[strspn(buff,"-0123456789")]=='\0') printf(".0");
277 	break;
278 	}
279   case LUA_TNUMINT:
280 	printf(LUA_INTEGER_FMT,ivalue(o));
281 	break;
282   case LUA_TSHRSTR: case LUA_TLNGSTR:
283 	PrintString(tsvalue(o));
284 	break;
285   default:				/* cannot happen */
286 	printf("? type=%d",ttype(o));
287 	break;
288  }
289 }
290 
291 #define UPVALNAME(x) ((f->upvalues[x].name) ? getstr(f->upvalues[x].name) : "-")
292 #define MYK(x)		(-1-(x))
293 
294 static void PrintCode(const Proto* f)
295 {
296  const Instruction* code=f->code;
297  int pc,n=f->sizecode;
298  for (pc=0; pc<n; pc++)
299  {
300   Instruction i=code[pc];
301   OpCode o=GET_OPCODE(i);
302   int a=GETARG_A(i);
303   int b=GETARG_B(i);
304   int c=GETARG_C(i);
305   int ax=GETARG_Ax(i);
306   int bx=GETARG_Bx(i);
307   int sbx=GETARG_sBx(i);
308   int line=getfuncline(f,pc);
309   printf("\t%d\t",pc+1);
310   if (line>0) printf("[%d]\t",line); else printf("[-]\t");
311   printf("%-9s\t",luaP_opnames[o]);
312   switch (getOpMode(o))
313   {
314    case iABC:
315     printf("%d",a);
316     if (getBMode(o)!=OpArgN) printf(" %d",ISK(b) ? (MYK(INDEXK(b))) : b);
317     if (getCMode(o)!=OpArgN) printf(" %d",ISK(c) ? (MYK(INDEXK(c))) : c);
318     break;
319    case iABx:
320     printf("%d",a);
321     if (getBMode(o)==OpArgK) printf(" %d",MYK(bx));
322     if (getBMode(o)==OpArgU) printf(" %d",bx);
323     break;
324    case iAsBx:
325     printf("%d %d",a,sbx);
326     break;
327    case iAx:
328     printf("%d",MYK(ax));
329     break;
330   }
331   switch (o)
332   {
333    case OP_LOADK:
334     printf("\t; "); PrintConstant(f,bx);
335     break;
336    case OP_GETUPVAL:
337    case OP_SETUPVAL:
338     printf("\t; %s",UPVALNAME(b));
339     break;
340    case OP_GETTABUP:
341     printf("\t; %s",UPVALNAME(b));
342     if (ISK(c)) { printf(" "); PrintConstant(f,INDEXK(c)); }
343     break;
344    case OP_SETTABUP:
345     printf("\t; %s",UPVALNAME(a));
346     if (ISK(b)) { printf(" "); PrintConstant(f,INDEXK(b)); }
347     if (ISK(c)) { printf(" "); PrintConstant(f,INDEXK(c)); }
348     break;
349    case OP_GETTABLE:
350    case OP_SELF:
351     if (ISK(c)) { printf("\t; "); PrintConstant(f,INDEXK(c)); }
352     break;
353    case OP_SETTABLE:
354    case OP_ADD:
355    case OP_SUB:
356    case OP_MUL:
357    case OP_MOD:
358    case OP_POW:
359    case OP_DIV:
360    case OP_IDIV:
361    case OP_BAND:
362    case OP_BOR:
363    case OP_BXOR:
364    case OP_SHL:
365    case OP_SHR:
366    case OP_EQ:
367    case OP_LT:
368    case OP_LE:
369     if (ISK(b) || ISK(c))
370     {
371      printf("\t; ");
372      if (ISK(b)) PrintConstant(f,INDEXK(b)); else printf("-");
373      printf(" ");
374      if (ISK(c)) PrintConstant(f,INDEXK(c)); else printf("-");
375     }
376     break;
377    case OP_JMP:
378    case OP_FORLOOP:
379    case OP_FORPREP:
380    case OP_TFORLOOP:
381     printf("\t; to %d",sbx+pc+2);
382     break;
383    case OP_CLOSURE:
384     printf("\t; %p",VOID(f->p[bx]));
385     break;
386    case OP_SETLIST:
387     if (c==0) printf("\t; %d",(int)code[++pc]); else printf("\t; %d",c);
388     break;
389    case OP_EXTRAARG:
390     printf("\t; "); PrintConstant(f,ax);
391     break;
392    default:
393     break;
394   }
395   printf("\n");
396  }
397 }
398 
399 #define SS(x)	((x==1)?"":"s")
400 #define S(x)	(int)(x),SS(x)
401 
402 static void PrintHeader(const Proto* f)
403 {
404  const char* s=f->source ? getstr(f->source) : "=?";
405  if (*s=='@' || *s=='=')
406   s++;
407  else if (*s==LUA_SIGNATURE[0])
408   s="(bstring)";
409  else
410   s="(string)";
411  printf("\n%s <%s:%d,%d> (%d instruction%s at %p)\n",
412  	(f->linedefined==0)?"main":"function",s,
413 	f->linedefined,f->lastlinedefined,
414 	S(f->sizecode),VOID(f));
415  printf("%d%s param%s, %d slot%s, %d upvalue%s, ",
416 	(int)(f->numparams),f->is_vararg?"+":"",SS(f->numparams),
417 	S(f->maxstacksize),S(f->sizeupvalues));
418  printf("%d local%s, %d constant%s, %d function%s\n",
419 	S(f->sizelocvars),S(f->sizek),S(f->sizep));
420 }
421 
422 static void PrintDebug(const Proto* f)
423 {
424  int i,n;
425  n=f->sizek;
426  printf("constants (%d) for %p:\n",n,VOID(f));
427  for (i=0; i<n; i++)
428  {
429   printf("\t%d\t",i+1);
430   PrintConstant(f,i);
431   printf("\n");
432  }
433  n=f->sizelocvars;
434  printf("locals (%d) for %p:\n",n,VOID(f));
435  for (i=0; i<n; i++)
436  {
437   printf("\t%d\t%s\t%d\t%d\n",
438   i,getstr(f->locvars[i].varname),f->locvars[i].startpc+1,f->locvars[i].endpc+1);
439  }
440  n=f->sizeupvalues;
441  printf("upvalues (%d) for %p:\n",n,VOID(f));
442  for (i=0; i<n; i++)
443  {
444   printf("\t%d\t%s\t%d\t%d\n",
445   i,UPVALNAME(i),f->upvalues[i].instack,f->upvalues[i].idx);
446  }
447 }
448 
449 static void PrintFunction(const Proto* f, int full)
450 {
451  int i,n=f->sizep;
452  PrintHeader(f);
453  PrintCode(f);
454  if (full) PrintDebug(f);
455  for (i=0; i<n; i++) PrintFunction(f->p[i],full);
456 }
457