8d419f
From 3087505025b78b80951ab3a5f496eb255f1a9a21 Mon Sep 17 00:00:00 2001
8d419f
From: =?UTF-8?q?Zbigniew=20J=C4=99drzejewski-Szmek?= <zbyszek@in.waw.pl>
8d419f
Date: Mon, 9 May 2022 10:41:36 +0200
8d419f
Subject: [PATCH] fuzz-json: optionally allow logging and output
8d419f
MIME-Version: 1.0
8d419f
Content-Type: text/plain; charset=UTF-8
8d419f
Content-Transfer-Encoding: 8bit
8d419f
8d419f
Similarly to other fuzzers… this makes development easier.
8d419f
8d419f
(cherry picked from commit 9ad955ce40e244a52984c68ae2a6b151d918b4a8)
8d419f
Related: #2087652
8d419f
---
8d419f
 src/fuzz/fuzz-json.c | 19 ++++++++++++++-----
8d419f
 1 file changed, 14 insertions(+), 5 deletions(-)
8d419f
8d419f
diff --git a/src/fuzz/fuzz-json.c b/src/fuzz/fuzz-json.c
8d419f
index ad7460c6fd..648a6d441d 100644
8d419f
--- a/src/fuzz/fuzz-json.c
8d419f
+++ b/src/fuzz/fuzz-json.c
8d419f
@@ -1,6 +1,7 @@
8d419f
 /* SPDX-License-Identifier: LGPL-2.1-or-later */
8d419f
 
8d419f
 #include "alloc-util.h"
8d419f
+#include "env-util.h"
8d419f
 #include "fd-util.h"
8d419f
 #include "fuzz.h"
8d419f
 #include "json.h"
8d419f
@@ -10,18 +11,26 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
8d419f
         size_t out_size;
8d419f
         _cleanup_fclose_ FILE *f = NULL, *g = NULL;
8d419f
         _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
8d419f
+        int r;
8d419f
+
8d419f
+        /* Disable most logging if not running standalone */
8d419f
+        if (!getenv("SYSTEMD_LOG_LEVEL"))
8d419f
+                log_set_max_level(LOG_CRIT);
8d419f
 
8d419f
         f = data_to_file(data, size);
8d419f
         assert_se(f);
8d419f
 
8d419f
-        if (json_parse_file(f, NULL, 0, &v, NULL, NULL) < 0)
8d419f
+        r = json_parse_file(f, NULL, 0, &v, NULL, NULL);
8d419f
+        if (r < 0) {
8d419f
+                log_debug_errno(r, "failed to parse input: %m");
8d419f
                 return 0;
8d419f
+        }
8d419f
 
8d419f
-        g = open_memstream_unlocked(&out, &out_size);
8d419f
-        assert_se(g);
8d419f
+        if (getenv_bool("SYSTEMD_FUZZ_OUTPUT") <= 0)
8d419f
+                assert_se(g = open_memstream_unlocked(&out, &out_size));
8d419f
 
8d419f
-        json_variant_dump(v, 0, g, NULL);
8d419f
-        json_variant_dump(v, JSON_FORMAT_PRETTY|JSON_FORMAT_COLOR|JSON_FORMAT_SOURCE, g, NULL);
8d419f
+        json_variant_dump(v, 0, g ?: stdout, NULL);
8d419f
+        json_variant_dump(v, JSON_FORMAT_PRETTY|JSON_FORMAT_COLOR|JSON_FORMAT_SOURCE, g ?: stdout, NULL);
8d419f
 
8d419f
         return 0;
8d419f
 }