Example #1
0
// If configured to do so, dump memory around *all* registers
// for the crashing thread.
void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
  pt_regs r;
  if (ptrace(PTRACE_GETREGS, backtrace->Tid(), 0, &r)) {
    ALOGE("cannot get registers: %s\n", strerror(errno));
    return;
  }

  static const char reg_names[] = "$0atv0v1a0a1a2a3a4a5a6a7t0t1t2t3s0s1s2s3s4s5s6s7t8t9k0k1gpsps8ra";

  for (int reg = 0; reg < 32; reg++) {
    // skip uninteresting registers
    if (reg == 0 // $0
        || reg == 26 // $k0
        || reg == 27 // $k1
        || reg == 31 // $ra (done below)
       )
      continue;

    dump_memory(log, backtrace, R(r.regs[reg]), "memory near %.2s:", &reg_names[reg * 2]);
  }

  uintptr_t pc = R(r.cp0_epc);
  uintptr_t ra = R(r.regs[31]);
  dump_memory(log, backtrace, pc, "code around pc:");
  if (pc != ra) {
    dump_memory(log, backtrace, ra, "code around ra:");
  }
}
Example #2
0
// If configured to do so, dump memory around *all* registers
// for the crashing thread.
void dump_memory_and_code(log_t* log, pid_t tid, int scope_flags) {
  struct pt_regs regs;
  if (ptrace(PTRACE_GETREGS, tid, 0, &regs)) {
    return;
  }

  if (IS_AT_FAULT(scope_flags) && DUMP_MEMORY_FOR_ALL_REGISTERS) {
    static const char REG_NAMES[] = "r0r1r2r3r4r5r6r7r8r9slfpipsp";

    for (int reg = 0; reg < 14; reg++) {
      // this may not be a valid way to access, but it'll do for now
      uintptr_t addr = regs.uregs[reg];

      // Don't bother if it looks like a small int or ~= null, or if
      // it's in the kernel area.
      if (addr < 4096 || addr >= 0xc0000000) {
        continue;
      }

      _LOG(log, scope_flags | SCOPE_SENSITIVE, "\nmemory near %.2s:\n", &REG_NAMES[reg * 2]);
      dump_memory(log, tid, addr, scope_flags | SCOPE_SENSITIVE);
    }
  }

  // explicitly allow upload of code dump logging
  _LOG(log, scope_flags, "\ncode around pc:\n");
  dump_memory(log, tid, static_cast<uintptr_t>(regs.ARM_pc), scope_flags);

  if (regs.ARM_pc != regs.ARM_lr) {
    _LOG(log, scope_flags, "\ncode around lr:\n");
    dump_memory(log, tid, static_cast<uintptr_t>(regs.ARM_lr), scope_flags);
  }
}
Example #3
0
int	launch_vm(t_param *param)
{
  t_vm	*vm;
  int	i;

  if ((vm = my_malloc(sizeof(t_vm), "Error: fail to malloc vm\n")) == 0)
    return (1);
  vm->screen = SDL_SetVideoMode(MEM_SIZE / NB_COL * WIDTH + DECAL, NB_COL * WIDTH, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
  SDL_WM_SetCaption("Corewar", NULL);
  if (vm->screen == NULL)
    err_SDL();
  vm->police = TTF_OpenFont("arial.ttf", 20);
  vm->param = param;
  vm->cycle = 0;
  vm->cycle_to_die = CYCLE_TO_DIE;
  vm->nb_live = 0;
  owner_set(vm->mem_owner, -1, 0, MEM_SIZE);
  my_memset(vm->register_player, 0, (MAX_PLAYER + 1) * sizeof(char));
  i = 0;
  while (i < MAX_PROG_NUMBER)
    vm->progs_live[i++] = -1;
  if (load_all_programs(vm) != 0)
    return (1);
  my_printf("%d program(s) loaded\n", vm->prog_list->nb_elm);
  if (param->debug == 1)
    dump_memory(vm->memory);
  pause_vm(vm, 1);
  vm_run(vm);
  pause_vm(vm, 0);
  if (param->debug == 1)
    dump_memory(vm->memory);
  TTF_CloseFont(vm->police);
  return (0);
}
Example #4
0
void on_break(int32_t s) {
    puts("");

    static bool s_double = false;
    if (s_double)
    {
        puts("User interrupt.");

#ifdef DEBUG
        dump_memory(0);
#endif

        _exit(1);
    }
    s_double = true;

#ifdef WIN32
    exlib::OSThread _thread;
    _thread.bindCurrent();
#endif

    Isolate *p = s_isolates.head();
    while (p != 0) {
        p->m_isolate->RequestInterrupt(cb_interrupt, NULL);
        p->m_interrupt = true;
        // p->RequestInterrupt(InterruptCallbackEx);

        p = s_isolates.next(p);
    }
}
Example #5
0
int main(int argc, char *argv[]) {

  printf("[*] Android Dalvik Unpacker/Unprotector - <*****@*****.**>\n");

  if(argc <= 0) {
    printf(" [!] Nothing to unpack, quitting\n");
    return 0;
  }

  if(getuid() != 0) {
    printf(" [!] Not root, quitting\n");
    return -1;
  }

  char *package_name = argv[1];
  printf(" [+] Hunting for %s\n", package_name);

  uint32_t pid = get_process_pid(package_name);
  if(pid <= 0) {
    printf(" [!] Process could not be found!\n");
    return -1;
  }
  printf(" [+] %d is service pid\n", pid);

  uint32_t clone_pid = get_clone_pid(pid);
  if(clone_pid <= 0) {
    printf(" [!] A suitable clone process could not be found!");
    return -1;
  }
  printf(" [+] %d is clone pid\n", clone_pid);

  int mem_file = attach_get_memory(clone_pid);
  if(mem_file == -1) {
    printf(" [!] An error occured attaching and finding the memory!\n");
    return -1;
  }

  // Determine if we are dealing with APKProtect or Bangcle
  char *extra_filter = determine_filter(clone_pid, mem_file);

  memory_region memory;
  if(find_magic_memory(clone_pid, mem_file, &memory, extra_filter) <= 0) {
    printf(" [!] Something unexpected happened, new version of packer/protectors? Or it wasn't packed/protected!\n");
    return -1;
  }
  printf(" [+] Unpacked odex found in memory!\n");

  // Build a safe file to dump to and call the memory dumping function
  char *dumped_file_name = malloc(strlen(static_safe_location) + strlen(package_name) + strlen(suffix));
  sprintf(dumped_file_name, "%s%s%s", static_safe_location, package_name, suffix);
  if(dump_memory(mem_file, &memory, dumped_file_name) <= 0) {
    printf(" [!] An issue occured trying to dump the memory to a file!\n");
    return -1;
  }
  printf(" [+] Unpacked/protected file dumped to : %s\n", dumped_file_name);

  close(mem_file);
  ptrace(PTRACE_DETACH, clone_pid, NULL, 0);
  return 1;
}
Example #6
0
void dispatch_wait2(dispatch_t * self, int timeout)
{
	if (unlikely(self == NULL))
		throw_unexpected(DISPATCH_NULL);

	if (-1 < self->fd) {
		struct epoll_event events[DISPATCH_EVENT_SIZE];

		int rc = epoll_wait(self->fd, events,
				    DISPATCH_EVENT_SIZE, timeout);

		if (0 < rc) {
			dump_memory(stdout, 0, events, sizeof(events));
		}
		for (int n = 0; n < rc; n++) {
			dispatch_callback_t *cb =
			    (dispatch_callback_t *) events[n].data.ptr;
			if (cb != NULL) {
				printf
				    ("cb[%p] fd[%d] data[%p] ep->data.u64[%lld]\n",
				     cb, cb->fd, cb->data, events[n].data.u64);
				if (cb->func != NULL) {
					// dispatch_event ev = {events[n].data.u64 >> 32, events[n].events};
					dispatch_event_t ev =
					    { cb->fd, events[n].events };
					cb->func(&ev, cb->data);
				}
			}
		}
	}
}
Example #7
0
void		battle_begins(int dump, t_uchar *arena,
			      t_champ *champ, t_cycle *cycles)
{
  t_champ	*tmp;

  while (cycles->cycle_to_die > 0 && check_round(champ, cycles))
    {
      tmp = champ->next;
      while (tmp != champ)
	{
	  check_cycles(tmp, arena, cycles);
	  tmp->cycle_to_die++;
	  tmp = tmp->next;
	  if (cycles->nbr_live >= NBR_LIVE)
	    {
	      cycles->cycle_to_die -= CYCLE_DELTA;
	      cycles->nbr_live = 0;
	    }
	}
      if (cycles->current_cycle == dump)
	dump_memory(champ, cycles, arena);
      cycles->current_cycle += 1;
    }
  is_there_a_winner(arena, champ, cycles);
}
int execute_command(char cmd_char, int reg[], int nreg,
                    int mem[], int memlen)
{

  if (cmd_char == '?' || cmd_char == 'h')
    help_message();

  switch (cmd_char) {
  case 'd':
    dump_control_unit(pc, ir, running, reg, nreg);
    dump_memory(mem, memlen);
    return 0;
    break;

  case 'q':
    return 1;
    break;

  case '\n':
    one_instruction_cycle(reg, nreg, mem, memlen);
    return 0;
    break;

  default:
    printf("Please enter a valid character");
    break;
  }

  return 0;
}
Example #9
0
void main(int argc,char **argv)
{
	DWORD iLength;
	void * pvStartingAddress;
	DWORD PID;
	static char * szPid;
	static char * szAddress;
	static char * szLength;
	static char * szFile;

	static BEGIN_ARGS	
		ARG("f:",szFile,"char *","Output file name.")
		ARG("p:",szPid,"char *","PID of the destination process(hex)")
		ARG("a:",szAddress,"char *","Starting address(hex).")
		ARG("l:",szLength,"char *","Length of memory to dump(hex).")
	END_ARGS

	process_args_1(argc,argv);
	if(!szFile || !szPid || !szAddress || !szLength){
		print_usage(__CmdLineArgValues);
		return;
	};
	sscanf(szPid,"%x",&PID);
	sscanf(szLength,"%x",&iLength);
	sscanf(szAddress,"%x",&pvStartingAddress);
	dump_memory(PID,pvStartingAddress,iLength,szFile);
}
Example #10
0
int main(int argc, const char *argv[]) {
	volatile double d;
	volatile float f;
	volatile unsigned char *p;

	/* FLT_MAX: (1 - 2^(-24)) * 2^128. */
	printf("- FLT_MAX\n");
	d = FLT_MAX;
	f = (float) d;
	printf("d: %f\n", d);
	printf("f: %f\n", f);
	dump_memory((volatile unsigned char *) &d, 8);
	dump_memory((volatile unsigned char *) &f, 4);

	/* FLT_MAX + floating point unit: 2^128. */
	printf("- FLT_MAX_PLUS\n");
	d = FLT_MAX_PLUS;
	f = (float) d;
	printf("d: %f\n", d);
	printf("f: %f\n", f);
	dump_memory((volatile unsigned char *) &d, 8);
	dump_memory((volatile unsigned char *) &f, 4);

	/* Number between FLT_MAX and FLT_MAX + unit. */
	printf("- between FLT_MAX and FLT_MAX_PLUS\n");
	d = (FLT_MAX + FLT_MAX_PLUS) / 2.0;
	f = (float) d;
	printf("d: %f\n", d);
	printf("f: %f\n", f);
	dump_memory((volatile unsigned char *) &d, 8);
	dump_memory((volatile unsigned char *) &f, 4);

	/* Same as above, but one double unit less.
	 * 47effffff0000000 ->
	 * 47efffffefffffff
	 *
	 * This is the largest double that doesn't round to infinity on x64.
	 */
	printf("- just below above\n");
	p = (volatile unsigned char *) &d;
	p[7] = 0x47U;
	p[6] = 0xefU;
	p[5] = 0xffU;
	p[4] = 0xffU;
	p[3] = 0xefU;
	p[2] = 0xffU;
	p[1] = 0xffU;
	p[0] = 0xffU;
	f = (float) d;
	printf("d: %f\n", d);
	printf("f: %f\n", f);
	dump_memory((volatile unsigned char *) &d, 8);
	dump_memory((volatile unsigned char *) &f, 4);

	return 0;
}
Example #11
0
// Read and dump initial values for memory
//
void initialize_memory(int argc, char *argv[], CPU *cpu) {
    FILE *datafile = get_datafile(argc, argv);
    printf("\nBefore While");
    // Buffer to read next line of text into
    #define BUFFER_LEN 80
    char buffer[BUFFER_LEN];
    printf("\nBefore While");
    // Will read the next line (words_read = 1 if it started
    // with a memory value). Will set memory location loc to
    // value_read
    //
    int value_read, words_read, loc = 0, done = 0;

    char *read_success;    // NULL if reading in a line fails.
    read_success = fgets(buffer, BUFFER_LEN, datafile);
    int range = MEMLEN -1;
    
    while (read_success != NULL && !done) {
        // If the line of input begins with an integer, treat
        // it as the memory value to read in.  Ignore junk
        // after the number and ignore blank lines and lines
        // that don't begin with a number.
        //

        words_read = sscanf(buffer, "%d", &value_read);
        
        //printf("\nWords Read: %d",words_read);
        // *** STUB *** set memory value at current location to
        // value_read and increment location.  Exceptions: If
        // loc is out of range, complain and quit the loop. If
        // value_read is outside -9999...9999, then it's a
        // sentinel and we should say so and quit the loop.
        if(words_read == 1){
            if(loc>range){
                printf("\nERROR: Location %d is outside range",value_read);
                done = 1;
            } else if(value_read < -9999 || value_read > 9999) {
                printf("\nSentinel %d at location %d",value_read,loc);
                done = 1;
            } else {
                (*cpu).mem[loc] = value_read;
                loc++;
            }
        }
        
        // Get next line and continue the loop
        //
        // *** STUB ***
        words_read = sscanf(buffer,"%d",&value_read);
    }//end while
    
    // Initialize rest of memory
    //
    while (loc < MEMLEN) {
        cpu -> mem[loc++] = 0;
    }
    dump_memory(cpu);
}
Example #12
0
int main() {
  registers regs; /* Registers */
  memory mem; /* Main memory */
  int i; /* Instruction count */

  /* 
   * 'Boot up'??
   */

  /* Initialize memory/registers to zero */
  memset(mem.data, 0, MEMSIZE);
  memset(&regs, 0, sizeof(registers));

  /* 'Load' sample program into memory */
  memcpy(mem.data + OS_SIZE, test_program, sizeof(test_program));

  /* Initialize some register and memory values 
   * (hard-coded for the purposes of testing)
   */
  const uint32_t sample_value_addr = OS_SIZE + sizeof(test_program);

  regs.general[0] = 0xDEADBEEF;
  regs.general[1] = sample_value_addr; 
  regs.general[3] = 0xCAFEBABE;

  printf("Initial state:\n");
  dump_registers(&regs);
  dump_memory(&mem);

  /* Execute program */
  regs.prog_counter = OS_SIZE;

  for (i = 0; i < sizeof(test_program)/sizeof(uint32_t); i++) {
    printf("Executing instruction %u in test_program\n", i);

    /* Execute instruction */
    execute(&regs, &mem);

    /* Dump */
    dump_registers(&regs);
    dump_memory(&mem);
  }

  return EXIT_SUCCESS;
}
Example #13
0
void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
  pt_regs regs;
  if (ptrace(PTRACE_GETREGS, backtrace->Tid(), 0, &regs)) {
    ALOGE("cannot get registers: %s\n", strerror(errno));
    return;
  }

  static const char reg_names[] = "r0r1r2r3r4r5r6r7r8r9slfpipsp";

  for (int reg = 0; reg < 14; reg++) {
    dump_memory(log, backtrace, regs.uregs[reg], "memory near %.2s:", &reg_names[reg * 2]);
  }

  dump_memory(log, backtrace, static_cast<uintptr_t>(regs.ARM_pc), "code around pc:");

  if (regs.ARM_pc != regs.ARM_lr) {
    dump_memory(log, backtrace, static_cast<uintptr_t>(regs.ARM_lr), "code around lr:");
  }
}
Example #14
0
// If configured to do so, dump memory around *all* registers
// for the crashing thread.
void dump_memory_and_code(log_t* log, pid_t tid, int scope_flags) {
  pt_regs_mips_t r;
  if (ptrace(PTRACE_GETREGS, tid, 0, &r)) {
    return;
  }

  if (IS_AT_FAULT(scope_flags) && DUMP_MEMORY_FOR_ALL_REGISTERS) {
    static const char REG_NAMES[] = "$0atv0v1a0a1a2a3t0t1t2t3t4t5t6t7s0s1s2s3s4s5s6s7t8t9k0k1gpsps8ra";

    for (int reg = 0; reg < 32; reg++) {
      // skip uninteresting registers
      if (reg == 0 // $0
          || reg == 26 // $k0
          || reg == 27 // $k1
          || reg == 31 // $ra (done below)
         )
        continue;

      uintptr_t addr = R(r.regs[reg]);

      // Don't bother if it looks like a small int or ~= null, or if
      // it's in the kernel area.
      if (addr < 4096 || addr >= 0x80000000) {
        continue;
      }

      _LOG(log, scope_flags | SCOPE_SENSITIVE, "\nmemory near %.2s:\n", &REG_NAMES[reg * 2]);
      dump_memory(log, tid, addr, scope_flags | SCOPE_SENSITIVE);
    }
  }

  unsigned int pc = R(r.cp0_epc);
  unsigned int ra = R(r.regs[31]);

  _LOG(log, scope_flags, "\ncode around pc:\n");
  dump_memory(log, tid, (uintptr_t)pc, scope_flags);

  if (pc != ra) {
    _LOG(log, scope_flags, "\ncode around ra:\n");
    dump_memory(log, tid, (uintptr_t)ra, scope_flags);
  }
}
Example #15
0
File: ecc.c Project: eddiejames/ffs
static void ecc_1(void) {
    int size[] = {7, 8, 16, 1024+16, 4096+32, 8*1024*4+64, 0};

    for (int * s = size; *s != 0; s++) {
        unsigned char in[*s];
        unsigned char out[*s + (*s / 8)];

        ssize_t in_sz = sizeof in;
        ssize_t out_sz = sizeof out;

        memset(in, 0, in_sz);
        memset(out, 0, out_sz);

        FILE * f = fopen("/dev/urandom", "r");
        CU_ASSERT_FATAL(f != NULL);
        CU_ASSERT_FATAL(fread(in, in_sz, 1, f) == 1);
        fclose(f);

        ssize_t rc = sfc_ecc_inject(out, out_sz, in, in_sz);
        if ((*s % 8) != 0) {
            CU_ASSERT(rc == -1);
        } else {
            CU_ASSERT(rc == in_sz + (in_sz / 8));
        }

        unsigned char cmp[*s];
        ssize_t cmp_sz = sizeof cmp;
        memset(cmp, 0, cmp_sz);

        rc = sfc_ecc_remove(cmp, cmp_sz, out, out_sz);
        if ((out_sz % 9) != 0) {
            CU_ASSERT(rc == -1);
        } else {
            CU_ASSERT(rc == in_sz)
            CU_ASSERT_FATAL(memcmp(in, cmp, in_sz) == 0);
#ifdef DEBUG
            dump_memory(stdout, 0, in, in_sz);
            dump_memory(stdout, 0, cmp, cmp_sz);
#endif
        }
    }
}
void process_command ()
{ char action;
  char fname[100];
  int pid, time, ret;

  printf ("command> ");
  scanf ("%c", &action);
  while (action != 'T')
  { switch (action)
    { case 's':   // submit
        scanf ("%s", &fname);
        if (Debug) printf ("File name: %s is submitted\n", fname);
        submit_process (fname);
        break;
      case 'x':  // execute
        execute_process ();
        break;
      case 'r':  // dump register
        dump_registers ();
        break;
      case 'q':  // dump ready queue and list of processes completed IO
        dump_ready_queue ();
        dump_doneWait_list ();
        break;
      case 'p':   // dump PCB
        printf ("PCB Dump Starts: Checks from 0 to %d\n", currentPid);
        for (pid=1; pid<currentPid; pid++)
          if (PCB[pid] != NULL) dump_PCB (pid);
        break;
      case 'e':   // dump events in timer
        dump_events ();
        break;
      case 'm':   // dump Memory
        for (pid=1; pid<currentPid; pid++)
          if (PCB[pid] != NULL) dump_memory (pid);
        break;
      case 'w':   // dump Swap Space
         for (pid=1; pid<currentPid; pid++)
            if (PCB[pid] != NULL) dump_swap_memory (pid);
        break;
      case 'l':   // dump Spool
        for (pid=1; pid<currentPid; pid++)
          if (PCB[pid] != NULL) dump_spool (pid);
        break;
      case 'T':  // Terminate, do nothing, terminate in while loop
        break;
      default: 
        printf ("Incorrect command!!!\n");
    }
    printf ("\ncommand> ");
    scanf ("\n%c", &action);
    if (Debug) printf ("Next command is %c\n", action);
  }
}
Example #17
0
static void out_segment(OutputBuffer* buf,
                        WasmSegment* segment,
                        const char* desc) {
  size_t offset = buf->size;
  ensure_output_buffer_capacity(buf, offset + segment->size);
  void* dest = buf->start + offset;
  wasm_copy_segment_data(segment->data, dest, segment->size);
  if (g_verbose)
    dump_memory(buf->start + offset, segment->size, offset, 1, desc);
  buf->size += segment->size;
}
Example #18
0
File: utils.c Project: AEUG/400plus
static void mem_dumper_task() {
	int i;

	beep();

	for (i=0; i<10; i++) {
		LEDBLUE ^= 2;
		SleepTask(500);
	}

	dump_memory();
}
Example #19
0
result_t process_base::exit(int32_t code)
{
    flushLog(false);

#ifdef DEBUG
    global_base::GC();
    dump_memory();
#endif

    ::_exit(code);
    return 0;
}
Example #20
0
static size_t out_data(OutputBuffer* buf,
                       size_t offset,
                       const void* src,
                       size_t size,
                       const char* desc) {
  assert(offset <= buf->size);
  ensure_output_buffer_capacity(buf, offset + size);
  memcpy(buf->start + offset, src, size);
  if (g_verbose)
    dump_memory(buf->start + offset, size, offset, 0, desc);
  return offset + size;
}
Example #21
0
int main(int argc, char **argv)
{
	struct io_space *ios;
	struct list_head *pvs, *tmp;
	struct dm_pool *mem;

	init_log(stderr);
	init_debug(_LOG_INFO);

	if (!dev_cache_init()) {
		fprintf(stderr, "init of dev-cache failed\n");
		exit(1);
	}

	if (!dev_cache_add_dir("/dev/loop")) {
		fprintf(stderr, "couldn't add /dev to dir-cache\n");
		exit(1);
	}

	if (!(mem = dm_pool_create(10 * 1024))) {
		fprintf(stderr, "couldn't create pool\n");
		exit(1);
	}

	ios = create_lvm1_format("/dev", mem, NULL);

	if (!ios) {
		fprintf(stderr, "failed to create io_space for format1\n");
		exit(1);
	}

	pvs = ios->get_pvs(ios);

	if (!pvs) {
		fprintf(stderr, "couldn't read vg %s\n", argv[1]);
		exit(1);
	}

	list_for_each(tmp, pvs) {
		struct pv_list *pvl = list_entry(tmp, struct pv_list, list);
		dump_pv(&pvl->pv, stdout);
	}

	ios->destroy(ios);

	dm_pool_destroy(mem);
	dev_cache_exit();
	dump_memory();
	fin_log();
	return 0;
}
Example #22
0
// Main program: Initialize the cpu, and read the initial memory values
//
int main(int argc, char *argv[]) {
    printf("SDC Simulator pt 1 Devanshu Bharel: CS 350 Lab 6\n");
    CPU cpu_value, *cpu = &cpu_value;
    printf("Initalizing CPU:\n");
    initialize_CPU(cpu);
    printf("Initalizing MEM:\n");
    initialize_memory(argc, argv, cpu);

    dump_CPU(cpu);
    dump_memory(cpu);
    dump_registers(cpu);
    // That's it for Lab 6
    //
    return 0;
}
/**
 * Shows a mixed hexadecimal+ASCII dump for all allocated chunks within the
 * heap.
 */
