Skip to content

Commit

Permalink
Bugfix: using strtok on a buffer we planned to reuse
Browse files Browse the repository at this point in the history
  • Loading branch information
danieldegrasse committed Aug 10, 2020
1 parent 8fc0b5b commit 4f8980e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
15 changes: 9 additions & 6 deletions cli.c
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@
* This code assumes that the connected terminal emulates a VT-100.
*/


/* XDCtools Header files */
#include <xdc/std.h>
#include <xdc/runtime/System.h>
#include <xdc/std.h>

#include <stdarg.h>
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>

#include "cli.h"
#include "commands.h"
Expand Down Expand Up @@ -58,12 +57,16 @@ void cli_printf(CLIContext *context, const char *format, ...) {
va_start(args, format);
// Print to buffer and destroy varargs list.
/*
* Note: newlib's implementation of vnsprintf appears to require a heap,
* Note: newlib's implementation of vnsprintf appears to require a heap,
* which we do not have. Use the xdc version.
* TODO: ideally, we'd implement printf with a circular buffer, so we can
* print a string of any length.
*/
num_print = System_vsnprintf(output_buf, PRINT_BUFLEN, format, args);
va_end(args);
context->cli_write(output_buf, num_print);
// Write the shorter value between the buffer size and num_print
context->cli_write(output_buf,
num_print > PRINT_BUFLEN ? PRINT_BUFLEN : num_print);
}

/**
Expand Down
6 changes: 4 additions & 2 deletions commands.c
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,11 @@ const CmdEntry COMMANDS[] = {
int handle_command(CLIContext *ctx, char *cmd) {
const CmdEntry *entry;
int argc;
char *arguments[MAX_ARGC], *saveptr;
char *arguments[MAX_ARGC], *saveptr, cmd_buf[CLI_MAX_LINE];
strncpy(cmd_buf, cmd, CLI_MAX_LINE);
// The parser interprets a space as a delimeter between arguments.
// Init strtok_r.
arguments[0] = strtok_r(cmd, DELIMETER, &saveptr);
arguments[0] = strtok_r(cmd_buf, DELIMETER, &saveptr);
// Parse the rest of the arguments.
for (argc = 1; argc < MAX_ARGC; argc++) {
arguments[argc] = strtok_r(NULL, DELIMETER, &saveptr);
Expand Down Expand Up @@ -97,6 +98,7 @@ static int help(CLIContext *ctx, char **argv, int argc) {
cli_printf(ctx, "%s: %s\r\n", entry->cmd_name, entry->cmd_help);
return 0;
}
entry++;
}
// If we make it here, the command name was unknown.
cli_printf(ctx, "Unknown command: %s\r\n", argv[1]);
Expand Down

0 comments on commit 4f8980e

Please sign in to comment.