diff --git a/include/splinter.h b/include/splinter.h index f8f9a50..27fd8c2 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -82,6 +82,12 @@ struct sp_tool { enum sp_auth auth; sp_tool_run run; void *ctx; + /* + * Called once when the registry is freed. A tool whose name, + * description, params or ctx were allocated (an MCP server's tools) sets + * it; builtins point at static strings and leave it NULL. + */ + void (*dispose)(struct sp_tool *); }; struct sp_registry { diff --git a/plugins/junction/junction.c b/plugins/junction/junction.c index 186ff99..d9ac03f 100644 --- a/plugins/junction/junction.c +++ b/plugins/junction/junction.c @@ -1210,6 +1210,7 @@ junction_init(struct sp_host *h) "{\"type\":\"object\",\"properties\":{}}", SP_AUTH_READ, junction_tool, + NULL, NULL }; diff --git a/plugins/lcm/lcm.c b/plugins/lcm/lcm.c index 6bb7882..517c8f5 100644 --- a/plugins/lcm/lcm.c +++ b/plugins/lcm/lcm.c @@ -417,6 +417,7 @@ static const struct sp_tool recall_tool = { "default 10\"}},\"required\":[\"query\"]}", SP_AUTH_READ, lcm_recall, + NULL, NULL }; diff --git a/plugins/mcp/mcp.c b/plugins/mcp/mcp.c index 3b760c8..e23003d 100644 --- a/plugins/mcp/mcp.c +++ b/plugins/mcp/mcp.c @@ -73,6 +73,9 @@ struct server { volatile int up; /* handshake done and answering */ int registered; /* its tools are in the registry (once) */ pthread_mutex_t lock; /* one round trip at a time */ + pthread_t th; /* the reconnect thread, joined on shutdown */ + int th_started; + int th_done; /* set under done_mu right before it returns */ }; #define RETRY_S 10 @@ -82,6 +85,16 @@ static struct server sv[MAX_SERVERS]; static size_t nsv; static struct sp_host *host; +/* + * The server threads are joinable. Shutdown has to know they are gone before + * it frees the buffers they read into and before the host they register tools + * in disappears; without the join a thread could call sp_host_add_tool() into + * a freed host. Bounded, because a thread stuck in connect() must not hang the + * shutdown forever. + */ +static pthread_mutex_t done_mu = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t done_cv = PTHREAD_COND_INITIALIZER; + /* A registered tool knows which server it belongs to and what it is called there. */ struct toolref { size_t srv; @@ -802,6 +815,23 @@ call_tool(const char *args, struct sp_buf *out, void *ctx) /* ---- registration ---- */ +/* + * The registry copies the tool struct, not the strings. Everything that was + * allocated for this tool goes with it: the prefixed name, the description, + * the printed schema and the toolref the call needs. Without this the tools of + * an MCP server leaked when the registry was freed (ASAN found 40 KB across a + * single test). + */ +static void +mcp_tool_dispose(struct sp_tool *t) +{ + free((char *)t->name); + free((char *)t->description); + free((char *)t->params); + free(t->ctx); + memset(t, 0, sizeof(*t)); +} + static int register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err) { @@ -893,13 +923,23 @@ register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err) } } if (tool.params == NULL) - tool.params = "{\"type\":\"object\",\"properties\":{}}"; + tool.params = strdup( + "{\"type\":\"object\",\"properties\":{}}"); + if (tool.params == NULL) { + free((char *)tool.name); + free((char *)tool.description); + free(ref); + continue; + } /* an MCP server can do anything; the class is the honest default */ tool.auth = SP_AUTH_MUTATE; tool.run = call_tool; tool.ctx = ref; + tool.dispose = mcp_tool_dispose; if (sp_host_add_tool(host, &tool) == 0) added++; + else + mcp_tool_dispose(&tool); } mcp_json_free(v); free(reply); @@ -976,19 +1016,25 @@ handshake(size_t which, struct sp_buf *err) static void teardown(struct server *s) { - if (!s->http && s->pid > 0) { - (void)kill(s->pid, SIGTERM); - (void)waitpid(s->pid, NULL, 0); - s->pid = 0; - if (s->to != NULL) + if (!s->http) { + if (s->pid > 0) { + (void)kill(s->pid, SIGTERM); + (void)waitpid(s->pid, NULL, 0); + s->pid = 0; + } + if (s->to != NULL) { fclose(s->to); - s->to = NULL; - if (s->from > 0) + s->to = NULL; + } + if (s->from > 0) { close(s->from); - s->from = 0; - if (s->in.p != NULL) - sp_buf_free(&s->in); + s->from = 0; + } } + /* The HTTP transport fills the same line buffer while reading its SSE + * answer; it leaked because this was freed only for stdio. */ + if (s->in.p != NULL) + sp_buf_free(&s->in); s->session[0] = '\0'; s->up = 0; /* until connect_server() has new pipes, a call fails cleanly */ @@ -1061,7 +1107,7 @@ alive_after(const char *err) * reconnect when the link is gone. */ static void * -server_thread(void *arg) +server_thread_body(void *arg) { size_t i = (size_t)(uintptr_t)arg; struct server *s = &sv[i]; @@ -1127,6 +1173,23 @@ server_thread(void *arg) return NULL; } +/* + * Every return of the body goes through here, so shutdown can tell when the + * thread is finished instead of guessing with a sleep. + */ +static void * +server_thread(void *arg) +{ + size_t i = (size_t)(uintptr_t)arg; + void *rc = server_thread_body(arg); + + pthread_mutex_lock(&done_mu); + sv[i].th_done = 1; + pthread_cond_broadcast(&done_cv); + pthread_mutex_unlock(&done_mu); + return rc; +} + static int mcp_init(struct sp_host *h) { @@ -1171,23 +1234,51 @@ mcp_init(struct sp_host *h) } (void)sp_host_add_widget(h, &widget); for (i = 0; i < nsv; i++) { - pthread_t t; - pthread_mutex_init(&sv[i].lock, NULL); + sv[i].th_done = 0; say(sv[i].id, "connecting in the background", NULL); - if (pthread_create(&t, NULL, server_thread, + if (pthread_create(&sv[i].th, NULL, server_thread, (void *)(uintptr_t)i) == 0) - pthread_detach(t); + sv[i].th_started = 1; else sv[i].dead = 1; } return 0; } +/* + * Wait (bounded) until every server thread has returned. A thread stuck in a + * connect must not hang the shutdown; such a thread is left running and its + * state is not freed. + */ +static void +stop_threads(void) +{ + struct timespec deadline; + size_t i; + int pending; + + clock_gettime(CLOCK_REALTIME, &deadline); + deadline.tv_sec += 5; + pthread_mutex_lock(&done_mu); + for (;;) { + pending = 0; + for (i = 0; i < nsv; i++) + if (sv[i].th_started && !sv[i].th_done) + pending++; + if (pending == 0) + break; + if (pthread_cond_timedwait(&done_cv, &done_mu, &deadline) != 0) + break; + } + pthread_mutex_unlock(&done_mu); +} + static void mcp_shutdown(struct sp_host *h) { - size_t i; + size_t i; + int done; (void)h; stopping = 1; @@ -1203,6 +1294,29 @@ mcp_shutdown(struct sp_host *h) (void)kill(sv[i].http_pid, SIGKILL); sv[i].dead = 1; } + /* + * Only a thread that has returned may have its buffers freed: the HTTP + * line buffer (up to RPC_MAX_LINE) and the tools it registers live there. + * Before the join, a late register_tools() could also write into a host + * that is being freed. + */ + stop_threads(); + for (i = 0; i < nsv; i++) { + if (!sv[i].th_started) + continue; + pthread_mutex_lock(&done_mu); + done = sv[i].th_done; + pthread_mutex_unlock(&done_mu); + if (!done) { + fprintf(stderr, "mcp: %s did not stop within 5 s; its " + "buffers stay\n", sv[i].id); + continue; + } + (void)pthread_join(sv[i].th, NULL); + sv[i].th_started = 0; + teardown(&sv[i]); + pthread_mutex_destroy(&sv[i].lock); + } } static const struct sp_plugin plugin = { diff --git a/plugins/processes/processes.c b/plugins/processes/processes.c index 1e79917..0fc2a77 100644 --- a/plugins/processes/processes.c +++ b/plugins/processes/processes.c @@ -523,25 +523,29 @@ static const struct sp_tool t_start = { "{\"type\":\"object\",\"properties\":{\"command\":{\"type\":\"string\"}," "\"label\":{\"type\":\"string\",\"description\":\"short name\"}}," "\"required\":[\"command\"]}", - SP_AUTH_DESTRUCTIVE, tool_process_start, NULL + SP_AUTH_DESTRUCTIVE, tool_process_start, NULL, + NULL }; static const struct sp_tool t_list = { "process_list", "List background tasks: id, state, time, size, label.", "{\"type\":\"object\",\"properties\":{}}", SP_AUTH_READ, tool_process_list, + NULL, NULL }; static const struct sp_tool t_result = { "process_result", "Output and exit status of a finished task.", "{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\"}}," - "\"required\":[\"id\"]}", SP_AUTH_READ, tool_process_result, NULL + "\"required\":[\"id\"]}", SP_AUTH_READ, tool_process_result, NULL, + NULL }; static const struct sp_tool t_kill = { "process_kill", "Stop a running task.", "{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\"}}," - "\"required\":[\"id\"]}", SP_AUTH_DESTRUCTIVE, tool_process_kill, NULL + "\"required\":[\"id\"]}", SP_AUTH_DESTRUCTIVE, tool_process_kill, NULL, + NULL }; static int diff --git a/plugins/self/self.c b/plugins/self/self.c index 136f8ed..0f170e4 100644 --- a/plugins/self/self.c +++ b/plugins/self/self.c @@ -434,6 +434,7 @@ self_init(struct sp_host *h) "{\"type\":\"object\",\"properties\":{}}", SP_AUTH_READ, self_tool, + NULL, NULL }; const char *iv; diff --git a/src/backend/tool.c b/src/backend/tool.c index 6aa54ff..8a27fa5 100644 --- a/src/backend/tool.c +++ b/src/backend/tool.c @@ -80,6 +80,9 @@ sp_registry_free(struct sp_registry *r) { size_t i; + for (i = 0; i < r->len; i++) + if (r->tools[i].dispose != NULL) + r->tools[i].dispose(&r->tools[i]); for (i = 0; i < r->nretired; i++) free(r->retired[i]); free(r->retired); diff --git a/tests/asan.supp b/tests/asan.supp index 759456c..3e471e5 100644 --- a/tests/asan.supp +++ b/tests/asan.supp @@ -1,11 +1,10 @@ # LeakSanitizer suppressions for `make check-asan`. # -# The MCP plugin keeps one connection per server in a static table. Its server -# thread is detached and reconnects on its own; shutdown kills the child but -# does not join the thread, so the thread's line buffer (bounded at -# RPC_MAX_LINE) and the tools it registers can still be allocated while the -# host is being torn down. Bounded, only at teardown, and tracked separately; -# everything else must be leak-free. -leak:read_line -leak:register_tools -leak:connect_server +# Empty on purpose. The three entries that used to be here (read_line, +# register_tools, connect_server) were the MCP plugin's per-connection line +# buffer and the tools its reconnect thread registered: the thread was +# detached, so shutdown could not join it and freed nothing it might still +# touch. The thread now has a handle and a bounded join, teardown frees the +# line buffer for both transports, and the whole suite runs without a +# suppression. Add an entry here only with a comment that says why the leak +# cannot be fixed. diff --git a/tests/plugin_lifecycle.c b/tests/plugin_lifecycle.c index 96bb11a..3e5b59b 100644 --- a/tests/plugin_lifecycle.c +++ b/tests/plugin_lifecycle.c @@ -26,6 +26,7 @@ lc_tick(struct sp_host *h, const char *name, void *ctx) static const struct sp_tool tool = { "lifecycle_tool", "test", "{\"type\":\"object\"}", SP_AUTH_READ, lc_tool, + NULL, NULL };