void hexdump_heap()
{
    Chunk *cur = alloc_list;

    while (cur) {
        printf("SIZE = %zu:\n", cur->size);
        dump_memory(cur->addr, cur->size);

        if (cur->next) {
            printf("\n");
        }

        cur = cur->next;
    }
}
void initialize_memory(int argc, char *argv[], int mem[], int memlen)
{
  FILE *datafile = get_datafile(argc, argv);

  int value_read, words_read, loc = 0, done = 0;

  char *buffer = NULL;
  size_t buffer_len = 0, bytes_read = 0;


  /* Fetch first instruction */
  bytes_read = getline(&buffer, &buffer_len, datafile);
  while (bytes_read != -1 && !done) {

    words_read = sscanf(buffer, "%d", &value_read);

    /* If beginning was not an integer (junk) discard it and go on
     * else populate memory location and advance to the next one.
     * Always check that you have not hit the memory bound */
    if (words_read == 0 || words_read == -1) {
      bytes_read = getline(&buffer, &buffer_len, datafile);
      continue;
    }

    if (loc > memlen) {
      printf("The memory location is out of range");
      done = 1;
    } else if (value_read > 9999 || value_read < -9999) {
      printf("Hit sentinel, quitting loop");
      done = 1;
    } else {
      mem[loc++] = value_read;
      bytes_read = getline(&buffer, &buffer_len, datafile);
    }
  }

  /* buffer is not needed anymore */
  free(buffer);

  /* zero-out the rest of the memory locations */
  while (loc < memlen) {
    mem[loc] = 0;
    loc++;
  }

  dump_memory(mem, memlen);
}
void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
  struct user_regs_struct r;
  if (ptrace(PTRACE_GETREGS, backtrace->Tid(), 0, &r) == -1) {
    _LOG(log, logtype::ERROR, "cannot get registers: %s\n", strerror(errno));
    return;
  }

  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rax), "memory near rax:");
  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rbx), "memory near rbx:");
  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rcx), "memory near rcx:");
  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rdx), "memory near rdx:");
  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rsi), "memory near rsi:");
  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rdi), "memory near rdi:");

  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rip), "code around rip:");
}
Example #26
0
// Execute a nonnumeric command; complain if it's not 'h', '?', 'd', 'q' or '\n'
// Return true for the q command, false otherwise
//
int execute_command(char cmd_char, int reg[], int nreg, int mem[], int memlen) {
	if (cmd_char == '?' || cmd_char == 'h') {
		help_message();
	} else if (cmd_char == 'd') {
		printf("Dumping control and memory:\n");
		dump_control_unit(pc, ir, running, reg, NREG);
		dump_memory(mem, MEMLEN);
	} else if (cmd_char == 'q') {
		printf("Quitting\n");
		exit(0);
	} else if (cmd_char == '\n' || cmd_char == ' ') {
		one_instruction_cycle(reg,nreg,mem,memlen);
	} else {
		printf("Unkown command: %c; Ignoring it.\n",cmd_char);
		return 1;
	}
	return 0;
}
Example #27
0
int execute_command(char cmd_char, CPU *cpu) {
  if (cmd_char == '?' || cmd_char == 'h') {
    help_message();
  } else if (cmd_char == 'd') {
    printf("Dumping CPU and MEM:\n");
    dump_CPU(cpu);
    dump_memory(cpu);
  } else if (cmd_char == 'q') {
    printf("Quitting. \n");
    exit(0);
  } else if (cmd_char == '\n' || cmd_char == ' ') {
    one_instruction_cycle(cpu);
  } else {
    printf("Unkown Command: %c \n",cmd_char);
    return 1;
  }
  return 0;
}
Example #28
0
// Main program: Initialize the cpu, read initial memory values,
// and execute the read-in program starting at location 00.
//
int main(int argc, char *argv[]) {
	printf("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n");
	printf("=-=-=-=-=-=-= SDC SIM lab06 CS350 Devanshu Bharel =-=-=-=-=-=-=\n");
	printf("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n");
	initialize_control_unit(reg, NREG);
	initialize_memory(argc, argv, mem, MEMLEN);

	char *prompt = "> ";
	printf("\nBeginning execution; type h for help\n%s", prompt);

	int done = read_execute_command(reg, NREG, mem, MEMLEN);
	while (!done) {
		printf("%s", prompt);
		done = read_execute_command(reg, NREG, mem, MEMLEN);
	}
	printf("At termination\n");
	dump_control_unit(pc, ir, running, reg, NREG);
	dump_memory(mem, MEMLEN);
	return 0;
}
Example #29
0
static void dumpFibers()
{
    std::string msg;

    msg.append(COLOR_LIGHTRED "User interrupt.");

    if (Isolate::rt::g_trace)
        msg.append(traceFiber());
    else if (JSFiber::current())
        msg.append(traceInfo(300));

    msg.append(COLOR_RESET "\n");

    std_logger::out(msg.c_str());

#ifdef DEBUG
    dump_memory(0);
#endif

    _exit(1);
}
Example #30
0
// Read and dump initial values for memory
void initialize_memory(int argc, char *argv[], CPU *cpu) {
    FILE *datafile = get_datafile(argc, argv);
    
    #define BUFFER_LEN 80
    char buffer[BUFFER_LEN];

    int value_read, words_read, loc = 0, done = 0;

    char *read_success;    // NULL if reading in a line fails.
    int max=MEMLEN;
    
    read_success = fgets(buffer, BUFFER_LEN, datafile);
    while (read_success != NULL && !done) {
        words_read = sscanf(buffer, "%d", &value_read);
	    if (words_read==1){
	       if(loc>max){
	           printf("\nERROR: Memory out of Range!.");
	           done = 1;
	        }
	    else if (value_read < -9999 || value_read > 9999){
	       printf("\nSentinel %d at %d\n",value_read,loc);
	       done = 1;
	    }
	    else{
	      (*cpu).mem[loc]=value_read;
	      loc++;
	    }
	}
	read_success = fgets(buffer, BUFFER_LEN, datafile);
    }
    
    // Initialize rest of memory with zeroes.
    while (loc < MEMLEN) {
        cpu -> mem[loc++] = 0;
    }
    dump_memory(cpu);
}