Exemplo n.º 1
0
Arquivo: lvm.c Projeto: dividuum/infon
void luaV_concat (lua_State *L, int total, int last) {
  do {
    StkId top = L->base + last + 1;
    int n = 2;  /* number of elements handled in this pass (at least 2) */
    if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1)) {
      setpvalue(L->top, (void *)(ptrdiff_t)(last - 1));  /* for luaV_resume */
      L->top++;
      if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT))
        luaG_concaterror(L, top-2, top-1);
      L->top--;
    } else if (tsvalue(top-1)->len == 0)  /* second op is empty? */
      (void)tostring(L, top - 2);  /* result is first op (as string) */
    else {
      /* at least two string values; get as many as possible */
      size_t tl = tsvalue(top-1)->len;
      char *buffer;
      int i;
      /* collect total length */
      for (n = 1; n < total && tostring(L, top-n-1); n++) {
        size_t l = tsvalue(top-n-1)->len;
        if (l >= MAX_SIZET - tl) luaG_runerror(L, "string length overflow");
        tl += l;
      }
      buffer = luaZ_openspace(L, &G(L)->buff, tl);
      tl = 0;
      for (i=n; i>0; i--) {  /* concat all strings */
        size_t l = tsvalue(top-i)->len;
        memcpy(buffer+tl, svalue(top-i), l);
        tl += l;
      }
      setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl));
    }
    total -= n-1;  /* got `n' strings to create 1 new */
    last -= n-1;
  } while (total > 1);  /* repeat until only 1 result left */
}
Exemplo n.º 2
0
static void PrintString(const Proto* f, int n)
{
 const char* s=svalue(&f->k[n]);
 putchar('"');
 for (; *s; s++)
 {
  switch (*s)
  {
   case '"': printf("\\\""); break;
   case '\a': printf("\\a"); break;
   case '\b': printf("\\b"); break;
   case '\f': printf("\\f"); break;
   case '\n': printf("\\n"); break;
   case '\r': printf("\\r"); break;
   case '\t': printf("\\t"); break;
   case '\v': printf("\\v"); break;
   default:	if (isprint((unsigned char)*s))
   			printf("%c",*s);
		else
			printf("\\%03u",(unsigned char)*s);
  }
 }
 putchar('"');
}
Exemplo n.º 3
0
/*
** try to convert a value to an integer, rounding according to 'mode':
** mode == 0: accepts only integral values
** mode == 1: takes the floor of the number
** mode == 2: takes the ceil of the number
*/
int luaV_tointeger (const TValue *obj, lua_Integer *p, int mode) {
  TValue v;
 again:
  if (ttisfloat(obj)) {
    lua_Number n = fltvalue(obj);
    lua_Number f = l_floor(n);
    if (n != f) {  /* not an integral value? */
      if (mode == 0) return 0;  /* fails if mode demands integral value */
      else if (mode > 1)  /* needs ceil? */
        f += 1;  /* convert floor to ceil (remember: n != f) */
    }
    return lua_numbertointeger(f, p);
  }
  else if (ttisinteger(obj)) {
    *p = ivalue(obj);
    return 1;
  }
  else if (cvt2num(obj) &&
            luaO_str2num(svalue(obj), &v) == vslen(obj) + 1) {
    obj = &v;
    goto again;  /* convert result from 'luaO_str2num' to an integer */
  }
  return 0;  /* conversion failed */
}
Exemplo n.º 4
0
Arquivo: opcode.c Projeto: cskau/VM
/*
** Given an object handle, return its string pointer. On error, return NULL.
*/
char *lua_getstring (lua_Object object)
{
 if (object == LUA_NOOBJECT) return NULL;
 if (tostring (Address(object))) return NULL;
 else return (svalue(Address(object)));
}
Exemplo n.º 5
0
Arquivo: main.c Projeto: cfregly/ktap
/* this is a debug function used for check bytecode chunk file */
static void dump_function(int level, ktap_proto *f)
{
	int i;

	printf("\n----------------------------------------------------\n");
	printf("function %d [level %d]:\n", function_nr++, level);
	printf("linedefined: %d\n", f->linedefined);
	printf("lastlinedefined: %d\n", f->lastlinedefined);
	printf("numparams: %d\n", f->numparams);
	printf("is_vararg: %d\n", f->is_vararg);
	printf("maxstacksize: %d\n", f->maxstacksize);
	printf("source: %s\n", getstr(f->source));
	printf("sizelineinfo: %d \t", f->sizelineinfo);
	for (i = 0; i < f->sizelineinfo; i++)
		printf("%d ", f->lineinfo[i]);
	printf("\n");

	printf("sizek: %d\n", f->sizek);
	for (i = 0; i < f->sizek; i++) {
		switch(f->k[i].type) {
		case KTAP_TNIL:
			printf("\tNIL\n");
			break;
		case KTAP_TBOOLEAN:
			printf("\tBOOLEAN: ");
			printf("%d\n", f->k[i].val.b);
			break;
		case KTAP_TNUMBER:
			printf("\tTNUMBER: ");
			printf("%ld\n", f->k[i].val.n);
			break;
		case KTAP_TSHRSTR:
		case KTAP_TLNGSTR:
			printf("\tTSTRING: ");
			printf("%s\n", svalue(&(f->k[i])));
			break;
		default:
			printf("\tUnknow constant type %d: ", f->k[i].type);
			kp_showobj(NULL, &(f->k[i]));
			printf("\n");
		}
	}

	printf("sizelocvars: %d\n", f->sizelocvars);
	for (i = 0; i < f->sizelocvars; i++) {
		printf("\tlocvars: %s startpc: %d endpc: %d\n",
			getstr(f->locvars[i].varname), f->locvars[i].startpc,
			f->locvars[i].endpc);
	}

	printf("sizeupvalues: %d\n", f->sizeupvalues);
	for (i = 0; i < f->sizeupvalues; i++) {
		printf("\tname: %s instack: %d idx: %d\n",
			getstr(f->upvalues[i].name), f->upvalues[i].instack,
			f->upvalues[i].idx);
	}

	printf("\n");
	printf("sizecode: %d\n", f->sizecode);
	for (i = 0; i < f->sizecode; i++)
		decode_instruction(f, f->code[i]);

	printf("sizep: %d\n", f->sizep);
	for (i = 0; i < f->sizep; i++)
		dump_function(level + 1, f->p[i]);

}
Exemplo n.º 6
0
// PrintString from luac is not 8-bit clean
char *DecompileString(const Proto * f, int n)
{
    int i;
    const unsigned char *s = svalue(&f->k[n]);
    int len = tsvalue(&f->k[n])->tsv.len;
    char *ret = malloc(strlen(s) * 4 + 3);
    int p = 0;
    ret[p++] = '"';
    for (i = 0; i < len; i++, s++) {
        switch (*s) {
        case '"':
            ret[p++] = '\\';
            ret[p++] = '"';
            break;
        case '\a':
            ret[p++] = '\\';
            ret[p++] = 'a';
            break;
        case '\b':
            ret[p++] = '\\';
            ret[p++] = 'b';
            break;
        case '\f':
            ret[p++] = '\\';
            ret[p++] = 'f';
            break;
        case '\n':
            ret[p++] = '\\';
            ret[p++] = 'n';
            break;
        case '\r':
            ret[p++] = '\\';
            ret[p++] = 'r';
            break;
        case '\t':
            ret[p++] = '\\';
            ret[p++] = 't';
            break;
        case '\v':
            ret[p++] = '\\';
            ret[p++] = 'v';
            break;
        case '\\':
            ret[p++] = '\\';
            ret[p++] = '\\';
            break;
        default:
            if (*s < 32 || *s > 127) {
               char* pos = &(ret[p]);
               sprintf(pos, "\\%d", *s);
               p += strlen(pos);
            } else {
               ret[p++] = *s;
            }
            break;
        }
    }
    ret[p++] = '"';
    ret[p] = '\0';
    return ret;
}
Exemplo n.º 7
0
void Decompiler::decompileRange(Byte *start, Byte *end) {
  // First, scan for IFFUPJMP, which is used for repeat/until, so
  // we can recognize the start of such loops.  We only keep the
  // last value to match each address, which represents the outermost
  // repeat/until loop starting at that point.
  std::map<Byte *, Byte *> rev_iffupjmp_map;

  for (Byte *scan = start; end == NULL || scan < end;
       scan += get_instr_len(*scan)) {
    if (*scan == IFFUPJMP)
      rev_iffupjmp_map[scan + 2 - scan[1]] = scan;
    else if (*scan == IFFUPJMPW)
      rev_iffupjmp_map[scan + 3 - (scan[1] | (scan[2] << 8))] = scan;
    else if (*scan == ENDCODE)
      break;
  }

  while (end == NULL || start < end) {
    int locs_here = local_var_defs->count(start);
    if (locs_here > 0) {
      // There were local variable slots just pushed onto the stack
      // Print them out (in the second pass)

      // First, if there are multiple defined, it must be from
      // local x, y, z = f() or local a, b.  So just ignore the extra
      // entries.
      for (int i = 1; i < locs_here; i++) {
	delete stk->top(); stk->pop();
      }
      Expression *def = stk->top(); stk->pop();

      // Print the local variable names, and at the same time push
      // fake values onto the stack
      *os << indent_str << "local ";
      for (int i = 0; i < locs_here; i++) {
	std::string locname = localname(tf, tf->code[1] + stk->size());
	*os << locname;
	if (i + 1 < locs_here)
	  *os << ", ";
	stk->push(new VarExpr(start, "<" + locname + " stack slot>"));
      }

      // Print the definition, unless it's nil
      VarExpr *v = dynamic_cast<VarExpr *>(def);
      if (v == NULL || v->name != "nil")
	*os << " = " << *def;
      *os << std::endl;
	  delete def;

      local_var_defs->erase(start);
    }

    if (rev_iffupjmp_map.find(start) != rev_iffupjmp_map.end()) {
      // aha, do a repeat/until loop
      *os << indent_str << "repeat\n";
      Decompiler indented_dc = *this;
      indented_dc.indent_str += std::string(4, ' ');
      indented_dc.break_pos = rev_iffupjmp_map[start];
      indented_dc.break_pos += get_instr_len(*indented_dc.break_pos);
      indented_dc.decompileRange(start, rev_iffupjmp_map[start]);

      Expression *e = stk->top(); stk->pop();
      *os << indent_str << "until " << *e << std::endl;
      delete e;

      start = indented_dc.break_pos;
      continue;
    }

    Byte opc = *start++;
    int aux;

    switch (opc) {
    case ENDCODE:
      return;

    case PUSHNIL:
      aux = *start++;
      goto pushnil;

    case PUSHNIL0:
      aux = 0;
    pushnil:
      for (int i = 0; i <= aux; i++)
	stk->push(new VarExpr(start, "nil")); // Cheat a little :)
      break;

    case PUSHNUMBER:
      aux = *start++;
      goto pushnumber;

    case PUSHNUMBER0:
    case PUSHNUMBER1:
    case PUSHNUMBER2:
      aux = opc - PUSHNUMBER0;
      goto pushnumber;

    case PUSHNUMBERW:
      aux = start[0] | (start[1] << 8);
      start += 2;
    pushnumber:
      stk->push(new NumberExpr(start, aux));
      break;

    case PUSHCONSTANT:
      aux = *start++;
      goto pushconst;

    case PUSHCONSTANT0:
    case PUSHCONSTANT1:
    case PUSHCONSTANT2:
    case PUSHCONSTANT3:
    case PUSHCONSTANT4:
    case PUSHCONSTANT5:
    case PUSHCONSTANT6:
    case PUSHCONSTANT7:
      aux = opc - PUSHCONSTANT0;
      goto pushconst;

    case PUSHCONSTANTW:
      aux = start[0] | (start[1] << 8);
      start += 2;
    pushconst:
      switch (ttype(tf->consts + aux)) {
      case LUA_T_STRING:
	stk->push(new StringExpr(start, tsvalue(tf->consts + aux)));
	break;
      case LUA_T_NUMBER:
	stk->push(new NumberExpr(start, nvalue(tf->consts + aux)));
	break;
      case LUA_T_PROTO:
	stk->push(new FuncExpr(start, tfvalue(tf->consts + aux), indent_str));
	break;
      default:
	*os << indent_str << "error: invalid constant type "
	    << int(ttype(tf->consts + aux)) << std::endl;
      }
      break;

    case PUSHUPVALUE:
      aux = *start++;
      goto pushupvalue;

    case PUSHUPVALUE0:
    case PUSHUPVALUE1:
      aux = opc - PUSHUPVALUE0;
    pushupvalue:
      {
	if (aux >= num_upvals) {
	  *os << indent_str << "error: invalid upvalue #"
	      << aux << std::endl;
	}

	std::ostringstream s;
	s << "%" << *upvals[aux];
	stk->push(new VarExpr(start, s.str()));
      }
      break;

    case PUSHLOCAL:
      aux = *start++;
      goto pushlocal;

    case PUSHLOCAL0:
    case PUSHLOCAL1:
    case PUSHLOCAL2:
    case PUSHLOCAL3:
    case PUSHLOCAL4:
    case PUSHLOCAL5:
    case PUSHLOCAL6:
    case PUSHLOCAL7:
      aux = opc - PUSHLOCAL0;
    pushlocal:
      stk->push(new VarExpr(start, localname(tf, aux)));
      break;

    case GETGLOBAL:
      aux = *start++;
      goto getglobal;

    case GETGLOBAL0:
    case GETGLOBAL1:
    case GETGLOBAL2:
    case GETGLOBAL3:
    case GETGLOBAL4:
    case GETGLOBAL5:
    case GETGLOBAL6:
    case GETGLOBAL7:
      aux = opc - GETGLOBAL0;
      goto getglobal;

    case GETGLOBALW:
      aux = start[0] | (start[1] << 8);
      start += 2;
    getglobal:
      stk->push(new VarExpr(start, svalue(tf->consts + aux)));
      break;

    case GETTABLE:
      {
	Expression *index = stk->top(); stk->pop();
	Expression *table = stk->top(); stk->pop();

	stk->push(new BracketsIndexExpr(start, table, index));
      }
      break;

    case GETDOTTED:
      aux = *start++;
      goto getdotted;

    case GETDOTTED0:
    case GETDOTTED1:
    case GETDOTTED2:
    case GETDOTTED3:
    case GETDOTTED4:
    case GETDOTTED5:
    case GETDOTTED6:
    case GETDOTTED7:
      aux = opc - GETDOTTED0;
      goto getdotted;

    case GETDOTTEDW:
      aux = start[0] | (start[1] << 8);
      start += 2;
    getdotted:
      {
	Expression *tbl = stk->top(); stk->pop();
	stk->push(new DotIndexExpr(start, tbl, new StringExpr
				(start, tsvalue(tf->consts + aux))));
      }
      break;

    case PUSHSELF:
      aux = *start++;
      goto pushself;

    case PUSHSELF0:
    case PUSHSELF1:
    case PUSHSELF2:
    case PUSHSELF3:
    case PUSHSELF4:
    case PUSHSELF5:
    case PUSHSELF6:
    case PUSHSELF7:
      aux = opc - PUSHSELF0;
      goto pushself;

    case PUSHSELFW:
      aux = start[0] | (start[1] << 8);
      start += 2;
    pushself:
      {
	Expression *tbl = stk->top(); stk->pop();
	stk->push(new SelfExpr(start, tbl, new StringExpr
			       (start, tsvalue(tf->consts + aux))));
	stk->push(new VarExpr(start, "<self>"));
	// Fake value, FuncCallExpr will handle it
      }
      break;

    case CREATEARRAY:
      start++;
      goto createarray;

    case CREATEARRAY0:
    case CREATEARRAY1:
      goto createarray;

    case CREATEARRAYW:
      start += 2;
    createarray:
      stk->push(new ArrayExpr(start));
      break;

    case SETLOCAL:
    case SETLOCAL0:
    case SETLOCAL1:
    case SETLOCAL2:
    case SETLOCAL3:
    case SETLOCAL4:
    case SETLOCAL5:
    case SETLOCAL6:
    case SETLOCAL7:
    case SETGLOBAL:
    case SETGLOBAL0:
    case SETGLOBAL1:
    case SETGLOBAL2:
    case SETGLOBAL3:
    case SETGLOBAL4:
    case SETGLOBAL5:
    case SETGLOBAL6:
    case SETGLOBAL7:
    case SETGLOBALW:
    case SETTABLE0:
    case SETTABLE:
      start--;
      do_multi_assign(start);
      break;

    case SETLIST:
      start++;			// assume offset is correct
      goto setlist;

    case SETLISTW:
      start += 2;

    case SETLIST0:
    setlist:
      aux = *start++;
      {
	ArrayExpr::mapping_list new_mappings;
	for (int i = 0; i < aux; i++) {
	  Expression *val = stk->top(); stk->pop();
	  new_mappings.push_front(std::make_pair((Expression *) NULL, val));
	}
	ArrayExpr *a = dynamic_cast<ArrayExpr *>(stk->top());
	if (a == NULL) {
	  *os << indent_str
	      << "error: attempt to setlist a non-array object\n";
	}
	// Append the new list
	a->mappings.splice(a->mappings.end(), new_mappings);
	a->pos = start;
      }
      break;

    case SETMAP:
      aux = *start++;
      goto setmap;

    case SETMAP0:
      aux = 0;
    setmap:
      {
	ArrayExpr::mapping_list new_mappings;
	for (int i = 0; i <= aux; i++) {
	  Expression *val = stk->top(); stk->pop();
	  Expression *key = stk->top(); stk->pop();
	  new_mappings.push_front(std::make_pair(key, val));
	}
	ArrayExpr *a = dynamic_cast<ArrayExpr *>(stk->top());
	if (a == NULL) {
	  *os << indent_str
	      << "error: attempt to setmap a non-array object\n";
	}
	// Append the new list
	a->mappings.splice(a->mappings.end(), new_mappings);
	a->pos = start;
      }
      break;

    case EQOP:
      do_binary_op(start, 1, false, " == ");
      break;

    case NEQOP:
      do_binary_op(start, 1, false, " ~= ");
      break;

    case LTOP:
      do_binary_op(start, 1, false, " < ");
      break;

    case LEOP:
      do_binary_op(start, 1, false, " <= ");
      break;

    case GTOP:
      do_binary_op(start, 1, false, " > ");
      break;

    case GEOP:
      do_binary_op(start, 1, false, " >= ");
      break;

    case ADDOP:
      do_binary_op(start, 3, false, " + ");
      break;

    case SUBOP:
      do_binary_op(start, 3, false, " - ");
      break;

    case MULTOP:
      do_binary_op(start, 4, false, " * ");
      break;

    case DIVOP:
      do_binary_op(start, 4, false, " / ");
      break;

    case POWOP:
      do_binary_op(start, 6, true, " ^ ");
      break;

    case CONCOP:
      do_binary_op(start, 2, false, " .. ");
      break;

    case MINUSOP:
      do_unary_op(start, 5, "-");
      break;

    case NOTOP:
      do_unary_op(start, 5, "not ");
      break;

    case ONTJMP:
      aux = *start++;
      goto ontjmp;

    case ONTJMPW:
      aux = start[0] | (start[1] << 8);
      start += 2;
    ontjmp:
      // push_expr_1 ontjmp(label) push_expr_2 label:  -> expr_1 || expr_2
      decompileRange(start, start + aux);
      do_binary_op(start + aux, 0, false, " or ");
      start = start + aux;
      break;

    case ONFJMP:
      aux = *start++;
      goto onfjmp;

    case ONFJMPW:
      aux = start[0] | (start[1] << 8);
      start += 2;
    onfjmp:
      // push_expr_1 onfjmp(label) push_expr_2 label:  -> expr_2 && expr_2
      decompileRange(start, start + aux);
      do_binary_op(start + aux, 0, false, " and ");
      start = start + aux;
      break;

    case JMP:
      aux = *start++;
      goto jmp;

    case JMPW:
      aux = start[0] | (start[1] << 8);
      start += 2;
    jmp:
      {
	Byte *dest = start + aux;
	if (dest == break_pos) {
	  *os << indent_str << "break\n";
	  break;
	}

	// otherwise, must be the start of a while statement
	Byte *while_cond_end;
	for (while_cond_end = dest; end == NULL || while_cond_end < end;
	     while_cond_end += get_instr_len(*while_cond_end))
	  if (*while_cond_end == IFTUPJMP || *while_cond_end == IFTUPJMPW)
	    break;
	if (end != NULL && while_cond_end >= end) {
	  *os << indent_str
	      << "error: JMP not in break, while, if/else\n";
	}

	// push the while condition onto the stack
	decompileRange(dest, while_cond_end);

	*os << indent_str << "while " << *stk->top()
	    << " do\n";
	delete stk->top();
	stk->pop();

	// decompile the while body
	Decompiler indented_dc = *this;
	indented_dc.indent_str += std::string(4, ' ');
	indented_dc.break_pos = while_cond_end + get_instr_len(*while_cond_end);
	indented_dc.decompileRange(start, dest);

	*os << indent_str << "end\n";
	start = indented_dc.break_pos;
      }
      break;

    case IFFJMP:
      aux = *start++;
      goto iffjmp;

    case IFFJMPW:
      aux = start[0] | (start[1] << 8);
      start += 2;
    iffjmp:
      {
	// Output an if/end, if/else/end, if/elseif/else/end, ... statement
	Byte *if_part_end = start + aux;
	Decompiler indented_dc = *this;
	indented_dc.indent_str += std::string(4, ' ');

	*os << indent_str << "if " << *stk->top();
	delete stk->top();
	stk->pop();
	*os << " then\n";

	bool has_else;
	Byte *else_part_end;
	get_else_part(start, if_part_end, has_else, else_part_end);

	// Output the if part
      output_if:
	indented_dc.decompileRange(start, if_part_end);
	start = start + aux;

	if (has_else) {
	  // Check whether the entire else part is a single
	  // if or if/else statement
	  Byte *instr_scan = start;
	  while (is_expr_opc(*instr_scan) &&
		 (end == NULL || instr_scan < else_part_end))
	    instr_scan += get_instr_len(*instr_scan);
	  if ((end == NULL || instr_scan < else_part_end) &&
	      (*instr_scan == IFFJMP || *instr_scan == IFFJMPW)) {
	    // OK, first line will be if, check if it will go all
	    // the way through
	    Byte *new_start, *new_if_part_end, *new_else_part_end;
	    bool new_has_else;
	    if (*instr_scan == IFFJMP) {
	      aux = instr_scan[1];
	      new_start = instr_scan + 2;
	    }
	    else {
	      aux = instr_scan[1] | (instr_scan[2] << 8);
	      new_start = instr_scan + 3;
	    }
	    new_if_part_end = new_start + aux;
	    get_else_part(new_start, new_if_part_end, new_has_else,
			  new_else_part_end);
	    if (new_if_part_end == else_part_end ||
		(new_has_else && new_else_part_end == else_part_end)) {
	      // Yes, output an elseif
	      decompileRange(start, instr_scan); // push condition
	      *os << indent_str << "elseif " << *stk->top() << " then\n";
	      delete stk->top();
	      stk->pop();

	      start = new_start;
	      if_part_end = new_if_part_end;
	      has_else = new_has_else;
	      else_part_end = new_else_part_end;
	      goto output_if;
	    }
	  }
	  *os << indent_str << "else\n";
	  indented_dc.decompileRange(start, else_part_end);
	  start = else_part_end;
	}
	*os << indent_str << "end\n";
      }
      break;

    case CLOSURE:
      aux = *start++;
      goto closure;

    case CLOSURE0:
    case CLOSURE1:
      aux = opc - CLOSURE0;
    closure:
      {
	FuncExpr *f = dynamic_cast<FuncExpr *>(stk->top());
	if (f == NULL) {
	  *os << indent_str
	      << "error: closure requires a function\n";
	}
	stk->pop();
	f->num_upvals = aux;
	f->upvals = new Expression*[aux];
	for (int i = aux - 1; i >= 0; i--) {
	  f->upvals[i] = stk->top(); stk->pop();
	}
	stk->push(f);
      }
      break;

    case CALLFUNC:
      aux = *start++;
      goto callfunc;

    case CALLFUNC0:
    case CALLFUNC1:
      aux = opc - CALLFUNC0;
    callfunc:
      {
	int num_args = *start++;
	FuncCallExpr *e = new FuncCallExpr(start);
	e->num_args = num_args;
	e->args = new Expression*[num_args];
	for (int i = num_args - 1; i >= 0; i--) {
	  e->args[i] = stk->top();
	  stk->pop();
	}
	e->func = stk->top();
	stk->pop();
	if (aux == 0) {
	  *os << indent_str << *e << std::endl;
	  delete e;
	}
	else if (aux == 1 || aux == 255) // 255 for return f()
	  stk->push(e);
	else {
	  stk->push(e);
	  for (int i = 1; i < aux; i++)
	    stk->push(new VarExpr(start, "<extra result>"));
	}
      }
      break;

    case RETCODE:
      {
	int num_rets = stk->size() + tf->code[1] - *start++;
	ExprStack rets;

	for (int i = 0; i < num_rets; i++) {
	  rets.push(stk->top());
	  stk->pop();
	}
	*os << indent_str << "return";
	for (int i = 0; i < num_rets; i++) {
	  *os << " " << *rets.top();
	  delete rets.top();
	  rets.pop();
	  if (i + 1 < num_rets)
	    *os << ",";
	}
	*os << std::endl;
      }
      break;

    case SETLINE:
      aux = *start++;
      goto setline;

    case SETLINEW:
      aux = start[0] | (start[1] << 8);
      start += 2;
    setline:
      break;			// ignore line info

    case POP:
      aux = *start++;
      goto pop;

    case POP0:
    case POP1:
      aux = opc - POP0;
    pop:
      for (int i = 0; i <= aux; i++) {
	local_var_defs->insert(stk->top()->pos);
	delete stk->top(); stk->pop();
      }
      break;

    //Nop
    default:
      break;
    }
  }
}
Exemplo n.º 8
0
static const char *kname (Proto *p, int c) {
  if (ISK(c) && ttisstring(&p->k[INDEXK(c)]))
    return svalue(&p->k[INDEXK(c)]);
  else
    return "?";
}
Exemplo n.º 9
0
static void PrintCode(const Proto* f)
{
 const Instruction* code=f->code;
 int pc,n=f->sizecode;
 for (pc=0; pc<n; pc++)
 {
  Instruction i=code[pc];
  OpCode o=GET_OPCODE(i);
  int a=GETARG_A(i);
  int b=GETARG_B(i);
  int c=GETARG_C(i);
  int bx=GETARG_Bx(i);
  int sbx=GETARG_sBx(i);
  int line=getline(f,pc);
  printf("\t%d\t",pc+1);
  if (line>0) printf("[%d]\t",line); else printf("[-]\t");
  printf("%-9s\t",luaP_opnames[o]);
  switch (getOpMode(o))
  {
   case iABC:
    printf("%d",a);
    if (getBMode(o)!=OpArgN) printf(" %d",ISK(b) ? (-1-INDEXK(b)) : b);
    if (getCMode(o)!=OpArgN) printf(" %d",ISK(c) ? (-1-INDEXK(c)) : c);
    break;
   case iABx:
    if (getBMode(o)==OpArgK) printf("%d %d",a,-1-bx); else printf("%d %d",a,bx);
    break;
   case iAsBx:
    if (o==OP_JMP) printf("%d",sbx); else printf("%d %d",a,sbx);
    break;
  }
  switch (o)
  {
   case OP_LOADK:
    printf("\t; "); PrintConstant(f,bx);
    break;
   case OP_GETUPVAL:
   case OP_SETUPVAL:
    printf("\t; %s", (f->sizeupvalues>0) ? getstr(f->upvalues[b]) : "-");
    break;
   case OP_GETGLOBAL:
   case OP_SETGLOBAL:
    printf("\t; %s",svalue(&f->k[bx]));
    break;
   case OP_GETTABLE:
   case OP_SELF:
    if (ISK(c)) { printf("\t; "); PrintConstant(f,INDEXK(c)); }
    break;
   case OP_SETTABLE:
   case OP_ADD:
   case OP_SUB:
   case OP_MUL:
   case OP_DIV:
   case OP_POW:
   case OP_EQ:
   case OP_LT:
   case OP_LE:
    if (ISK(b) || ISK(c))
    {
     printf("\t; ");
     if (ISK(b)) PrintConstant(f,INDEXK(b)); else printf("-");
     printf(" ");
     if (ISK(c)) PrintConstant(f,INDEXK(c)); else printf("-");
    }
    break;
   case OP_JMP:
   case OP_FORLOOP:
   case OP_FORPREP:
    printf("\t; to %d",sbx+pc+2);
    break;
   case OP_CLOSURE:
    printf("\t; %p",VOID(f->p[bx]));
    break;
   case OP_SETLIST:
    if (c==0) printf("\t; %d",(int)code[++pc]);
    else printf("\t; %d",c);
    break;
   default:
    break;
  }
  printf("\n");
 }
}
Exemplo n.º 10
0
/*
 * Glob the argument words in genbuf, or if no globbing
 * is implied, just split them up directly.
 */
