/*
** $Id: lundump.c,v 2.7.1.4 2008/04/04 19:51:41 roberto Exp $
** load precompiled Lua chunks
** See Copyright Notice in lua.h
**
** Modified to support loading 32-bit bytecode on 64-bit systems
*/

#include <string.h>

#define lundump_c
#define LUA_CORE

#include "lua.h"

#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lmem.h"
#include "lobject.h"
#include "lstring.h"
#include "lundump.h"
#include "lzio.h"

typedef struct {
 lua_State* L;
 ZIO* Z;
 Mbuffer* b;
 const char* name;
 int swap;           /* endianness swap required */
 int sizeof_int;     /* sizeof(int) in bytecode */
 int sizeof_size_t;  /* sizeof(size_t) in bytecode */
 int sizeof_instr;   /* sizeof(Instruction) in bytecode */
 int sizeof_number;  /* sizeof(lua_Number) in bytecode */
} LoadState;

#ifdef LUAC_TRUST_BINARIES
#define IF(c,s)
#define error(S,s)
#else
#define IF(c,s)		if (c) error(S,s)

static void error(LoadState* S, const char* why)
{
 luaO_pushfstring(S->L,"%s: %s in precompiled chunk",S->name,why);
 luaD_throw(S->L,LUA_ERRSYNTAX);
}
#endif

#define LoadMem(S,b,n,size)	LoadBlock(S,b,(n)*(size))
#define	LoadByte(S)		(lu_byte)LoadChar(S)
#define LoadVar(S,x)		LoadMem(S,&x,1,sizeof(x))
#define LoadVector(S,b,n,size)	LoadMem(S,b,n,size)

static void LoadBlock(LoadState* S, void* b, size_t size)
{
 size_t r=luaZ_read(S->Z,b,size);
 IF (r!=0, "unexpected end");
}

static int LoadChar(LoadState* S)
{
 char x;
 LoadVar(S,x);
 return x;
}

static void SwapBytes(void* b, size_t size)
{
 char* p = (char*)b;
 size_t i;
 for (i = 0; i < size/2; i++) {
  char temp = p[i];
  p[i] = p[size - 1 - i];
  p[size - 1 - i] = temp;
 }
}

static int LoadInt(LoadState* S)
{
 int x;
 if (S->sizeof_int == sizeof(int)) {
  LoadVar(S,x);
  if (S->swap) SwapBytes(&x, sizeof(x));
 } else if (S->sizeof_int == 4 && sizeof(int) >= 4) {
  /* 32-bit int from bytecode */
  lu_int32 t;
  LoadMem(S,&t,1,4);
  if (S->swap) SwapBytes(&t, 4);
  x = (int)t;
 } else if (S->sizeof_int == 8 && sizeof(int) == 4) {
  /* 64-bit int in bytecode on 32-bit system - use lower 32 bits */
  lu_int32 lo, hi;
  LoadMem(S, &lo, 1, 4);
  LoadMem(S, &hi, 1, 4);
  if (S->swap) {
   SwapBytes(&lo, 4);
   SwapBytes(&hi, 4);
   x = (int)hi;
  } else {
   x = (int)lo;
  }
 } else {
  error(S, "unsupported int size in bytecode");
  x = 0;
 }
 IF (x<0, "bad integer");
 return x;
}

static size_t LoadSize(LoadState* S)
{
 size_t x;
 if (S->sizeof_size_t == sizeof(size_t)) {
  LoadVar(S,x);
  if (S->swap) SwapBytes(&x, sizeof(x));
 } else if (S->sizeof_size_t == 4 && sizeof(size_t) == 8) {
  /* 32-bit bytecode on 64-bit system */
  lu_int32 t;
  LoadMem(S,&t,1,4);
  if (S->swap) SwapBytes(&t, 4);
  x = (size_t)t;
 } else if (S->sizeof_size_t == 8 && sizeof(size_t) == 4) {
  /* 64-bit bytecode on 32-bit system - use lower 32 bits */
  lu_int32 lo, hi;
  LoadMem(S, &lo, 1, 4);
  LoadMem(S, &hi, 1, 4);
  if (S->swap) {
   SwapBytes(&lo, 4);
   SwapBytes(&hi, 4);
   x = (size_t)hi;  /* big-endian: high bytes first */
  } else {
   x = (size_t)lo;  /* little-endian: low bytes first */
  }
 } else {
  error(S, "unsupported size_t size in bytecode");
  x = 0;
 }
 return x;
}

