]> granicus.if.org Git - esp-idf/commitdiff
console: initialize buf_size before calling open_memstream
authorIvan Grokhotkov <ivan@espressif.com>
Tue, 22 Aug 2017 17:07:03 +0000 (01:07 +0800)
committerIvan Grokhotkov <ivan@espressif.com>
Tue, 22 Aug 2017 17:10:30 +0000 (01:10 +0800)
POSIX open_memstream documentation [1] does not mention that it may use
the  value supplied in buf_size before the call.
newlib implementation of open_memstream does use it as a hint of the
buffer size [2]. To avoid using potential garbage in this variable,
newlib caps the size to 64kB (!).

If the allocation of this initial buffer fails, NULL file pointer is
returned. Previous code did not check returned file pointer and crashed
when it was used.

Initialize size to zero (in which case newlib allocates a 64 byte
buffer), and check the returned file pointer.

[1] http://pubs.opengroup.org/onlinepubs/9699919799/functions/open_memstream.html
[2] https://github.com/espressif/newlib-esp32/blob/23c0f21/newlib/libc/stdio/open_memstream.c#L26-L29
    https://github.com/espressif/newlib-esp32/blob/23c0f21/newlib/libc/stdio/open_memstream.c#L324-L336

components/console/commands.c

index a451584d569b61b06f4e816837b3a5e1d808bfbf..dfcbf450c1a44a1773137596d4075271b4368f32 100644 (file)
@@ -105,11 +105,13 @@ esp_err_t esp_console_cmd_register(const esp_console_cmd_t *cmd)
         asprintf(&item->hint, " %s", cmd->hint);
     } else if (cmd->argtable) {
         /* Generate hint based on cmd->argtable */
-        char* buf;
-        size_t buf_size;
+        char* buf = NULL;
+        size_t buf_size = 0;
         FILE* f = open_memstream(&buf, &buf_size);
-        arg_print_syntax(f, cmd->argtable, NULL);
-        fclose(f);
+        if (f != NULL) {
+            arg_print_syntax(f, cmd->argtable, NULL);
+            fclose(f);
+        }
         item->hint = buf;
     }
     item->argtable = cmd->argtable;