void
glob(struct glob *gp)
{
	int pvec[2];
	register char **argv = gp->argv;
	register char *cp = gp->argspac;
	register int c;
	char ch;
	int nleft = NCARGS;

	gp->argc0 = 0;
	if (gscan() == 0) {
		register char *v = genbuf + 5;		/* strlen("echo ") */

		for (;;) {
			while (isspace((int)*v))
				v++;
			if (!*v)
				break;
			*argv++ = cp;
			while (*v && !isspace((int)*v))
				*cp++ = *v++;
			*cp++ = 0;
			gp->argc0++;
		}
		*argv = 0;
		return;
	}
	if (pipe(pvec) < 0)
		error("Can't make pipe to glob");
	pid = fork();
	io = pvec[0];
	if (pid < 0) {
		close(pvec[1]);
		error("Can't fork to do glob");
	}
	if (pid == 0) {
		int oerrno;

		close(1);
		dup(pvec[1]);
		close(pvec[0]);
		close(2);	/* so errors don't mess up the screen */
		open("/dev/null", O_WRONLY);
		execl(svalue(SHELL), "sh", "-c", genbuf, NULL);
		oerrno = errno; close(1); dup(2); errno = oerrno;
		filioerr(svalue(SHELL));
	}
	close(pvec[1]);
	do {
		*argv = cp;
		for (;;) {
			if (read(io, &ch, 1) != 1) {
				close(io);
				c = -1;
			} else
				c = ch & TRIM;
			if (c <= 0 || isspace(c))
				break;
			*cp++ = c;
			if (--nleft <= 0)
				error("Arg list too long");
		}
		if (cp != *argv) {
			--nleft;
			*cp++ = 0;
			gp->argc0++;
			if (gp->argc0 >= NARGS)
				error("Arg list too long");
			argv++;
		}
	} while (c >= 0);
	waitfor();
	if (gp->argc0 == 0)
		error("No match");
}
Exemplo n.º 11
0
/* this function handles only `%d', `%c', %f, %p, and `%s' formats */
const char* luaO_pushvfstring(lua_State* L, const char* fmt, va_list argp)
{
	int n = 1;
	pushstr(L, "");
	for (;;)
	{
		const char* e = strchr(fmt, '%');
		if (e == NULL) break;
		setsvalue2s(L, L->top, luaS_newlstr(L, fmt, e - fmt));
		incr_top(L);
		switch (*(e + 1))
		{
			case 's':
			{
				const char* s = va_arg(argp, char*);
				if (s == NULL) s = "(null)";
				pushstr(L, s);
				break;
			}
			case 'c':
			{
				char buff[2];
				buff[0] = cast(char, va_arg(argp, int));
				buff[1] = '\0';
				pushstr(L, buff);
				break;
			}
			case 'd':
			{
				setnvalue(L->top, cast_num(va_arg(argp, int)));
				incr_top(L);
				break;
			}
			case 'f':
			{
				setnvalue(L->top, cast_num(va_arg(argp, l_uacNumber)));
				incr_top(L);
				break;
			}
			case 'p':
			{
				char buff[4 * sizeof(void*) + 8]; /* should be enough space for a `%p' */
				sprintf(buff, "%p", va_arg(argp, void*));
				pushstr(L, buff);
				break;
			}
			case '%':
			{
				pushstr(L, "%");
				break;
			}
			default:
			{
				char buff[3];
				buff[0] = '%';
				buff[1] = *(e + 1);
				buff[2] = '\0';
				pushstr(L, buff);
				break;
			}
		}
		n += 2;
		fmt = e + 2;
	}
	pushstr(L, fmt);
	luaV_concat(L, n + 1, cast_int(L->top - L->base) - 1);
	L->top -= n;
	return svalue(L->top - 1);
}
Exemplo n.º 12
0
/* histogram: key should be number or string, value must be number */
void kp_table_histogram(ktap_State *ks, Table *t)
{
	struct table_hist_record *thr;
	char dist_str[40];
	int i, ratio, total = 0, count = 0;

	thr = kp_malloc(ks, sizeof(*thr) * (t->sizearray + sizenode(t)));

	for (i = 0; i < t->sizearray; i++) {
		Tvalue *v = &t->array[i];

		if (isnil(v))
			continue;

		if (!ttisnumber(v))
			goto error;

		setnvalue(&thr[count++].key, i + 1);
		total += nvalue(v);
	}

	for (i = 0; i < sizenode(t); i++) {
		Node *n = &t->node[i];
		int num;

		if (isnil(gkey(n)))
			continue;

		if (!ttisnumber(gval(n)))
			goto error;

		num = nvalue(gval(n));
		setobj(ks, &thr[count].key, gkey(n));
		setobj(ks, &thr[count].val, gval(n));
		count++;
		total += nvalue(gval(n));
	}

	sort(thr, count, sizeof(struct table_hist_record), hist_record_cmp, NULL);

	kp_printf(ks, "%32s%s%s\n", "value ", DISTRIBUTION_STR, " count");
	dist_str[sizeof(dist_str) - 1] = '\0';
	for (i = 0; i < count; i++) {
		Tvalue *key = &thr[i].key;
		Tvalue *val = &thr[i].val;

		memset(dist_str, ' ', sizeof(dist_str) - 1);
		ratio = (nvalue(val) * (sizeof(dist_str) - 1)) / total;
		memset(dist_str, '@', ratio);

		if (ttisstring(key)) {
			char buf[32 + 1] = {0};
			char *keystr;

			if (strlen(svalue(key)) > 32) {
				strncpy(buf, svalue(key), 32-4);
				memset(buf + 32-4, '.', 3);
				keystr = buf;
			} else
				keystr = svalue(key);

			kp_printf(ks, "%32s |%s%-10d\n", keystr, dist_str,
					nvalue(val));
		} else
			kp_printf(ks, "%32d | %s%-10d\n", nvalue(key),
					dist_str, nvalue(val));
	}

	goto out;

 error:
	kp_printf(ks, "error: table histogram only handle "
			" (key: string/number val: number)\n");
 out:
	kp_free(ks, thr);
}
Exemplo n.º 13
0
/*
** Execute the given opcode, until a RET. Parameters are between
** [stack+base,top). Returns n such that the the results are between
** [stack+n,top).
*/
static StkId lua_execute (Byte *pc, StkId base)
{
  if (lua_callhook)
    callHook (base, LUA_T_MARK, 0);
 while (1)
 {
  OpCode opcode;
  switch (opcode = (OpCode)*pc++)
  {
   case PUSHNIL: ttype(top) = LUA_T_NIL; incr_top; break;

   case PUSH0: case PUSH1: case PUSH2:
     ttype(top) = LUA_T_NUMBER;
     nvalue(top) = opcode-PUSH0;
     incr_top;
     break;

   case PUSHBYTE: 
     ttype(top) = LUA_T_NUMBER; nvalue(top) = *pc++; incr_top; break;

   case PUSHWORD:
   {
    Word w;
    get_word(w,pc);
    ttype(top) = LUA_T_NUMBER; nvalue(top) = w;
    incr_top;
   }
   break;

   case PUSHFLOAT:
   {
    real num;
    get_float(num,pc);
    ttype(top) = LUA_T_NUMBER; nvalue(top) = num;
    incr_top;
   }
   break;

   case PUSHSTRING:
   {
    Word w;
    get_word(w,pc);
    ttype(top) = LUA_T_STRING; tsvalue(top) = lua_constant[w];
    incr_top;
   }
   break;

   case PUSHFUNCTION:
   {
    TFunc *f;
    get_code(f,pc);
    luaI_insertfunction(f);  /* may take part in GC */
    top->ttype = LUA_T_FUNCTION;
    top->value.tf = f;
    incr_top;
   }
   break;

   case PUSHLOCAL0: case PUSHLOCAL1: case PUSHLOCAL2:
   case PUSHLOCAL3: case PUSHLOCAL4: case PUSHLOCAL5:
   case PUSHLOCAL6: case PUSHLOCAL7: case PUSHLOCAL8:
   case PUSHLOCAL9: 
     *top = *((stack+base) + (int)(opcode-PUSHLOCAL0)); incr_top; break;

   case PUSHLOCAL: *top = *((stack+base) + (*pc++)); incr_top; break;

   case PUSHGLOBAL:
   {
    Word w;
    get_word(w,pc);
    getglobal(w);
   }
   break;

   case PUSHINDEXED:
    pushsubscript();
    break;

   case PUSHSELF:
   {
     TObject receiver = *(top-1);
     Word w;
     get_word(w,pc);
     ttype(top) = LUA_T_STRING; tsvalue(top) = lua_constant[w];
     incr_top;
     pushsubscript();
     *top = receiver;
     incr_top;
     break;
   }

   case STORELOCAL0: case STORELOCAL1: case STORELOCAL2:
   case STORELOCAL3: case STORELOCAL4: case STORELOCAL5:
   case STORELOCAL6: case STORELOCAL7: case STORELOCAL8:
   case STORELOCAL9:
     *((stack+base) + (int)(opcode-STORELOCAL0)) = *(--top);
     break;

   case STORELOCAL: *((stack+base) + (*pc++)) = *(--top); break;

   case STOREGLOBAL:
   {
    Word w;
    get_word(w,pc);
    setglobal(w);
   }
   break;

   case STOREINDEXED0:
    storesubscript(top-3, 1);
    break;

   case STOREINDEXED: {
     int n = *pc++;
     storesubscript(top-3-n, 2);
     break;
   }

   case STORELIST0:
   case STORELIST:
   {
    int m, n;
    TObject *arr;
    if (opcode == STORELIST0) m = 0;
    else m = *(pc++) * FIELDS_PER_FLUSH;
    n = *(pc++);
    arr = top-n-1;
    while (n)
    {
     ttype(top) = LUA_T_NUMBER; nvalue(top) = n+m;
     *(lua_hashdefine (avalue(arr), top)) = *(top-1);
     top--;
     n--;
    }
   }
   break;

   case STORERECORD:  /* opcode obsolete: supersed by STOREMAP */
   {
    int n = *(pc++);
    TObject *arr = top-n-1;
    while (n)
    {
     Word w;
     get_word(w,pc);
     ttype(top) = LUA_T_STRING; tsvalue(top) = lua_constant[w];
     *(lua_hashdefine (avalue(arr), top)) = *(top-1);
     top--;
     n--;
    }
   }
   break;

   case STOREMAP: {
     int n = *(pc++);
     TObject *arr = top-(2*n)-1;
     while (n--) {
       *(lua_hashdefine (avalue(arr), top-2)) = *(top-1);
       top-=2;
     }
   }
   break;

   case ADJUST0:
     adjust_top(base);
     break;

   case ADJUST: {
     StkId newtop = base + *(pc++);
     adjust_top(newtop);
     break;
   }

   case VARARGS:
     adjust_varargs(base + *(pc++));
     break;

   case CREATEARRAY:
   {
    Word size;
    get_word(size,pc);
    avalue(top) = lua_createarray(size);
    ttype(top) = LUA_T_ARRAY;
    incr_top;
   }
   break;

   case EQOP:
   {
    int res = lua_equalObj(top-2, top-1);
    --top;
    ttype(top-1) = res ? LUA_T_NUMBER : LUA_T_NIL;
    nvalue(top-1) = 1;
   }
   break;

    case LTOP:
      comparison(LUA_T_NUMBER, LUA_T_NIL, LUA_T_NIL, IM_LT);
      break;

   case LEOP:
      comparison(LUA_T_NUMBER, LUA_T_NUMBER, LUA_T_NIL, IM_LE);
      break;

   case GTOP:
      comparison(LUA_T_NIL, LUA_T_NIL, LUA_T_NUMBER, IM_GT);
      break;

   case GEOP:
      comparison(LUA_T_NIL, LUA_T_NUMBER, LUA_T_NUMBER, IM_GE);
      break;

   case ADDOP:
   {
    TObject *l = top-2;
    TObject *r = top-1;
    if (tonumber(r) || tonumber(l))
      call_arith(IM_ADD);
    else
    {
      nvalue(l) += nvalue(r);
      --top;
    }
   }
   break;

   case SUBOP:
   {
    TObject *l = top-2;
    TObject *r = top-1;
    if (tonumber(r) || tonumber(l))
      call_arith(IM_SUB);
    else
    {
      nvalue(l) -= nvalue(r);
      --top;
    }
   }
   break;

   case MULTOP:
   {
    TObject *l = top-2;
    TObject *r = top-1;
    if (tonumber(r) || tonumber(l))
      call_arith(IM_MUL);
    else
    {
      nvalue(l) *= nvalue(r);
      --top;
    }
   }
   break;

   case DIVOP:
   {
    TObject *l = top-2;
    TObject *r = top-1;
    if (tonumber(r) || tonumber(l))
      call_arith(IM_DIV);
    else
    {
      nvalue(l) /= nvalue(r);
      --top;
    }
   }
   break;

   case POWOP:
    call_arith(IM_POW);
    break;

   case CONCOP: {
     TObject *l = top-2;
     TObject *r = top-1;
     if (tostring(l) || tostring(r))
       call_binTM(IM_CONCAT, "unexpected type for concatenation");
     else {
       tsvalue(l) = lua_createstring(lua_strconc(svalue(l),svalue(r)));
       --top;
     }
   }
   break;

   case MINUSOP:
    if (tonumber(top-1))
    {
      ttype(top) = LUA_T_NIL;
      incr_top;
      call_arith(IM_UNM);
    }
    else
      nvalue(top-1) = - nvalue(top-1);
   break;

   case NOTOP:
    ttype(top-1) = (ttype(top-1) == LUA_T_NIL) ? LUA_T_NUMBER : LUA_T_NIL;
    nvalue(top-1) = 1;
   break;

   case ONTJMP:
   {
    Word w;
    get_word(w,pc);
    if (ttype(top-1) != LUA_T_NIL) pc += w;
   }
   break;

   case ONFJMP:
   {
    Word w;
    get_word(w,pc);
    if (ttype(top-1) == LUA_T_NIL) pc += w;
   }
   break;

   case JMP:
   {
    Word w;
    get_word(w,pc);
    pc += w;
   }
   break;

   case UPJMP:
   {
    Word w;
    get_word(w,pc);
    pc -= w;
   }
   break;

   case IFFJMP:
   {
    Word w;
    get_word(w,pc);
    top--;
    if (ttype(top) == LUA_T_NIL) pc += w;
   }
   break;

   case IFFUPJMP:
   {
    Word w;
    get_word(w,pc);
    top--;
    if (ttype(top) == LUA_T_NIL) pc -= w;
   }
   break;

   case POP: --top; break;

   case CALLFUNC:
   {
     int nParams = *(pc++);
     int nResults = *(pc++);
     StkId newBase = (top-stack)-nParams;
     do_call(newBase, nResults);
   }
   break;

   case RETCODE0:
   case RETCODE:
     if (lua_callhook)
       callHook (base, LUA_T_MARK, 1);
     return (base + ((opcode==RETCODE0) ? 0 : *pc));

   case SETLINE:
   {
    Word line;
    get_word(line,pc);
    if ((stack+base-1)->ttype != LUA_T_LINE)
    {
      /* open space for LINE value */
      open_stack((top-stack)-base);
      base++;
      (stack+base-1)->ttype = LUA_T_LINE;
    }
    (stack+base-1)->value.i = line;
    if (lua_linehook)
      lineHook (line);
    break;
   }

   default:
    lua_error ("internal error - opcode doesn't match");
  }
 }
}
Exemplo n.º 14
0
StkId luaV_execute(lua_Task *task) {
	if (!task->some_flag) {
		luaD_checkstack((*task->pc++) + EXTRA_STACK);
		if (*task->pc < ZEROVARARG) {
			luaD_adjusttop(task->base + *(task->pc++));
		} else {
			luaC_checkGC();
			adjust_varargs(task->base + (*task->pc++) - ZEROVARARG);
		}
		task->some_flag = 1;
	}
	lua_state->state_counter2++;

	while (1) {
		switch ((OpCode)(task->aux = *task->pc++)) {
		case PUSHNIL0:
			ttype(task->S->top++) = LUA_T_NIL;
			break;
		case PUSHNIL:
			task->aux = *task->pc++;
			do {
				ttype(task->S->top++) = LUA_T_NIL;
			} while (task->aux--);
			break;
		case PUSHNUMBER:
			task->aux = *task->pc++;
			goto pushnumber;
		case PUSHNUMBERW:
			task->aux = next_word(task->pc);
			goto pushnumber;
		case PUSHNUMBER0:
		case PUSHNUMBER1:
		case PUSHNUMBER2:
			task->aux -= PUSHNUMBER0;
pushnumber:
			ttype(task->S->top) = LUA_T_NUMBER;
			nvalue(task->S->top) = (float)task->aux;
			task->S->top++;
			break;
		case PUSHLOCAL:
			task->aux = *task->pc++;
			goto pushlocal;
		case PUSHLOCAL0:
		case PUSHLOCAL1:
		case PUSHLOCAL2:
		case PUSHLOCAL3:
		case PUSHLOCAL4:
		case PUSHLOCAL5:
		case PUSHLOCAL6:
		case PUSHLOCAL7:
			task->aux -= PUSHLOCAL0;
pushlocal:
			*task->S->top++ = *((task->S->stack + task->base) + task->aux);
			break;
		case GETGLOBALW:
			task->aux = next_word(task->pc);
			goto getglobal;
		case GETGLOBAL:
			task->aux = *task->pc++;
			goto getglobal;
		case GETGLOBAL0:
		case GETGLOBAL1:
		case GETGLOBAL2:
		case GETGLOBAL3:
		case GETGLOBAL4:
		case GETGLOBAL5:
		case GETGLOBAL6:
		case GETGLOBAL7:
			task->aux -= GETGLOBAL0;
getglobal:
			luaV_getglobal(tsvalue(&task->consts[task->aux]));
			break;
		case GETTABLE:
			luaV_gettable();
			break;
		case GETDOTTEDW:
			task->aux = next_word(task->pc); goto getdotted;
		case GETDOTTED:
			task->aux = *task->pc++;
			goto getdotted;
		case GETDOTTED0:
		case GETDOTTED1:
		case GETDOTTED2:
		case GETDOTTED3:
		case GETDOTTED4:
		case GETDOTTED5:
		case GETDOTTED6:
		case GETDOTTED7:
			task->aux -= GETDOTTED0;
getdotted:
			*task->S->top++ = task->consts[task->aux];
			luaV_gettable();
			break;
		case PUSHSELFW:
			task->aux = next_word(task->pc);
			goto pushself;
		case PUSHSELF:
			task->aux = *task->pc++;
			goto pushself;
		case PUSHSELF0:
		case PUSHSELF1:
		case PUSHSELF2:
		case PUSHSELF3:
		case PUSHSELF4:
		case PUSHSELF5:
		case PUSHSELF6:
		case PUSHSELF7:
			task->aux -= PUSHSELF0;
pushself:
			{
				TObject receiver = *(task->S->top - 1);
				*task->S->top++ = task->consts[task->aux];
				luaV_gettable();
				*task->S->top++ = receiver;
				break;
			}
		case PUSHCONSTANTW:
			task->aux = next_word(task->pc);
			goto pushconstant;
		case PUSHCONSTANT:
			task->aux = *task->pc++; goto pushconstant;
		case PUSHCONSTANT0:
		case PUSHCONSTANT1:
		case PUSHCONSTANT2:
		case PUSHCONSTANT3:
		case PUSHCONSTANT4:
		case PUSHCONSTANT5:
		case PUSHCONSTANT6:
		case PUSHCONSTANT7:
			task->aux -= PUSHCONSTANT0;
pushconstant:
			*task->S->top++ = task->consts[task->aux];
			break;
		case PUSHUPVALUE:
			task->aux = *task->pc++;
			goto pushupvalue;
		case PUSHUPVALUE0:
		case PUSHUPVALUE1:
			task->aux -= PUSHUPVALUE0;
pushupvalue:
			*task->S->top++ = task->cl->consts[task->aux + 1];
			break;
		case SETLOCAL:
			task->aux = *task->pc++;
			goto setlocal;
		case SETLOCAL0:
		case SETLOCAL1:
		case SETLOCAL2:
		case SETLOCAL3:
		case SETLOCAL4:
		case SETLOCAL5:
		case SETLOCAL6:
		case SETLOCAL7:
			task->aux -= SETLOCAL0;
setlocal:
			*((task->S->stack + task->base) + task->aux) = *(--task->S->top);
			break;
		case SETGLOBALW:
			task->aux = next_word(task->pc);
			goto setglobal;
		case SETGLOBAL:
			task->aux = *task->pc++;
			goto setglobal;
		case SETGLOBAL0:
		case SETGLOBAL1:
		case SETGLOBAL2:
		case SETGLOBAL3:
		case SETGLOBAL4:
		case SETGLOBAL5:
		case SETGLOBAL6:
		case SETGLOBAL7:
			task->aux -= SETGLOBAL0;
setglobal:
			luaV_setglobal(tsvalue(&task->consts[task->aux]));
			break;
		case SETTABLE0:
			luaV_settable(task->S->top - 3, 1);
			break;
		case SETTABLE:
			luaV_settable(task->S->top - 3 - (*task->pc++), 2);
			break;
		case SETLISTW:
			task->aux = next_word(task->pc);
			task->aux *= LFIELDS_PER_FLUSH;
			goto setlist;
		case SETLIST:
			task->aux = *(task->pc++) * LFIELDS_PER_FLUSH;
			goto setlist;
		case SETLIST0:
			task->aux = 0;
setlist:
			{
				int32 n = *(task->pc++);
				TObject *arr = task->S->top - n - 1;
				for (; n; n--) {
					ttype(task->S->top) = LUA_T_NUMBER;
					nvalue(task->S->top) = (float)(n + task->aux);
					*(luaH_set(avalue(arr), task->S->top)) = *(task->S->top - 1);
					task->S->top--;
			}
			break;
		}
		case SETMAP0:
			task->aux = 0;
			goto setmap;
		case SETMAP:
			task->aux = *task->pc++;
setmap:
			{
				TObject *arr = task->S->top - (2 * task->aux) - 3;
				do {
					*(luaH_set(avalue(arr), task->S->top - 2)) = *(task->S->top - 1);
					task->S->top -= 2;
				} while (task->aux--);
				break;
			}
		case POP:
			task->aux = *task->pc++;
			goto pop;
		case POP0:
		case POP1:
			task->aux -= POP0;
pop:
			task->S->top -= (task->aux + 1);
			break;
		case CREATEARRAYW:
			task->aux = next_word(task->pc);
			goto createarray;
		case CREATEARRAY0:
		case CREATEARRAY1:
			task->aux -= CREATEARRAY0;
			goto createarray;
		case CREATEARRAY:
			task->aux = *task->pc++;
createarray:
			luaC_checkGC();
			avalue(task->S->top) = luaH_new(task->aux);
			ttype(task->S->top) = LUA_T_ARRAY;
			task->S->top++;
			break;
		case EQOP:
		case NEQOP:
			{
				int32 res = luaO_equalObj(task->S->top - 2, task->S->top - 1);
				task->S->top--;
				if (task->aux == NEQOP)
					res = !res;
				ttype(task->S->top - 1) = res ? LUA_T_NUMBER : LUA_T_NIL;
				nvalue(task->S->top - 1) = 1;
				break;
			}
		case LTOP:
			comparison(LUA_T_NUMBER, LUA_T_NIL, LUA_T_NIL, IM_LT);
			break;
		case LEOP:
			comparison(LUA_T_NUMBER, LUA_T_NUMBER, LUA_T_NIL, IM_LE);
			break;
		case GTOP:
			comparison(LUA_T_NIL, LUA_T_NIL, LUA_T_NUMBER, IM_GT);
			break;
		case GEOP:
			comparison(LUA_T_NIL, LUA_T_NUMBER, LUA_T_NUMBER, IM_GE);
			break;
		case ADDOP:
			{
				TObject *l = task->S->top - 2;
				TObject *r = task->S->top - 1;
				if (tonumber(r) || tonumber(l))
					call_arith(IM_ADD);
				else {
					nvalue(l) += nvalue(r);
					--task->S->top;
				}
			break;
			}
		case SUBOP:
			{
				TObject *l = task->S->top - 2;
				TObject *r = task->S->top - 1;
				if (tonumber(r) || tonumber(l))
					call_arith(IM_SUB);
				else {
					nvalue(l) -= nvalue(r);
					--task->S->top;
				}
				break;
			}
		case MULTOP:
			{
				TObject *l = task->S->top - 2;
				TObject *r = task->S->top - 1;
				if (tonumber(r) || tonumber(l))
					call_arith(IM_MUL);
				else {
					nvalue(l) *= nvalue(r);
					--task->S->top;
				}
				break;
			}
		case DIVOP:
			{
				TObject *l = task->S->top - 2;
				TObject *r = task->S->top - 1;
				if (tonumber(r) || tonumber(l))
					call_arith(IM_DIV);
				else {
					nvalue(l) /= nvalue(r);
					--task->S->top;
				}
				break;
			}
		case POWOP:
			call_arith(IM_POW);
			break;
		case CONCOP:
			{
				TObject *l = task->S->top - 2;
				TObject *r = task->S->top - 1;
				if (tostring(l) || tostring(r))
					call_binTM(IM_CONCAT, "unexpected type for concatenation");
				else {
					tsvalue(l) = strconc(svalue(l), svalue(r));
					--task->S->top;
				}
				luaC_checkGC();
				break;
			}
		case MINUSOP:
			if (tonumber(task->S->top - 1)) {
				ttype(task->S->top) = LUA_T_NIL;
				task->S->top++;
				call_arith(IM_UNM);
			} else
				nvalue(task->S->top - 1) = -nvalue(task->S->top - 1);
			break;
		case NOTOP:
			ttype(task->S->top - 1) = (ttype(task->S->top - 1) == LUA_T_NIL) ? LUA_T_NUMBER : LUA_T_NIL;
			nvalue(task->S->top - 1) = 1;
			break;
		case ONTJMPW:
			task->aux = next_word(task->pc);
			goto ontjmp;
		case ONTJMP:
			task->aux = *task->pc++;
ontjmp:
			if (ttype(task->S->top - 1) != LUA_T_NIL)
				task->pc += task->aux;
			else
				task->S->top--;
			break;
		case ONFJMPW:
			task->aux = next_word(task->pc);
			goto onfjmp;
		case ONFJMP:
			task->aux = *task->pc++;
onfjmp:
			if (ttype(task->S->top - 1) == LUA_T_NIL)
				task->pc += task->aux;
			else
				task->S->top--;
			break;
		case JMPW:
			task->aux = next_word(task->pc);
			goto jmp;
		case JMP:
			task->aux = *task->pc++;
jmp:
			task->pc += task->aux;
			break;
		case IFFJMPW:
			task->aux = next_word(task->pc);
			goto iffjmp;
		case IFFJMP:
			task->aux = *task->pc++;
iffjmp:
			if (ttype(--task->S->top) == LUA_T_NIL)
				task->pc += task->aux;
			break;
		case IFTUPJMPW:
			task->aux = next_word(task->pc);
			goto iftupjmp;
		case IFTUPJMP:
			task->aux = *task->pc++;
iftupjmp:
			if (ttype(--task->S->top) != LUA_T_NIL)
				task->pc -= task->aux;
			break;
		case IFFUPJMPW:
			task->aux = next_word(task->pc);
			goto iffupjmp;
		case IFFUPJMP:
			task->aux = *task->pc++;
iffupjmp:
			if (ttype(--task->S->top) == LUA_T_NIL)
				task->pc -= task->aux;
			break;
		case CLOSURE:
			task->aux = *task->pc++;
			goto closure;
		case CLOSURE0:
		case CLOSURE1:
			task->aux -= CLOSURE0;
closure:
			luaV_closure(task->aux);
			luaC_checkGC();
			break;
	  case CALLFUNC:
			task->aux = *task->pc++;
			goto callfunc;
	  case CALLFUNC0:
	  case CALLFUNC1:
			task->aux -= CALLFUNC0;
callfunc:
			lua_state->state_counter2--;
			return -((task->S->top - task->S->stack) - (*task->pc++));
		case ENDCODE:
			task->S->top = task->S->stack + task->base;
			// goes through
		case RETCODE:
			lua_state->state_counter2--;
			return (task->base + ((task->aux == 123) ? *task->pc : 0));
		case SETLINEW:
			task->aux = next_word(task->pc);
			goto setline;
		case SETLINE:
			task->aux = *task->pc++;
setline:
			if ((task->S->stack + task->base - 1)->ttype != LUA_T_LINE) {
				// open space for LINE value */
				luaD_openstack((task->S->top - task->S->stack) - task->base);
				task->base++;
				(task->S->stack + task->base - 1)->ttype = LUA_T_LINE;
			}
			(task->S->stack + task->base - 1)->value.i = task->aux;
			if (lua_linehook)
				luaD_lineHook(task->aux);
			break;
#ifdef LUA_DEBUG
		default:
			LUA_INTERNALERROR("internal error - opcode doesn't match");
#endif
		}
	}
}
Exemplo n.º 15
0
Arquivo: opcode.c Projeto: cskau/VM
/*
** Execute the given opcode, until a RET. Parameters are between
** [stack+base,top). Returns n such that the the results are between
** [stack+n,top).
*/
static StkId lua_execute (Byte *pc, StkId base)
{
  void* table[] = {
    &&pushnil,
    &&push0,
    &&push1,
    &&push2,
    &&pushbyte,
    &&pushword,
    &&pushfloat,
    &&pushstring,
    &&pushfunction,
    &&pushlocal0,
    &&pushlocal1,
    &&pushlocal2,
    &&pushlocal3,
    &&pushlocal4,
    &&pushlocal5,
    &&pushlocal6,
    &&pushlocal7,
    &&pushlocal8,
    &&pushlocal9,
    &&pushlocal,
    &&pushglobal,
    &&pushindexed,
    &&pushself,
    &&storelocal0,
    &&storelocal1,
    &&storelocal2,
    &&storelocal3,
    &&storelocal4,
    &&storelocal5,
    &&storelocal6,
    &&storelocal7,
    &&storelocal8,
    &&storelocal9,
    &&storelocal,
    &&storeglobal,
    &&storeindexed0,
    &&storeindexed,
    &&storelist0,
    &&storelist,
    &&storerecord,
    &&adjust0,
    &&adjust,
    &&createarray,
    &&eqop,
    &&ltop,
    &&leop,
    &&gtop,
    &&geop,
    &&addop,
    &&subop,
    &&multop,
    &&divop,
    &&powop,
    &&concop,
    &&minusop,
    &&notop,
    &&ontjmp,
    &&onfjmp,
    &&jmp,
    &&upjmp,
    &&iffjmp,
    &&iffupjmp,
    &&pop,
    &&callfunc,
    &&retcode0,
    &&retcode,
    &&setline,
    &&varargs
  };

  if (lua_callhook)
    callHook (base, LUA_T_MARK, 0);

  goto *table[*pc++];

   pushnil: tag(top) = LUA_T_NIL; incr_top; goto *table[*pc++];

   push0: push1: push2:
     tag(top) = LUA_T_NUMBER;
     nvalue(top) = ((OpCode)*(pc-1))-PUSH0;
     incr_top;
     goto *table[*pc++];

   pushbyte: 
     tag(top) = LUA_T_NUMBER; nvalue(top) = *pc++; incr_top; goto *table[*pc++];

   pushword:
   {
    Word w;
    get_word(w,pc);
    tag(top) = LUA_T_NUMBER; nvalue(top) = w;
    incr_top;
   }
   goto *table[*pc++];

   pushfloat:
   {
    real num;
    get_float(num,pc);
    tag(top) = LUA_T_NUMBER; nvalue(top) = num;
    incr_top;
   }
   goto *table[*pc++];

   pushstring:
   {
    Word w;
    get_word(w,pc);
    tag(top) = LUA_T_STRING; tsvalue(top) = lua_constant[w];
    incr_top;
   }
   goto *table[*pc++];

   pushfunction:
   {
    TFunc *f;
    get_code(f,pc);
    luaI_insertfunction(f);  /* may take part in GC */
    top->tag = LUA_T_FUNCTION;
    top->value.tf = f;
    incr_top;
   }
   goto *table[*pc++];

   pushlocal0: pushlocal1: pushlocal2:
   pushlocal3: pushlocal4: pushlocal5:
   pushlocal6: pushlocal7: pushlocal8:
   pushlocal9: 
     *top = *((stack+base) + (int)(((OpCode)*(pc-1))-PUSHLOCAL0)); incr_top; goto *table[*pc++];

   pushlocal: *top = *((stack+base) + (*pc++)); incr_top; goto *table[*pc++];

   pushglobal:
   {
    Word w;
    get_word(w,pc);
    getglobal(w);
   }
   goto *table[*pc++];

   pushindexed:
    pushsubscript();
    goto *table[*pc++];

   pushself:
   {
     Object receiver = *(top-1);
     Word w;
     get_word(w,pc);
     tag(top) = LUA_T_STRING; tsvalue(top) = lua_constant[w];
     incr_top;
     pushsubscript();
     *top = receiver;
     incr_top;
     goto *table[*pc++];
   }

   storelocal0: storelocal1: storelocal2:
   storelocal3: storelocal4: storelocal5:
   storelocal6: storelocal7: storelocal8:
   storelocal9:
     *((stack+base) + (int)(((OpCode)*(pc-1))-STORELOCAL0)) = *(--top);
     goto *table[*pc++];

   storelocal: *((stack+base) + (*pc++)) = *(--top); goto *table[*pc++];

   storeglobal:
   {
    Word w;
    get_word(w,pc);
    s_object(w) = *(--top);
   }
   goto *table[*pc++];

   storeindexed0:
    storesubscript();
    goto *table[*pc++];

   storeindexed:
   {
    int n = *pc++;
    if (tag(top-3-n) != LUA_T_ARRAY)
    {
      lua_checkstack(top+2);
      *(top+1) = *(top-1);
      *(top) = *(top-2-n);
      *(top-1) = *(top-3-n);
      top += 2;
      callFB(FB_SETTABLE);
    }
    else
    {
     Object *h = lua_hashdefine (avalue(top-3-n), top-2-n);
     *h = *(top-1);
     top--;
    }
   }
   goto *table[*pc++];

   storelist0:
   storelist:
   {
    int m, n;
    Object *arr;
    if (((OpCode)*(pc-1)) == STORELIST0) m = 0;
    else m = *(pc++) * FIELDS_PER_FLUSH;
    n = *(pc++);
    arr = top-n-1;
    while (n)
    {
     tag(top) = LUA_T_NUMBER; nvalue(top) = n+m;
     *(lua_hashdefine (avalue(arr), top)) = *(top-1);
     top--;
     n--;
    }
   }
   goto *table[*pc++];

   storerecord:
   {
    int n = *(pc++);
    Object *arr = top-n-1;
    while (n)
    {
     Word w;
     get_word(w,pc);
     tag(top) = LUA_T_STRING; tsvalue(top) = lua_constant[w];
     *(lua_hashdefine (avalue(arr), top)) = *(top-1);
     top--;
     n--;
    }
   }
   goto *table[*pc++];

   adjust0:
     adjust_top(base);
     goto *table[*pc++];

   adjust:
     adjust_top(base + *(pc++));
     goto *table[*pc++];

   varargs:
     adjust_varargs(base + *(pc++));
     goto *table[*pc++];

   createarray:
   {
    Word size;
    get_word(size,pc);
    avalue(top) = lua_createarray(size);
    tag(top) = LUA_T_ARRAY;
    incr_top;
   }
   goto *table[*pc++];

   eqop:
   {
    int res = lua_equalObj(top-2, top-1);
    --top;
    tag(top-1) = res ? LUA_T_NUMBER : LUA_T_NIL;
    nvalue(top-1) = 1;
   }
   goto *table[*pc++];

    ltop:
      comparison(LUA_T_NUMBER, LUA_T_NIL, LUA_T_NIL, "lt");
      goto *table[*pc++];

   leop:
      comparison(LUA_T_NUMBER, LUA_T_NUMBER, LUA_T_NIL, "le");
      goto *table[*pc++];

   gtop:
      comparison(LUA_T_NIL, LUA_T_NIL, LUA_T_NUMBER, "gt");
      goto *table[*pc++];

   geop:
      comparison(LUA_T_NIL, LUA_T_NUMBER, LUA_T_NUMBER, "ge");
      goto *table[*pc++];

   addop:
   {
    Object *l = top-2;
    Object *r = top-1;
    if (tonumber(r) || tonumber(l))
      call_arith("add");
    else
    {
      nvalue(l) += nvalue(r);
      --top;
    }
   }
   goto *table[*pc++];

   subop:
   {
    Object *l = top-2;
    Object *r = top-1;
    if (tonumber(r) || tonumber(l))
      call_arith("sub");
    else
    {
      nvalue(l) -= nvalue(r);
      --top;
    }
   }
   goto *table[*pc++];

   multop:
   {
    Object *l = top-2;
    Object *r = top-1;
    if (tonumber(r) || tonumber(l))
      call_arith("mul");
    else
    {
      nvalue(l) *= nvalue(r);
      --top;
    }
   }
   goto *table[*pc++];

   divop:
   {
    Object *l = top-2;
    Object *r = top-1;
    if (tonumber(r) || tonumber(l))
      call_arith("div");
    else
    {
      nvalue(l) /= nvalue(r);
      --top;
    }
   }
   goto *table[*pc++];

   powop:
    call_arith("pow");
    goto *table[*pc++];

   concop:
   {
    Object *l = top-2;
    Object *r = top-1;
    if (tostring(r) || tostring(l))
      callFB(FB_CONCAT);
    else
    {
      tsvalue(l) = lua_createstring (lua_strconc(svalue(l),svalue(r)));
      --top;
    }
   }
   goto *table[*pc++];

   minusop:
    if (tonumber(top-1))
    {
      tag(top) = LUA_T_NIL;
      incr_top;
      call_arith("unm");
    }
    else
      nvalue(top-1) = - nvalue(top-1);
   goto *table[*pc++];

   notop:
    tag(top-1) = (tag(top-1) == LUA_T_NIL) ? LUA_T_NUMBER : LUA_T_NIL;
    nvalue(top-1) = 1;
   goto *table[*pc++];

   ontjmp:
   {
    Word w;
    get_word(w,pc);
    if (tag(top-1) != LUA_T_NIL) pc += w;
   }
   goto *table[*pc++];

   onfjmp:
   {
    Word w;
    get_word(w,pc);
    if (tag(top-1) == LUA_T_NIL) pc += w;
   }
   goto *table[*pc++];

   jmp:
   {
    Word w;
    get_word(w,pc);
    pc += w;
   }
   goto *table[*pc++];

   upjmp:
   {
    Word w;
    get_word(w,pc);
    pc -= w;
   }
   goto *table[*pc++];

   iffjmp:
   {
    Word w;
    get_word(w,pc);
    top--;
    if (tag(top) == LUA_T_NIL) pc += w;
   }
   goto *table[*pc++];

   iffupjmp:
   {
    Word w;
    get_word(w,pc);
    top--;
    if (tag(top) == LUA_T_NIL) pc -= w;
   }
   goto *table[*pc++];

   pop: --top; goto *table[*pc++];

   callfunc:
   {
     int nParams = *(pc++);
     int nResults = *(pc++);
     StkId newBase = (top-stack)-nParams;
     do_call(newBase, nResults);
   }
   goto *table[*pc++];

   retcode0:
   retcode:
     if (lua_callhook)
       callHook (base, LUA_T_MARK, 1);
     return (base + ((((OpCode)*(pc-1))==RETCODE0) ? 0 : *pc));

   setline:
   {
    Word line;
    get_word(line,pc);
    if ((stack+base-1)->tag != LUA_T_LINE)
    {
      /* open space for LINE value */
      open_stack((top-stack)-base);
      base++;
      (stack+base-1)->tag = LUA_T_LINE;
    }
    (stack+base-1)->value.i = line;
    if (lua_linehook)
      lineHook (line);
    goto *table[*pc++];
   }


  lua_error ("internal error - opcode doesn't match");
}
Exemplo n.º 16
0
Arquivo: lvm.c Projeto: zapline/zlib
void luaV_concat (lua_State *L, int total, int last) {
  int useType = LUA_TSTRING;
  int i;
  StkId top = L->base + last + 1;

  for (i = 0; i < total; ++i)
  {
    if (ttype(top-1-i) == LUA_TSTRING || ttype(top-1-i) == LUA_TWSTRING)
    {
      useType = ttype(top-1-i);
      break;
    }
  }

  if (useType == LUA_TSTRING)
  {
    do {
      StkId top = L->base + last + 1;
      int n = 2;  /* number of elements handled in this pass (at least 2) */
      if (!tostring(L, top-2) || !tostring(L, top-1)) {
        if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT))
          luaG_concaterror(L, top-2, top-1);
      } else if (tsvalue(top-1)->len > 0) {  /* if len=0, do nothing */
        /* at least two string values; get as many as possible */
        size_t tl = tsvalue(top-1)->len;
        char *buffer;
        int i;
        /* collect total length */
        for (n = 1; n < total && tostring(L, top-n-1); n++) {
          size_t l = tsvalue(top-n-1)->len;
          if (l >= MAX_SIZET - tl) luaG_runerror(L, "string length overflow");
          tl += l;
        }
        buffer = luaZ_openspace(L, &G(L)->buff, tl);
        tl = 0;
        for (i=n; i>0; i--) {  /* concat all strings */
          size_t l = tsvalue(top-i)->len;
          memcpy(buffer+tl, svalue(top-i), l);
          tl += l;
#if LUA_REFCOUNT
          luarc_cleanvalue(top-i);
#endif /* LUA_REFCOUNT */
        }
        setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl));
      }
      total -= n-1;  /* got `n' strings to create 1 new */
      last -= n-1;
    } while (total > 1);  /* repeat until only 1 result left */
  } else {
    do {
      StkId top = L->base + last + 1;
      int n = 2;  /* number of elements handled in this pass (at least 2) */
      if (!towstring(L, top-2) || !towstring(L, top-1)) {
        if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT))
          luaG_concaterror(L, top-2, top-1);
      } else if (tsvalue(top-1)->len > 0) {  /* if len=0, do nothing */
        /* at least two string values; get as many as possible */
        size_t tl = tsvalue(top-1)->len;
        char *buffer;
        int i;
        /* collect total length */
        for (n = 1; n < total && towstring(L, top-n-1); n++) {
          size_t l = tsvalue(top-n-1)->len;
          if (l >= MAX_SIZET - tl) luaG_runerror(L, "string length overflow");
          tl += l;
        }
        buffer = luaZ_openspace(L, &G(L)->buff, tl*2);
        tl = 0;
        for (i=n; i>0; i--) {  /* concat all strings */
          size_t l = tsvalue(top-i)->len;
          memcpy(buffer+tl*2, wsvalue(top-i), l*2);
          tl += l;
#if LUA_REFCOUNT
          luarc_cleanvalue(top-i);
#endif /* LUA_REFCOUNT */
        }
        setwsvalue2s(L, top-n, luaS_newlwstr(L, (const lua_WChar*)buffer, tl));
      }
      total -= n-1;  /* got `n' strings to create 1 new */
      last -= n-1;
    } while (total > 1);  /* repeat until only 1 result left */
  }
}
Exemplo n.º 17
0
const char *lua_getstring (lua_Object object) {
	if (object == LUA_NOOBJECT || tostring(Address(object)))
		return nullptr;
	else
		return (svalue(Address(object)));
}
Exemplo n.º 18
0
LUA_API const char *lua_tostring (lua_State *L, int index) {
  StkId o = luaA_indexAcceptable(L, index);
  return (o == NULL || tostring(L, o)) ? NULL : svalue(o);
}
Exemplo n.º 19
0
/* this function handles only `%d', `%c', %f, %p, and `%s' formats
   and now it handles %x and %X as well */
