1% texluac.w
2%
3% Copyright (C) 1994-2007 Lua.org, PUC-Rio.  All rights reserved.
4% Copyright 2006-2013 Taco Hoekwater <taco@@luatex.org>
5%
6% Permission is hereby granted, free of charge, to any person obtaining
7% a copy of this software and associated documentation files (the
8% "Software"), to deal in the Software without restriction, including
9% without limitation the rights to use, copy, modify, merge, publish,
10% distribute, sublicense, and/or sell copies of the Software, and to
11% permit persons to whom the Software is furnished to do so, subject to
12% the following conditions:
13%
14% The above copyright notice and this permission notice shall be
15% included in all copies or substantial portions of the Software.
16%
17% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19% MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20% IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21% CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22% TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23% SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24%
25% This file is part of LuaTeX.
26
27@ @c
28
29
30#include <ctype.h>
31#include <errno.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <string.h>
35
36#define luac_c
37#define LUA_CORE
38
39#include "lua.h"
40#include "lauxlib.h"
41
42#include "ldebug.h"
43#include "ldo.h"
44#include "lfunc.h"
45#include "lmem.h"
46#include "lobject.h"
47#include "lopcodes.h"
48#include "lstring.h"
49#include "lundump.h"
50
51#include "lua/luatex-api.h"
52
53static void PrintFunction(const Proto* f, int full);
54#define luaU_print	PrintFunction
55
56@ @c
57/*  fix for non-gcc compilation: */
58#if !defined(__GNUC__) || (__GNUC__ < 2)
59# define __attribute__(x)
60#endif /* !defined(__GNUC__) || (__GNUC__ < 2) */
61
62@ @c
63#define PROGNAME        "texluac"       /* default program name */
64#define OUTPUT          PROGNAME ".out" /* default output file */
65
66static int listing=0;			/* list bytecodes? */
67static int dumping = 1;         /* dump bytecodes? */
68static int stripping = 0;       /* strip debug information? */
69static char Output[] = { OUTPUT };      /* default output file name */
70
71static const char *output = Output;     /* actual output file name */
72static const char *progname = PROGNAME; /* actual program name */
73
74@ @c
75__attribute__ ((noreturn))
76static void fatal(const char *message)
77{
78 fprintf(stderr,"%s: %s\n",progname,message);
79 exit(EXIT_FAILURE);
80}
81
82@ @c
83__attribute__ ((noreturn))
84static void cannot(const char *what)
85{
86 fprintf(stderr,"%s: cannot %s %s: %s\n",progname,what,output,strerror(errno));
87 exit(EXIT_FAILURE);
88}
89
90@ @c
91__attribute__ ((noreturn))
92static void usage(const char* message)
93{
94 if (*message=='-')
95  fprintf(stderr,"%s: unrecognized option " LUA_QS "\n",progname,message);
96 else
97  fprintf(stderr,"%s: %s\n",progname,message);
98 fprintf(stderr,
99  "usage: %s [options] [filenames]\n"
100  "Available options are:\n"
101  "  -l       list (use -l -l for full listing)\n"
102  "  -o name  output to file " LUA_QL("name") " (default is \"%s\")\n"
103  "  -p       parse only\n"
104  "  -s       strip debug information\n"
105  "  -v       show version information\n"
106  "  --       stop handling options\n"
107  "  -        stop handling options and process stdin\n"
108  ,progname,Output);
109 exit(EXIT_FAILURE);
110}
111
112@ @c
113#define IS(s)   (strcmp(argv[i],s)==0)
114
115static int doargs(int argc, char* argv[])
116{
117 int i;
118 int version=0;
119 if (argv[0]!=NULL && *argv[0]!=0) progname=argv[0];
120 for (i=1; i<argc; i++)
121 {
122  if (*argv[i]!='-')			/* end of options; keep it */
123   break;
124  else if (IS("--"))			/* end of options; skip it */
125  {
126   ++i;
127   if (version) ++version;
128   break;
129  }
130  else if (IS("-"))			/* end of options; use stdin */
131   break;
132  else if (IS("-l"))			/* list */
133   ++listing;
134  else if (IS("-o"))			/* output file */
135  {
136   output=argv[++i];
137   if (output==NULL || *output==0 || (*output=='-' && output[1]!=0))
138    usage(LUA_QL("-o") " needs argument");
139   if (IS("-")) output=NULL;
140  }
141  else if (IS("-p"))			/* parse only */
142   dumping=0;
143  else if (IS("-s"))			/* strip debug information */
144   stripping=1;
145  else if (IS("-v"))			/* show version */
146   ++version;
147  else					/* unknown option */
148   usage(argv[i]);
149 }
150 if (i==argc && (listing || !dumping))
151 {
152  dumping=0;
153  argv[--i]=Output;
154 }
155 if (version)
156 {
157  printf("%s\n",LUA_COPYRIGHT);
158  if (version==argc-1) exit(EXIT_SUCCESS);
159 }
160 return i;
161}
162
163@ @c
164#define FUNCTION "(function()end)();"
165
166static const char* reader(lua_State *L, void *ud, size_t *size)
167{
168 UNUSED(L);
169 if ((*(int*)ud)--)
170 {
171  *size=sizeof(FUNCTION)-1;
172  return FUNCTION;
173 }
174 else
175 {
176  *size=0;
177  return NULL;
178 }
179}
180
181#define toproto(L,i) getproto(L->top+(i))
182
183static const Proto* combine(lua_State* L, int n)
184{
185 if (n==1)
186  return toproto(L,-1);
187 else
188 {
189  Proto* f;
190  int i=n;
191  if (lua_load(L,reader,&i,"=(" PROGNAME ")",NULL)!=LUA_OK) fatal(lua_tostring(L,-1));
192  f=toproto(L,-1);
193  for (i=0; i<n; i++)
194  {
195   f->p[i]=toproto(L,i-n-1);
196   if (f->p[i]->sizeupvalues>0) f->p[i]->upvalues[0].instack=0;
197  }
198  f->sizelineinfo=0;
199  return f;
200 }
201}
202
203@ @c
204static int writer(lua_State* L, const void* p, size_t size, void* u)
205{
206 UNUSED(L);
207 return (fwrite(p,size,1,(FILE*)u)!=1) && (size!=0);
208}
209
210static int pmain(lua_State* L)
211{
212 int argc=(int)lua_tointeger(L,1);
213 char** argv=(char**)lua_touserdata(L,2);
214 const Proto* f;
215 int i;
216 if (!lua_checkstack(L,argc)) fatal("too many input files");
217 for (i=0; i<argc; i++)
218 {
219  const char* filename=IS("-") ? NULL : argv[i];
220  if (luaL_loadfile(L,filename)!=LUA_OK) fatal(lua_tostring(L,-1));
221 }
222 f=combine(L,argc);
223 if (listing) luaU_print(f,listing>1);
224 if (dumping)
225 {
226  FILE* D= (output==NULL) ? stdout : fopen(output,"wb");
227  if (D==NULL) cannot("open");
228  lua_lock(L);
229  luaU_dump(L,f,writer,D,stripping);
230  lua_unlock(L);
231  if (ferror(D)) cannot("write");
232  if (fclose(D)) cannot("close");
233 }
234 return 0;
235}
236
237@ @c
238int luac_main(int ac, char *av[])
239{
240    lua_State *L;
241    int i = doargs(ac, av);
242    ac -= i;
243    av += i;
244    if (ac <= 0)
245        usage("no input files given");
246    L=luaL_newstate();
247    if (L == NULL)
248        fatal("not enough memory for state");
249    lua_pushcfunction(L,&pmain);
250    lua_pushinteger(L,ac);
251    lua_pushlightuserdata(L,av);
252    if (lua_pcall(L,2,0,0)!=LUA_OK)
253      fatal(lua_tostring(L,-1));
254    lua_close(L);
255    return EXIT_SUCCESS;
256}
257
258/*
259** print bytecodes
260** See Copyright Notice in lua.h
261*/
262
263#define VOID(p)		((const void*)(p))
264
265static void PrintString(const TString* ts)
266{
267 const char* s=getstr(ts);
268 size_t i,n=ts->tsv.len;
269 printf("%c",'"');
270 for (i=0; i<n; i++)
271 {
272  int c=(int)(unsigned char)s[i];
273  switch (c)
274  {
275   case '"':  printf("\\\""); break;
276   case '\\': printf("\\\\"); break;
277   case '\a': printf("\\a"); break;
278   case '\b': printf("\\b"); break;
279   case '\f': printf("\\f"); break;
280   case '\n': printf("\\n"); break;
281   case '\r': printf("\\r"); break;
282   case '\t': printf("\\t"); break;
283   case '\v': printf("\\v"); break;
284   default:	if (isprint(c))
285   			printf("%c",c);
286		else
287			printf("\\%03d",c);
288  }
289 }
290 printf("%c",'"');
291}
292
293static void PrintConstant(const Proto* f, int i)
294{
295 const TValue* o=&f->k[i];
296 switch (ttype(o))
297 {
298  case LUA_TNIL:
299	printf("nil");
300	break;
301  case LUA_TBOOLEAN:
302	printf(bvalue(o) ? "true" : "false");
303	break;
304  case LUA_TNUMBER:
305	printf(LUA_NUMBER_FMT,nvalue(o));
306	break;
307  case LUA_TSTRING:
308	PrintString(rawtsvalue(o));
309	break;
310  default:				/* cannot happen */
311	printf("? type=%d",ttype(o));
312	break;
313 }
314}
315
316#define UPVALNAME(x) ((f->upvalues[x].name) ? getstr(f->upvalues[x].name) : "-")
317#define MYK(x)		(-1-(x))
318
319static void PrintCode(const Proto* f)
320{
321 const Instruction* code=f->code;
322 int pc,n=f->sizecode;
323 for (pc=0; pc<n; pc++)
324 {
325  Instruction i=code[pc];
326  OpCode o=GET_OPCODE(i);
327  int a=GETARG_A(i);
328  int b=GETARG_B(i);
329  int c=GETARG_C(i);
330  int ax=GETARG_Ax(i);
331  int bx=GETARG_Bx(i);
332  int sbx=GETARG_sBx(i);
333  int line=getfuncline(f,pc);
334  printf("\t%d\t",pc+1);
335  if (line>0) printf("[%d]\t",line); else printf("[-]\t");
336  printf("%-9s\t",luaP_opnames[o]);
337  switch (getOpMode(o))
338  {
339   case iABC:
340    printf("%d",a);
341    if (getBMode(o)!=OpArgN) printf(" %d",ISK(b) ? (MYK(INDEXK(b))) : b);
342    if (getCMode(o)!=OpArgN) printf(" %d",ISK(c) ? (MYK(INDEXK(c))) : c);
343    break;
344   case iABx:
345    printf("%d",a);
346    if (getBMode(o)==OpArgK) printf(" %d",MYK(bx));
347    if (getBMode(o)==OpArgU) printf(" %d",bx);
348    break;
349   case iAsBx:
350    printf("%d %d",a,sbx);
351    break;
352   case iAx:
353    printf("%d",MYK(ax));
354    break;
355  }
356  switch (o)
357  {
358   case OP_LOADK:
359    printf("\t; "); PrintConstant(f,bx);
360    break;
361   case OP_GETUPVAL:
362   case OP_SETUPVAL:
363    printf("\t; %s",UPVALNAME(b));
364    break;
365   case OP_GETTABUP:
366    printf("\t; %s",UPVALNAME(b));
367    if (ISK(c)) { printf(" "); PrintConstant(f,INDEXK(c)); }
368    break;
369   case OP_SETTABUP:
370    printf("\t; %s",UPVALNAME(a));
371    if (ISK(b)) { printf(" "); PrintConstant(f,INDEXK(b)); }
372    if (ISK(c)) { printf(" "); PrintConstant(f,INDEXK(c)); }
373    break;
374   case OP_GETTABLE:
375   case OP_SELF:
376    if (ISK(c)) { printf("\t; "); PrintConstant(f,INDEXK(c)); }
377    break;
378   case OP_SETTABLE:
379   case OP_ADD:
380   case OP_SUB:
381   case OP_MUL:
382   case OP_DIV:
383   case OP_POW:
384   case OP_EQ:
385   case OP_LT:
386   case OP_LE:
387    if (ISK(b) || ISK(c))
388    {
389     printf("\t; ");
390     if (ISK(b)) PrintConstant(f,INDEXK(b)); else printf("-");
391     printf(" ");
392     if (ISK(c)) PrintConstant(f,INDEXK(c)); else printf("-");
393    }
394    break;
395   case OP_JMP:
396   case OP_FORLOOP:
397   case OP_FORPREP:
398   case OP_TFORLOOP:
399    printf("\t; to %d",sbx+pc+2);
400    break;
401   case OP_CLOSURE:
402    printf("\t; %p",VOID(f->p[bx]));
403    break;
404   case OP_SETLIST:
405    if (c==0) printf("\t; %d",(int)code[++pc]); else printf("\t; %d",c);
406    break;
407   case OP_EXTRAARG:
408    printf("\t; "); PrintConstant(f,ax);
409    break;
410   default:
411    break;
412  }
413  printf("\n");
414 }
415}
416
417#define SS(x)	((x==1)?"":"s")
418#define S(x)	(int)(x),SS(x)
419
420static void PrintHeader(const Proto* f)
421{
422 const char* s=f->source ? getstr(f->source) : "=?";
423 if (*s=='@@' || *s=='=')
424  s++;
425 else if (*s==LUA_SIGNATURE[0])
426  s="(bstring)";
427 else
428  s="(string)";
429 printf("\n%s <%s:%d,%d> (%d instruction%s at %p)\n",
430 	(f->linedefined==0)?"main":"function",s,
431	f->linedefined,f->lastlinedefined,
432	S(f->sizecode),VOID(f));
433 printf("%d%s param%s, %d slot%s, %d upvalue%s, ",
434	(int)(f->numparams),f->is_vararg?"+":"",SS(f->numparams),
435	S(f->maxstacksize),S(f->sizeupvalues));
436 printf("%d local%s, %d constant%s, %d function%s\n",
437	S(f->sizelocvars),S(f->sizek),S(f->sizep));
438}
439
440static void PrintDebug(const Proto* f)
441{
442 int i,n;
443 n=f->sizek;
444 printf("constants (%d) for %p:\n",n,VOID(f));
445 for (i=0; i<n; i++)
446 {
447  printf("\t%d\t",i+1);
448  PrintConstant(f,i);
449  printf("\n");
450 }
451 n=f->sizelocvars;
452 printf("locals (%d) for %p:\n",n,VOID(f));
453 for (i=0; i<n; i++)
454 {
455  printf("\t%d\t%s\t%d\t%d\n",
456  i,getstr(f->locvars[i].varname),f->locvars[i].startpc+1,f->locvars[i].endpc+1);
457 }
458 n=f->sizeupvalues;
459 printf("upvalues (%d) for %p:\n",n,VOID(f));
460 for (i=0; i<n; i++)
461 {
462  printf("\t%d\t%s\t%d\t%d\n",
463  i,UPVALNAME(i),f->upvalues[i].instack,f->upvalues[i].idx);
464 }
465}
466
467static void PrintFunction(const Proto* f, int full)
468{
469 int i,n=f->sizep;
470 PrintHeader(f);
471 PrintCode(f);
472 if (full) PrintDebug(f);
473 for (i=0; i<n; i++) PrintFunction(f->p[i],full);
474}
475