/* * TinyBlocks - tb_api.c * Implementacao do gestor publico de modulos/libraries (tinyblocks-api). */ #define _POSIX_C_SOURCE 200809L #include #include #include #include #include #ifdef __linux__ # include # include #endif #include #include "tb_api.h" typedef const TinyBlocks_LibraryDescriptor* (*GetLibFn)(void); static TinyBlocks* s_rt = NULL; static TbApiModule s_mods[TB_API_MAX_MODULES]; static int s_n = 0; static char s_err[256]; /* -- Helpers --- */ static time_t file_mtime(const char* p) { struct stat st; return (stat(p, &st) == 0) ? st.st_mtime : 0; } static void set_err(const char* fmt, const char* a); static void path_dirname(const char* p, char* out, size_t cap); static const char* path_basename(const char* p) { const char* s = strrchr(p, '/'); return s ? s + 1 : p; } /* -- Modulos de codigo (bundle) e watcher de arquivos ------------------- */ typedef struct { char name[64]; char path[TB_API_PATH_LEN]; void* handle; time_t mtime; bool dirty; } TbApiCode; static TbApiCode s_code[TB_API_MAX_CODE]; static int s_cn = 0; static int code_find(const char* name) { if (!name) return -1; for (int i = 0; i < s_cn; i++) if (strcmp(s_code[i].name, name) == 0) return i; return -1; } #ifdef __linux__ # define TB_API_WATCH_MAX 64 typedef struct { int wd; int idx; /* indice em s_code (-1 = so diretorio) */ char base[128]; /* nome do arquivo vigiado */ char dir[TB_API_PATH_LEN]; } TbWatch; static TbWatch s_watch[TB_API_WATCH_MAX]; static int s_wn = 0; static int s_inot = -1; /* Vigia o DIRETORIO do arquivo: cobre tanto escrita no lugar quanto "make" (escreve num temp e renomeia por cima). */ static int watch_add(const char* path) { if (s_inot < 0) return -1; char dir[TB_API_PATH_LEN]; path_dirname(path, dir, sizeof(dir)); if (s_wn > 0 && strcmp(s_watch[s_wn - 1].dir, dir) == 0) { /* mesmo diretorio: reaproveita o wd */ snprintf(s_watch[s_wn - 1].base, sizeof(s_watch[s_wn-1].base), "%s", path_basename(path)); return s_watch[s_wn - 1].wd; } if (s_wn >= TB_API_WATCH_MAX) return -1; int wd = inotify_add_watch(s_inot, dir, IN_CLOSE_WRITE | IN_MOVED_TO | IN_CREATE | IN_ATTRIB); if (wd < 0) return -1; TbWatch* w = &s_watch[s_wn++]; w->wd = wd; w->idx = -1; snprintf(w->dir, sizeof(w->dir), "%s", dir); snprintf(w->base, sizeof(w->base), "%s", path_basename(path)); return wd; } #endif bool tb_api_watch(const char* path) { if (!path || !path[0]) return false; #ifdef __linux__ if (s_inot < 0) { s_inot = inotify_init1(IN_NONBLOCK); if (s_inot < 0) return false; } return watch_add(path) >= 0; #else (void)path; return false; #endif } int tb_api_poll_watch(void) { #ifdef __linux__ if (s_inot < 0 || s_wn <= 0) return 0; char buf[4096] __attribute__((aligned(8))); ssize_t n; int changed = 0; while ((n = read(s_inot, buf, sizeof(buf))) > 0) { for (char* p = buf; p < buf + n; ) { struct inotify_event* ev = (struct inotify_event*)p; p += sizeof(*ev) + ev->len; if (!ev->len) continue; for (int i = 0; i < s_cn; i++) { if (strcmp(ev->name, path_basename(s_code[i].path)) != 0) continue; char d[TB_API_PATH_LEN]; path_dirname(s_code[i].path, d, sizeof(d)); for (int k = 0; k < s_wn; k++) if (s_watch[k].wd == ev->wd && strcmp(s_watch[k].dir, d) == 0) { s_code[i].dirty = true; changed++; } } } } return changed; #else return 0; #endif } static void path_dirname(const char* p, char* out, size_t cap) { snprintf(out, cap, "%s", p); char* sl = strrchr(out, '/'); if (sl) *sl = 0; else snprintf(out, cap, "."); } static bool code_changed_mtime(void) { bool any = false; for (int i = 0; i < s_cn; i++) { time_t mt = file_mtime(s_code[i].path); if (mt && mt != s_code[i].mtime) { s_code[i].dirty = true; any = true; } } return any; } int tb_api_code_load(const char* name, const char* path) { if (!name || !name[0] || !path || !path[0]) { set_err("%s", "tb_api: nome/caminho invalido"); return -1; } int ex = code_find(name); if (ex >= 0 && s_code[ex].handle && strcmp(s_code[ex].path, path) == 0) return ex; if (ex >= 0) tb_api_code_unload(name); if (s_cn >= TB_API_MAX_CODE) { set_err("%s", "tb_api: limite de modulos de codigo"); return -1; } #ifdef __linux__ void* dl = dlopen(path, RTLD_NOW | RTLD_GLOBAL); if (!dl) { set_err("dlopen: %s", dlerror()); return -1; } TbApiCode* c = &s_code[s_cn]; memset(c, 0, sizeof(*c)); snprintf(c->name, sizeof(c->name), "%s", name); snprintf(c->path, sizeof(c->path), "%s", path); c->handle = dl; c->mtime = file_mtime(path); c->dirty = false; /* watcher: registro por arquivo, apontando para o modulo */ if (tb_api_watch(path)) { for (int k = s_wn - 1; k >= 0; k--) { if (strcmp(s_watch[k].base, path_basename(path)) == 0) { s_watch[k].idx = s_cn; break; } } } s_err[0] = 0; return s_cn++; #else (void)name; (void)path; set_err("%s", "tb_api: dlopen nao suportado nesta plataforma"); return -1; #endif } bool tb_api_code_unload(const char* name) { int i = code_find(name); if (i < 0) return false; #ifdef __linux__ if (s_code[i].handle) dlclose(s_code[i].handle); #endif for (int k = i; k < s_cn - 1; k++) s_code[k] = s_code[k + 1]; s_cn--; return true; } void tb_api_code_unload_all(void) { for (int i = s_cn - 1; i >= 0; i--) { #ifdef __linux__ if (s_code[i].handle) dlclose(s_code[i].handle); #endif s_code[i].handle = NULL; } s_cn = 0; } int tb_api_code_count(void) { return s_cn; } const char* tb_api_code_name(int i) { return (i >= 0 && i < s_cn) ? s_code[i].name : NULL; } const char* tb_api_code_path(int i) { return (i >= 0 && i < s_cn) ? s_code[i].path : NULL; } void* tb_api_code_handle(const char* name) { int i = code_find(name); return i >= 0 ? s_code[i].handle : NULL; } void* tb_api_code_symbol(const char* name, const char* symbol) { void* h = tb_api_code_handle(name); #ifdef __linux__ if (!h || !symbol) return NULL; return dlsym(h, symbol); #else (void)h; (void)symbol; return NULL; #endif } int tb_api_code_reload_all(void) { char names[TB_API_MAX_CODE][64]; char paths[TB_API_MAX_CODE][TB_API_PATH_LEN]; int n = s_cn; for (int i = 0; i < n; i++) { snprintf(names[i], sizeof(names[i]), "%s", s_code[i].name); snprintf(paths[i], sizeof(paths[i]), "%s", s_code[i].path); } tb_api_code_unload_all(); /* ordem inversa de dependencia */ int ok = 0; for (int i = 0; i < n; i++) if (tb_api_code_load(names[i], paths[i]) >= 0) ok++; return ok; } bool tb_api_code_changed(void) { bool any = false; #ifdef __linux__ if (tb_api_poll_watch() > 0) any = true; #endif if (code_changed_mtime()) any = true; if (!any) { for (int i = 0; i < s_cn; i++) if (s_code[i].dirty) { any = true; break; } } return any; } static void set_err(const char* fmt, const char* a) { snprintf(s_err, sizeof(s_err), fmt, a ? a : ""); } static int find_by_lib(const TinyBlocks_LibraryBlock* lib) { for (int i = 0; i < s_n; i++) if (s_mods[i].lib == lib) return i; return -1; } static int find_by_name(const char* name) { if (!name) return -1; for (int i = 0; i < s_n; i++) if (strcmp(s_mods[i].name, name) == 0) return i; return -1; } /* -- Ciclo de vida --- */ bool tb_api_init(TinyBlocks* rt) { s_rt = rt; s_n = 0; s_err[0] = 0; return rt != NULL; } void tb_api_shutdown(void) { /* O runtime e o dono dos blocos; aqui so esquecemos os modulos. */ tb_api_code_unload_all(); #ifdef __linux__ if (s_inot >= 0) { close(s_inot); s_inot = -1; } s_wn = 0; #endif s_n = 0; s_rt = NULL; } TinyBlocks* tb_api_runtime(void) { return s_rt; } const char* tb_api_last_error(void) { return s_err; } /* -- Registro de modulos --- */ int tb_api_adopt_all(void) { if (!s_rt) return 0; for (uint32_t i = 0; i < tb_rt_library_count(s_rt); i++) { TinyBlocks_LibraryBlock* lib = tb_rt_library_at(s_rt, i); if (!lib || find_by_lib(lib) >= 0) continue; if (s_n >= TB_API_MAX_MODULES) break; TbApiModule* m = &s_mods[s_n]; memset(m, 0, sizeof(*m)); const char* nm = tb_library_name(lib); snprintf(m->name, sizeof(m->name), "%s", nm ? nm : "?"); m->lib = lib; m->category = tb_library_category(lib); m->block_count = tb_library_block_count(lib); s_n++; } return s_n; } int tb_api_module_count(void) { return s_n; } const TbApiModule* tb_api_module(int i) { return (i >= 0 && i < s_n) ? &s_mods[i] : NULL; } const TbApiModule* tb_api_module_find(const char* name) { int i = find_by_name(name); return i >= 0 ? &s_mods[i] : NULL; } bool tb_api_is_loaded(const char* name) { return find_by_name(name) >= 0; } /* -- Carregamento dinamico --- */ int tb_api_load(const char* path) { if (!s_rt) { set_err("%s", "tb_api: runtime nao inicializado"); return -1; } if (!path || !path[0]) { set_err("%s", "tb_api: caminho vazio"); return -1; } if (s_n >= TB_API_MAX_MODULES) { set_err("%s", "tb_api: limite de modulos atingido"); return -1; } #ifdef __linux__ void* dl = dlopen(path, RTLD_NOW | RTLD_LOCAL); if (!dl) { set_err("dlopen: %s", dlerror()); return -1; } GetLibFn get_lib = (GetLibFn)(uintptr_t)dlsym(dl, TINYBLOCKS_LIBRARY_SYMBOL); if (!get_lib) { const char* base = strrchr(path, '/'); base = base ? base + 1 : path; if (strncmp(base, "libtinyblocks-", 14) == 0) set_err("'%s' e dependencia = carregue a library (ex: python.so)", base); else set_err("'%s' nao exporta tinyblocks_get_library", base); dlclose(dl); return -1; } const TinyBlocks_LibraryDescriptor* desc = get_lib(); TinyBlocks_LibraryBlock* lib = tb_library_register(s_rt, desc); if (!lib) { set_err("tb_library_register falhou para %s", path); dlclose(dl); return -1; } TbApiModule* m = &s_mods[s_n]; memset(m, 0, sizeof(*m)); snprintf(m->name, sizeof(m->name), "%s", desc->name ? desc->name : "?"); snprintf(m->version, sizeof(m->version), "%s", desc->version ? desc->version : ""); snprintf(m->path, sizeof(m->path), "%s", path); m->handle = dl; m->lib = lib; m->category = tb_library_category(lib); m->block_count = tb_library_block_count(lib); m->mtime = file_mtime(path); s_err[0] = 0; return s_n++; #else (void)path; set_err("%s", "tb_api: dlopen nao suportado nesta plataforma"); return -1; #endif } bool tb_api_unload(int idx) { if (idx < 0 || idx >= s_n) return false; TbApiModule* m = &s_mods[idx]; if (m->lib) tb_library_unload(s_rt, m->lib); #ifdef __linux__ if (m->handle) dlclose(m->handle); #endif for (int i = idx; i < s_n - 1; i++) s_mods[i] = s_mods[i + 1]; s_n--; return true; } bool tb_api_reload(int idx) { if (idx < 0 || idx >= s_n) return false; if (!s_mods[idx].path[0]) return false; /* embutida nao recarrega */ char path[TB_API_PATH_LEN]; snprintf(path, sizeof(path), "%s", s_mods[idx].path); tb_api_unload(idx); return tb_api_load(path) >= 0; } bool tb_api_any_changed(void) { for (int i = 0; i < s_n; i++) { TbApiModule* m = &s_mods[i]; if (!m->path[0]) continue; time_t mt = file_mtime(m->path); if (mt && mt != m->mtime) return true; } return false; } int tb_api_poll_reload(void) { int n = 0; #ifdef __linux__ tb_api_poll_watch(); #endif for (int i = 0; i < s_n; i++) { TbApiModule* m = &s_mods[i]; if (!m->path[0]) continue; time_t mt = file_mtime(m->path); if (!mt || mt == m->mtime) continue; char path[TB_API_PATH_LEN]; snprintf(path, sizeof(path), "%s", m->path); tb_api_unload(i); if (tb_api_load(path) >= 0) n++; i = -1; /* a lista mudou; reinicia a varredura */ } return n; } /* -- Introspeccao de tipos --- */ int tb_api_type_count(void) { return (int)tb_rt_type_count(s_rt); } const TinyBlocks_TypeBlock* tb_api_type(int i) { if (i < 0) return NULL; return tb_rt_type_at(s_rt, (uint32_t)i); } const TinyBlocks_TypeBlock* tb_api_type_find(const char* name) { return s_rt ? tb_rt_find_type(s_rt, name) : NULL; }