1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
|
/*****
* stack.cc
* Andy Hammerlindl 2002/06/27
*
* The general stack machine used to run compiled camp code.
*****/
#include <fstream>
#include <sstream>
#include "stack.h"
#include "program.h"
#include "callable.h"
#include "errormsg.h"
#include "util.h"
#include "runtime.h"
#include "asyprocess.h"
#include "profiler.h"
#ifdef DEBUG_STACK
#include <iostream>
namespace vm {
void draw(ostream& out, vmFrame *v);
}
#endif
namespace run {
void breakpoint(vm::stack *Stack, absyntax::runnable *r);
}
namespace vm {
const char *dereferenceNullPointer="dereference of null pointer";
mem::list<bpinfo> bplist;
namespace {
position curPos = nullPos;
const program::label nulllabel;
}
inline stack::vars_t base_frame(
size_t size,
size_t parentIndex,
stack::vars_t closure
#ifdef DEBUG_FRAME
, string name
#endif
)
{
stack::vars_t vars;
#ifdef SIMPLE_FRAME
vars = new item[size];
vars[parentIndex] = closure;
#else
# ifdef DEBUG_FRAME
assert(!name.empty());
vars = new vmFrame(name, parentIndex, size);
# else
vars = new vmFrame(size);
# endif
(*vars)[parentIndex] = closure;
#endif
// TODO: Re-factor closure.
return vars;
}
#ifdef DEBUG_FRAME
#define BASEFRAME(s,p,c,n) (base_frame((s), (p), (c), (n)))
#else
#define BASEFRAME(s,p,c,n) (base_frame((s), (p), (c)))
#endif
// Abstractions needed.
//accessor(frame_handle)
// operator[] for accessor
inline stack::vars_t make_frame(lambda *l, stack::vars_t closure)
{
return BASEFRAME(l->framesize, l->parentIndex, closure, l->name);
}
inline stack::vars_t make_pushframe(size_t size, stack::vars_t closure)
{
assert(size >= 1);
return BASEFRAME(size, 0, closure, "<pushed frame>");
}
stack::vars_t make_dummyframe(string name)
{
return BASEFRAME(1, 0, 0, "<dummy frame for "+name+">");
}
inline stack::vars_t make_globalframe(size_t size)
{
assert(size > 0);
#ifdef SIMPLE_FRAME
// The global frame is an indirect frame. It holds one item, which is the
// link to another frame.
stack::vars_t direct = new item[1];
stack::vars_t indirect = new item[size];
direct[0] = indirect;
return direct;
#else
return BASEFRAME(size, 0, 0, "<globals>");
#if 0
#ifdef DEBUG_FRAME
stack::vars_t vars = new frame("<pushed frame>", 0, size);
#else
stack::vars_t vars = new frame(size);
#endif
return vars;
#endif
#endif
}
inline void resize_frame(vmFrame *f, size_t oldsize, size_t newsize)
{
//assert("Need to fix this" == 0);
assert(newsize > oldsize);
#ifdef SIMPLE_FRAME
vmFrame *old_indirect = get<vmFrame *>(f[0]);
vmFrame *new_indirect = new item[newsize];
std::copy(old_indirect, old_indirect+oldsize, new_indirect);
f[0] = new_indirect;
#else
f->extend(newsize);
#endif
}
void run(lambda *l)
{
func f;
f.body = l;
stack s;
s.run(&f);
}
// Move arguments from stack to frame.
void stack::marshall(size_t args, stack::vars_t vars)
{
for (size_t i = args; i > 0; --i) {
# ifdef SIMPLE_FRAME
vars[i-1] = pop();
# else
(*vars)[i-1] = pop();
# endif
}
}
#ifdef PROFILE
#ifndef DEBUG_FRAME
#pragma message("WARNING: profiler needs DEBUG_FRAME for function names")
#endif
#ifndef DEBUG_BLTIN
#pragma message("WARNING: profiler needs DEBUG_BLTIN for builtin function names")
#endif
profiler prof;
void dumpProfile() {
std::ofstream out("asyprof");
if (!out.fail())
prof.dump(out);
}
#endif
void assessClosure(lambda *body) {
// If we have already determined if it needs closure, just return.
if (body->closureReq != lambda::MAYBE_NEEDS_CLOSURE)
return;
for (program::label l = body->code->begin(); l != body->code->end(); ++l)
if (l->op == inst::pushclosure ||
l->op == inst::pushframe) {
body->closureReq = lambda::NEEDS_CLOSURE;
return;
}
body->closureReq = lambda::DOESNT_NEED_CLOSURE;
}
void stack::run(func *f)
{
lambda *body = f->body;
#ifdef PROFILE
prof.beginFunction(body);
#endif
#ifdef DEBUG_STACK
#ifdef DEBUG_FRAME
cout << "running lambda " + body->name + ": \n";
#else
cout << "running lambda: \n";
#endif
print(cout, body->code);
cout << endl;
#endif
runWithOrWithoutClosure(body, 0, f->closure);
#ifdef PROFILE
prof.endFunction(body);
#endif
}
void stack::breakpoint(absyntax::runnable *r)
{
lastPos=curPos;
indebugger=true;
::run::breakpoint(this,r);
string s=vm::pop<string>(this);
debugOp=(s.length() > 0) ? s[0] : (char) 0;
indebugger=false;
}
void stack::debug()
{
if(!curPos) return;
if(indebugger) {em.clear(); return;}
switch(debugOp) {
case 'i': // inst
breakpoint();
break;
case 's': // step
if((!curPos.match(lastPos.filename()) || !curPos.match(lastPos.Line())))
breakpoint();
break;
case 'n': // next
if(curPos.match(lastPos.filename()) && !curPos.match(lastPos.Line()))
breakpoint();
break;
case 'f': // file
if(!curPos.match(lastPos.filename()))
breakpoint();
break;
case 'r': // return
if(curPos.match(breakPos.filename()))
breakpoint();
break;
case 'c': // continue
default:
for(auto p=bplist.begin(); p != bplist.end(); ++p) {
if(curPos.match(p->f.name()) && curPos.match(p->f.line()) &&
(newline || !curPos.match(breakPos.filename()) ||
!curPos.match(breakPos.Line()))) {
breakPos=curPos;
breakpoint(p->r);
newline=false;
break;
}
if(!newline &&
(curPos.match(lastPos.filename()) && !curPos.match(lastPos.Line())))
newline=true;
}
break;
}
}
void stack::runWithOrWithoutClosure(lambda *l, vars_t vars, vars_t parent)
{
// The size of the frame (when running without closure).
size_t frameSize = l->parentIndex;
#ifdef SIMPLE_FRAME
// Link to the variables, be they in a closure or on the stack.
vmFrame *varlink;
# define SET_VARLINK assert(vars); varlink = vars;
# define VAR(n) ( (varlink)[(n) + frameStart] )
# define FRAMEVAR(frame,n) (frame[(n)])
#else
// Link to the variables, be they in a closure or on the stack.
mem::vector<item> *varlink=NULL;
# define SET_VARLINK assert(vars); varlink = &vars->vars
# define VAR(n) ( (*varlink)[(n) + frameStart] )
# define FRAMEVAR(frame,n) ((*frame)[(n)])
#endif
size_t frameStart = 0;
// Set up the closure, if necessary.
if (vars == 0)
{
#ifndef SIMPLE_FRAME
assessClosure(l);
if (l->closureReq == lambda::NEEDS_CLOSURE)
#endif
{
/* make new activation record */
vars = vm::make_frame(l, parent);
assert(vars);
}
#ifndef SIMPLE_FRAME
else
{
assert(l->closureReq == lambda::DOESNT_NEED_CLOSURE);
// Use the stack to store variables.
varlink = &theStack;
// Record where the parameters start on the stack.
frameStart = theStack.size() - frameSize;
// Add the parent's closure to the frame.
push(parent);
++frameSize;
size_t newFrameSize = (size_t)l->framesize;
if (newFrameSize > frameSize) {
theStack.resize(frameStart + newFrameSize);
frameSize = newFrameSize;
}
}
#endif
}
if (vars) {
marshall(l->parentIndex, vars);
SET_VARLINK;
}
/* start the new function */
program::label ip = l->code->begin();
processDataStruct& P=processData();
position& topPos=P.topPos;
string& fileName=P.fileName;
unsigned int offset=P.xmapCount;
bool traceless=!settings::debug;
bool xasy=settings::xasy || offset || settings::keys;
if(xasy && curPos.filename() == fileName)
topPos=curPos.shift(offset);
try {
for (;;) {
const inst &i = *ip;
curPos = i.pos;
#ifdef PROFILE
prof.recordInstruction();
#endif
#ifdef DEBUG_STACK
printInst(cout, ip, l->code->begin());
cout << " (";
i.pos.printTerse(cout);
cout << ")\n";
#endif
if(settings::verbose > 4) em.trace(curPos);
if(!bplist.empty()) debug();
if(errorstream::interrupt) throw interrupted();
switch (i.op)
{
case inst::varpush:
push(VAR(get<Int>(i)));
break;
case inst::varsave:
VAR(get<Int>(i)) = top();
break;
#ifdef COMBO
case inst::varpop:
VAR(get<Int>(i)) = pop();
break;
#endif
case inst::ret: {
if (vars == 0)
// Delete the frame from the stack.
// TODO: Optimize for common cases.
theStack.erase(theStack.begin() + frameStart,
theStack.begin() + frameStart + frameSize);
return;
}
case inst::pushframe:
{
assert(vars);
Int size = get<Int>(i);
vars=make_pushframe(size, vars);
SET_VARLINK;
break;
}
case inst::popframe:
{
assert(vars);
vars=get<vmFrame *>(VAR(0));
SET_VARLINK;
break;
}
case inst::pushclosure:
assert(vars);
push(vars);
break;
case inst::nop:
break;
case inst::pop:
pop();
break;
case inst::intpush:
case inst::constpush:
push(i.ref);
break;
case inst::fieldpush: {
vars_t frame = pop<vars_t>();
if (!frame)
error(dereferenceNullPointer);
push(FRAMEVAR(frame, get<Int>(i)));
break;
}
case inst::fieldsave: {
vars_t frame = pop<vars_t>();
if (!frame)
error(dereferenceNullPointer);
FRAMEVAR(frame, get<Int>(i)) = top();
break;
}
#if COMBO
case inst::fieldpop: {
#error NOT REIMPLEMENTED
vars_t frame = pop<vars_t>();
if (!frame)
error(dereferenceNullPointer);
FRAMEVAR(get<Int>(i)) = pop();
break;
}
#endif
case inst::builtin: {
bltin func = get<bltin>(i);
#ifdef PROFILE
prof.beginFunction(func);
#endif
func(this);
#ifdef PROFILE
prof.endFunction(func);
#endif
break;
}
case inst::jmp:
ip = get<program::label>(i);
continue;
case inst::cjmp:
if (pop<bool>()) { ip = get<program::label>(i); continue; }
break;
case inst::njmp:
if (!pop<bool>()) { ip = get<program::label>(i); continue; }
break;
case inst::jump_if_not_default:
if (!isdefault(pop())) { ip = get<program::label>(i); continue; }
break;
#ifdef COMBO
case inst::gejmp: {
Int y = pop<Int>();
Int x = pop<Int>();
if (x>=y)
{ ip = get<program::label>(i); continue; }
break;
}
#if 0
case inst::jump_if_func_eq: {
callable * b=pop<callable *>();
callable * a=pop<callable *>();
if (a->compare(b))
{ ip = get<program::label>(i); continue; }
break;
}
case inst::jump_if_func_neq: {
callable * b=pop<callable *>();
callable * a=pop<callable *>();
if (!a->compare(b))
{ ip = get<program::label>(i); continue; }
break;
}
#endif
#endif
case inst::push_default:
push(Default);
break;
case inst::popcall: {
/* get the function reference off of the stack */
if(xasy && curPos.filename() == fileName)
topPos=curPos.shift(offset);
callable* f = pop<callable*>();
if(traceless)
f->call(this);
else {
em.traceback.push_back(curPos);
f->call(this);
if(em.traceback.size())
em.traceback.pop_back();
}
break;
}
case inst::makefunc: {
func *f = new func;
f->closure = pop<vars_t>();
f->body = get<lambda*>(i);
push((callable*)f);
break;
}
default:
error("Internal VM error: Bad stack operand");
}
#ifdef DEBUG_STACK
draw(cerr);
vm::draw(cerr,vars);
cerr << "\n";
#endif
++ip;
}
} catch (bad_item_value&) {
error("Trying to use uninitialized value.");
}
#undef SET_VARLINK
#undef VAR
#undef FRAMEVAR
}
void stack::loadModule(string index, Int numPushedParents) {
vmFrame *inst=instMap[index];
if (inst) {
for (Int i = 0; i < numPushedParents; ++i) {
pop();
}
push(inst);
}
else {
func f;
assert(initMap);
f.body=(*initMap)[index];
assert(f.body);
run(&f);
instMap[index]=get<vmFrame *>(top());
}
}
#ifdef DEBUG_STACK
const size_t MAX_ITEMS=20;
void stack::draw(ostream& out)
{
// out.setf(out.hex);
out << "operands:";
stack_t::const_iterator left = theStack.begin();
if (theStack.size() > MAX_ITEMS) {
left = theStack.end()-MAX_ITEMS;
out << " ...";
}
else
out << " ";
while (left != theStack.end())
{
if (left != theStack.begin())
out << " | " ;
out << *left;
left++;
}
out << "\n";
}
void draw(ostream& out, vmFrame* v)
{
out << "vars:" << endl;
while (!!v) {
item link=(*v)[v->getParentIndex()];
out << " " << v->getName() << ": ";
for (size_t i = 0; i < MAX_ITEMS && i < v->size(); i++) {
if (i > 0)
out << " | ";
out << i << ": ";
if (i == v->getParentIndex()) {
try {
vmFrame *parent = get<vmFrame *>(link);
out << (parent ? "link" : "----");
} catch (bad_item_value&) {
out << "non-link " << (*v)[0];
}
} else {
out << (*v)[i];
}
}
if (v->size() > MAX_ITEMS)
out << "...";
out << "\n";
vmFrame *parent;
try {
parent = get<vmFrame *>(link);
} catch (bad_item_value&) {
parent = 0;
}
v = parent;
}
}
#endif // DEBUG_STACK
position getPos() {
return curPos;
}
void errornothrow(const char* message)
{
em.error(curPos);
em << message;
em.sync(true);
}
void error(const char* message)
{
errornothrow(message);
throw handled_error();
}
void error(const ostringstream& message)
{
const string& s=message.str();
error(s.c_str());
}
const size_t STARTING_GLOBALS_SIZE = 1;
interactiveStack::interactiveStack()
: globals(make_globalframe(STARTING_GLOBALS_SIZE)),
globals_size(STARTING_GLOBALS_SIZE) {}
void interactiveStack::run(lambda *codelet) {
if (globals_size < codelet->framesize) {
resize_frame(globals, globals_size, codelet->framesize);
globals_size = codelet->framesize;
}
stack::runWithOrWithoutClosure(codelet, globals, 0);
}
} // namespace vm
|