#include #include #include #include #include #include #include "linenoise.h" #include "mujs.h" #define LOG_ERR(fmt, ...) fprintf(stderr, "Error: " fmt, ##__VA_ARGS__) #define LOG_INF(fmt, ...) fprintf(stdout, "Info: " fmt, ##__VA_ARGS__) #define unused(x) ((void)(x)) #define shift(argc, argv, msg, ...) (argc <= 0 ? (LOG_ERR(msg, ##__VA_ARGS__), exit(EXIT_FAILURE)) : (void)0, argc--, *argv++) typedef struct { const char *file; pid_t pid; js_State *js; } Dbg; void dbg_js_print_file(js_State *js) { void *data = js_currentfunctiondata(js); Dbg *dbg = (Dbg *)data; printf("File: %s\n", dbg->file); } void dbg_init_js(Dbg *dbg) { dbg->js = js_newstate(NULL, NULL, JS_STRICT); js_newcfunctionx(dbg->js, &dbg_js_print_file, "print_file", 0, dbg, NULL); js_setglobal(dbg->js, "print_file"); } void dbg_init(Dbg *dbg, const char *file, pid_t pid) { dbg->file = file; dbg->pid = pid; dbg_init_js(dbg); } void dbg_deinit(Dbg *dbg) { js_freestate(dbg->js); } void dbg_loop(Dbg *dbg) { int status, options = 0; waitpid(dbg->pid, &status, options); char *line = NULL; while ((line = linenoise("debugus # ")) != NULL) { js_dostring(dbg->js, line); linenoiseHistoryAdd(line); linenoiseFree(line); } } void start_debugging(const char *input_file_path) { pid_t pid = fork(); if (pid == 0) { /* ptrace(PTRACE_TRACEME, 0, NULL, NULL); */ /* execl(input_file_path, input_file_path, NULL); */ } else if (pid >= 1) { Dbg dbg; dbg_init(&dbg, input_file_path, pid); dbg_loop(&dbg); dbg_deinit(&dbg); } } int main(int argc, char ** argv) { const char *program_name = shift(argc, argv, ""); unused(program_name); const char *input_file_path = shift(argc, argv, "No input file provided\n"); start_debugging(input_file_path); return 0; }