Skip to content

Commit 0edd4d4

Browse files
agnostic-apolloGrimler91
authored andcommitted
Fixed: only malloc as many bytes as are actully needed
And make malloc&memcpy handling clearer. Before we potentially had an element with uninitialised memory, see discussion in #203. Fixes: 1ec1334 ("Initial push")
1 parent 512a252 commit 0edd4d4

1 file changed

Lines changed: 13 additions & 7 deletions

File tree

termux-api.c

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -246,13 +246,20 @@ _Noreturn void exec_am_broadcast(int argc, char** argv,
246246
// Close stdin:
247247
close(STDIN_FILENO);
248248

249-
int const extra_args = 15; // Including ending NULL.
250-
char** child_argv = malloc((sizeof(char*)) * (argc + extra_args));
251-
if (child_argv == NULL) {
249+
const int child_pre_argc = 14;
250+
const int child_post_argc = argc - 1; // Except `argv[0]`.
251+
const int child_argc = child_pre_argc + child_post_argc;
252+
253+
size_t child_argv_size = (sizeof(char*)) * (child_argc + 1); // Including trailing `NULL`.
254+
// Do not directly cast, otherwise can trigger null pointer dereference if `NULL` is returned.
255+
void* result = malloc(child_argv_size);
256+
if (result == NULL) {
252257
perror("malloc failed for am child args");
253258
exit(1);
254259
}
255260

261+
char **child_argv = (char **) result;
262+
256263
child_argv[0] = "am";
257264
child_argv[1] = "broadcast";
258265
child_argv[2] = "--user";
@@ -268,13 +275,12 @@ _Noreturn void exec_am_broadcast(int argc, char** argv,
268275
child_argv[11] = input_address_string;
269276
child_argv[12] = "--es";
270277
child_argv[13] = "api_method";
271-
child_argv[14] = argv[1];
272278

273-
// Copy the remaining arguments -2 for first binary and second api name:
274-
memcpy(child_argv + extra_args, argv + 2, (argc-1) * sizeof(char*));
279+
// Copy the remaining arguments except `argv[0]`, `argv[1]` should be `api_method` extra value:
280+
memcpy(child_argv + child_pre_argc, argv + 1, child_post_argc * sizeof(char*));
275281

276282
// End with NULL:
277-
child_argv[argc + extra_args - 1] = NULL;
283+
child_argv[child_argc] = NULL;
278284

279285
// Use an a executable taking care of PATH and LD_LIBRARY_PATH:
280286
execv(PREFIX "/bin/am", child_argv);

0 commit comments

Comments
 (0)