/* * AVR8 emulator * * Copyright (C) 2007 Michael Buesch * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include "emulator/avr8emu.h" #include #include #include #include #include static struct avr8emu *emulator; static void cb_status_message(struct avr8emu *emu, const char *msg) { printf("MM %s", msg); } static const struct avr8emu_callbacks callbacks = { .status_message = cb_status_message, }; static void usage(char **argv) { printf("Usage: %s BINARY_AVR_CODE\n", argv[0]); } static void signal_handler(int signr) { int err; if (emulator) { do { err = avr8emu_poll_status(emulator); } while (!err); avr8emu_remove(emulator); } exit(1); } int main(int argc, char **argv) { struct sigaction sa; const char *filename; struct avr8emu *emu; FILE *fd; long int filesize; char *bin; int err; size_t res; if (argc != 2) { usage(argv); return 1; } filename = argv[1]; sa.sa_handler = signal_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGSEGV, &sa, NULL); sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); fd = fopen(filename, "r"); if (!fd) { fprintf(stderr, "Could not open file %s\n", filename); return 1; } err = fseek(fd, 0, SEEK_END); if (err) { fprintf(stderr, "Failed to seek in file %s\n", filename); fclose(fd); } filesize = ftell(fd); err = fseek(fd, 0, SEEK_SET); if (err) { fprintf(stderr, "Failed to seek in file %s\n", filename); fclose(fd); return 1; } bin = malloc(filesize); if (!bin) { fprintf(stderr, "Out of memory\n"); fclose(fd); return 1; } res = fread(bin, filesize, 1, fd); fclose(fd); if (res != 1) { fprintf(stderr, "Could not read file (%u)\n", res); free(bin); return 1; } emu = avr8emu_create(AVR_ATMEGA168, &callbacks);//FIXME if (!emu) { free(bin); return 1; } err = avr8emu_initialize(emu, bin, filesize); if (err) { fprintf(stderr, "emulator init failed\n"); goto out; } err = avr8emu_reset(emu); if (err) { fprintf(stderr, "emulator reset failed\n"); goto out; } printf("emulator running...\n"); emulator = emu; while (1) { avr8emu_poll_messages(emu); while (!avr8emu_poll_status(emu)) ; } out: avr8emu_remove(emu); free(bin); }