2
0
Эх сурвалжийг харах

Fix frozen

PUBLISHED_FROM=a6a33a2f627e135a419865652b40ecf808a12be8
Sergey Lyubka 8 жил өмнө
parent
commit
2763408005
2 өөрчлөгдсөн 28 нэмэгдсэн , 7 устгасан
  1. 12 7
      frozen.c
  2. 16 0
      unit_test.c

+ 12 - 7
frozen.c

@@ -117,12 +117,11 @@ struct fstate {
 
 static int append_to_path(struct frozen *f, const char *str, int size) {
   int n = f->path_len;
-  f->path_len +=
-      snprintf(f->path + f->path_len, sizeof(f->path) - (f->path_len), "%.*s", size, str);
-  if (f->path_len > sizeof(f->path) - 1) {
-    f->path_len = sizeof(f->path) - 1;
-  }
-
+  int left = sizeof(f->path) - n - 1;
+  if (size > left) size = left;
+  memcpy(f->path + n, str, size);
+  f->path[n + size] = '\0';
+  f->path_len += size;
   return n;
 }
 
@@ -859,6 +858,7 @@ static void json_scanf_cb(void *callback_data, const char *name,
                           size_t name_len, const char *path,
                           const struct json_token *token) {
   struct json_scanf_info *info = (struct json_scanf_info *) callback_data;
+  char buf[32];  /* Must be enough to hold numbers */
 
   (void) name;
   (void) name_len;
@@ -944,7 +944,12 @@ static void json_scanf_cb(void *callback_data, const char *name,
       *(struct json_token *) info->target = *token;
       break;
     default:
-      info->num_conversions += sscanf(token->ptr, info->fmt, info->target);
+      /* Before scanf, copy into tmp buffer in order to 0-terminate it */
+      if (token->len < (int) sizeof(buf)) {
+        memcpy(buf, token->ptr, token->len);
+        buf[token->len] = '\0';
+        info->num_conversions += sscanf(buf, info->fmt, info->target);
+      }
       break;
   }
 }

+ 16 - 0
unit_test.c

@@ -586,6 +586,9 @@ static void cb2(void *data, const char *name, size_t name_len, const char *path,
   struct json_token *pt = (struct json_token *)data;
   pt->ptr = token->ptr;
   pt->len = token->len;
+  (void) path;
+  (void) name_len;
+  (void) name;
 }
 
 static const char *test_parse_string(void) {
@@ -605,7 +608,20 @@ static const char *test_parse_string(void) {
   return NULL;
 }
 
+static const char *test_eos(void) {
+  const char *s = "{\"a\": 12345}";
+  size_t n = 999;
+  char *buf = (char *) malloc(n);
+  int s_len = strlen(s), a = 0;
+  memset(buf, 'x', n);
+  memcpy(buf, s, s_len);
+  ASSERT(json_scanf(buf, n, "{a:%d}", &a) == 1);
+  ASSERT(a == 12345);
+  return NULL;
+}
+
 static const char *run_all_tests(void) {
+  RUN_TEST(test_eos);
   RUN_TEST(test_scanf);
   RUN_TEST(test_errors);
   RUN_TEST(test_json_printf);