Skip to content

Commit

Permalink
sub-process: avoid leaking cmd
Browse files Browse the repository at this point in the history
In some instances (particularly the `read_object` hook), the `cmd`
attribute is set to an `strdup()`ed value. This value needs to be
released in the end!

Since other users assign a non-`strdup()`ed value, be careful to add
_another_ attribute (called `to_free`) that can hold a reference to such
a string that needs to be released once the sub process is done.

Signed-off-by: Johannes Schindelin <[email protected]>
  • Loading branch information
dscho committed Dec 18, 2024
1 parent f4f85c7 commit 6ac52d2
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
9 changes: 8 additions & 1 deletion sub-process.c
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ void subprocess_stop(struct hashmap *hashmap, struct subprocess_entry *entry)
finish_command(&entry->process);

hashmap_remove(hashmap, &entry->ent, NULL);
FREE_AND_NULL(entry->to_free);
entry->cmd = NULL;
}

static void subprocess_exit_handler(struct child_process *process)
Expand Down Expand Up @@ -100,6 +102,7 @@ int subprocess_start(struct hashmap *hashmap, struct subprocess_entry *entry, co
process->trace2_child_class = "subprocess";

entry->cmd = process->args.v[0];
entry->to_free = NULL;

err = start_command(process);
if (err) {
Expand Down Expand Up @@ -145,11 +148,13 @@ int subprocess_start_strvec(struct hashmap *hashmap,
process->trace2_child_class = "subprocess";

sq_quote_argv_pretty(&quoted, argv->v);
entry->cmd = strbuf_detach(&quoted, NULL);
entry->cmd = entry->to_free = strbuf_detach(&quoted, NULL);

err = start_command(process);
if (err) {
error("cannot fork to run subprocess '%s'", entry->cmd);
FREE_AND_NULL(entry->to_free);
entry->cmd = NULL;
return err;
}

Expand All @@ -158,6 +163,8 @@ int subprocess_start_strvec(struct hashmap *hashmap,
err = startfn(entry);
if (err) {
error("initialization for subprocess '%s' failed", entry->cmd);
FREE_AND_NULL(entry->to_free);
entry->cmd = NULL;
subprocess_stop(hashmap, entry);
return err;
}
Expand Down
6 changes: 6 additions & 0 deletions sub-process.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@
struct subprocess_entry {
struct hashmap_entry ent;
const char *cmd;
/**
* In case `cmd` is a `strdup()`ed value that needs to be released,
* you can assign the pointer to `to_free` so that `subprocess_stop()`
* will release it.
*/
char *to_free;
struct child_process process;
};

Expand Down

0 comments on commit 6ac52d2

Please sign in to comment.