const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp)
{
#if LUAXS_CORE_FORMAT == 2
    size_t alloclen = _vscprintf(fmt, argp) + 1;
    char* buf = luaM_malloc(L, alloclen);
    vsprintf_s(buf, alloclen, fmt, argp);
    pushstr(L, buf);
    luaM_freemem(L, buf, alloclen);
    return svalue(L->top - 1);
#else
    int n = 1;
    pushstr(L, "");
    for (;;) {
        const char *e = strchr(fmt, '%');
        if (e == NULL) break;
        setsvalue2s(L, L-&gt;top, luaS_newlstr(L, fmt, e-fmt));
        incr_top(L);
        switch (*(e+1)) {
        case 's': {
            const char *s = va_arg(argp, char *);
            if (s == NULL) s = "(null)";
            pushstr(L, s);
            break;
            }
        case 'c': {
            char buff[2];
            buff[0] = cast(char, va_arg(argp, int));
            buff[1] = '\0';
            pushstr(L, buff);
            break;
            }
        case 'd': {
            setnvalue(L-&gt;top, cast_num(va_arg(argp, int)));
            incr_top(L);
            break;
            }
        case 'f': {
            setnvalue(L-&gt;top, cast_num(va_arg(argp, l_uacNumber)));
            incr_top(L);
            break;
            }
        case 'p': {
            char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */
            sprintf(buff, "%p", va_arg(argp, void *));
            pushstr(L, buff);
            break;
            }
#if LUAXS_CORE_FORMAT == 1
        case 'X': {
            char buff[sizeof(int)*2+3];
            sprintf(buff, "%X", va_arg(argp, int));
            pushstr(L, buff);
            break;
            }
        case 'x': {
            char buff[sizeof(int)*2+3];
            sprintf(buff, "%x", va_arg(argp, int));
            pushstr(L, buff);
            break;
            }
#endif
        case '%': {
            pushstr(L, "%");
            break;
            }
        default: {
            char buff[3];
            buff[0] = '%';
            buff[1] = *(e+1);
            buff[2] = '\0';
            pushstr(L, buff);
            break;
            }
        }
        n += 2;
        fmt = e+2;
    }
    pushstr(L, fmt);
    luaV_concat(L, n+1, cast_int(L-&gt;top - L-&gt;base) - 1);
    L-&gt;top -= n;
    return svalue(L-&gt;top - 1);
#endif
}
Exemplo n.º 20
0
static void PrintCode(const Proto* f)
{
    const Instruction* code=f->code;
    int pc,n=f->sizecode;
    for (pc=0; pc<n; pc++)
    {
        Instruction i=code[pc];
        OpCode o=GET_OPCODE(i);
        int a=GETARG_A(i);
        int b=GETARG_B(i);
        int c=GETARG_C(i);
        int bc=GETARG_Bx(i);
        int sbc=GETARG_sBx(i);
        int line=getline(f,pc);
#if 0
        printf("%0*lX",Sizeof(i)*2,i);
#endif
        printf("\t%d\t",pc+1);
        if (line>0) printf("[%d]\t",line);
        else printf("[-]\t");
        printf("%-9s\t",luaP_opnames[o]);
        switch (getOpMode(o))
        {
        case iABC:
            printf("%d %d %d",a,b,c);
            break;
        case iABx:
            printf("%d %d",a,bc);
            break;
        case iAsBx:
            printf("%d %d",a,sbc);
            break;
        }
        switch (o)
        {
        case OP_LOADK:
            printf("\t; ");
            PrintConstant(f,bc);
            break;
        case OP_GETUPVAL:
        case OP_SETUPVAL:
            printf("\t; %s", (f->sizeupvalues>0) ? getstr(f->upvalues[b]) : "-");
            break;
        case OP_GETGLOBAL:
        case OP_SETGLOBAL:
            printf("\t; %s",svalue(&f->k[bc]));
            break;
        case OP_GETTABLE:
        case OP_SELF:
            if (c>=MAXSTACK) {
                printf("\t; ");
                PrintConstant(f,c-MAXSTACK);
            }
            break;
        case OP_SETTABLE:
        case OP_ADD:
        case OP_SUB:
        case OP_MUL:
        case OP_DIV:
        case OP_POW:
        case OP_EQ:
        case OP_LT:
        case OP_LE:
            if (b>=MAXSTACK || c>=MAXSTACK)
            {
                printf("\t; ");
                if (b>=MAXSTACK) PrintConstant(f,b-MAXSTACK);
                else printf("-");
                printf(" ");
                if (c>=MAXSTACK) PrintConstant(f,c-MAXSTACK);
            }
            break;
        case OP_JMP:
        case OP_FORLOOP:
        case OP_TFORPREP:
            printf("\t; to %d",sbc+pc+2);
            break;
        case OP_CLOSURE:
            printf("\t; %p",VOID(f->p[bc]));
            break;
        default:
            break;
        }
        printf("\n");
    }
}
Exemplo n.º 21
0
int kp_strfmt(ktap_state *ks, struct trace_seq *seq)
{
	int arg = 1;
	size_t sfl;
	ktap_value *arg_fmt = kp_arg(ks, 1);
	int argnum = kp_arg_nr(ks);
	const char *strfrmt, *strfrmt_end;

	strfrmt = svalue(arg_fmt);
	sfl = rawtsvalue(arg_fmt)->tsv.len;
	strfrmt_end = strfrmt + sfl;

	while (strfrmt < strfrmt_end) {
		if (*strfrmt != L_ESC)
			trace_seq_putc(seq, *strfrmt++);
		else if (*++strfrmt == L_ESC)
			trace_seq_putc(seq, *strfrmt++);
		else { /* format item */
			char form[MAX_FORMAT];

			if (++arg > argnum) {
				ktap_argerror(ks, arg, "no value");
				return -1;
			}

			strfrmt = scanformat(ks, strfrmt, form);
			switch (*strfrmt++) {
			case 'c':
				trace_seq_printf(seq, form,
						 nvalue(kp_arg(ks, arg)));
				break;
			case 'd':  case 'i': {
				ktap_number n = nvalue(kp_arg(ks, arg));
				INTFRM_T ni = (INTFRM_T)n;
				addlenmod(form, INTFRMLEN);
				trace_seq_printf(seq, form, ni);
				break;
			}
			case 'p': {
				char str[KSYM_SYMBOL_LEN];
				SPRINT_SYMBOL(str, nvalue(kp_arg(ks, arg)));
				trace_seq_puts(seq, str);
				break;
			}
			case 'o':  case 'u':  case 'x':  case 'X': {
				ktap_number n = nvalue(kp_arg(ks, arg));
				unsigned INTFRM_T ni = (unsigned INTFRM_T)n;
				addlenmod(form, INTFRMLEN);
				trace_seq_printf(seq, form, ni);
				break;
			}
			case 's': {
				ktap_value *v = kp_arg(ks, arg);
				const char *s;
				size_t l;

				if (isnil(v)) {
					trace_seq_puts(seq, "nil");
					return 0;
				}

				if (ttisevent(v)) {
					kp_event_tostring(ks, seq);
					return 0;
				}

				s = svalue(v);
				l = rawtsvalue(v)->tsv.len;
				if (!strchr(form, '.') && l >= 100) {
					/*
					 * no precision and string is too long
					 * to be formatted;
					 * keep original string
					 */
					trace_seq_puts(seq, s);
					break;
				} else {
					trace_seq_printf(seq, form, s);
					break;
				}
			}
			default: /* also treat cases `pnLlh' */
				kp_error(ks, "invalid option " KTAP_QL("%%%c")
					     " to " KTAP_QL("format"),
					     *(strfrmt - 1));
			}
		}
	}

	return 0;
}
Exemplo n.º 22
0
// Scan for a series of assignments
void Decompiler::do_multi_assign(Byte *&start) {
  std::queue<Expression *> results;
  ExprStack values;

  bool done;
  int num_tables = 0;
  do {
    int aux, opc;
    done = false;

    opc = *start++;
    switch (opc) {
    case SETLOCAL:
      aux = *start++;
      goto setlocal;

    case SETLOCAL0:
    case SETLOCAL1:
    case SETLOCAL2:
    case SETLOCAL3:
    case SETLOCAL4:
    case SETLOCAL5:
    case SETLOCAL6:
    case SETLOCAL7:
      aux = opc - SETLOCAL0;
    setlocal:
      results.push(new VarExpr(start, localname(tf, aux)));
      break;

    case SETGLOBAL:
      aux = *start++;
      goto setglobal;

    case SETGLOBAL0:
    case SETGLOBAL1:
    case SETGLOBAL2:
    case SETGLOBAL3:
    case SETGLOBAL4:
    case SETGLOBAL5:
    case SETGLOBAL6:
    case SETGLOBAL7:
      aux = opc - SETGLOBAL0;
      goto setglobal;

    case SETGLOBALW:
      aux = start[0] | (start[1] << 8);
      start += 2;
    setglobal:
      results.push(new VarExpr(start, svalue(tf->consts + aux)));
      break;

    case SETTABLE:
      start++;			// assume offset is correct
      num_tables++;
      // this needs stuff from farther up the stack, wait until
      // it's available

    case SETTABLE0:
      results.push(new IndexExpr(start, NULL, NULL));
      break;

    default:
      start--;
      done = true;
    }

    if (! done) {
      Expression *e = stk->top();
      // Check for fake result from function calls with multiple return values
      VarExpr *v = dynamic_cast<VarExpr *>(e);
      if (v != NULL && v->name == "<extra result>")
	delete e;
      else
	values.push(e);
      stk->pop();
    }
  } while (! done);

  // Check for popping tables and indices
  if (num_tables > 0 && (*start == POP || *start == POP0 || *start == POP1)) {
    start++;
    if (start[-1] == POP)
      start++;
  }

  // Now get actual tables and indices from the stack, reversing
  // the list to the right order at the same time

  ExprStack results2;
  while (! results.empty()) {
    Expression *var = results.front(); results.pop();
    IndexExpr *tbl = dynamic_cast<IndexExpr *>(var);
    if (tbl != NULL) {
      tbl->index = stk->top(); stk->pop();
      tbl->table = stk->top(); stk->pop();
    }
    results2.push(var);
  }

  *os << indent_str;
  while (! results2.empty()) {
    Expression *var = results2.top(); results2.pop();
    *os << *var;
    delete var;
    if (! results2.empty())
      *os << ", ";
  }
  *os << " = ";
  while (! values.empty()) {
    Expression *val = values.top(); values.pop();
    *os << *val;
    delete val;
    if (! values.empty())
      *os << ", ";
  }
  *os << std::endl;
}
Exemplo n.º 23
0
void AFXAPI DDX_Text(CDataExchange* pDX, int nIDC, CDWordArray& avalue)
{
	HWND hWndCtrl = pDX->PrepareEditCtrl(nIDC);
	CString value;

	if (pDX->m_bSaveAndValidate)
	{
		int nLen = ::GetWindowTextLength(hWndCtrl);
		::GetWindowText(hWndCtrl, value.GetBufferSetLength(nLen), nLen+1);
		value.ReleaseBuffer();

		//all this loop should be replaced by a regular expression search engine
		std::string svalue(value);

		int idata1,idata2=0;
		int index=0;
		WORD first,last;
		bool bFlag;

		do{

			bFlag=false;

			do{
				idata1=svalue.find_first_of("0123456789",idata2);
				first=svalue[idata1]-'0';

				if(idata1==std::string::npos){
					break;
				}

				idata1=svalue.find_first_of("-",idata1);

				if(idata1==std::string::npos){
					break;
				}

				idata1=svalue.find_first_of("0123456789",idata1);
				last=svalue[idata1]-'0';

				if(idata1==std::string::npos){
					break;
				}

				if(idata1-idata2>2){
					break;
				}

				avalue.Add(MAKELONG(first,last));

				idata2+=3;

				bFlag=true;

			}while(0);

			do{
				idata1=svalue.find_first_of("0123456789",idata2);
				first=svalue[idata1]-'0';

				if(idata1==std::string::npos){
					break;
				}

				idata1=svalue.find_first_of(",",idata1);

				if(idata1==std::string::npos){
					break;
				}

				if(idata1-idata2>1){
					break;
				}

				avalue.Add(MAKELONG(first,first));

				idata2+=2;

				bFlag=true;

			}while(0);

		}while(bFlag);
	}
	else
	{
		//AfxSetWindowText(hWndCtrl, value);
	}

}
Exemplo n.º 24
0
/*
** try to convert a value to an integer, rounding according to 'mode':
** mode == 0: accepts only integral values
** mode == 1: takes the floor of the number
** mode == 2: takes the ceil of the number
*/
int luaV_tointeger (const TValue *obj, lua_Integer *p, int mode) {
  TValue v;
 again:
#ifndef _KERNEL
  if (ttisfloat(obj)) {
    lua_Number n = fltvalue(obj);
    lua_Number f = l_floor(n);
    if (n != f) {  /* not an integral value? */
      if (mode == 0) return 0;  /* fails if mode demands integral value */
      else if (mode > 1)  /* needs ceil? */
        f += 1;  /* convert floor to ceil (remember: n != f) */
    }
    return lua_numbertointeger(f, p);
  }
  else if (ttisinteger(obj)) {
#else /* _KERNEL */
  if (ttisinteger(obj)) {
    UNUSED(mode);
#endif
    *p = ivalue(obj);
    return 1;
  }
  else if (cvt2num(obj) &&
            luaO_str2num(svalue(obj), &v) == vslen(obj) + 1) {
    obj = &v;
    goto again;  /* convert result from 'luaO_str2num' to an integer */
  }
  return 0;  /* conversion failed */
}


#ifndef _KERNEL
/*
** Try to convert a 'for' limit to an integer, preserving the
** semantics of the loop.
** (The following explanation assumes a non-negative step; it is valid
** for negative steps mutatis mutandis.)
** If the limit can be converted to an integer, rounding down, that is
** it.
** Otherwise, check whether the limit can be converted to a number.  If
** the number is too large, it is OK to set the limit as LUA_MAXINTEGER,
** which means no limit.  If the number is too negative, the loop
** should not run, because any initial integer value is larger than the
** limit. So, it sets the limit to LUA_MININTEGER. 'stopnow' corrects
** the extreme case when the initial value is LUA_MININTEGER, in which
** case the LUA_MININTEGER limit would still run the loop once.
*/
static int forlimit (const TValue *obj, lua_Integer *p, lua_Integer step,
                     int *stopnow) {
  *stopnow = 0;  /* usually, let loops run */
  if (!luaV_tointeger(obj, p, (step < 0 ? 2 : 1))) {  /* not fit in integer? */
    lua_Number n;  /* try to convert to float */
    if (!tonumber(obj, &n)) /* cannot convert to float? */
      return 0;  /* not a number */
    if (luai_numlt(0, n)) {  /* if true, float is larger than max integer */
      *p = LUA_MAXINTEGER;
      if (step < 0) *stopnow = 1;
    }
    else {  /* float is smaller than min integer */
      *p = LUA_MININTEGER;
      if (step >= 0) *stopnow = 1;
    }
  }
  return 1;
}
Exemplo n.º 25
0
fileinit()
{
	register char *p;
	register int i, j;
	struct stat stbuf;

	if (tline == INCRMT * (HBLKS+2))
		return;
	cleanup(0);
	if (tfile >= 0)
		close(tfile);
	tline = INCRMT * (HBLKS+2);
	blocks[0] = HBLKS;
	blocks[1] = HBLKS+1;
	blocks[2] = -1;
	dirtcnt = 0;
	iblock = -1;
	iblock2 = -1;
	oblock = -1;
	CP(tfname, svalue(DIRECTORY));
#ifndef vms
	if (stat(tfname, &stbuf))
#else
	goto vms_no_check_dir;
#endif
	{
dumbness:
		if (setexit() == 0)
			filioerr(tfname);
		else
			putNFL();
		cleanup(1);
		ex_exit(1);
	}
#ifndef	vms
	if ((stbuf.st_mode & S_IFMT) != S_IFDIR) {
		errno = ENOTDIR;
		goto dumbness;
	}
#else
vms_no_check_dir:
#endif
	ichanged = 0;
	ichang2 = 0;
#ifndef	vms
	ignore(strcat(tfname, "/ExXXXXX"));
#else
	ignore(strcat(tfname, "ExXXXXX"));
#endif
	for (p = strend(tfname), i = 5, j = getpid(); i > 0; i--, j /= 10)
		*--p = j % 10 | '0';
#ifdef vms
	ignore(strcat(tfname, ".txt.1"));
	unlink(tfname);
#endif
	tfile = creat(tfname, 0600);
	if (tfile < 0)
		goto dumbness;
#ifdef VMUNIX
	{
		extern stilinc;		/* see below */
		stilinc = 0;
	}
#endif
	havetmp = 1;
	if (tfile >= 0)
		close(tfile);
	tfile = open(tfname, 2);
	if (tfile < 0)
		goto dumbness;
#ifdef UNIX_SBRK
/* 	brk((char *)fendcore); */
#endif
}