int main(int argc, char *argv[]) { char out_filename[256]; if (argc >= 2) { make_out_filename(out_filename, argv[1]); freopen(argv[1], "r", stdin); freopen(out_filename, "w", stdout); } puts("#include <stdio.h>"); puts("#include <stdlib.h>"); puts("#include <string.h>\n"); puts("typedef unsigned char byte;"); puts("static byte *ptr_start, *ptr_end, *ptr;\n"); puts("#define MEM_SIZE ( 32768 )"); puts("#ifdef NOCHECK"); puts("#define CHK(p) ( p )"); puts("#else"); puts("#define CHK(p) ( chk(p) )"); puts("static void chk(byte *p){"); puts(" if(p<ptr_start||ptr_end<=p){"); puts(" fprintf(stderr,\"Error: Memory Out Of Bounds.\\n\");"); puts(" exit(1);"); puts(" }"); puts("}"); puts("#endif\n"); puts("int main(int argc, char *argv[]){"); puts(" int i=1,mem_size=MEM_SIZE;"); puts(" for (; i < argc;){"); puts(" if (strcmp(argv[i], \"-m\") == 0){"); puts(" i++;"); puts(" if (i < argc) mem_size=atoi(argv[i++]);"); puts(" } else i++;"); puts(" }"); puts(" if (mem_size<1) mem_size=1;"); puts(" ptr_start=(byte *)calloc(mem_size, 1);"); puts(" ptr_end=ptr_start+mem_size;"); puts(" ptr=ptr_start;"); puts("/* -- translated code -- */"); emit_code(); while (g_indent_level > 0) { print_code("break;"); --g_indent_level; print_code("}"); fprintf(stderr, "Warning: Incorrect Nesting.\n"); } puts("/* -- end -- */"); puts(" putchar('\\n');"); puts(" free(ptr_start);"); puts(" return 0;"); puts("}\n"); return 0; }
static void emit_code(void) { int c, n, op, id, commented = 0; c = getchar(); while (c != EOF) { id = get_index_of("[]+-<>.,", c); if (commented && id != -1) { printf(" */\n"); commented = 0; } if (id == 0) { /* '[' */ print_code("for(;*ptr;){"); ++g_indent_level; c = getchar(); } else if (id == 1) { /* ']' */ if (--g_indent_level < 0) { fprintf(stderr, "Error: Extra ']' found.\n"); return; } print_code("}"); c = getchar(); } else if (2 <= id && id <= 5) { /* '+', '-', '<', '>' */ op = c; n = 0; for (;c == op; n++) c = getchar(); emit_ptr_arith(n, op); } else if (id == 6) { /* '.' */ print_code("putchar(*ptr);"); c = getchar(); } else if (id == 7) { /* ',' */ print_code("*ptr=getchar();"); c = getchar(); } else { /* others */ if (c != '\r' && c != '\n') { if (!commented) { printf("/* "); commented = 1; } putchar(c); } c = getchar(); } } }
int main() { enum xen_api_failure internal_error = xen_api_failure_from_string("INTERNAL_ERROR"); const char * handle_invalid = xen_api_failure_to_string(XEN_API_FAILURE_HANDLE_INVALID); assert(internal_error == XEN_API_FAILURE_INTERNAL_ERROR); assert(strcmp(handle_invalid, "HANDLE_INVALID") == 0); print_code(XEN_API_FAILURE_INTERNAL_ERROR, "INTERNAL_ERROR"); print_code(XEN_API_FAILURE_HANDLE_INVALID, handle_invalid); return 0; }
static void dowhile_test(){ quad_list code = create_quad_list(); add_to_code(code, create_full_quad(vardec, "int", "x", NULL)); add_to_code(code, create_full_quad(func_dec, "int", "main", NULL)); add_to_code(code, create_full_quad(enter, NULL, NULL, NULL)); add_to_code(code, create_full_quad(vardec, "int", "y", NULL)); add_to_code(code, create_full_quad(assn, "y", "1", NULL)); add_to_code(code, create_full_quad(dowhileloop, NULL, NULL, NULL)); add_to_code(code, create_full_quad(enter, NULL, NULL, NULL)); add_to_code(code, create_full_quad(mult, "t0", "y", "2")); add_to_code(code, create_full_quad(assn, "x", "t0", NULL)); add_to_code(code, create_full_quad(leave, NULL, NULL, NULL)); add_to_code(code, create_full_quad(end_dowhileloop, NULL, NULL, NULL)); add_to_code(code, create_full_quad(lt, "t1", "y", "5")); add_to_code(code, create_full_quad(ifFalse, "t1", "12", NULL)); add_to_code(code, create_full_quad(jumpTo, "5", NULL, NULL)); add_to_code(code, create_full_quad(assn, "x", "3", NULL)); add_to_code(code, create_full_quad(leave, NULL, NULL, NULL)); add_to_code(code, create_full_quad(exit_sub, NULL, NULL, NULL)); add_to_code(code, create_full_quad(halt, NULL, NULL, NULL)); add_to_code(code, create_full_quad(end, NULL, NULL, NULL)); print_code(code); generate_target(code); }
/** * This is the main function for parsing/code generation. * * @param input_file the raw token file to read from (all numbers and spaces) */ int pl0_parse(FILE *input_file, int a_flag) { token_type token = nulsym; int error_code = 0; token = get_token(input_file); error_code = block(input_file, &token); if(!error_code) { if(token != periodsym) { error_code = 9; } else { // return 0; in main() error_code = emit(OPR, 0, OPR_RET); if(error_code) return error_code; } } if(!error_code && a_flag) { printf("%s\n\n", get_parse_error(error_code)); print_code(stdout); print_code_pretty(stdout); printf("\n"); } return error_code; }
/* int x; * double y; * * int f(){ * x = 0; * x = x + 1; * return x; * } * * int main(){ * f(); * } */ static void test1(){ quad_list code = create_quad_list(); add_to_code(code, create_full_quad(vardec, "int", "x", NULL)); add_to_code(code, create_full_quad(vardec, "double", "y", NULL)); add_to_code(code, create_full_quad(func_dec, "int", "f", NULL)); add_to_code(code, create_full_quad(enter, NULL, NULL, NULL)); add_to_code(code, create_full_quad(assn, "x", "0", NULL)); add_to_code(code, create_full_quad(add, "t0", "x", "1")); add_to_code(code, create_full_quad(assn, "x", "t0", NULL)); add_to_code(code, create_full_quad(rtrn, "x", NULL, NULL)); add_to_code(code, create_full_quad(leave, NULL, NULL, NULL)); add_to_code(code, create_full_quad(exit_sub, NULL, NULL, NULL)); add_to_code(code, create_full_quad(func_dec, "int", "main", NULL)); add_to_code(code, create_full_quad(enter, NULL, NULL, NULL)); add_to_code(code, create_full_quad(goto_sub, "f", NULL, NULL)); add_to_code(code, create_full_quad(get_rtrn, "t1", NULL, NULL)); add_to_code(code, create_full_quad(leave, NULL, NULL, NULL)); add_to_code(code, create_full_quad(exit_sub, NULL, NULL, NULL)); add_to_code(code, create_full_quad(halt, NULL, NULL, NULL)); add_to_code(code, create_full_quad(end, NULL, NULL, NULL)); print_code(code); generate_target(code); }
static void ifelse_test(){ quad_list code = create_quad_list(); add_to_code(code, create_full_quad(vardec, "int", "x", NULL)); add_to_code(code, create_full_quad(func_dec, "int", "main", NULL)); add_to_code(code, create_full_quad(enter, NULL, NULL, NULL)); add_to_code(code, create_full_quad(vardec, "int", "y", NULL)); add_to_code(code, create_full_quad(assn, "y", "1", NULL)); add_to_code(code, create_full_quad(ifelse, NULL, NULL, NULL)); add_to_code(code, create_full_quad(lt, "t0", "y", "5")); add_to_code(code, create_full_quad(ifFalse, "t0", "16", NULL)); add_to_code(code, create_full_quad(enter, NULL, NULL, NULL)); add_to_code(code, create_full_quad(add, "t1", "y", "1")); add_to_code(code, create_full_quad(assn, "y", "t1", NULL)); add_to_code(code, create_full_quad(leave, NULL, NULL, NULL)); add_to_code(code, create_full_quad(end_ifstmt, NULL, NULL, NULL)); add_to_code(code, create_full_quad(jumpTo, "18", NULL, NULL)); add_to_code(code, create_full_quad(elsestmt, NULL, NULL, NULL)); add_to_code(code, create_full_quad(enter, NULL, NULL, NULL)); add_to_code(code, create_full_quad(divide, "t2", "y", "5")); add_to_code(code, create_full_quad(assn, "y", "t2", NULL)); add_to_code(code, create_full_quad(leave, NULL, NULL, NULL)); add_to_code(code, create_full_quad(end_elsestmt, NULL, NULL, NULL)); add_to_code(code, create_full_quad(assn, "x", "3", NULL)); add_to_code(code, create_full_quad(leave, NULL, NULL, NULL)); add_to_code(code, create_full_quad(exit_sub, NULL, NULL, NULL)); add_to_code(code, create_full_quad(halt, NULL, NULL, NULL)); add_to_code(code, create_full_quad(end, NULL, NULL, NULL)); print_code(code); generate_target(code); }
void print_gray_reverse(int code[], int n, int idx) { if(idx == n){ print_code(code, n); return; } code[idx]=1; print_gray(code, n ,idx+1); code[idx]=0; print_gray_reverse(code, n ,idx+1); }
void recv_cb(const msg_lvl2_t * msg, void * context) { pmd_net_reader_data_t reader_data; uint8_t rc; if(msg) { rc = pmd_net_reader_read_data(&(msg->data), &reader_data); if((rc == 0) && (reader_data.operation == PMD_NET_READER_SEND_MSG)) { print_code(&reader_data); } } }
/** @brief Print content of code table @param tbl Code table */ void print_code_tbl(const struct hf_code *const tbl) { int i; CHKPTR(tbl); puts("=== TABLE OF ASSIGNED HUFFMAN CODES ==="); for (i = 0; i < MAX_CODE_TBL_SIZE; ++i) print_code(i, tbl[i]); puts("======================================="); }
int main(){ oprand op1, op2, op3; quad qd; op1 = create_oprand(OP_TYPE_INT, 1); op2 = create_oprand(OP_TYPE_NA, 1); op3 = create_oprand(OP_TYPE_DOUBLE, 1.5); qd = create_quad(FUNC_BODY, op1, op2, op3); insert_quad(qd); insert_quad(qd); insert_quad(qd); print_code(); return 0; }
int main(int argc, char **argv) { int c; while((c = getopt(argc, argv, "s:")) != -1) { switch(c) { case 's': break; default: abort(); } } if(optind >= argc) { fprintf(stderr, "Usage: %s [opts] <bin>\n", argv[0]); return 1; } srand(time(NULL)); load_bin(argv[optind]); print_data(); print_code(); cpu = malloc(sizeof(VM_CPU)); int i; for(i = optind + 1; i < argc; i++) { cpu->registers[ARG_REG(i)] = (int)argv[i]; } cpu->stack_size = bin_hdr->stack_size; cpu->stack = malloc(sizeof(int) * cpu->stack_size); cpu->registers[RESERVED_REG(REG_STACKP)] = cpu->stack_size; cpu->registers[RESERVED_REG(REG_IP)] = bin_hdr->entry_point; print_dbg("Set IP: %d\n", cpu->registers[RESERVED_REG(REG_IP)]); cpu->running = 1; cycle(); }
void generate_three_address_code(block_node * statements) { // Writes basic functions to be used when generating three address code //prepare_cfile("out.c"); int i = 0; //init_array_vars(&vars, 2); init_array(&lines, 2); init_array(&functions, 2); init_errors(); scope * root_scope = new_scope(NULL); compile_block(statements, root_scope, &lines, 0); if(num_of_errors > 0) { print_array(&errors); } else { print_code(&lines); write_to_file(&lines, 0, "w+"); } }
void persist_bit(Code *encode, Text * text) { int fd; fd = text->encode_fd; printf("persist_bit:"); print_code(encode); if(encode->bit_len > 0) encode->fill_len += 1; if( write(fd, encode->content, encode->fill_len) == -1 ) { printf("persist_bit write failed\n"); exit(1); } encode->fill_len = 0; encode->bit_len = 0; memset(encode->content, 0, encode->len); }
int main(int argc, char** argv) { if (argc < 2) { fprintf(stderr, "usage: %s <message-code>\n", __progname); return -1; } int32 number = atol(argv[1]); BQuery query; query.SetPredicate("name=ServerProtocol.h"); // search on current volume only dev_t device = dev_for_path("."); BVolume volume(device); query.SetVolume(&volume); query.Fetch(); status_t status; BEntry entry; while ((status = query.GetNextEntry(&entry)) == B_OK) { BPath path(&entry); puts(path.Path()); if (strstr(path.Path(), "headers/private/app/ServerProtocol.h") != NULL) { print_code(path, number); break; } } if (status != B_OK) { fprintf(stderr, "%s: could not find ServerProtocol.h", __progname); return -1; } return 0; }
void nmethod::printCode() { ResourceMark m; // in case methods get printed from gdb print_code(this, (char*)insts(), (char*)instsEnd()); }
void print_code_disassembled(struct object_heap* oh, struct OopArray* slatecode) { std::vector<struct Object*> code; optimizer_append_code_to_vector(slatecode, code); print_code(oh, code); }
nmethod* Compiler::compile() { NewBackendGuard guard; if ((PrintProgress > 0) && (nofCompilations % PrintProgress == 0)) std->print("."); const char* compiling; if (DeltaProcess::active()->isUncommon()) { compiling = recompilee ? "Uncommon-Recompiling " : "Uncommon-Compiling "; } else { if (_uses_inlining_database) { compiling = recompilee ? "Recompiling (database)" : "Compiling (database)"; } else { compiling = recompilee ? "Recompiling " : "Compiling "; } } EventMarker em("%s%#lx %#lx", compiling, key->selector(), NULL); // don't use uncommon traps when recompiling because of trap useUncommonTraps = DeferUncommonBranches && !is_uncommon_compile(); if (is_uncommon_compile()) reporter->report_uncommon(false); if (recompilee && recompilee->isUncommonRecompiled()) reporter->report_uncommon(true); // don't use counters when compiling from DB FlagSetting fs(UseRecompilation, UseRecompilation && !is_database_compile()); bool should_trace = _uses_inlining_database ? PrintInliningDatabaseCompilation : PrintCompilation; TraceTime t(compiling, should_trace); if (should_trace || PrintCode) { print_key(std); if (PrintCode || PrintInlining) std->print("\n"); } topScope->genCode(); fixupNLRTestPoints(); buildBBs(); if (PrintCode) print_code(false); if (verifyOften) bbIterator->verify(); // compute escaping blocks and up-level accessed vars bbIterator->computeEscapingBlocks(); bbIterator->computeUplevelAccesses(); if (verifyOften) bbIterator->verify(); //if (PrintCode) print_code(false); // construct def & use information bbIterator->makeUses(); if (verifyOften) bbIterator->verify(); //if (PrintCode) print_code(false); if (LocalCopyPropagate) { bbIterator->localCopyPropagate(); if (verifyOften) bbIterator->verify(); } //if (PrintCode) print_code(false); if (GlobalCopyPropagate) { bbIterator->globalCopyPropagate(); if (verifyOften) bbIterator->verify(); } //if (PrintCode) print_code(false); if (BruteForcePropagate) { bbIterator->bruteForceCopyPropagate(); if (verifyOften) bbIterator->verify(); } //if (PrintCode) print_code(false); if (EliminateUnneededNodes) { bbIterator->eliminateUnneededResults(); if (verifyOften) bbIterator->verify(); } //if (PrintCode) print_code(false); if (OptimizeIntegerLoops) { // run after copy propagation so that loop increment is easier to recognize // also run after eliminateUnneededResults so that cpInfo is set for eliminated PRegs topScope->optimizeLoops(); if (verifyOften) bbIterator->verify(); } //if (PrintCode) print_code(false); // compute existence & format of run-time context objects and blocks computeBlockInfo(); // allocate floats _totalNofFloatTemporaries = topScope->allocateFloatTemporaries(0); // HACK: Fix preallocation // Necessary because a few primitives (allocateContext/Closure) need self or // the previous context after calling a primitive; i.e., self or the previous // context should not be allocated to a register. Currently not working correctly // -> allocated to stack as a temporary fix for the problem. theAllocator->preAllocate(topScope->self()->preg()); bbIterator->localAlloc(); // allocate regs within basic blocks theAllocator->allocate(bbIterator->globals); if (PrintCode) print_code(false); #ifdef ASSERT bbIterator->verify(); #endif if (PrintDebugInfoGeneration) { std->cr(); std->cr(); std->print_cr("Start of debugging info."); } topScope->generateDebugInfo(); // must come before gen to set scopeInfo topScope->generateDebugInfoForNonInlinedBlocks(); // generate machine code theMacroAssm = new MacroAssembler(_code); if (UseNewBackend) { PRegMapping* mapping = new PRegMapping(theMacroAssm, topScope->nofArguments(), 6, topScope->nofTemporaries()); CodeGenerator* cgen = new CodeGenerator(theMacroAssm, mapping); cgen->initialize(topScope); bbIterator->apply(cgen); cgen->finalize(topScope); } else { // use a node visitor to generate code OldCodeGenerator* cgen = new OldCodeGenerator(); bbIterator->apply(cgen); } theMacroAssm->finalize(); theMacroAssm = NULL; #ifndef ASSERT if (verifyOften) { #endif bool ok = bbIterator->verifyLabels(); if (!ok) print_code(false); #ifndef ASSERT } #endif rec->generate(); // write debugging info nmethod* nm = new_nmethod(this); // construct new nmethod em.event.args[1] = nm; if (PrintAssemblyCode) Disassembler::decode(nm); reporter->finish_reporting(); if (should_trace) { lprintf(": %#lx (%d bytes; level %ld v%d)\n", nm, nm->instsLen(), nm->level(), nm->version()); flush_logFile(); } if (verifyOften) nm->verify(); if (PrintDebugInfo) nm->print_inlining(std, true); return nm; }
void encode_text(Text * text, Code * encode) { unsigned int T; unsigned int R = 1; unsigned int l, u, ll, uu; unsigned int m = 0; unsigned int f_dl, f_du; unsigned char bit = 0x01; unsigned int bit_offset = 7; T = encode->f_d[P_LENGTH]; while(R <= (T * INTERVAL)) R = R << 1; printf("t_lenth = %u, T = %u, R = %u\n", text->len, T, R); l = 0; u = R - 1; persist_struct(text->encode_fd, (char *)(&encode->text_len), sizeof(unsigned int)); persist_struct(text->encode_fd, (char *)(encode->f_d), (P_LENGTH + 1) * sizeof(int)); for(unsigned long j = 0; j < text->len; j++) { ll = l; uu = u; //f_dl = (unsigned int)text.content[j]; f_dl = (unsigned int)(unsigned char)get_byte_from_file(text, j); //printf("before text = %u, fill_len = %u, ll = %u, uu = %u\n", // f_dl, encode->fill_len, ll, uu); for(unsigned int i = f_dl + 1; i < P_LENGTH + 1; i++) if(encode->f_d[i] != -1) { f_du = i; break; } //printf("f_dl = %u, f_du = %u\n", encode->f_d[f_dl], encode->f_d[f_du]); ll = l + floor((u - l + 1) * encode->f_d[f_dl] / T); uu = l + floor((u - l + 1) * encode->f_d[f_du] / T) - 1; //printf("encode fill_len = %u, ll = %u, uu = %u\n", encode->fill_len, ll, uu); while(1) { if(ll >= R/2) { add_bit(encode, 1, text); ll = 2 * ll - R ; uu = 2 * uu - R + 1; while(m-- > 0) add_bit(encode, 0, text); m = 0; //printf("upper encode_len = %u, fill_len = %u ll = %u, uu = %u\n", // encode->len, encode->fill_len, ll, uu); } else if(uu < R/2) { add_bit(encode, 0, text); ll = 2 * ll; uu = 2 * uu + 1; while(m-- > 0) add_bit(encode, 1, text); //printf("down encode_len = %u, fill_len = %u, ll = %u, uu = %u\n", // encode->len, encode->fill_len, ll, uu); m = 0; } else if((ll >= R/4) && (uu < 3*R/4)) { ll = 2 * ll - R/2; uu = 2 * uu - R/2 + 1; m++; //printf("middle encode_len = %u, fill_len = %u, ll = %u, uu = %u\n", // encode->len, encode->fill_len, ll, uu); } else { l = ll; u = uu; break; } } } if(l >= R/4) { add_bit(encode, 1, text); while(m-- > 0) add_bit(encode, 0, text); add_bit(encode, 0, text); } else { add_bit(encode, 0, text); while(m-- > 0) add_bit(encode, 1, text); add_bit(encode, 1, text); } // printf("#---snsn-----%d", encode->fill_len); persist_bit(encode, text); //printf("encode = %s\n", encode); //printf("encode = %u\n", encode->content[1]); print_code(encode); }
nmethod* SICompiler::compile() { EventMarker em("SIC-compiling %#lx %#lx", L->selector(), NULL); ShowCompileInMonitor sc(L->selector(), "SIC", recompilee != NULL); // cannot recompile uncommon branches in DI nmethods & top nmethod yet FlagSetting fs2(SICDeferUncommonBranches, SICDeferUncommonBranches && diLink == NULL && L->adeps->length() == 0 && L->selector() != VMString[DO_IT]); // don't use uncommon traps when recompiling because of trap useUncommonTraps = SICDeferUncommonBranches && !currentProcess->isUncommon(); // don't inline into doIt FlagSetting fs3(Inline, Inline && L->selector() != VMString[DO_IT]); # if TARGET_ARCH != I386_ARCH // no FastMapTest possible on I386 // don't use fast map loads if this nmethod trapped a lot FlagSetting fs4(FastMapTest, FastMapTest && (recompilee == NULL || recompilee->flags.trapCount < MapLoadTrapLimit)); # endif FlagSetting fs5(PrintCompilation, PrintCompilation || PrintSICCompilation); timer t; FlagSetting fs6(verifyOften, SICDebug || CheckAssertions); if(PrintCompilation || PrintLongCompilation || PrintCompilationStatistics || VMSICLongProfiling) { t.start(); } if (PrintCompilation || PrintSICCode) { lprintf("*SIC-%s%scompiling %s%s: (SICCompilationCount=%d)", currentProcess->isUncommon() ? "uncommon-" : "", recompilee ? "re" : "", sprintName( (methodMap*) method()->map(), L->selector()), sprintValueMethod( L->receiver ), (void*)SICCompilationCount); } topScope->genCode(); buildBBs(); if (verifyOften) bbIterator->verify(false); bbIterator->eliminateUnreachableNodes(); // needed for removeUptoMerge to work // compute exposed blocks and up-level accessed vars bbIterator->computeExposedBlocks(); bbIterator->computeUplevelAccesses(); // make defs & uses and insert flush nodes for uplevel-accessed vars bbIterator->makeUses(); // added verify here cause want to catch unreachable merge preds // before elimination -- dmu if (verifyOften) bbIterator->verify(); if (SICLocalCopyPropagate) { bbIterator->localCopyPropagate(); if (verifyOften) bbIterator->verify(); } if (SICGlobalCopyPropagate) { bbIterator->globalCopyPropagate(); if (verifyOften) bbIterator->verify(); } if (SICEliminateUnneededNodes) { bbIterator->eliminateUnneededResults(); if (verifyOften) bbIterator->verify(); } // do after CP to explot common type test source regs if (SICOptimizeTypeTests) { bbIterator->computeDominators(); bbIterator->optimizeTypeTests(); if (verifyOften) bbIterator->verify(); } // allocate the temp (i.e. volatile) registers bbIterator->allocateTempRegisters(); // allocate the callee-saved (i.e. non-volatile) registers SICAllocator* a = theAllocator; a->allocate(bbIterator->globals, topScope->incoming); stackLocCount = a->stackTemps; // make sure frame size is aligned properly int32 frame_size_so_far = frameSize(); stackLocCount += roundTo(frame_size_so_far, frame_word_alignment) - frame_size_so_far; // compute the register masks for inline caches bbIterator->computeMasks(stackLocCount, nonRegisterArgCount()); topScope->computeMasks(regStringToMask(topScope->incoming), stackLocCount, nonRegisterArgCount()); if (PrintSICCode) { print_code(false); lprintf("\n\n"); } topScope->describe(); // must come before gen to set scopeInfo genHelper = new SICGenHelper; bbIterator->gen(); assert(theAssembler->verifyLabels(), "undefined labels"); rec->generate(); topScope->fixupBlocks(); // must be after rec->gen to know offsets if (vscopes) computeMarkers(); // ditto nmethod* nm = new_nmethod(this, false); if (theAssembler->lastBackpatch >= theAssembler->instsEnd) fatal("dangling branch"); em.event.args[1] = nm; fint ms = IntervalTimer::dont_use_any_timer ? 0 : t.millisecs(); if (PrintCompilation || PrintLongCompilation) { if (!PrintCompilation && PrintLongCompilation && ms >= MaxCompilePause) { lprintf("*SIC-%s%scompiling ", currentProcess->isUncommon() ? "uncommon-" : "", recompilee ? "re" : ""); methodMap* mm = method() ? (methodMap*) method()->map() : NULL; printName(mm, L->selector()); lprintf(": %#lx (%ld ms; level %ld)\n", nm, (void*)ms, (void*)nm->level()); } else if (PrintCompilation) { lprintf(": %#lx (%ld ms; level %ld v%d)\n", (void*)nm, (void*)ms, (void*)nm->level(), (void*)nm->version()); } } if (SICDebug && estimatedSize() > inlineLimit[NmInstrLimit]) { float rat = (float)estimatedSize() / (float)nm->instsLen(); lprintf("*est. size = %ld, true size = %ld, ratio = %4.2f\n", (void*)estimatedSize(), (void*)nm->instsLen(), *(void**)&rat); } if (PrintCompilationStatistics) { static fint counter = 0; lprintf("\n*SIC-time= |%ld| ms; to/co/sc/lo/de= |%ld|%ld|%ld|%ld|%ld| %ld|%ld|%ld| %ld |", (void*)ms, (void*) (nm->instsLen() + nm->scopes->length() + nm->locsLen() + nm->depsLen), (void*)nm->instsLen(), (void*)nm->scopes->length(), (void*)nm->locsLen(), (void*)nm->depsLen, (void*)BasicNode::currentID, (void*)bbIterator->bbCount, (void*)ncodes, (void*)counter++); } # if GENERATE_DEBUGGING_AIDS if (CheckAssertions) { // nm->verify(); } # endif return nm; }
int main(int argc, char *argv[]) { char buffer[8], *wrapid, *var, *user_directory; FILE *fp; int i, handle, arg_offset, time_for_cgi, len; t_wrap wrap_data; bool follow_symlinks = true, usecgi_handler; char *cgiwrap_id = "CGIWRAP_ID"; char *cgiwrap_symlink = "CGIWRAP_FOLLOWSYMLINKS"; char *cgiwrap_cgitime = "CGIWRAP_TIMEFORCGI"; char *cgiwrap_userdir = "CGIWRAP_USERDIRECTORY"; if (argc < 3) { print_code(-1); } /* Check if parent is Araneum */ buffer[0] = buffer[7] = '\0'; if ((fp = fopen(PIDFILE_DIR"/araneum.pid", "r")) == NULL) { print_code(-1); } if (fgets(buffer, 7, fp) == NULL) { print_code(-1); } fclose(fp); if ((i = strlen(buffer)) == 0) { print_code(-1); } else if (buffer[i - 1] != '\n') { print_code(-1); } buffer[i - 1] = '\0'; if ((i = str2int(buffer)) == -1) { print_code(-1); } if (getsid(0) != getsid(i)) { print_code(-1); } /* Read environment settings */ if ((wrapid = getenv(cgiwrap_id)) == NULL) { log_error("getenv(CGIWRAP_ID) error"); print_code(500); } if ((var = getenv(cgiwrap_symlink)) == NULL) { log_error("getenv(CGIWRAP_FOLLOWSYMLINKS) error"); print_code(500); } follow_symlinks = (strcmp(var, "true") == 0); if ((var = getenv(cgiwrap_cgitime)) != NULL) { time_for_cgi = str2int(var); } else { time_for_cgi = 5; } if ((var = getenv(cgiwrap_userdir)) != NULL) { if ((user_directory = (char*)malloc(strlen(var) + 3)) == NULL) { print_code(500); } sprintf(user_directory, "/%s/", var); } else { user_directory = "/public_html/"; } /* Clear environment crap */ unsetenv(cgiwrap_id); unsetenv(cgiwrap_symlink); unsetenv(cgiwrap_cgitime); unsetenv(cgiwrap_userdir); /* Check for bad path */ if (strstr(argv[1], "/../") != NULL) { log_error("/../ in path detected"); print_code(500); } /* Read cgi-wrapper config */ if ((usecgi_handler = (strcmp(argv[0], "-") != 0))) { /* CGI handler */ if (get_wrap_data(wrapid, argv[0], argv[2], &wrap_data, user_directory) == false) { print_code(403); } } else { /* CGI program */ if (get_wrap_data(wrapid, NULL, argv[1], &wrap_data, user_directory) == false) { print_code(403); } } /* chroot */ if (wrap_data.chroot != NULL) { if (chdir(wrap_data.chroot) == -1) { log_error("chdir(CHROOTDIR) error"); print_code(404); } else if (chroot(wrap_data.chroot) == -1) { log_error("chroot() error"); print_code(500); } len = strlen(wrap_data.chroot); if (usecgi_handler == false) { *(argv + 1) += len; } *(argv + 2) += len; setenv("DOCUMENT_ROOT", wrap_data.cgiroot, 1); setenv("SCRIPT_FILENAME", argv[2], 1); } /* Set IDs */ if (setuid(0) == -1) { log_error("setuid(0) error"); print_code(500); } else if (setgroups(wrap_data.groups.number, wrap_data.groups.array) == -1) { log_error("setgroups() error"); print_code(500); } else if (setgid(wrap_data.gid) == -1) { log_error("setgid() error"); print_code(500); } else if (setuid(wrap_data.uid) == -1) { log_error("setuid(uid) error"); print_code(500); } /* New session */ if (setsid() == -1) { log_error("setsid() error"); print_code(500); } /* Does the CGI program exist? */ if ((handle = open(argv[2], O_RDONLY)) == -1) { if (errno == EACCES) { log_error("access to CGI program denied"); print_code(403); } log_error("CGI program does not exist"); print_code(404); } else { close(handle); } /* Symlink allowed? */ if (follow_symlinks == false) { switch (contains_not_allowed_symlink(argv[2], wrap_data.cgiroot)) { case error: log_error("contains_not_allowed_symlink() error"); print_code(500); case not_found: log_error("CGI program not found"); print_code(404); case no_access: case yes: log_error("symlinks not allowed"); print_code(403); case no: break; } } /* Check file accessrights */ if (usecgi_handler == false) { switch (can_execute(argv[1], wrap_data.uid, wrap_data.gid, &(wrap_data.groups))) { case error: log_error("can_execute() error"); print_code(500); case not_found: log_error("CGI program not found"); print_code(404); case no_access: case no: log_error("access to CGI program denied"); print_code(403); case yes: break; } arg_offset = 1; } else { arg_offset = 0; } /* And here we go */ switch (cgi_pid = fork()) { case -1: log_error("fork() error"); print_code(500); case 0: execvp(argv[arg_offset], argv + 1 + arg_offset); log_error("execvp() error"); print_code(500); exit(EXIT_FAILURE); default: signal(SIGALRM, ALRM_handler); alarm(time_for_cgi); waitpid(cgi_pid, NULL, 0); } return 0; }
int VCPU::print_state(FILE * o) const { int len = 0; if ( ! this->is_online() ) return len + FPUTS("\tVCPU Offline\n\n", o); if ( this->flags & CPU_PV_COMPAT ) return len + this->print_state_compat(o); if ( this->flags & CPU_GP_REGS ) { len += FPRINTF(o, "\tRIP: %04x:[<%016"PRIx64">] Ring %d\n", this->regs.cs, this->regs.rip, this->regs.cs & 0x3); len += FPRINTF(o, "\tRFLAGS: %016"PRIx64" ", this->regs.rflags); len += print_rflags(o, this->regs.rflags); len += FPUTS("\n\n", o); len += FPRINTF(o, "\trax: %016"PRIx64" rbx: %016"PRIx64" rcx: %016"PRIx64"\n", this->regs.rax, this->regs.rbx, this->regs.rcx); len += FPRINTF(o, "\trdx: %016"PRIx64" rsi: %016"PRIx64" rdi: %016"PRIx64"\n", this->regs.rdx, this->regs.rsi, this->regs.rdi); len += FPRINTF(o, "\trbp: %016"PRIx64" rsp: %016"PRIx64" r8: %016"PRIx64"\n", this->regs.rbp, this->regs.rsp, this->regs.r8); len += FPRINTF(o, "\tr9: %016"PRIx64" r10: %016"PRIx64" r11: %016"PRIx64"\n", this->regs.r9, this->regs.r10, this->regs.r11); len += FPRINTF(o, "\tr12: %016"PRIx64" r13: %016"PRIx64" r14: %016"PRIx64"\n", this->regs.r12, this->regs.r13, this->regs.r14); len += FPRINTF(o, "\tr15: %016"PRIx64"\n", this->regs.r15); } if ( this->flags & CPU_CR_REGS ) { len += FPUTS("\n", o); len += FPRINTF(o, "\tcr3: %016"PRIx64"\n", this->regs.cr3); } if ( this->flags & CPU_GP_REGS ) { len += FPUTS("\n", o); if ( this->flags & CPU_SEG_REGS ) len += FPRINTF(o, "\tds: %04"PRIx16" es: %04"PRIx16" " "fs: %04"PRIx16" gs: %04"PRIx16" " "ss: %04"PRIx16" cs: %04"PRIx16"\n", this->regs.ds, this->regs.es, this->regs.fs, this->regs.gs, this->regs.ss, this->regs.cs); else len += FPRINTF(o, "\tss: %04"PRIx16" cs: %04"PRIx16"\n", this->regs.ss, this->regs.cs); } len += FPUTS("\n", o); len += FPRINTF(o, "\tPause Count: %"PRId32", Flags: 0x%"PRIx32" ", this->pause_count, this->pause_flags); len += print_pause_flags(o, this->pause_flags); len += FPUTS("\n", o); switch ( this->runstate ) { case RST_NONE: len += FPRINTF(o, "\tNot running: Last run on PCPU%"PRIu32"\n", this->processor); break; case RST_RUNNING: len += FPRINTF(o, "\tCurrently running on PCPU%"PRIu32"\n", this->processor); break; case RST_CTX_SWITCH: len += FPUTS("\tBeing Context Switched: State unreliable\n", o); break; default: len += FPUTS("\tUnknown runstate\n", o); break; } len += FPRINTF(o, "\tStruct vcpu at %016"PRIx64"\n", this->vcpu_ptr); len += FPUTS("\n", o); if ( this->flags & CPU_GP_REGS && this->flags & CPU_CR_REGS && ( this->paging_support == VCPU::PAGING_NONE || this->paging_support == VCPU::PAGING_SHADOW ) ) { len += FPRINTF(o, "\tStack at %16"PRIx64":", this->regs.rsp); len += print_64bit_stack(o, *this->dompt, this->regs.rsp); len += FPUTS("\n\tCode:\n", o); len += print_code(o, *this->dompt, this->regs.rip); len += FPUTS("\n\tCall Trace:\n", o); if ( this->domid == 0 ) { vaddr_t sp = this->regs.rsp; vaddr_t top = (this->regs.rsp | (PAGE_SIZE-1))+1; uint64_t val; len += host.dom0_symtab.print_symbol64(o, this->regs.rip, true); try { while ( sp < top ) { memory.read64_vaddr(*this->dompt, sp, val); len += host.dom0_symtab.print_symbol64(o, val); sp += 8; } } catch ( const CommonError & e ) { e.log(); } } else len += FPUTS("\t No symbol table for domain\n", o); len += FPUTS("\n", o); } return len; }
void BB::print() { print_short(); lprintf("(%ld nodes):\n", (void*)nnodes); print_code(false); lprintf("duInfo: "); duInfo.print(); }
void parse_program(char *filename) { printf("parsing file: %s\n", filename); yyfiles = list_new(NULL, &free); log_assert(yyfiles); list_push_back(yyfiles, filename); yyclibs = list_new(NULL, &free); log_assert(yyclibs); yyincludes = hasht_new(8, true, NULL, NULL, NULL); log_assert(yyincludes); /* open file for lexer */ yyin = fopen(filename, "r"); if (yyin == NULL) log_error("could not open input file: %s", filename); /* push buffer state for lexer */ yypush_buffer_state(yy_create_buffer(yyin, YY_BUF_SIZE)); /* setup yytypes table for lexer */ yytypes = hasht_new(8, true, NULL, NULL, &free_typename); log_assert(yytypes); /* reset library flags */ libs.usingstd = false; libs.cstdlib = false; libs.cmath = false; libs.ctime = false; libs.cstring = false; libs.fstream = false; libs.iostream = false; libs.string = false; libs.iomanip = false; log_debug("invoking Bison"); int result = yyparse(); if (result != 0) exit(2); /* print syntax tree */ if (arguments.tree) tree_traverse(yyprogram, 0, &print_tree, NULL, NULL); /* initialize scope stack */ log_debug("setting up for semantic analysis"); yyscopes = list_new(NULL, NULL); log_assert(yyscopes); struct hasht *global = hasht_new(32, true, NULL, NULL, &symbol_free); log_assert(global); list_push_back(yyscopes, global); /* build the symbol tables */ log_debug("populating symbol tables"); region = GLOBE_R; offset = 0; symbol_populate(yyprogram); log_debug("global scope had %zu symbols", hasht_used(global)); /* constant symbol table put in front of stack for known location */ struct hasht *constant = hasht_new(32, true, NULL, NULL, &symbol_free); log_assert(constant); list_push_front(yyscopes, constant); region = CONST_R; offset = 0; log_debug("type checking"); type_check(yyprogram); /* generating intermediate code */ log_debug("generating intermediate code"); yylabels = 0; /* reset label counter */ code_generate(yyprogram); struct list *code = ((struct node *)yyprogram->data)->code; /* iterate to get correct size of constant region */ size_t string_size = 0; for (size_t i = 0; i < constant->size; ++i) { struct hasht_node *slot = constant->table[i]; if (slot && !hasht_node_deleted(slot)) { struct typeinfo *v = slot->value; if (v->base == FLOAT_T) string_size += 8; else if (v->base == CHAR_T && v->pointer) string_size += v->token->ssize; } } /* print intermediate code file if debugging */ if (arguments.debug) { char *output_file; asprintf(&output_file, "%s.ic", filename); FILE *ic = fopen(output_file, "w"); if (ic == NULL) log_error("could not save to output file: %s", output_file); fprintf(ic, ".file \"%s\"\n", filename); /* print .string region */ fprintf(ic, ".string %zu\n", string_size); /* iterate to print everything but ints, chars, and bools */ for (size_t i = 0; i < constant->size; ++i) { struct hasht_node *slot = constant->table[i]; if (slot && !hasht_node_deleted(slot)) { struct typeinfo *v = slot->value; if (v->base == FLOAT_T || (v->base == CHAR_T && v->pointer)) { fprintf(ic, " "); print_typeinfo(ic, slot->key, v); fprintf(ic, "\n"); } } } /* print .data region */ fprintf(ic, ".data\n"); for (size_t i = 0; i < global->size; ++i) { struct hasht_node *slot = global->table[i]; if (slot && !hasht_node_deleted(slot)) { struct typeinfo *value = slot->value; if (value->base != FUNCTION_T) { fprintf(ic, " "); print_typeinfo(ic, slot->key, value); fprintf(ic, "\n"); } } } fprintf(ic, ".code\n"); print_code(ic, code); fclose(ic); free(output_file); } log_debug("generating final code"); /* copy because Wormulon */ char *copy = strdup(filename); char *base = basename(copy); free(copy); char *output_file; asprintf(&output_file, "%s.c", base); FILE *fc = fopen(output_file, "w"); if (fc == NULL) log_error("could not save to output file: %s", output_file); time_t t = time(NULL); struct tm *local = localtime(&t); char timestamp[60]; strftime(timestamp, sizeof(timestamp), "%F %T", local); fprintf(fc, "/*\n"); fprintf(fc, " * %s - 120++ Three-Address C Code\n", output_file); fprintf(fc, " * Generated @ %s\n", timestamp); fprintf(fc, " *\n"); fprintf(fc, " * Created by Andrew Schwartzmeyer's 120++ Compiler\n"); fprintf(fc, " * Project located @ https://github.com/andschwa/uidaho-cs445\n"); fprintf(fc, " */\n\n"); fprintf(fc, "/* Required includes for TAC-C */\n"); fprintf(fc, "#include <stdlib.h>\n"); fprintf(fc, "#include <stdbool.h>\n"); fprintf(fc, "#include <string.h>\n"); if (libs.usingstd && libs.iostream) fprintf(fc, "#include <stdio.h>\n"); fprintf(fc, "\n"); /* include passed-through C headers */ fprintf(fc, "/* Source-file C headers */\n"); struct list_node *iter = list_head(yyclibs); while (!list_end(iter)) { fprintf(fc, "#include %s\n", (char *)iter->data); iter = iter->next; } fprintf(fc, "\n"); /* get maximum param size for faux stack */ size_t max_param_size = 0; iter = list_head(code); while (!list_end(iter)) { struct op *op = iter->data; if (op->code == PROC_O) { size_t param_size = op->address[0].offset; if (param_size > max_param_size) max_param_size = param_size; } iter = iter->next; } fprintf(fc, "/* Memory regions */\n"); fprintf(fc, "char constant[%zu];\n", string_size); fprintf(fc, "char global[%zu];\n", global->size); fprintf(fc, "char stack[%zu];\n", max_param_size); fprintf(fc, "\n"); fprintf(fc, "/* Final Three-Address C Generated Code */\n"); final_code(fc, code); fclose(fc); /* remove TAC-C "assembler" code */ if (!arguments.assemble) { /* compile object files */ char *command; asprintf(&command, "gcc -c %s", output_file); int status = system(command); if (status != 0) log_error("command failed: %s", command); remove(output_file); } free(output_file); /* clean up */ log_debug("cleaning up"); tree_free(yyprogram); yylex_destroy(); hasht_free(yytypes); free(yyincludes); /* values all referenced elsewhere */ list_free(yyfiles); list_free(yyclibs); list_free(yyscopes); }
int main(int argc, char* argv[]) { // deal with args if (argc < 2) { print_usage(); return 1; } int c; unsigned char ch; bool onlyPrint = false, verbose = false; opterr = 0; while ((c = getopt(argc, argv, ":e:t:" BOUNDS_ARGS "hpv")) != -1) { ch = (unsigned char) c; if (c == 'e') { onEof = EOF_VALUE; eofValue = (unsigned char) atoi(optarg); } else if (c == 't') { int len = atoi(optarg); if (len <= 0) { fprintf(stderr, "err: tape size must be positive integer\n"); return 1; } tapeLength = (size_t) len; #ifndef NO_CHECK_BOUNDS } else if (c == 'b') { check = true; } else if (c == 'c') { check = circular = true; if (infinite) { fprintf(stderr, "err: options 'c', 'f' mutually exclusive\n"); return 1; } } else if (c == 'f') { check = infinite = true; if (circular) { fprintf(stderr, "err: options 'c', 'f' mutually exclusive\n"); return 1; } #endif } else if (c == 'h') { print_usage(); return 0; } else if (c == 'p') { onlyPrint = true; } else if (c == 'v') { verbose = true; } else if (c == '?') { fprintf(stderr, "err: unknown option '%c'\n", optopt); return 1; } else if (c == ':') { fprintf(stderr, "err: option '%c' requires argument\n", optopt); return 1; } } if (optind >= argc) { fprintf(stderr, "err: no file provided\n"); return 1; } // read entire file FILE* f = fopen(argv[optind], "r"); if (!f) { fprintf(stderr, "err: unable to open file '%s'\n", argv[1]); return 1; } size_t i, length = 0, maxLength = 1024, depth = 0, maxDepth = 1, line = 1, col = 0; unsigned char* code = malloc(maxLength * sizeof(char)); if (!code) { fprintf(stderr, "err: failed to allocate file read buffer\n"); fclose(f); return 1; } while ((c = fgetc(f)) != EOF) { ch = (unsigned char) c; if (ch == '\n') { line++; col = 0; } col++; if (ch != '+' && ch != '-' && ch != '<' && ch != '>' && ch != '[' && ch != ']' && ch != '.' && ch != ',') continue; if (ch == '[') { depth++; if (depth > maxDepth) { // overestimate of loop depth b/c later optimizations, should be good enough maxDepth = depth; } } else if (ch == ']') { if (depth == 0) { fprintf(stderr, "err: closing bracket with no opening bracket at line %zu col %zu\n", line, col); fclose(f); free(code); return 1; } depth--; } length++; if (length > maxLength) { maxLength *= 2; unsigned char* newCode = realloc(code, maxLength * sizeof(char)); if (!newCode) { fprintf(stderr, "err: failed to allocate file read buffer\n"); fclose(f); free(code); return 1; } code = newCode; } code[length - 1] = ch; } fclose(f); if (depth != 0) { fprintf(stderr, "err: opening bracket with no closing bracket (need %zu at end)\n", depth); free(code); return 1; } if (verbose) fprintf(stderr, "read %zu bf instructions\n", length); // convert bf into optimized bytecode-like structure size_t instrCt; // true only if cell currently pointed to during execution must be zero (program start, end of loop) bool definiteZero = true; unsigned char deltaInc; int deltaShift; i = instrCt = depth = deltaInc = deltaShift = 0; size_t *stk = malloc(maxDepth * sizeof(size_t)); if (!stk) { fprintf(stderr, "err: failed to allocate stack\n"); free(code); return 1; } // quite a bit more memory that we will probably end up using... // can't easily realloc later without moving ptrs around Code* bytecode = calloc(length + 1, sizeof(Code)); if (!bytecode) { fprintf(stderr, "err: failed to allocate bytecode\n"); free(code); free(stk); return 1; } bf_func bf_getc = onEof == EOF_UNCHANGED ? bf_getc_unc : bf_getc_val; while (i < length) { ch = code[i]; // optimize simple loops that set cell to 0 ([-], [+]) if (!definiteZero && i < length - 2 && ch == '[' && (code[i + 1] == '+' || code[i + 1] == '-') && code[i + 2] == ']') { // definiteZero == true case handled below along with other loops if (deltaShift) { emit_code(&bytecode[instrCt], deltaInc, deltaShift); deltaInc = deltaShift = 0; instrCt++; } deltaInc = 0; bytecode[instrCt].func = bf_zero; i += 2; instrCt++; definiteZero = true; } else if (ch == '<') { deltaShift--; definiteZero = false; } else if (ch == '>') { deltaShift++; definiteZero = false; } else if (ch == '-') { if (deltaShift) { emit_code(&bytecode[instrCt], deltaInc, deltaShift); deltaInc = deltaShift = 0; instrCt++; } deltaInc--; definiteZero = false; } else if (ch == '+') { if (deltaShift) { emit_code(&bytecode[instrCt], deltaInc, deltaShift); deltaInc = deltaShift = 0; instrCt++; } deltaInc++; definiteZero = false; } else if (ch == '[') { bool emitted = false; if (deltaInc || deltaShift) { emit_code(&bytecode[instrCt], deltaInc, deltaShift); deltaInc = deltaShift = 0; //instrCt++; // don't increment instrction count yet definiteZero = false; emitted = true; } // prune dead code if (definiteZero) { size_t currentDepth = depth; depth++; while (depth > currentDepth) { i++; if (code[i] == '[') depth++; else if (code[i] == ']') depth--; // i now pts to closing bracket, but incremented again at bottom of loop } } else { bytecode[instrCt].func = emitted ? bf_inc_shift_lb : bf_lb; stk[depth++] = instrCt; // now increment ct here instrCt++; } } else if (ch == ']') { bool emitted = false; if (deltaInc || deltaShift) { emit_code(&bytecode[instrCt], deltaInc, deltaShift); deltaInc = deltaShift = 0; //instrCt++; // similar to above definiteZero = false; emitted = true; } bytecode[instrCt].func = emitted ? bf_inc_shift_rb : definiteZero ? bf_rb_nop : bf_rb; size_t open = stk[--depth]; // point at each other for now, will get changed later bytecode[open].branch = &bytecode[instrCt]; bytecode[instrCt].branch = &bytecode[open]; instrCt++; definiteZero = true; } else if (ch == '.') { if (deltaInc || deltaShift) { emit_code(&bytecode[instrCt], deltaInc, deltaShift); deltaInc = deltaShift = 0; instrCt++; definiteZero = false; } bytecode[instrCt].func = bf_putc; instrCt++; } else if (ch == ',') { if (deltaInc || deltaShift) { emit_code(&bytecode[instrCt], deltaInc, deltaShift); deltaInc = deltaShift = 0; instrCt++; } deltaInc = 0; bytecode[instrCt].func = bf_getc; instrCt++; definiteZero = false; } i++; } if (deltaInc || deltaShift) { emit_code(&bytecode[instrCt], deltaInc, deltaShift); deltaInc = deltaShift = 0; instrCt++; } free(code); free(stk); if (onlyPrint) { print_code(stdout, bytecode, instrCt, true); free(bytecode); return 0; } // set next ptrs size_t realCt = 0; for (i = 0; i < instrCt; i++) { // addition loop: left bracket + inc_shift + inc_shift_rb, where the shifts are opposite if (i < instrCt - 2) { if ((bytecode[i].func == bf_lb || bytecode[i].func == bf_inc_shift_lb) && bytecode[i + 1].func == bf_inc_shift && bytecode[i + 2].func == bf_inc_shift_rb) { if (bytecode[i + 1].inc == (unsigned char) -1 && bytecode[i + 1].shift == -bytecode[i + 2].shift) { bytecode[i + 1].func = bf_nop; bytecode[i + 2].func = bf_nop; size_t change; if (bytecode[i].func == bf_inc_shift_lb) { bytecode[i].func = bf_inc_shift; change = i + 1; } else { change = i; } bytecode[change].func = bf_add; bytecode[change].inc = bytecode[i + 2].inc; bytecode[change].shift = bytecode[i + 1].shift; } } } // micro-opt: skip nops if (bytecode[i].func == bf_rb_nop) { (*(bytecode[i].branch - 1)).branch = &bytecode[realCt]; } else if (bytecode[i].func != bf_nop) { if (i != realCt) { memcpy(&bytecode[realCt], &bytecode[i], sizeof(Code)); } if (bytecode[realCt].func == bf_lb || bytecode[realCt].func == bf_inc_shift_lb) { bytecode[realCt].branch->branch = &bytecode[realCt + 1]; } else if (bytecode[realCt].func == bf_rb || bytecode[realCt].func == bf_inc_shift_rb) { (*(bytecode[realCt].branch - 1)).branch = &bytecode[realCt + 1]; } bytecode[realCt].next = &bytecode[realCt + 1]; realCt++; } } // emit last instruction // realCt == number of instructions not counting this last one bytecode[realCt].func = bf_end; // run if (verbose) fprintf(stderr, "translated to %zu bytecode instructions\n", realCt); tape = tapePtr = calloc((size_t) tapeLength, sizeof(unsigned char)); if (!tape) { fprintf(stderr, "err: failed to allocate tape\n"); free(bytecode); return 1; } #ifndef NO_CHECK_BOUNDS tapeEnd = tape + tapeLength; #endif // ip Code* ptr = bytecode; while (ptr) { ptr = ptr->func(ptr); } free(bytecode); free(tape); return 0; }
int VCPU::print_state_compat(FILE * o) const { int len = 0; if ( this->flags & CPU_GP_REGS ) { len += FPRINTF(o, "\tEIP: %04"PRIx16":[<%08"PRIx32">] Ring %d\n", this->regs.cs, this->regs.eip, this->regs.cs & 0x3); len += FPRINTF(o, "\tEFLAGS: %08"PRIx32" ", this->regs.eflags); len += print_rflags(o, this->regs.rflags & -((uint32_t)1)); len += FPUTS("\n", o); len += FPRINTF(o, "\teax: %08"PRIx32" ebx: %08"PRIx32" ", this->regs.eax, this->regs.ebx); len += FPRINTF(o, "ecx: %08"PRIx32" edx: %08"PRIx32"\n", this->regs.ecx, this->regs.edx); len += FPRINTF(o, "\tesi: %08"PRIx32" edi: %08"PRIx32" ", this->regs.esi, this->regs.edi); len += FPRINTF(o, "ebp: %08"PRIx32" esp: %08"PRIx32"\n", this->regs.ebp, this->regs.esp); } if ( this->flags & CPU_CR_REGS ) { len += FPRINTF(o, "\tcr3: %016"PRIx64"\n", this->regs.cr3); } if ( this->flags & CPU_GP_REGS ) { len += FPUTS("\n", o); if ( this->flags & CPU_SEG_REGS ) len += FPRINTF(o, "\tds: %04"PRIx16" es: %04"PRIx16" " "fs: %04"PRIx16" gs: %04"PRIx16" " "ss: %04"PRIx16" cs: %04"PRIx16"\n", this->regs.ds, this->regs.es, this->regs.fs, this->regs.gs, this->regs.ss, this->regs.cs); else len += FPRINTF(o, "\tss: %04"PRIx16" cs: %04"PRIx16"\n", this->regs.ss, this->regs.cs); } len += FPUTS("\n", o); len += FPRINTF(o, "\tPause Count: %"PRId32", Flags: 0x%"PRIx32" ", this->pause_count, this->pause_flags); len += print_pause_flags(o, this->pause_flags); len += FPUTS("\n", o); switch ( this->runstate ) { case RST_NONE: len += FPRINTF(o, "\tNot running: Last run on PCPU%"PRIu32"\n", this->processor); break; case RST_RUNNING: len += FPRINTF(o, "\tCurrently running on PCPU%"PRIu32"\n", this->processor); break; case RST_CTX_SWITCH: len += FPUTS("\tBeing Context Switched: State unreliable\n", o); break; default: len += FPUTS("\tUnknown runstate\n", o); break; } len += FPRINTF(o, "\tStruct vcpu at %016"PRIx64"\n", this->vcpu_ptr); len += FPUTS("\n", o); if ( this->flags & CPU_GP_REGS && this->flags & CPU_CR_REGS ) { len += FPRINTF(o, "\tStack at %08"PRIx32":", this->regs.esp); len += print_32bit_stack(o, *this->dompt, this->regs.rsp); len += FPUTS("\n\tCode:\n", o); len += print_code(o, *this->dompt, this->regs.rip); len += FPUTS("\n\tCall Trace:\n", o); if ( this->domid == 0 ) { vaddr_t sp = this->regs.rsp; vaddr_t top = (this->regs.rsp | (PAGE_SIZE-1))+1; union { uint32_t val32; uint64_t val64; } val; val.val64 = 0; len += host.dom0_symtab.print_symbol32(o, this->regs.rip, true); try { while ( sp < top ) { memory.read32_vaddr(*this->dompt, sp, val.val32); len += host.dom0_symtab.print_symbol32(o, val.val64); sp += 4; } } catch ( const CommonError & e ) { e.log(); } } else len += FPUTS("\t No symbol table for domain\n", o); } len += FPUTS("\n", o); return len; }
int main(int argc, char **argv) { unsigned char *start_libc; unsigned long num_pages; unsigned char code[100]; unsigned char generated[500]; unsigned long size = 100; unsigned char *address, *gen = generated, *pop_rax, *sysenter; const char *hello = "Hello, world!\n"; if (argc != 3) { fprintf(stderr, "usage: %s start_libc num_pages\n", argv[0]); return EXIT_FAILURE; } start_libc = (unsigned char *)strtoull(argv[1], NULL, 0); num_pages = strtoul(argv[2], NULL, 0); find_all_ret(start_libc, num_pages); get_bytes("retq", code, &size); print_code(code, size); size = 100; get_bytes("syscall", code, &size); sysenter = look_in_libc(code, size); if (!sysenter) { printf(":(\n"); return EXIT_FAILURE; } size = 100; //hello world in ROP! get_bytes("popq %rax", code, &size); pop_rax = address = look_in_libc(code, size); memcpy(gen, &address, sizeof(address)); gen += sizeof(address); *((unsigned long long *)gen) = 1ULL; // syscall code gen += sizeof(unsigned long long); size = 100; get_bytes("popq %rdi", code, &size); address = look_in_libc(code, size); memcpy(gen, &address, sizeof(address)); gen += sizeof(address); *((unsigned long long *)gen) = 1ULL; // stdout gen += sizeof(address); size = 100; get_bytes("popq %rsi", code, &size); address = look_in_libc(code, size); memcpy(gen, &address, sizeof(address)); gen += sizeof(address); *((unsigned long long *)gen) = (unsigned long long)(generated + 500 - strlen(hello)); gen += sizeof(address); size = 100; get_bytes("popq %rdx", code, &size); address = look_in_libc(code, size); memcpy(gen, &address, sizeof(address)); gen += sizeof(address); *((unsigned long long *)gen) = 14ULL; // Hello, world!\n gen += sizeof(address); memcpy(gen, &sysenter, sizeof(sysenter)); gen += sizeof(address); memcpy(gen, &pop_rax, sizeof(pop_rax)); gen += sizeof(address); *((unsigned long long *)gen) = 60ULL; // syscall exit gen += sizeof(address); memcpy(gen, &sysenter, sizeof(sysenter)); size = 100; memcpy(generated + 500 - strlen(hello), hello, strlen(hello)); clean_ret_list(); set_sp_relevant(generated - sizeof(void *)); return 0; }
static void gen_exp (rtx x, enum rtx_code subroutine_type, char *used) { RTX_CODE code; int i; int len; const char *fmt; if (x == 0) { printf ("NULL_RTX"); return; } code = GET_CODE (x); switch (code) { case MATCH_OPERAND: case MATCH_DUP: if (used) { if (used[XINT (x, 0)]) { printf ("copy_rtx (operand%d)", XINT (x, 0)); return; } used[XINT (x, 0)] = 1; } printf ("operand%d", XINT (x, 0)); return; case MATCH_OP_DUP: printf ("gen_rtx_fmt_"); for (i = 0; i < XVECLEN (x, 1); i++) printf ("e"); printf (" (GET_CODE (operand%d), ", XINT (x, 0)); if (GET_MODE (x) == VOIDmode) printf ("GET_MODE (operand%d)", XINT (x, 0)); else printf ("%smode", GET_MODE_NAME (GET_MODE (x))); for (i = 0; i < XVECLEN (x, 1); i++) { printf (",\n\t\t"); gen_exp (XVECEXP (x, 1, i), subroutine_type, used); } printf (")"); return; case MATCH_OPERATOR: printf ("gen_rtx_fmt_"); for (i = 0; i < XVECLEN (x, 2); i++) printf ("e"); printf (" (GET_CODE (operand%d)", XINT (x, 0)); printf (", %smode", GET_MODE_NAME (GET_MODE (x))); for (i = 0; i < XVECLEN (x, 2); i++) { printf (",\n\t\t"); gen_exp (XVECEXP (x, 2, i), subroutine_type, used); } printf (")"); return; case MATCH_PARALLEL: case MATCH_PAR_DUP: printf ("operand%d", XINT (x, 0)); return; case MATCH_SCRATCH: gen_rtx_scratch (x, subroutine_type); return; case PC: printf ("pc_rtx"); return; case RETURN: printf ("ret_rtx"); return; case SIMPLE_RETURN: printf ("simple_return_rtx"); return; case CLOBBER: if (REG_P (XEXP (x, 0))) { printf ("gen_hard_reg_clobber (%smode, %i)", GET_MODE_NAME (GET_MODE (XEXP (x, 0))), REGNO (XEXP (x, 0))); return; } break; case CC0: printf ("cc0_rtx"); return; case CONST_INT: if (INTVAL (x) == 0) printf ("const0_rtx"); else if (INTVAL (x) == 1) printf ("const1_rtx"); else if (INTVAL (x) == -1) printf ("constm1_rtx"); else if (-MAX_SAVED_CONST_INT <= INTVAL (x) && INTVAL (x) <= MAX_SAVED_CONST_INT) printf ("const_int_rtx[MAX_SAVED_CONST_INT + (%d)]", (int) INTVAL (x)); else if (INTVAL (x) == STORE_FLAG_VALUE) printf ("const_true_rtx"); else { printf ("GEN_INT ("); printf (HOST_WIDE_INT_PRINT_DEC_C, INTVAL (x)); printf (")"); } return; case CONST_DOUBLE: case CONST_FIXED: case CONST_WIDE_INT: /* These shouldn't be written in MD files. Instead, the appropriate routines in varasm.c should be called. */ gcc_unreachable (); default: break; } printf ("gen_rtx_"); print_code (code); printf (" (%smode", GET_MODE_NAME (GET_MODE (x))); fmt = GET_RTX_FORMAT (code); len = GET_RTX_LENGTH (code); for (i = 0; i < len; i++) { if (fmt[i] == '0') break; printf (",\n\t"); switch (fmt[i]) { case 'e': case 'u': gen_exp (XEXP (x, i), subroutine_type, used); break; case 'i': printf ("%u", XINT (x, i)); break; case 's': printf ("\"%s\"", XSTR (x, i)); break; case 'E': { int j; printf ("gen_rtvec (%d", XVECLEN (x, i)); for (j = 0; j < XVECLEN (x, i); j++) { printf (",\n\t\t"); gen_exp (XVECEXP (x, i, j), subroutine_type, used); } printf (")"); break; } default: gcc_unreachable (); } } printf (")"); }
int main(int argc, char **argv) { FILE *input_file = NULL; int l_flag = 0, a_flag = 0, v_flag = 0; // output flags if(argc > 1) { int i; for(i = 1; i < argc; i++) { // last arg must be the input_file if((i+1) == argc) { input_file = fopen(argv[i], "r"); if(!input_file) { printf("File %s not found.\n", argv[1]); exit(EXIT_FAILURE); } } else { if(argv[i][0] == '-') { int j; for(j = 1; j < strlen(argv[i]); j++) { if(argv[i][j] == 'l') l_flag = 1; else if(argv[i][j] == 'a') a_flag = 1; else if(argv[i][j] == 'v') v_flag = 1; else { printf("Unknown option: %s\n", argv[i]); exit(EXIT_FAILURE); } } } } } } else { printf("Usage: pl0-compiler [-l] [-a] [-v] /path/to/input_file\n"); exit(EXIT_FAILURE); } FILE *lexeme_file = tmpfile(); pl0_lex(input_file, lexeme_file, l_flag); fclose(input_file); rewind(lexeme_file); int error_code = pl0_parse(lexeme_file, a_flag); fclose(lexeme_file); if(error_code == 0) { FILE *code_file = tmpfile(); print_code(code_file); rewind(code_file); if(v_flag) { printf("Running in PM/0\n"); printf("===============\n\n"); } error_code = pm0(code_file, v_flag); if(v_flag) { printf("\n===============\n\n"); } if(!error_code) { if(v_flag) { printf("Finished without error.\n"); } } else { printf("Error number %d.\n", error_code); } fclose(code_file); } else { printf("Error number %d, %s\n", error_code, get_parse_error(error_code)); } return EXIT_SUCCESS; }