blob: 6295483d465b545b9a6f28da7734f79d17c429dc [file] [log] [blame]
Nigel Tao1b073492020-02-16 22:11:36 +11001// Copyright 2020 The Wuffs Authors.
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// https://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
17/*
Nigel Tao0cd2f982020-03-03 23:03:02 +110018jsonptr is a JSON formatter (pretty-printer) that supports the JSON Pointer
Nigel Tao0291a472020-08-13 22:40:10 +100019(RFC 6901) query syntax. It reads UTF-8 JSON from stdin and writes
20canonicalized, formatted UTF-8 JSON to stdout.
Nigel Tao0cd2f982020-03-03 23:03:02 +110021
Nigel Taod60815c2020-03-26 14:32:35 +110022See the "const char* g_usage" string below for details.
Nigel Tao0cd2f982020-03-03 23:03:02 +110023
24----
25
26JSON Pointer (and this program's implementation) is one of many JSON query
27languages and JSON tools, such as jq, jql and JMESPath. This one is relatively
28simple and fewer-featured compared to those others.
29
Nigel Tao0291a472020-08-13 22:40:10 +100030One benefit of simplicity is that this program's JSON and JSON Pointer
Nigel Tao0cd2f982020-03-03 23:03:02 +110031implementations do not dynamically allocate or free memory (yet it does not
32require that the entire input fits in memory at once). They are therefore
33trivially protected against certain bug classes: memory leaks, double-frees and
34use-after-frees.
35
Nigel Tao0291a472020-08-13 22:40:10 +100036The core JSON implementation is also written in the Wuffs programming language
37(and then transpiled to C/C++), which is memory-safe (e.g. array indexing is
38bounds-checked) but also guards against integer arithmetic overflows.
Nigel Tao0cd2f982020-03-03 23:03:02 +110039
Nigel Taofe0cbbd2020-03-05 22:01:30 +110040For defense in depth, on Linux, this program also self-imposes a
41SECCOMP_MODE_STRICT sandbox before reading (or otherwise processing) its input
42or writing its output. Under this sandbox, the only permitted system calls are
43read, write, exit and sigreturn.
44
Nigel Tao0291a472020-08-13 22:40:10 +100045All together, this program aims to safely handle untrusted JSON files without
46fear of security bugs such as remote code execution.
Nigel Tao0cd2f982020-03-03 23:03:02 +110047
48----
Nigel Tao1b073492020-02-16 22:11:36 +110049
Nigel Taoc5b3a9e2020-02-24 11:54:35 +110050As of 2020-02-24, this program passes all 318 "test_parsing" cases from the
51JSON test suite (https://github.com/nst/JSONTestSuite), an appendix to the
52"Parsing JSON is a Minefield" article (http://seriot.ch/parsing_json.php) that
53was first published on 2016-10-26 and updated on 2018-03-30.
54
Nigel Tao0cd2f982020-03-03 23:03:02 +110055After modifying this program, run "build-example.sh example/jsonptr/" and then
56"script/run-json-test-suite.sh" to catch correctness regressions.
57
58----
59
Nigel Taod0b16cb2020-03-14 10:15:54 +110060This program uses Wuffs' JSON decoder at a relatively low level, processing the
61decoder's token-stream output individually. The core loop, in pseudo-code, is
62"for_each_token { handle_token(etc); }", where the handle_token function
Nigel Taod60815c2020-03-26 14:32:35 +110063changes global state (e.g. the `g_depth` and `g_ctx` variables) and prints
Nigel Taod0b16cb2020-03-14 10:15:54 +110064output text based on that state and the token's source text. Notably,
65handle_token is not recursive, even though JSON values can nest.
66
67This approach is centered around JSON tokens. Each JSON 'thing' (e.g. number,
68string, object) comprises one or more JSON tokens.
69
70An alternative, higher-level approach is in the sibling example/jsonfindptrs
71program. Neither approach is better or worse per se, but when studying this
72program, be aware that there are multiple ways to use Wuffs' JSON decoder.
73
74The two programs, jsonfindptrs and jsonptr, also demonstrate different
75trade-offs with regard to JSON object duplicate keys. The JSON spec permits
76different implementations to allow or reject duplicate keys. It is not always
77clear which approach is safer. Rejecting them is certainly unambiguous, and
78security bugs can lurk in ambiguous corners of a file format, if two different
79implementations both silently accept a file but differ on how to interpret it.
80On the other hand, in the worst case, detecting duplicate keys requires O(N)
81memory, where N is the size of the (potentially untrusted) input.
82
83This program (jsonptr) allows duplicate keys and requires only O(1) memory. As
84mentioned above, it doesn't dynamically allocate memory at all, and on Linux,
85it runs in a SECCOMP_MODE_STRICT sandbox.
86
87----
88
Nigel Tao50bfab92020-08-05 11:39:09 +100089To run:
Nigel Tao1b073492020-02-16 22:11:36 +110090
91$CXX jsonptr.cc && ./a.out < ../../test/data/github-tags.json; rm -f a.out
92
93for a C++ compiler $CXX, such as clang++ or g++.
94*/
95
Nigel Tao721190a2020-04-03 22:25:21 +110096#if defined(__cplusplus) && (__cplusplus < 201103L)
97#error "This C++ program requires -std=c++11 or later"
98#endif
99
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100100#include <errno.h>
Nigel Tao01abc842020-03-06 21:42:33 +1100101#include <fcntl.h>
102#include <stdio.h>
Nigel Tao9cc2c252020-02-23 17:05:49 +1100103#include <string.h>
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100104#include <unistd.h>
Nigel Tao1b073492020-02-16 22:11:36 +1100105
106// Wuffs ships as a "single file C library" or "header file library" as per
107// https://github.com/nothings/stb/blob/master/docs/stb_howto.txt
108//
109// To use that single file as a "foo.c"-like implementation, instead of a
110// "foo.h"-like header, #define WUFFS_IMPLEMENTATION before #include'ing or
111// compiling it.
112#define WUFFS_IMPLEMENTATION
113
114// Defining the WUFFS_CONFIG__MODULE* macros are optional, but it lets users of
115// release/c/etc.c whitelist which parts of Wuffs to build. That file contains
116// the entire Wuffs standard library, implementing a variety of codecs and file
117// formats. Without this macro definition, an optimizing compiler or linker may
118// very well discard Wuffs code for unused codecs, but listing the Wuffs
119// modules we use makes that process explicit. Preprocessing means that such
120// code simply isn't compiled.
121#define WUFFS_CONFIG__MODULES
122#define WUFFS_CONFIG__MODULE__BASE
123#define WUFFS_CONFIG__MODULE__JSON
124
125// If building this program in an environment that doesn't easily accommodate
126// relative includes, you can use the script/inline-c-relative-includes.go
127// program to generate a stand-alone C++ file.
128#include "../../release/c/wuffs-unsupported-snapshot.c"
129
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100130#if defined(__linux__)
131#include <linux/prctl.h>
132#include <linux/seccomp.h>
133#include <sys/prctl.h>
134#include <sys/syscall.h>
135#define WUFFS_EXAMPLE_USE_SECCOMP
136#endif
137
Nigel Tao2cf76db2020-02-27 22:42:01 +1100138#define TRY(error_msg) \
139 do { \
140 const char* z = error_msg; \
141 if (z) { \
142 return z; \
143 } \
144 } while (false)
145
Nigel Taod60815c2020-03-26 14:32:35 +1100146static const char* g_eod = "main: end of data";
Nigel Tao2cf76db2020-02-27 22:42:01 +1100147
Nigel Taod60815c2020-03-26 14:32:35 +1100148static const char* g_usage =
Nigel Tao01abc842020-03-06 21:42:33 +1100149 "Usage: jsonptr -flags input.json\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100150 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100151 "Flags:\n"
Nigel Tao3690e832020-03-12 16:52:26 +1100152 " -c -compact-output\n"
Nigel Tao94440cf2020-04-02 22:28:24 +1100153 " -d=NUM -max-output-depth=NUM\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100154 " -q=STR -query=STR\n"
Nigel Taoecadf722020-07-13 08:22:34 +1000155 " -s=NUM -spaces=NUM\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100156 " -t -tabs\n"
157 " -fail-if-unsandboxed\n"
Nigel Tao0291a472020-08-13 22:40:10 +1000158 " -input-allow-comments\n"
159 " -input-allow-extra-comma\n"
160 " -input-allow-inf-nan-numbers\n"
161 " -output-extra-comma\n"
Nigel Taoecadf722020-07-13 08:22:34 +1000162 " -strict-json-pointer-syntax\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100163 "\n"
Nigel Tao01abc842020-03-06 21:42:33 +1100164 "The input.json filename is optional. If absent, it reads from stdin.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100165 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100166 "----\n"
167 "\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100168 "jsonptr is a JSON formatter (pretty-printer) that supports the JSON\n"
Nigel Tao0291a472020-08-13 22:40:10 +1000169 "Pointer (RFC 6901) query syntax. It reads UTF-8 JSON from stdin and\n"
170 "writes canonicalized, formatted UTF-8 JSON to stdout.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100171 "\n"
Nigel Tao0291a472020-08-13 22:40:10 +1000172 "Canonicalized means that e.g. \"abc\\u000A\\tx\\u0177z\" is re-written\n"
173 "as \"abc\\n\\txÅ·z\". It does not sort object keys, nor does it reject\n"
Nigel Tao01abc842020-03-06 21:42:33 +1100174 "duplicate keys. Canonicalization does not imply Unicode normalization.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100175 "\n"
176 "Formatted means that arrays' and objects' elements are indented, each\n"
Nigel Taoecadf722020-07-13 08:22:34 +1000177 "on its own line. Configure this with the -c / -compact-output, -s=NUM /\n"
Nigel Tao0291a472020-08-13 22:40:10 +1000178 "-spaces=NUM (for NUM ranging from 0 to 8) and -t / -tabs flags.\n"
Nigel Tao168f60a2020-07-14 13:19:33 +1000179 "\n"
Nigel Tao0291a472020-08-13 22:40:10 +1000180 "The -input-allow-comments flag allows \"/*slash-star*/\" and\n"
181 "\"//slash-slash\" C-style comments within JSON input. Such comments are\n"
182 "stripped from the output.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100183 "\n"
Nigel Tao0291a472020-08-13 22:40:10 +1000184 "The -input-allow-extra-comma flag allows input like \"[1,2,]\", with a\n"
185 "comma after the final element of a JSON list or dictionary.\n"
Nigel Tao3c8589b2020-07-19 21:49:00 +1000186 "\n"
Nigel Tao0291a472020-08-13 22:40:10 +1000187 "The -input-allow-inf-nan-numbers flag allows non-finite floating point\n"
188 "numbers (infinities and not-a-numbers) within JSON input.\n"
Nigel Tao3c8589b2020-07-19 21:49:00 +1000189 "\n"
Nigel Tao0291a472020-08-13 22:40:10 +1000190 "The -output-extra-comma flag writes output like \"[1,2,]\", with a comma\n"
191 "after the final element of a JSON list or dictionary. Such commas are\n"
192 "non-compliant with the JSON specification but many parsers accept them\n"
193 "and they can produce simpler line-based diffs. This flag is ignored when\n"
194 "-compact-output is set.\n"
Nigel Taof8dfc762020-07-23 23:35:44 +1000195 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100196 "----\n"
197 "\n"
198 "The -q=STR or -query=STR flag gives an optional JSON Pointer query, to\n"
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100199 "print a subset of the input. For example, given RFC 6901 section 5's\n"
Nigel Tao01abc842020-03-06 21:42:33 +1100200 "sample input (https://tools.ietf.org/rfc/rfc6901.txt), this command:\n"
201 " jsonptr -query=/foo/1 rfc-6901-json-pointer.json\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100202 "will print:\n"
203 " \"baz\"\n"
204 "\n"
205 "An absent query is equivalent to the empty query, which identifies the\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100206 "entire input (the root value). Unlike a file system, the \"/\" query\n"
Nigel Taod0b16cb2020-03-14 10:15:54 +1100207 "does not identify the root. Instead, \"\" is the root and \"/\" is the\n"
208 "child (the value in a key-value pair) of the root whose key is the empty\n"
209 "string. Similarly, \"/xyz\" and \"/xyz/\" are two different nodes.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100210 "\n"
Nigel Tao0291a472020-08-13 22:40:10 +1000211 "If the query found a valid JSON value, this program will return a zero\n"
212 "exit code even if the rest of the input isn't valid JSON. If the query\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100213 "did not find a value, or found an invalid one, this program returns a\n"
214 "non-zero exit code, but may still print partial output to stdout.\n"
215 "\n"
Nigel Tao0291a472020-08-13 22:40:10 +1000216 "The JSON specification (https://json.org/) permits implementations that\n"
217 "allow duplicate keys, as this one does. This JSON Pointer implementation\n"
218 "is also greedy, following the first match for each fragment without\n"
219 "back-tracking. For example, the \"/foo/bar\" query will fail if the root\n"
220 "object has multiple \"foo\" children but the first one doesn't have a\n"
221 "\"bar\" child, even if later ones do.\n"
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100222 "\n"
Nigel Taoecadf722020-07-13 08:22:34 +1000223 "The -strict-json-pointer-syntax flag restricts the -query=STR string to\n"
224 "exactly RFC 6901, with only two escape sequences: \"~0\" and \"~1\" for\n"
225 "\"~\" and \"/\". Without this flag, this program also lets \"~n\" and\n"
226 "\"~r\" escape the New Line and Carriage Return ASCII control characters,\n"
227 "which can work better with line oriented Unix tools that assume exactly\n"
228 "one value (i.e. one JSON Pointer string) per line.\n"
Nigel Taod6fdfb12020-03-11 12:24:14 +1100229 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100230 "----\n"
231 "\n"
Nigel Tao94440cf2020-04-02 22:28:24 +1100232 "The -d=NUM or -max-output-depth=NUM flag gives the maximum (inclusive)\n"
Nigel Tao0291a472020-08-13 22:40:10 +1000233 "output depth. JSON containers ([] arrays and {} objects) can hold other\n"
234 "containers. When this flag is set, containers at depth NUM are replaced\n"
235 "with \"[…]\" or \"{…}\". A bare -d or -max-output-depth is equivalent to\n"
236 "-d=1. The flag's absence is equivalent to an unlimited output depth.\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100237 "\n"
238 "The -max-output-depth flag only affects the program's output. It doesn't\n"
Nigel Tao0291a472020-08-13 22:40:10 +1000239 "affect whether or not the input is considered valid JSON. The JSON\n"
240 "specification permits implementations to set their own maximum input\n"
241 "depth. This JSON implementation sets it to 1024.\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100242 "\n"
243 "Depth is measured in terms of nested containers. It is unaffected by the\n"
244 "number of spaces or tabs used to indent.\n"
245 "\n"
246 "When both -max-output-depth and -query are set, the output depth is\n"
247 "measured from when the query resolves, not from the input root. The\n"
248 "input depth (measured from the root) is still limited to 1024.\n"
249 "\n"
250 "----\n"
251 "\n"
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100252 "The -fail-if-unsandboxed flag causes the program to exit if it does not\n"
253 "self-impose a sandbox. On Linux, it self-imposes a SECCOMP_MODE_STRICT\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100254 "sandbox, regardless of whether this flag was set.";
Nigel Tao0cd2f982020-03-03 23:03:02 +1100255
Nigel Tao2cf76db2020-02-27 22:42:01 +1100256// ----
257
Nigel Taof3146c22020-03-26 08:47:42 +1100258// Wuffs allows either statically or dynamically allocated work buffers. This
259// program exercises static allocation.
260#define WORK_BUFFER_ARRAY_SIZE \
261 WUFFS_JSON__DECODER_WORKBUF_LEN_MAX_INCL_WORST_CASE
262#if WORK_BUFFER_ARRAY_SIZE > 0
Nigel Taod60815c2020-03-26 14:32:35 +1100263uint8_t g_work_buffer_array[WORK_BUFFER_ARRAY_SIZE];
Nigel Taof3146c22020-03-26 08:47:42 +1100264#else
265// Not all C/C++ compilers support 0-length arrays.
Nigel Taod60815c2020-03-26 14:32:35 +1100266uint8_t g_work_buffer_array[1];
Nigel Taof3146c22020-03-26 08:47:42 +1100267#endif
268
Nigel Taod60815c2020-03-26 14:32:35 +1100269bool g_sandboxed = false;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100270
Nigel Taod60815c2020-03-26 14:32:35 +1100271int g_input_file_descriptor = 0; // A 0 default means stdin.
Nigel Tao01abc842020-03-06 21:42:33 +1100272
Nigel Tao0a0c7d62020-08-18 23:31:27 +1000273#define NEW_LINE_THEN_256_SPACES \
274 "\n " \
275 " " \
276 " " \
277 " "
278#define NEW_LINE_THEN_256_TABS \
279 "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" \
280 "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" \
281 "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" \
282 "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" \
283 "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" \
284 "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" \
285 "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"
286
287const char* g_new_line_then_256_indent_bytes;
288uint32_t g_bytes_per_indent_depth;
Nigel Tao107f0ef2020-03-01 21:35:02 +1100289
Nigel Taofdac24a2020-03-06 21:53:08 +1100290#ifndef DST_BUFFER_ARRAY_SIZE
291#define DST_BUFFER_ARRAY_SIZE (32 * 1024)
Nigel Tao1b073492020-02-16 22:11:36 +1100292#endif
Nigel Taofdac24a2020-03-06 21:53:08 +1100293#ifndef SRC_BUFFER_ARRAY_SIZE
294#define SRC_BUFFER_ARRAY_SIZE (32 * 1024)
Nigel Tao1b073492020-02-16 22:11:36 +1100295#endif
Nigel Taofdac24a2020-03-06 21:53:08 +1100296#ifndef TOKEN_BUFFER_ARRAY_SIZE
297#define TOKEN_BUFFER_ARRAY_SIZE (4 * 1024)
Nigel Tao1b073492020-02-16 22:11:36 +1100298#endif
299
Nigel Taod60815c2020-03-26 14:32:35 +1100300uint8_t g_dst_array[DST_BUFFER_ARRAY_SIZE];
301uint8_t g_src_array[SRC_BUFFER_ARRAY_SIZE];
302wuffs_base__token g_tok_array[TOKEN_BUFFER_ARRAY_SIZE];
Nigel Tao1b073492020-02-16 22:11:36 +1100303
Nigel Taod60815c2020-03-26 14:32:35 +1100304wuffs_base__io_buffer g_dst;
305wuffs_base__io_buffer g_src;
306wuffs_base__token_buffer g_tok;
Nigel Tao1b073492020-02-16 22:11:36 +1100307
Nigel Taod60815c2020-03-26 14:32:35 +1100308// g_curr_token_end_src_index is the g_src.data.ptr index of the end of the
309// current token. An invariant is that (g_curr_token_end_src_index <=
310// g_src.meta.ri).
311size_t g_curr_token_end_src_index;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100312
Nigel Taod60815c2020-03-26 14:32:35 +1100313uint32_t g_depth;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100314
315enum class context {
316 none,
317 in_list_after_bracket,
318 in_list_after_value,
319 in_dict_after_brace,
320 in_dict_after_key,
321 in_dict_after_value,
Nigel Taod60815c2020-03-26 14:32:35 +1100322} g_ctx;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100323
Nigel Tao0cd2f982020-03-03 23:03:02 +1100324bool //
325in_dict_before_key() {
Nigel Taod60815c2020-03-26 14:32:35 +1100326 return (g_ctx == context::in_dict_after_brace) ||
327 (g_ctx == context::in_dict_after_value);
Nigel Tao0cd2f982020-03-03 23:03:02 +1100328}
329
Nigel Taod60815c2020-03-26 14:32:35 +1100330uint32_t g_suppress_write_dst;
331bool g_wrote_to_dst;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100332
Nigel Tao0291a472020-08-13 22:40:10 +1000333wuffs_json__decoder g_dec;
Nigel Taoea532452020-07-27 00:03:00 +1000334
Nigel Tao0cd2f982020-03-03 23:03:02 +1100335// ----
336
337// Query is a JSON Pointer query. After initializing with a NUL-terminated C
338// string, its multiple fragments are consumed as the program walks the JSON
339// data from stdin. For example, letting "$" denote a NUL, suppose that we
340// started with a query string of "/apple/banana/12/durian" and are currently
Nigel Taob48ee752020-03-13 09:27:33 +1100341// trying to match the second fragment, "banana", so that Query::m_depth is 2:
Nigel Tao0cd2f982020-03-03 23:03:02 +1100342//
343// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
344// / a p p l e / b a n a n a / 1 2 / d u r i a n $
345// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
346// ^ ^
Nigel Taob48ee752020-03-13 09:27:33 +1100347// m_frag_i m_frag_k
Nigel Tao0cd2f982020-03-03 23:03:02 +1100348//
Nigel Taob48ee752020-03-13 09:27:33 +1100349// The two pointers m_frag_i and m_frag_k (abbreviated as mfi and mfk) are the
350// start (inclusive) and end (exclusive) of the query fragment. They satisfy
351// (mfi <= mfk) and may be equal if the fragment empty (note that "" is a valid
352// JSON object key).
Nigel Tao0cd2f982020-03-03 23:03:02 +1100353//
Nigel Taob48ee752020-03-13 09:27:33 +1100354// The m_frag_j (mfj) pointer moves between these two, or is nullptr. An
355// invariant is that (((mfi <= mfj) && (mfj <= mfk)) || (mfj == nullptr)).
Nigel Tao0cd2f982020-03-03 23:03:02 +1100356//
357// Wuffs' JSON tokenizer can portray a single JSON string as multiple Wuffs
358// tokens, as backslash-escaped values within that JSON string may each get
359// their own token.
360//
Nigel Taob48ee752020-03-13 09:27:33 +1100361// At the start of each object key (a JSON string), mfj is set to mfi.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100362//
Nigel Taob48ee752020-03-13 09:27:33 +1100363// While mfj remains non-nullptr, each token's unescaped contents are then
364// compared to that part of the fragment from mfj to mfk. If it is a prefix
365// (including the case of an exact match), then mfj is advanced by the
366// unescaped length. Otherwise, mfj is set to nullptr.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100367//
368// Comparison accounts for JSON Pointer's escaping notation: "~0" and "~1" in
369// the query (not the JSON value) are unescaped to "~" and "/" respectively.
Nigel Taob48ee752020-03-13 09:27:33 +1100370// "~n" and "~r" are also unescaped to "\n" and "\r". The program is
371// responsible for calling Query::validate (with a strict_json_pointer_syntax
372// argument) before otherwise using this class.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100373//
Nigel Taob48ee752020-03-13 09:27:33 +1100374// The mfj pointer therefore advances from mfi to mfk, or drops out, as we
375// incrementally match the object key with the query fragment. For example, if
376// we have already matched the "ban" of "banana", then we would accept any of
377// an "ana" token, an "a" token or a "\u0061" token, amongst others. They would
378// advance mfj by 3, 1 or 1 bytes respectively.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100379//
Nigel Taob48ee752020-03-13 09:27:33 +1100380// mfj
Nigel Tao0cd2f982020-03-03 23:03:02 +1100381// v
382// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
383// / a p p l e / b a n a n a / 1 2 / d u r i a n $
384// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
385// ^ ^
Nigel Taob48ee752020-03-13 09:27:33 +1100386// mfi mfk
Nigel Tao0cd2f982020-03-03 23:03:02 +1100387//
388// At the end of each object key (or equivalently, at the start of each object
Nigel Taob48ee752020-03-13 09:27:33 +1100389// value), if mfj is non-nullptr and equal to (but not less than) mfk then we
390// have a fragment match: the query fragment equals the object key. If there is
391// a next fragment (in this example, "12") we move the frag_etc pointers to its
392// start and end and increment Query::m_depth. Otherwise, we have matched the
393// complete query, and the upcoming JSON value is the result of that query.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100394//
395// The discussion above centers on object keys. If the query fragment is
396// numeric then it can also match as an array index: the string fragment "12"
397// will match an array's 13th element (starting counting from zero). See RFC
398// 6901 for its precise definition of an "array index" number.
399//
Nigel Taob48ee752020-03-13 09:27:33 +1100400// Array index fragment match is represented by the Query::m_array_index field,
Nigel Tao0cd2f982020-03-03 23:03:02 +1100401// whose type (wuffs_base__result_u64) is a result type. An error result means
402// that the fragment is not an array index. A value result holds the number of
403// list elements remaining. When matching a query fragment in an array (instead
404// of in an object), each element ticks this number down towards zero. At zero,
405// the upcoming JSON value is the one that matches the query fragment.
406class Query {
407 private:
Nigel Taob48ee752020-03-13 09:27:33 +1100408 uint8_t* m_frag_i;
409 uint8_t* m_frag_j;
410 uint8_t* m_frag_k;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100411
Nigel Taob48ee752020-03-13 09:27:33 +1100412 uint32_t m_depth;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100413
Nigel Taob48ee752020-03-13 09:27:33 +1100414 wuffs_base__result_u64 m_array_index;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100415
416 public:
417 void reset(char* query_c_string) {
Nigel Taob48ee752020-03-13 09:27:33 +1100418 m_frag_i = (uint8_t*)query_c_string;
419 m_frag_j = (uint8_t*)query_c_string;
420 m_frag_k = (uint8_t*)query_c_string;
421 m_depth = 0;
422 m_array_index.status.repr = "#main: not an array index query fragment";
423 m_array_index.value = 0;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100424 }
425
Nigel Taob48ee752020-03-13 09:27:33 +1100426 void restart_fragment(bool enable) { m_frag_j = enable ? m_frag_i : nullptr; }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100427
Nigel Taob48ee752020-03-13 09:27:33 +1100428 bool is_at(uint32_t depth) { return m_depth == depth; }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100429
430 // tick returns whether the fragment is a valid array index whose value is
431 // zero. If valid but non-zero, it decrements it and returns false.
432 bool tick() {
Nigel Taob48ee752020-03-13 09:27:33 +1100433 if (m_array_index.status.is_ok()) {
Nigel Tao0291a472020-08-13 22:40:10 +1000434 if (m_array_index.value == 0) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100435 return true;
436 }
Nigel Tao0291a472020-08-13 22:40:10 +1000437 m_array_index.value--;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100438 }
439 return false;
440 }
441
442 // next_fragment moves to the next fragment, returning whether it existed.
443 bool next_fragment() {
Nigel Taob48ee752020-03-13 09:27:33 +1100444 uint8_t* k = m_frag_k;
445 uint32_t d = m_depth;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100446
447 this->reset(nullptr);
448
449 if (!k || (*k != '/')) {
450 return false;
451 }
452 k++;
453
454 bool all_digits = true;
455 uint8_t* i = k;
456 while ((*k != '\x00') && (*k != '/')) {
457 all_digits = all_digits && ('0' <= *k) && (*k <= '9');
458 k++;
459 }
Nigel Taob48ee752020-03-13 09:27:33 +1100460 m_frag_i = i;
461 m_frag_j = i;
462 m_frag_k = k;
463 m_depth = d + 1;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100464 if (all_digits) {
465 // wuffs_base__parse_number_u64 rejects leading zeroes, e.g. "00", "07".
Nigel Tao6b7ce302020-07-07 16:19:46 +1000466 m_array_index = wuffs_base__parse_number_u64(
467 wuffs_base__make_slice_u8(i, k - i),
468 WUFFS_BASE__PARSE_NUMBER_XXX__DEFAULT_OPTIONS);
Nigel Tao0cd2f982020-03-03 23:03:02 +1100469 }
470 return true;
471 }
472
Nigel Taob48ee752020-03-13 09:27:33 +1100473 bool matched_all() { return m_frag_k == nullptr; }
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100474
Nigel Taob48ee752020-03-13 09:27:33 +1100475 bool matched_fragment() { return m_frag_j && (m_frag_j == m_frag_k); }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100476
477 void incremental_match_slice(uint8_t* ptr, size_t len) {
Nigel Taob48ee752020-03-13 09:27:33 +1100478 if (!m_frag_j) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100479 return;
480 }
Nigel Taob48ee752020-03-13 09:27:33 +1100481 uint8_t* j = m_frag_j;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100482 while (true) {
483 if (len == 0) {
Nigel Taob48ee752020-03-13 09:27:33 +1100484 m_frag_j = j;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100485 return;
486 }
487
488 if (*j == '\x00') {
489 break;
490
491 } else if (*j == '~') {
492 j++;
493 if (*j == '0') {
494 if (*ptr != '~') {
495 break;
496 }
497 } else if (*j == '1') {
498 if (*ptr != '/') {
499 break;
500 }
Nigel Taod6fdfb12020-03-11 12:24:14 +1100501 } else if (*j == 'n') {
502 if (*ptr != '\n') {
503 break;
504 }
505 } else if (*j == 'r') {
506 if (*ptr != '\r') {
507 break;
508 }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100509 } else {
510 break;
511 }
512
513 } else if (*j != *ptr) {
514 break;
515 }
516
517 j++;
518 ptr++;
519 len--;
520 }
Nigel Taob48ee752020-03-13 09:27:33 +1100521 m_frag_j = nullptr;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100522 }
523
524 void incremental_match_code_point(uint32_t code_point) {
Nigel Taob48ee752020-03-13 09:27:33 +1100525 if (!m_frag_j) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100526 return;
527 }
528 uint8_t u[WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL];
529 size_t n = wuffs_base__utf_8__encode(
530 wuffs_base__make_slice_u8(&u[0],
531 WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL),
532 code_point);
533 if (n > 0) {
534 this->incremental_match_slice(&u[0], n);
535 }
536 }
537
538 // validate returns whether the (ptr, len) arguments form a valid JSON
539 // Pointer. In particular, it must be valid UTF-8, and either be empty or
540 // start with a '/'. Any '~' within must immediately be followed by either
Nigel Taod6fdfb12020-03-11 12:24:14 +1100541 // '0' or '1'. If strict_json_pointer_syntax is false, a '~' may also be
542 // followed by either 'n' or 'r'.
543 static bool validate(char* query_c_string,
544 size_t length,
545 bool strict_json_pointer_syntax) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100546 if (length <= 0) {
547 return true;
548 }
549 if (query_c_string[0] != '/') {
550 return false;
551 }
552 wuffs_base__slice_u8 s =
553 wuffs_base__make_slice_u8((uint8_t*)query_c_string, length);
554 bool previous_was_tilde = false;
555 while (s.len > 0) {
Nigel Tao702c7b22020-07-22 15:42:54 +1000556 wuffs_base__utf_8__next__output o = wuffs_base__utf_8__next(s.ptr, s.len);
Nigel Tao0cd2f982020-03-03 23:03:02 +1100557 if (!o.is_valid()) {
558 return false;
559 }
Nigel Taod6fdfb12020-03-11 12:24:14 +1100560
561 if (previous_was_tilde) {
562 switch (o.code_point) {
563 case '0':
564 case '1':
565 break;
566 case 'n':
567 case 'r':
568 if (strict_json_pointer_syntax) {
569 return false;
570 }
571 break;
572 default:
573 return false;
574 }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100575 }
576 previous_was_tilde = o.code_point == '~';
Nigel Taod6fdfb12020-03-11 12:24:14 +1100577
Nigel Tao0cd2f982020-03-03 23:03:02 +1100578 s.ptr += o.byte_length;
579 s.len -= o.byte_length;
580 }
581 return !previous_was_tilde;
582 }
Nigel Taod60815c2020-03-26 14:32:35 +1100583} g_query;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100584
585// ----
586
Nigel Tao68920952020-03-03 11:25:18 +1100587struct {
588 int remaining_argc;
589 char** remaining_argv;
590
Nigel Tao3690e832020-03-12 16:52:26 +1100591 bool compact_output;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100592 bool fail_if_unsandboxed;
Nigel Tao0291a472020-08-13 22:40:10 +1000593 bool input_allow_comments;
594 bool input_allow_extra_comma;
595 bool input_allow_inf_nan_numbers;
Nigel Tao0291a472020-08-13 22:40:10 +1000596 bool output_extra_comma;
Nigel Taod6fdfb12020-03-11 12:24:14 +1100597 bool strict_json_pointer_syntax;
Nigel Tao68920952020-03-03 11:25:18 +1100598 bool tabs;
Nigel Tao0a0c7d62020-08-18 23:31:27 +1000599
600 uint32_t max_output_depth;
601 uint32_t spaces;
602
603 char* query_c_string;
Nigel Taod60815c2020-03-26 14:32:35 +1100604} g_flags = {0};
Nigel Tao68920952020-03-03 11:25:18 +1100605
606const char* //
607parse_flags(int argc, char** argv) {
Nigel Taoecadf722020-07-13 08:22:34 +1000608 g_flags.spaces = 4;
Nigel Taod60815c2020-03-26 14:32:35 +1100609 g_flags.max_output_depth = 0xFFFFFFFF;
Nigel Tao68920952020-03-03 11:25:18 +1100610
611 int c = (argc > 0) ? 1 : 0; // Skip argv[0], the program name.
612 for (; c < argc; c++) {
613 char* arg = argv[c];
614 if (*arg++ != '-') {
615 break;
616 }
617
618 // A double-dash "--foo" is equivalent to a single-dash "-foo". As special
619 // cases, a bare "-" is not a flag (some programs may interpret it as
620 // stdin) and a bare "--" means to stop parsing flags.
621 if (*arg == '\x00') {
622 break;
623 } else if (*arg == '-') {
624 arg++;
625 if (*arg == '\x00') {
626 c++;
627 break;
628 }
629 }
630
Nigel Tao3690e832020-03-12 16:52:26 +1100631 if (!strcmp(arg, "c") || !strcmp(arg, "compact-output")) {
Nigel Taod60815c2020-03-26 14:32:35 +1100632 g_flags.compact_output = true;
Nigel Tao68920952020-03-03 11:25:18 +1100633 continue;
634 }
Nigel Tao94440cf2020-04-02 22:28:24 +1100635 if (!strcmp(arg, "d") || !strcmp(arg, "max-output-depth")) {
636 g_flags.max_output_depth = 1;
637 continue;
638 } else if (!strncmp(arg, "d=", 2) ||
639 !strncmp(arg, "max-output-depth=", 16)) {
640 while (*arg++ != '=') {
641 }
642 wuffs_base__result_u64 u = wuffs_base__parse_number_u64(
Nigel Tao6b7ce302020-07-07 16:19:46 +1000643 wuffs_base__make_slice_u8((uint8_t*)arg, strlen(arg)),
644 WUFFS_BASE__PARSE_NUMBER_XXX__DEFAULT_OPTIONS);
Nigel Taoaf757722020-07-18 17:27:11 +1000645 if (u.status.is_ok() && (u.value <= 0xFFFFFFFF)) {
Nigel Tao94440cf2020-04-02 22:28:24 +1100646 g_flags.max_output_depth = (uint32_t)(u.value);
647 continue;
648 }
649 return g_usage;
650 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100651 if (!strcmp(arg, "fail-if-unsandboxed")) {
Nigel Taod60815c2020-03-26 14:32:35 +1100652 g_flags.fail_if_unsandboxed = true;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100653 continue;
654 }
Nigel Tao0291a472020-08-13 22:40:10 +1000655 if (!strcmp(arg, "input-allow-comments")) {
656 g_flags.input_allow_comments = true;
Nigel Tao4e193592020-07-15 12:48:57 +1000657 continue;
658 }
Nigel Tao0291a472020-08-13 22:40:10 +1000659 if (!strcmp(arg, "input-allow-extra-comma")) {
660 g_flags.input_allow_extra_comma = true;
Nigel Tao4e193592020-07-15 12:48:57 +1000661 continue;
662 }
Nigel Tao0291a472020-08-13 22:40:10 +1000663 if (!strcmp(arg, "input-allow-inf-nan-numbers")) {
664 g_flags.input_allow_inf_nan_numbers = true;
Nigel Tao3c8589b2020-07-19 21:49:00 +1000665 continue;
666 }
Nigel Tao0291a472020-08-13 22:40:10 +1000667 if (!strcmp(arg, "output-extra-comma")) {
668 g_flags.output_extra_comma = true;
Nigel Taodd114692020-07-25 21:54:12 +1000669 continue;
670 }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100671 if (!strncmp(arg, "q=", 2) || !strncmp(arg, "query=", 6)) {
672 while (*arg++ != '=') {
673 }
Nigel Taod60815c2020-03-26 14:32:35 +1100674 g_flags.query_c_string = arg;
Nigel Taod6fdfb12020-03-11 12:24:14 +1100675 continue;
676 }
Nigel Taoecadf722020-07-13 08:22:34 +1000677 if (!strncmp(arg, "s=", 2) || !strncmp(arg, "spaces=", 7)) {
678 while (*arg++ != '=') {
679 }
680 if (('0' <= arg[0]) && (arg[0] <= '8') && (arg[1] == '\x00')) {
681 g_flags.spaces = arg[0] - '0';
682 continue;
683 }
684 return g_usage;
685 }
686 if (!strcmp(arg, "strict-json-pointer-syntax")) {
Nigel Taod60815c2020-03-26 14:32:35 +1100687 g_flags.strict_json_pointer_syntax = true;
Nigel Taod6fdfb12020-03-11 12:24:14 +1100688 continue;
Nigel Tao68920952020-03-03 11:25:18 +1100689 }
690 if (!strcmp(arg, "t") || !strcmp(arg, "tabs")) {
Nigel Taod60815c2020-03-26 14:32:35 +1100691 g_flags.tabs = true;
Nigel Tao68920952020-03-03 11:25:18 +1100692 continue;
693 }
694
Nigel Taod60815c2020-03-26 14:32:35 +1100695 return g_usage;
Nigel Tao68920952020-03-03 11:25:18 +1100696 }
697
Nigel Taod60815c2020-03-26 14:32:35 +1100698 if (g_flags.query_c_string &&
699 !Query::validate(g_flags.query_c_string, strlen(g_flags.query_c_string),
700 g_flags.strict_json_pointer_syntax)) {
Nigel Taod6fdfb12020-03-11 12:24:14 +1100701 return "main: bad JSON Pointer (RFC 6901) syntax for the -query=STR flag";
702 }
703
Nigel Taod60815c2020-03-26 14:32:35 +1100704 g_flags.remaining_argc = argc - c;
705 g_flags.remaining_argv = argv + c;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100706 return nullptr;
Nigel Tao68920952020-03-03 11:25:18 +1100707}
708
Nigel Tao2cf76db2020-02-27 22:42:01 +1100709const char* //
710initialize_globals(int argc, char** argv) {
Nigel Taod60815c2020-03-26 14:32:35 +1100711 g_dst = wuffs_base__make_io_buffer(
712 wuffs_base__make_slice_u8(g_dst_array, DST_BUFFER_ARRAY_SIZE),
Nigel Tao2cf76db2020-02-27 22:42:01 +1100713 wuffs_base__empty_io_buffer_meta());
Nigel Tao1b073492020-02-16 22:11:36 +1100714
Nigel Taod60815c2020-03-26 14:32:35 +1100715 g_src = wuffs_base__make_io_buffer(
716 wuffs_base__make_slice_u8(g_src_array, SRC_BUFFER_ARRAY_SIZE),
Nigel Tao2cf76db2020-02-27 22:42:01 +1100717 wuffs_base__empty_io_buffer_meta());
718
Nigel Taod60815c2020-03-26 14:32:35 +1100719 g_tok = wuffs_base__make_token_buffer(
720 wuffs_base__make_slice_token(g_tok_array, TOKEN_BUFFER_ARRAY_SIZE),
Nigel Tao2cf76db2020-02-27 22:42:01 +1100721 wuffs_base__empty_token_buffer_meta());
722
Nigel Taod60815c2020-03-26 14:32:35 +1100723 g_curr_token_end_src_index = 0;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100724
Nigel Taod60815c2020-03-26 14:32:35 +1100725 g_depth = 0;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100726
Nigel Taod60815c2020-03-26 14:32:35 +1100727 g_ctx = context::none;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100728
Nigel Tao68920952020-03-03 11:25:18 +1100729 TRY(parse_flags(argc, argv));
Nigel Taod60815c2020-03-26 14:32:35 +1100730 if (g_flags.fail_if_unsandboxed && !g_sandboxed) {
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100731 return "main: unsandboxed";
732 }
Nigel Tao01abc842020-03-06 21:42:33 +1100733 const int stdin_fd = 0;
Nigel Taod60815c2020-03-26 14:32:35 +1100734 if (g_flags.remaining_argc >
735 ((g_input_file_descriptor != stdin_fd) ? 1 : 0)) {
736 return g_usage;
Nigel Tao107f0ef2020-03-01 21:35:02 +1100737 }
738
Nigel Tao0a0c7d62020-08-18 23:31:27 +1000739 g_new_line_then_256_indent_bytes =
740 g_flags.tabs ? NEW_LINE_THEN_256_TABS : NEW_LINE_THEN_256_SPACES;
741 g_bytes_per_indent_depth = g_flags.tabs ? 1 : g_flags.spaces;
742
Nigel Taod60815c2020-03-26 14:32:35 +1100743 g_query.reset(g_flags.query_c_string);
Nigel Tao0cd2f982020-03-03 23:03:02 +1100744
Nigel Taoc96b31c2020-07-27 22:37:23 +1000745 // If the query is non-empty, suppress writing to stdout until we've
Nigel Tao0cd2f982020-03-03 23:03:02 +1100746 // completed the query.
Nigel Taod60815c2020-03-26 14:32:35 +1100747 g_suppress_write_dst = g_query.next_fragment() ? 1 : 0;
748 g_wrote_to_dst = false;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100749
Nigel Tao0291a472020-08-13 22:40:10 +1000750 TRY(g_dec.initialize(sizeof__wuffs_json__decoder(), WUFFS_VERSION, 0)
751 .message());
Nigel Tao4b186b02020-03-18 14:25:21 +1100752
Nigel Tao0291a472020-08-13 22:40:10 +1000753 if (g_flags.input_allow_comments) {
754 g_dec.set_quirk_enabled(WUFFS_JSON__QUIRK_ALLOW_COMMENT_BLOCK, true);
755 g_dec.set_quirk_enabled(WUFFS_JSON__QUIRK_ALLOW_COMMENT_LINE, true);
Nigel Tao3c8589b2020-07-19 21:49:00 +1000756 }
Nigel Tao0291a472020-08-13 22:40:10 +1000757 if (g_flags.input_allow_extra_comma) {
758 g_dec.set_quirk_enabled(WUFFS_JSON__QUIRK_ALLOW_EXTRA_COMMA, true);
Nigel Taoc766bb72020-07-09 12:59:32 +1000759 }
Nigel Tao0291a472020-08-13 22:40:10 +1000760 if (g_flags.input_allow_inf_nan_numbers) {
761 g_dec.set_quirk_enabled(WUFFS_JSON__QUIRK_ALLOW_INF_NAN_NUMBERS, true);
Nigel Tao51a38292020-07-19 22:43:17 +1000762 }
Nigel Taoc766bb72020-07-09 12:59:32 +1000763
Nigel Tao4b186b02020-03-18 14:25:21 +1100764 // Consume an optional whitespace trailer. This isn't part of the JSON spec,
765 // but it works better with line oriented Unix tools (such as "echo 123 |
766 // jsonptr" where it's "echo", not "echo -n") or hand-edited JSON files which
767 // can accidentally contain trailing whitespace.
Nigel Tao0291a472020-08-13 22:40:10 +1000768 g_dec.set_quirk_enabled(WUFFS_JSON__QUIRK_ALLOW_TRAILING_NEW_LINE, true);
Nigel Tao4b186b02020-03-18 14:25:21 +1100769
770 return nullptr;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100771}
Nigel Tao1b073492020-02-16 22:11:36 +1100772
773// ----
774
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100775// ignore_return_value suppresses errors from -Wall -Werror.
776static void //
777ignore_return_value(int ignored) {}
778
Nigel Tao2914bae2020-02-26 09:40:30 +1100779const char* //
780read_src() {
Nigel Taod60815c2020-03-26 14:32:35 +1100781 if (g_src.meta.closed) {
Nigel Tao9cc2c252020-02-23 17:05:49 +1100782 return "main: internal error: read requested on a closed source";
Nigel Taoa8406922020-02-19 12:22:00 +1100783 }
Nigel Taod60815c2020-03-26 14:32:35 +1100784 g_src.compact();
785 if (g_src.meta.wi >= g_src.data.len) {
786 return "main: g_src buffer is full";
Nigel Tao1b073492020-02-16 22:11:36 +1100787 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100788 while (true) {
Nigel Taod6a10df2020-07-27 11:47:47 +1000789 ssize_t n = read(g_input_file_descriptor, g_src.writer_pointer(),
790 g_src.writer_length());
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100791 if (n >= 0) {
Nigel Taod60815c2020-03-26 14:32:35 +1100792 g_src.meta.wi += n;
793 g_src.meta.closed = n == 0;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100794 break;
795 } else if (errno != EINTR) {
796 return strerror(errno);
797 }
Nigel Tao1b073492020-02-16 22:11:36 +1100798 }
799 return nullptr;
800}
801
Nigel Tao2914bae2020-02-26 09:40:30 +1100802const char* //
803flush_dst() {
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100804 while (true) {
Nigel Taod6a10df2020-07-27 11:47:47 +1000805 size_t n = g_dst.reader_length();
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100806 if (n == 0) {
807 break;
Nigel Tao1b073492020-02-16 22:11:36 +1100808 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100809 const int stdout_fd = 1;
Nigel Taod6a10df2020-07-27 11:47:47 +1000810 ssize_t i = write(stdout_fd, g_dst.reader_pointer(), n);
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100811 if (i >= 0) {
Nigel Taod60815c2020-03-26 14:32:35 +1100812 g_dst.meta.ri += i;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100813 } else if (errno != EINTR) {
814 return strerror(errno);
815 }
Nigel Tao1b073492020-02-16 22:11:36 +1100816 }
Nigel Taod60815c2020-03-26 14:32:35 +1100817 g_dst.compact();
Nigel Tao1b073492020-02-16 22:11:36 +1100818 return nullptr;
819}
820
Nigel Tao2914bae2020-02-26 09:40:30 +1100821const char* //
822write_dst(const void* s, size_t n) {
Nigel Taod60815c2020-03-26 14:32:35 +1100823 if (g_suppress_write_dst > 0) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100824 return nullptr;
825 }
Nigel Tao1b073492020-02-16 22:11:36 +1100826 const uint8_t* p = static_cast<const uint8_t*>(s);
827 while (n > 0) {
Nigel Taod6a10df2020-07-27 11:47:47 +1000828 size_t i = g_dst.writer_length();
Nigel Tao1b073492020-02-16 22:11:36 +1100829 if (i == 0) {
830 const char* z = flush_dst();
831 if (z) {
832 return z;
833 }
Nigel Taod6a10df2020-07-27 11:47:47 +1000834 i = g_dst.writer_length();
Nigel Tao1b073492020-02-16 22:11:36 +1100835 if (i == 0) {
Nigel Taod60815c2020-03-26 14:32:35 +1100836 return "main: g_dst buffer is full";
Nigel Tao1b073492020-02-16 22:11:36 +1100837 }
838 }
839
840 if (i > n) {
841 i = n;
842 }
Nigel Taod60815c2020-03-26 14:32:35 +1100843 memcpy(g_dst.data.ptr + g_dst.meta.wi, p, i);
844 g_dst.meta.wi += i;
Nigel Tao1b073492020-02-16 22:11:36 +1100845 p += i;
846 n -= i;
Nigel Taod60815c2020-03-26 14:32:35 +1100847 g_wrote_to_dst = true;
Nigel Tao1b073492020-02-16 22:11:36 +1100848 }
849 return nullptr;
850}
851
852// ----
853
Nigel Tao2914bae2020-02-26 09:40:30 +1100854uint8_t //
855hex_digit(uint8_t nibble) {
Nigel Taob5461bd2020-02-21 14:13:37 +1100856 nibble &= 0x0F;
857 if (nibble <= 9) {
858 return '0' + nibble;
859 }
860 return ('A' - 10) + nibble;
861}
862
Nigel Tao2914bae2020-02-26 09:40:30 +1100863const char* //
Nigel Tao7cb76542020-07-19 22:19:04 +1000864handle_unicode_code_point(uint32_t ucp) {
Nigel Tao0291a472020-08-13 22:40:10 +1000865 if (ucp < 0x0020) {
866 switch (ucp) {
867 case '\b':
868 return write_dst("\\b", 2);
869 case '\f':
870 return write_dst("\\f", 2);
871 case '\n':
872 return write_dst("\\n", 2);
873 case '\r':
874 return write_dst("\\r", 2);
875 case '\t':
876 return write_dst("\\t", 2);
Nigel Tao7cb76542020-07-19 22:19:04 +1000877 }
Nigel Tao0291a472020-08-13 22:40:10 +1000878
879 // Other bytes less than 0x0020 are valid UTF-8 but not valid in a
880 // JSON string. They need to remain escaped.
881 uint8_t esc6[6];
882 esc6[0] = '\\';
883 esc6[1] = 'u';
884 esc6[2] = '0';
885 esc6[3] = '0';
886 esc6[4] = hex_digit(ucp >> 4);
887 esc6[5] = hex_digit(ucp >> 0);
888 return write_dst(&esc6[0], 6);
889
890 } else if (ucp == '\"') {
891 return write_dst("\\\"", 2);
892
893 } else if (ucp == '\\') {
894 return write_dst("\\\\", 2);
Nigel Tao7cb76542020-07-19 22:19:04 +1000895 }
896
897 uint8_t u[WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL];
898 size_t n = wuffs_base__utf_8__encode(
899 wuffs_base__make_slice_u8(&u[0],
900 WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL),
901 ucp);
902 if (n == 0) {
903 return "main: internal error: unexpected Unicode code point";
904 }
Nigel Tao0291a472020-08-13 22:40:10 +1000905 return write_dst(&u[0], n);
Nigel Tao168f60a2020-07-14 13:19:33 +1000906}
907
Nigel Taod191a3f2020-07-19 22:14:54 +1000908// ----
909
Nigel Tao3b486982020-02-27 15:05:59 +1100910const char* //
Nigel Tao2ef39992020-04-09 17:24:39 +1000911handle_token(wuffs_base__token t, bool start_of_token_chain) {
Nigel Tao2cf76db2020-02-27 22:42:01 +1100912 do {
Nigel Tao462f8662020-04-01 23:01:51 +1100913 int64_t vbc = t.value_base_category();
Nigel Tao2cf76db2020-02-27 22:42:01 +1100914 uint64_t vbd = t.value_base_detail();
Nigel Taoee6927f2020-07-27 12:08:33 +1000915 uint64_t token_length = t.length();
916 wuffs_base__slice_u8 tok = wuffs_base__make_slice_u8(
917 g_src.data.ptr + g_curr_token_end_src_index - token_length,
918 token_length);
Nigel Tao1b073492020-02-16 22:11:36 +1100919
920 // Handle ']' or '}'.
Nigel Tao9f7a2502020-02-23 09:42:02 +1100921 if ((vbc == WUFFS_BASE__TOKEN__VBC__STRUCTURE) &&
Nigel Tao2cf76db2020-02-27 22:42:01 +1100922 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__POP)) {
Nigel Taod60815c2020-03-26 14:32:35 +1100923 if (g_query.is_at(g_depth)) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100924 return "main: no match for query";
925 }
Nigel Taod60815c2020-03-26 14:32:35 +1100926 if (g_depth <= 0) {
927 return "main: internal error: inconsistent g_depth";
Nigel Tao1b073492020-02-16 22:11:36 +1100928 }
Nigel Taod60815c2020-03-26 14:32:35 +1100929 g_depth--;
Nigel Tao1b073492020-02-16 22:11:36 +1100930
Nigel Taod60815c2020-03-26 14:32:35 +1100931 if (g_query.matched_all() && (g_depth >= g_flags.max_output_depth)) {
932 g_suppress_write_dst--;
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100933 // '…' is U+2026 HORIZONTAL ELLIPSIS, which is 3 UTF-8 bytes.
Nigel Tao0291a472020-08-13 22:40:10 +1000934 TRY(write_dst((vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST)
935 ? "\"[…]\""
936 : "\"{…}\"",
937 7));
938 } else {
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100939 // Write preceding whitespace.
Nigel Taod60815c2020-03-26 14:32:35 +1100940 if ((g_ctx != context::in_list_after_bracket) &&
941 (g_ctx != context::in_dict_after_brace) &&
942 !g_flags.compact_output) {
Nigel Tao0291a472020-08-13 22:40:10 +1000943 if (g_flags.output_extra_comma) {
Nigel Tao0a0c7d62020-08-18 23:31:27 +1000944 TRY(write_dst(",", 1));
Nigel Taoc766bb72020-07-09 12:59:32 +1000945 }
Nigel Tao0a0c7d62020-08-18 23:31:27 +1000946 uint32_t indent = g_depth * g_bytes_per_indent_depth;
947 TRY(write_dst(g_new_line_then_256_indent_bytes, 1 + (indent & 0xFF)));
948 for (indent >>= 8; indent > 0; indent--) {
949 TRY(write_dst(g_new_line_then_256_indent_bytes + 1, 0x100));
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100950 }
Nigel Tao1b073492020-02-16 22:11:36 +1100951 }
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100952
953 TRY(write_dst(
954 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST) ? "]" : "}",
955 1));
Nigel Tao1b073492020-02-16 22:11:36 +1100956 }
957
Nigel Taod60815c2020-03-26 14:32:35 +1100958 g_ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
959 ? context::in_list_after_value
960 : context::in_dict_after_key;
Nigel Tao1b073492020-02-16 22:11:36 +1100961 goto after_value;
962 }
963
Nigel Taod1c928a2020-02-28 12:43:53 +1100964 // Write preceding whitespace and punctuation, if it wasn't ']', '}' or a
Nigel Tao0291a472020-08-13 22:40:10 +1000965 // continuation of a multi-token chain.
966 if (start_of_token_chain) {
967 if (g_ctx == context::in_dict_after_key) {
Nigel Taod60815c2020-03-26 14:32:35 +1100968 TRY(write_dst(": ", g_flags.compact_output ? 1 : 2));
969 } else if (g_ctx != context::none) {
Nigel Tao0291a472020-08-13 22:40:10 +1000970 if ((g_ctx != context::in_list_after_bracket) &&
971 (g_ctx != context::in_dict_after_brace)) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100972 TRY(write_dst(",", 1));
Nigel Tao107f0ef2020-03-01 21:35:02 +1100973 }
Nigel Taod60815c2020-03-26 14:32:35 +1100974 if (!g_flags.compact_output) {
Nigel Tao0a0c7d62020-08-18 23:31:27 +1000975 uint32_t indent = g_depth * g_bytes_per_indent_depth;
976 TRY(write_dst(g_new_line_then_256_indent_bytes, 1 + (indent & 0xFF)));
977 for (indent >>= 8; indent > 0; indent--) {
978 TRY(write_dst(g_new_line_then_256_indent_bytes + 1, 0x100));
Nigel Tao0cd2f982020-03-03 23:03:02 +1100979 }
980 }
981 }
982
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100983 bool query_matched_fragment = false;
Nigel Taod60815c2020-03-26 14:32:35 +1100984 if (g_query.is_at(g_depth)) {
985 switch (g_ctx) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100986 case context::in_list_after_bracket:
987 case context::in_list_after_value:
Nigel Taod60815c2020-03-26 14:32:35 +1100988 query_matched_fragment = g_query.tick();
Nigel Tao0cd2f982020-03-03 23:03:02 +1100989 break;
990 case context::in_dict_after_key:
Nigel Taod60815c2020-03-26 14:32:35 +1100991 query_matched_fragment = g_query.matched_fragment();
Nigel Tao0cd2f982020-03-03 23:03:02 +1100992 break;
Nigel Tao18ef5b42020-03-16 10:37:47 +1100993 default:
994 break;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100995 }
996 }
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100997 if (!query_matched_fragment) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100998 // No-op.
Nigel Taod60815c2020-03-26 14:32:35 +1100999 } else if (!g_query.next_fragment()) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001000 // There is no next fragment. We have matched the complete query, and
1001 // the upcoming JSON value is the result of that query.
1002 //
Nigel Taod60815c2020-03-26 14:32:35 +11001003 // Un-suppress writing to stdout and reset the g_ctx and g_depth as if
1004 // we were about to decode a top-level value. This makes any subsequent
1005 // indentation be relative to this point, and we will return g_eod
1006 // after the upcoming JSON value is complete.
1007 if (g_suppress_write_dst != 1) {
1008 return "main: internal error: inconsistent g_suppress_write_dst";
Nigel Tao52c4d6a2020-03-08 21:12:38 +11001009 }
Nigel Taod60815c2020-03-26 14:32:35 +11001010 g_suppress_write_dst = 0;
1011 g_ctx = context::none;
1012 g_depth = 0;
Nigel Tao0cd2f982020-03-03 23:03:02 +11001013 } else if ((vbc != WUFFS_BASE__TOKEN__VBC__STRUCTURE) ||
1014 !(vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__PUSH)) {
1015 // The query has moved on to the next fragment but the upcoming JSON
1016 // value is not a container.
1017 return "main: no match for query";
Nigel Tao1b073492020-02-16 22:11:36 +11001018 }
1019 }
1020
1021 // Handle the token itself: either a container ('[' or '{') or a simple
Nigel Tao85fba7f2020-02-29 16:28:06 +11001022 // value: string (a chain of raw or escaped parts), literal or number.
Nigel Tao1b073492020-02-16 22:11:36 +11001023 switch (vbc) {
Nigel Tao85fba7f2020-02-29 16:28:06 +11001024 case WUFFS_BASE__TOKEN__VBC__STRUCTURE:
Nigel Taod60815c2020-03-26 14:32:35 +11001025 if (g_query.matched_all() && (g_depth >= g_flags.max_output_depth)) {
1026 g_suppress_write_dst++;
Nigel Tao0291a472020-08-13 22:40:10 +10001027 } else {
Nigel Tao52c4d6a2020-03-08 21:12:38 +11001028 TRY(write_dst(
1029 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST) ? "[" : "{",
1030 1));
1031 }
Nigel Taod60815c2020-03-26 14:32:35 +11001032 g_depth++;
1033 g_ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
1034 ? context::in_list_after_bracket
1035 : context::in_dict_after_brace;
Nigel Tao85fba7f2020-02-29 16:28:06 +11001036 return nullptr;
1037
Nigel Tao2cf76db2020-02-27 22:42:01 +11001038 case WUFFS_BASE__TOKEN__VBC__STRING:
Nigel Tao0291a472020-08-13 22:40:10 +10001039 if (start_of_token_chain) {
1040 TRY(write_dst("\"", 1));
1041 g_query.restart_fragment(in_dict_before_key() &&
1042 g_query.is_at(g_depth));
1043 }
1044
1045 if (vbd & WUFFS_BASE__TOKEN__VBD__STRING__CONVERT_0_DST_1_SRC_DROP) {
1046 // No-op.
1047 } else if (vbd &
1048 WUFFS_BASE__TOKEN__VBD__STRING__CONVERT_1_DST_1_SRC_COPY) {
1049 TRY(write_dst(tok.ptr, tok.len));
1050 g_query.incremental_match_slice(tok.ptr, tok.len);
1051 } else {
1052 return "main: internal error: unexpected string-token conversion";
1053 }
1054
Nigel Tao496e88b2020-04-09 22:10:08 +10001055 if (t.continued()) {
Nigel Tao2cf76db2020-02-27 22:42:01 +11001056 return nullptr;
1057 }
Nigel Tao0291a472020-08-13 22:40:10 +10001058 TRY(write_dst("\"", 1));
Nigel Tao2cf76db2020-02-27 22:42:01 +11001059 goto after_value;
1060
1061 case WUFFS_BASE__TOKEN__VBC__UNICODE_CODE_POINT:
Nigel Tao496e88b2020-04-09 22:10:08 +10001062 if (!t.continued()) {
1063 return "main: internal error: unexpected non-continued UCP token";
Nigel Tao0cd2f982020-03-03 23:03:02 +11001064 }
1065 TRY(handle_unicode_code_point(vbd));
Nigel Taod60815c2020-03-26 14:32:35 +11001066 g_query.incremental_match_code_point(vbd);
Nigel Tao0cd2f982020-03-03 23:03:02 +11001067 return nullptr;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001068
Nigel Tao85fba7f2020-02-29 16:28:06 +11001069 case WUFFS_BASE__TOKEN__VBC__LITERAL:
Nigel Tao2cf76db2020-02-27 22:42:01 +11001070 case WUFFS_BASE__TOKEN__VBC__NUMBER:
Nigel Tao0291a472020-08-13 22:40:10 +10001071 TRY(write_dst(tok.ptr, tok.len));
Nigel Tao2cf76db2020-02-27 22:42:01 +11001072 goto after_value;
Nigel Tao1b073492020-02-16 22:11:36 +11001073 }
1074
Nigel Tao0291a472020-08-13 22:40:10 +10001075 // Return an error if we didn't match the (vbc, vbd) pair.
Nigel Tao2cf76db2020-02-27 22:42:01 +11001076 return "main: internal error: unexpected token";
1077 } while (0);
Nigel Tao1b073492020-02-16 22:11:36 +11001078
Nigel Tao2cf76db2020-02-27 22:42:01 +11001079 // Book-keeping after completing a value (whether a container value or a
1080 // simple value). Empty parent containers are no longer empty. If the parent
1081 // container is a "{...}" object, toggle between keys and values.
1082after_value:
Nigel Taod60815c2020-03-26 14:32:35 +11001083 if (g_depth == 0) {
1084 return g_eod;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001085 }
Nigel Taod60815c2020-03-26 14:32:35 +11001086 switch (g_ctx) {
Nigel Tao2cf76db2020-02-27 22:42:01 +11001087 case context::in_list_after_bracket:
Nigel Taod60815c2020-03-26 14:32:35 +11001088 g_ctx = context::in_list_after_value;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001089 break;
1090 case context::in_dict_after_brace:
Nigel Taod60815c2020-03-26 14:32:35 +11001091 g_ctx = context::in_dict_after_key;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001092 break;
1093 case context::in_dict_after_key:
Nigel Taod60815c2020-03-26 14:32:35 +11001094 g_ctx = context::in_dict_after_value;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001095 break;
1096 case context::in_dict_after_value:
Nigel Taod60815c2020-03-26 14:32:35 +11001097 g_ctx = context::in_dict_after_key;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001098 break;
Nigel Tao18ef5b42020-03-16 10:37:47 +11001099 default:
1100 break;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001101 }
1102 return nullptr;
1103}
1104
1105const char* //
1106main1(int argc, char** argv) {
1107 TRY(initialize_globals(argc, argv));
1108
Nigel Taocd183f92020-07-14 12:11:05 +10001109 bool start_of_token_chain = true;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001110 while (true) {
Nigel Tao0291a472020-08-13 22:40:10 +10001111 wuffs_base__status status = g_dec.decode_tokens(
Nigel Taod60815c2020-03-26 14:32:35 +11001112 &g_tok, &g_src,
1113 wuffs_base__make_slice_u8(g_work_buffer_array, WORK_BUFFER_ARRAY_SIZE));
Nigel Tao2cf76db2020-02-27 22:42:01 +11001114
Nigel Taod60815c2020-03-26 14:32:35 +11001115 while (g_tok.meta.ri < g_tok.meta.wi) {
1116 wuffs_base__token t = g_tok.data.ptr[g_tok.meta.ri++];
Nigel Tao2cf76db2020-02-27 22:42:01 +11001117 uint64_t n = t.length();
Nigel Taod60815c2020-03-26 14:32:35 +11001118 if ((g_src.meta.ri - g_curr_token_end_src_index) < n) {
1119 return "main: internal error: inconsistent g_src indexes";
Nigel Tao2cf76db2020-02-27 22:42:01 +11001120 }
Nigel Taod60815c2020-03-26 14:32:35 +11001121 g_curr_token_end_src_index += n;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001122
Nigel Taod0b16cb2020-03-14 10:15:54 +11001123 // Skip filler tokens (e.g. whitespace).
Nigel Tao3c8589b2020-07-19 21:49:00 +10001124 if (t.value_base_category() == WUFFS_BASE__TOKEN__VBC__FILLER) {
Nigel Tao496e88b2020-04-09 22:10:08 +10001125 start_of_token_chain = !t.continued();
Nigel Tao2cf76db2020-02-27 22:42:01 +11001126 continue;
1127 }
1128
Nigel Tao2ef39992020-04-09 17:24:39 +10001129 const char* z = handle_token(t, start_of_token_chain);
Nigel Tao496e88b2020-04-09 22:10:08 +10001130 start_of_token_chain = !t.continued();
Nigel Tao2cf76db2020-02-27 22:42:01 +11001131 if (z == nullptr) {
1132 continue;
Nigel Taod60815c2020-03-26 14:32:35 +11001133 } else if (z == g_eod) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001134 goto end_of_data;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001135 }
1136 return z;
Nigel Tao1b073492020-02-16 22:11:36 +11001137 }
Nigel Tao2cf76db2020-02-27 22:42:01 +11001138
1139 if (status.repr == nullptr) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001140 return "main: internal error: unexpected end of token stream";
Nigel Tao2cf76db2020-02-27 22:42:01 +11001141 } else if (status.repr == wuffs_base__suspension__short_read) {
Nigel Taod60815c2020-03-26 14:32:35 +11001142 if (g_curr_token_end_src_index != g_src.meta.ri) {
1143 return "main: internal error: inconsistent g_src indexes";
Nigel Tao2cf76db2020-02-27 22:42:01 +11001144 }
1145 TRY(read_src());
Nigel Taod60815c2020-03-26 14:32:35 +11001146 g_curr_token_end_src_index = g_src.meta.ri;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001147 } else if (status.repr == wuffs_base__suspension__short_write) {
Nigel Taod60815c2020-03-26 14:32:35 +11001148 g_tok.compact();
Nigel Tao2cf76db2020-02-27 22:42:01 +11001149 } else {
1150 return status.message();
Nigel Tao1b073492020-02-16 22:11:36 +11001151 }
1152 }
Nigel Tao0cd2f982020-03-03 23:03:02 +11001153end_of_data:
1154
Nigel Taod60815c2020-03-26 14:32:35 +11001155 // With a non-empty g_query, don't try to consume trailing whitespace or
Nigel Tao0cd2f982020-03-03 23:03:02 +11001156 // confirm that we've processed all the tokens.
Nigel Taod60815c2020-03-26 14:32:35 +11001157 if (g_flags.query_c_string && *g_flags.query_c_string) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001158 return nullptr;
1159 }
Nigel Tao6b161af2020-02-24 11:01:48 +11001160
Nigel Tao6b161af2020-02-24 11:01:48 +11001161 // Check that we've exhausted the input.
Nigel Taod60815c2020-03-26 14:32:35 +11001162 if ((g_src.meta.ri == g_src.meta.wi) && !g_src.meta.closed) {
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001163 TRY(read_src());
1164 }
Nigel Taod60815c2020-03-26 14:32:35 +11001165 if ((g_src.meta.ri < g_src.meta.wi) || !g_src.meta.closed) {
Nigel Tao0291a472020-08-13 22:40:10 +10001166 return "main: valid JSON followed by further (unexpected) data";
Nigel Tao6b161af2020-02-24 11:01:48 +11001167 }
1168
1169 // Check that we've used all of the decoded tokens, other than trailing
Nigel Tao4b186b02020-03-18 14:25:21 +11001170 // filler tokens. For example, "true\n" is valid JSON (and fully consumed
1171 // with WUFFS_JSON__QUIRK_ALLOW_TRAILING_NEW_LINE enabled) with a trailing
1172 // filler token for the "\n".
Nigel Taod60815c2020-03-26 14:32:35 +11001173 for (; g_tok.meta.ri < g_tok.meta.wi; g_tok.meta.ri++) {
1174 if (g_tok.data.ptr[g_tok.meta.ri].value_base_category() !=
Nigel Tao6b161af2020-02-24 11:01:48 +11001175 WUFFS_BASE__TOKEN__VBC__FILLER) {
1176 return "main: internal error: decoded OK but unprocessed tokens remain";
1177 }
1178 }
1179
1180 return nullptr;
Nigel Tao1b073492020-02-16 22:11:36 +11001181}
1182
Nigel Tao2914bae2020-02-26 09:40:30 +11001183int //
1184compute_exit_code(const char* status_msg) {
Nigel Tao9cc2c252020-02-23 17:05:49 +11001185 if (!status_msg) {
1186 return 0;
1187 }
Nigel Tao01abc842020-03-06 21:42:33 +11001188 size_t n;
Nigel Taod60815c2020-03-26 14:32:35 +11001189 if (status_msg == g_usage) {
Nigel Tao01abc842020-03-06 21:42:33 +11001190 n = strlen(status_msg);
1191 } else {
Nigel Tao9cc2c252020-02-23 17:05:49 +11001192 n = strnlen(status_msg, 2047);
Nigel Tao01abc842020-03-06 21:42:33 +11001193 if (n >= 2047) {
1194 status_msg = "main: internal error: error message is too long";
1195 n = strnlen(status_msg, 2047);
1196 }
Nigel Tao9cc2c252020-02-23 17:05:49 +11001197 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001198 const int stderr_fd = 2;
1199 ignore_return_value(write(stderr_fd, status_msg, n));
1200 ignore_return_value(write(stderr_fd, "\n", 1));
Nigel Tao9cc2c252020-02-23 17:05:49 +11001201 // Return an exit code of 1 for regular (forseen) errors, e.g. badly
1202 // formatted or unsupported input.
1203 //
1204 // Return an exit code of 2 for internal (exceptional) errors, e.g. defensive
1205 // run-time checks found that an internal invariant did not hold.
1206 //
1207 // Automated testing, including badly formatted inputs, can therefore
1208 // discriminate between expected failure (exit code 1) and unexpected failure
1209 // (other non-zero exit codes). Specifically, exit code 2 for internal
1210 // invariant violation, exit code 139 (which is 128 + SIGSEGV on x86_64
1211 // linux) for a segmentation fault (e.g. null pointer dereference).
1212 return strstr(status_msg, "internal error:") ? 2 : 1;
1213}
1214
Nigel Tao2914bae2020-02-26 09:40:30 +11001215int //
1216main(int argc, char** argv) {
Nigel Tao01abc842020-03-06 21:42:33 +11001217 // Look for an input filename (the first non-flag argument) in argv. If there
1218 // is one, open it (but do not read from it) before we self-impose a sandbox.
1219 //
1220 // Flags start with "-", unless it comes after a bare "--" arg.
1221 {
1222 bool dash_dash = false;
1223 int a;
1224 for (a = 1; a < argc; a++) {
1225 char* arg = argv[a];
1226 if ((arg[0] == '-') && !dash_dash) {
1227 dash_dash = (arg[1] == '-') && (arg[2] == '\x00');
1228 continue;
1229 }
Nigel Taod60815c2020-03-26 14:32:35 +11001230 g_input_file_descriptor = open(arg, O_RDONLY);
1231 if (g_input_file_descriptor < 0) {
Nigel Tao01abc842020-03-06 21:42:33 +11001232 fprintf(stderr, "%s: %s\n", arg, strerror(errno));
1233 return 1;
1234 }
1235 break;
1236 }
1237 }
1238
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001239#if defined(WUFFS_EXAMPLE_USE_SECCOMP)
1240 prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT);
Nigel Taod60815c2020-03-26 14:32:35 +11001241 g_sandboxed = true;
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001242#endif
1243
Nigel Tao0cd2f982020-03-03 23:03:02 +11001244 const char* z = main1(argc, argv);
Nigel Taod60815c2020-03-26 14:32:35 +11001245 if (g_wrote_to_dst) {
Nigel Tao0291a472020-08-13 22:40:10 +10001246 const char* z1 = write_dst("\n", 1);
Nigel Tao0cd2f982020-03-03 23:03:02 +11001247 const char* z2 = flush_dst();
1248 z = z ? z : (z1 ? z1 : z2);
1249 }
1250 int exit_code = compute_exit_code(z);
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001251
1252#if defined(WUFFS_EXAMPLE_USE_SECCOMP)
1253 // Call SYS_exit explicitly, instead of calling SYS_exit_group implicitly by
1254 // either calling _exit or returning from main. SECCOMP_MODE_STRICT allows
1255 // only SYS_exit.
1256 syscall(SYS_exit, exit_code);
1257#endif
Nigel Tao9cc2c252020-02-23 17:05:49 +11001258 return exit_code;
Nigel Tao1b073492020-02-16 22:11:36 +11001259}