|
| 1 | +// Copyright 2022 Google Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | +// |
| 15 | +//////////////////////////////////////////////////////////////////////////////// |
| 16 | +#include <cstddef> |
| 17 | +#include <cstdint> |
| 18 | +#include <cstring> |
| 19 | +#include <string> |
| 20 | + |
| 21 | +extern "C" { |
| 22 | +#include "libjsonnet.h" |
| 23 | +} |
| 24 | + |
| 25 | +int ImportCallback(void* ctx, const char* base, const char* rel, |
| 26 | + char** found_here, char **buf, size_t *buflen) { |
| 27 | + // Refuse to load any file. Per the JsonnetImportCallback contract, a |
| 28 | + // failure (return value 1) must deliver an error message in *buf, |
| 29 | + // allocated with jsonnet_realloc and without a trailing null byte. |
| 30 | + JsonnetVm* jvm = static_cast<JsonnetVm*>(ctx); |
| 31 | + const char* msg = "imports are disabled"; |
| 32 | + size_t len = std::strlen(msg); |
| 33 | + *buf = jsonnet_realloc(jvm, nullptr, len); |
| 34 | + std::memcpy(*buf, msg, len); |
| 35 | + *buflen = len; |
| 36 | + return 1; |
| 37 | +} |
| 38 | + |
| 39 | +std::string ConvertJsonnetToJson(const std::string& jsonnet) { |
| 40 | + JsonnetVm* jvm = jsonnet_make(); |
| 41 | + jsonnet_import_callback(jvm, ImportCallback, jvm); |
| 42 | + int error = 0; |
| 43 | + char* res = |
| 44 | + jsonnet_evaluate_snippet_stream(jvm, /*filename=*/"", jsonnet.c_str(), &error); |
| 45 | + |
| 46 | + std::string json; |
| 47 | + if (error == 0 && res != nullptr) { |
| 48 | + json = res; |
| 49 | + } |
| 50 | + |
| 51 | + if (res) { |
| 52 | + jsonnet_realloc(jvm, res, 0); |
| 53 | + } |
| 54 | + jsonnet_destroy(jvm); |
| 55 | + return json; |
| 56 | +} |
| 57 | + |
| 58 | +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { |
| 59 | + std::string fuzz_jsonnet(reinterpret_cast<const char*>(data), size); |
| 60 | + ConvertJsonnetToJson(fuzz_jsonnet); |
| 61 | + return 0; |
| 62 | +} |
0 commit comments