static lua_Number LoadNumber(LoadState* S)
{
 lua_Number x;
 if (S->sizeof_number == sizeof(lua_Number)) {
  LoadVar(S,x);
  if (S->swap) SwapBytes(&x, sizeof(x));
 } else {
  error(S, "unsupported lua_Number size in bytecode");
  x = 0;
 }
 return x;
}

static Instruction LoadInstruction(LoadState* S)
{
 Instruction x;
 if (S->sizeof_instr == sizeof(Instruction)) {
  LoadVar(S,x);
  if (S->swap) SwapBytes(&x, sizeof(x));
 } else if (S->sizeof_instr == 4) {
  lu_int32 t;
  LoadMem(S,&t,1,4);
  if (S->swap) SwapBytes(&t, 4);
  x = (Instruction)t;
 } else {
  error(S, "unsupported Instruction size in bytecode");
  x = 0;
 }
 return x;
}

static TString* LoadString(LoadState* S)
{
 size_t size = LoadSize(S);
 if (size==0)
  return NULL;
 else
 {
  char* s=luaZ_openspace(S->L,S->b,size);
  LoadBlock(S,s,size);
  return luaS_newlstr(S->L,s,size-1);		/* remove trailing '\0' */
 }
}

static void LoadCode(LoadState* S, Proto* f)
{
 int i, n=LoadInt(S);
 f->code=luaM_newvector(S->L,n,Instruction);
 f->sizecode=n;
 for (i=0; i<n; i++) {
  f->code[i] = LoadInstruction(S);
 }
}

static Proto* LoadFunction(LoadState* S, TString* p);

static void LoadConstants(LoadState* S, Proto* f)
{
 int i,n;
 n=LoadInt(S);
 f->k=luaM_newvector(S->L,n,TValue);
 f->sizek=n;
 for (i=0; i<n; i++) setnilvalue(&f->k[i]);
 for (i=0; i<n; i++)
 {
  TValue* o=&f->k[i];
  int t=LoadChar(S);
  switch (t)
  {
   case LUA_TNIL:
   	setnilvalue(o);
	break;
   case LUA_TBOOLEAN:
   	setbvalue(o,LoadChar(S)!=0);
	break;
   case LUA_TNUMBER:
	setnvalue(o,LoadNumber(S));
	break;
   case LUA_TSTRING:
	setsvalue2n(S->L,o,LoadString(S));
	break;
   default:
	error(S,"bad constant");
	break;
  }
 }
 n=LoadInt(S);
 f->p=luaM_newvector(S->L,n,Proto*);
 f->sizep=n;
 for (i=0; i<n; i++) f->p[i]=NULL;
 for (i=0; i<n; i++) f->p[i]=LoadFunction(S,f->source);
}

static void LoadDebug(LoadState* S, Proto* f)
{
 int i,n;
 n=LoadInt(S);
 f->lineinfo=luaM_newvector(S->L,n,int);
 f->sizelineinfo=n;
 for (i=0; i<n; i++) {
  f->lineinfo[i] = LoadInt(S);
 }
 n=LoadInt(S);
 f->locvars=luaM_newvector(S->L,n,LocVar);
 f->sizelocvars=n;
 for (i=0; i<n; i++) f->locvars[i].varname=NULL;
 for (i=0; i<n; i++)
 {
  f->locvars[i].varname=LoadString(S);
  f->locvars[i].startpc=LoadInt(S);
  f->locvars[i].endpc=LoadInt(S);
 }
 n=LoadInt(S);
 f->upvalues=luaM_newvector(S->L,n,TString*);
 f->sizeupvalues=n;
 for (i=0; i<n; i++) f->upvalues[i]=NULL;
 for (i=0; i<n; i++) f->upvalues[i]=LoadString(S);
}

static Proto* LoadFunction(LoadState* S, TString* p)
{
 Proto* f;
 if (++S->L->nCcalls > LUAI_MAXCCALLS) error(S,"code too deep");
 f=luaF_newproto(S->L);
 setptvalue2s(S->L,S->L->top,f); incr_top(S->L);
 f->source=LoadString(S); if (f->source==NULL) f->source=p;
 f->linedefined=LoadInt(S);
 f->lastlinedefined=LoadInt(S);
 f->nups=LoadByte(S);
 f->numparams=LoadByte(S);
 f->is_vararg=LoadByte(S);
 f->maxstacksize=LoadByte(S);
 LoadCode(S,f);
 LoadConstants(S,f);
 LoadDebug(S,f);
 IF (!luaG_checkcode(f), "bad code");
 S->L->top--;
 S->L->nCcalls--;
 return f;
}

static void LoadHeader(LoadState* S)
{
 char h[LUAC_HEADERSIZE];
 char s[LUAC_HEADERSIZE];
 int x = 1;
 int local_endian = (unsigned char)(*(char*)&x);
 int file_endian;

 LoadBlock(S,s,LUAC_HEADERSIZE);

 /* Check signature */
 luaU_header(h);
 IF (memcmp(h,s,sizeof(LUA_SIGNATURE)-1)!=0, "not a precompiled chunk");

 /* Check version */
 IF (s[4] != LUAC_VERSION, "version mismatch in precompiled chunk");

 /* Check format */
 IF (s[5] != LUAC_FORMAT, "incompatible format");

 /* Endianness */
 file_endian = (unsigned char)s[6];
 S->swap = (file_endian != local_endian);

 /* Size information from bytecode */
 S->sizeof_int = (unsigned char)s[7];
 S->sizeof_size_t = (unsigned char)s[8];
 S->sizeof_instr = (unsigned char)s[9];
 S->sizeof_number = (unsigned char)s[10];

 /* Validate sizes we can handle */
 IF (S->sizeof_int != 4 && S->sizeof_int != 8 && S->sizeof_int != (int)sizeof(int),
     "unsupported int size");
 IF (S->sizeof_size_t != 4 && S->sizeof_size_t != 8,
     "unsupported size_t size");
 IF (S->sizeof_instr != 4 && S->sizeof_instr != (int)sizeof(Instruction),
     "unsupported Instruction size");
 IF (S->sizeof_number != (int)sizeof(lua_Number),
     "incompatible lua_Number size");

 /* Check integral flag */
 IF (s[11] != (((lua_Number)0.5)==0), "incompatible number type");
}

/*
** load precompiled chunk
*/
Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name)
{
 LoadState S;
 if (*name=='@' || *name=='=')
  S.name=name+1;
 else if (*name==LUA_SIGNATURE[0])
  S.name="binary string";
 else
  S.name=name;
 S.L=L;
 S.Z=Z;
 S.b=buff;
 LoadHeader(&S);
 return LoadFunction(&S,luaS_newliteral(L,"=?"));
}

/*
* make header
*/
void luaU_header (char* h)
{
 int x=1;
 memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-1);
 h+=sizeof(LUA_SIGNATURE)-1;
 *h++=(char)LUAC_VERSION;
 *h++=(char)LUAC_FORMAT;
 *h++=(char)*(char*)&x;				/* endianness */
 *h++=(char)sizeof(int);
 *h++=(char)sizeof(size_t);
 *h++=(char)sizeof(Instruction);
 *h++=(char)sizeof(lua_Number);
 *h++=(char)(((lua_Number)0.5)==0);		/* is lua_Number integral? */
}
