4 * Copyright IBM, Corp. 2009
9 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
10 * See the COPYING.LIB file in the top-level directory.
14 #include "qemu/osdep.h"
15 #include "qemu/cutils.h"
16 #include "qemu/unicode.h"
17 #include "qapi/error.h"
18 #include "qemu-common.h"
19 #include "qapi/qmp/qbool.h"
20 #include "qapi/qmp/qdict.h"
21 #include "qapi/qmp/qlist.h"
22 #include "qapi/qmp/qnull.h"
23 #include "qapi/qmp/qnum.h"
24 #include "qapi/qmp/qstring.h"
25 #include "qapi/qmp/json-parser.h"
26 #include "qapi/qmp/json-lexer.h"
27 #include "qapi/qmp/json-streamer.h"
29 typedef struct JSONParserContext
36 #define BUG_ON(cond) assert(!(cond))
41 * 0) make errors meaningful again
42 * 1) add geometry information to tokens
43 * 3) should we return a parsed size?
44 * 4) deal with premature EOI
47 static QObject *parse_value(JSONParserContext *ctxt, va_list *ap);
52 static void GCC_FMT_ATTR(3, 4) parse_error(JSONParserContext *ctxt,
53 JSONToken *token, const char *msg, ...)
62 vsnprintf(message, sizeof(message), msg, ap);
64 error_setg(&ctxt->err, "JSON parse error, %s", message);
67 static int cvt4hex(const char *s)
72 for (i = 0; i < 4; i++) {
73 if (!qemu_isxdigit(s[i])) {
77 if (s[i] >= '0' && s[i] <= '9') {
79 } else if (s[i] >= 'a' && s[i] <= 'f') {
80 cp |= 10 + s[i] - 'a';
81 } else if (s[i] >= 'A' && s[i] <= 'F') {
82 cp |= 10 + s[i] - 'A';
91 * parse_string(): Parse a JSON string
93 * From RFC 8259 "The JavaScript Object Notation (JSON) Data
94 * Interchange Format":
98 * %x22 / ; " quotation mark U+0022
99 * %x5C / ; \ reverse solidus U+005C
100 * %x2F / ; / solidus U+002F
101 * %x62 / ; b backspace U+0008
102 * %x66 / ; f form feed U+000C
103 * %x6E / ; n line feed U+000A
104 * %x72 / ; r carriage return U+000D
105 * %x74 / ; t tab U+0009
106 * %x75 4HEXDIG ) ; uXXXX U+XXXX
108 * quotation-mark = %x22 ; "
109 * unescaped = %x20-21 / %x23-5B / %x5D-10FFFF
111 * Extensions over RFC 8259:
112 * - Extra escape sequence in strings:
113 * 0x27 (apostrophe) is recognized after escape, too
114 * - Single-quoted strings:
115 * Like double-quoted strings, except they're delimited by %x27
116 * (apostrophe) instead of %x22 (quotation mark), and can't contain
117 * unescaped apostrophe, but can contain unescaped quotation mark.
120 * - Encoding is modified UTF-8.
121 * - Invalid Unicode characters are rejected.
122 * - Control characters \x00..\x1F are rejected by the lexer.
124 static QString *parse_string(JSONParserContext *ctxt, JSONToken *token)
126 const char *ptr = token->str;
135 assert(*ptr == '"' || *ptr == '\'');
139 while (*ptr != quote) {
145 qstring_append_chr(str, '"');
148 qstring_append_chr(str, '\'');
151 qstring_append_chr(str, '\\');
154 qstring_append_chr(str, '/');
157 qstring_append_chr(str, '\b');
160 qstring_append_chr(str, '\f');
163 qstring_append_chr(str, '\n');
166 qstring_append_chr(str, '\r');
169 qstring_append_chr(str, '\t');
175 /* handle surrogate pairs */
176 if (cp >= 0xD800 && cp <= 0xDBFF
177 && ptr[0] == '\\' && ptr[1] == 'u') {
178 /* leading surrogate followed by \u */
179 cp = 0x10000 + ((cp & 0x3FF) << 10);
180 trailing = cvt4hex(ptr + 2);
181 if (trailing >= 0xDC00 && trailing <= 0xDFFF) {
182 /* followed by trailing surrogate */
183 cp |= trailing & 0x3FF;
186 cp = -1; /* invalid */
190 if (mod_utf8_encode(utf8_buf, sizeof(utf8_buf), cp) < 0) {
191 parse_error(ctxt, token,
192 "%.*s is not a valid Unicode character",
193 (int)(ptr - beg), beg);
196 qstring_append(str, utf8_buf);
199 parse_error(ctxt, token, "invalid escape sequence in string");
203 cp = mod_utf8_codepoint(ptr, 6, &end);
205 parse_error(ctxt, token, "invalid UTF-8 sequence in string");
209 len = mod_utf8_encode(utf8_buf, sizeof(utf8_buf), cp);
211 qstring_append(str, utf8_buf);
222 /* Note: the token object returned by parser_context_peek_token or
223 * parser_context_pop_token is deleted as soon as parser_context_pop_token
226 static JSONToken *parser_context_pop_token(JSONParserContext *ctxt)
228 g_free(ctxt->current);
229 assert(!g_queue_is_empty(ctxt->buf));
230 ctxt->current = g_queue_pop_head(ctxt->buf);
231 return ctxt->current;
234 static JSONToken *parser_context_peek_token(JSONParserContext *ctxt)
236 assert(!g_queue_is_empty(ctxt->buf));
237 return g_queue_peek_head(ctxt->buf);
243 static int parse_pair(JSONParserContext *ctxt, QDict *dict, va_list *ap)
247 JSONToken *peek, *token;
249 peek = parser_context_peek_token(ctxt);
251 parse_error(ctxt, NULL, "premature EOI");
255 key = qobject_to(QString, parse_value(ctxt, ap));
257 parse_error(ctxt, peek, "key is not a string in object");
261 token = parser_context_pop_token(ctxt);
263 parse_error(ctxt, NULL, "premature EOI");
267 if (token->type != JSON_COLON) {
268 parse_error(ctxt, token, "missing : in object pair");
272 value = parse_value(ctxt, ap);
274 parse_error(ctxt, token, "Missing value in dict");
278 qdict_put_obj(dict, qstring_get_str(key), value);
290 static QObject *parse_object(JSONParserContext *ctxt, va_list *ap)
293 JSONToken *token, *peek;
295 token = parser_context_pop_token(ctxt);
296 assert(token && token->type == JSON_LCURLY);
300 peek = parser_context_peek_token(ctxt);
302 parse_error(ctxt, NULL, "premature EOI");
306 if (peek->type != JSON_RCURLY) {
307 if (parse_pair(ctxt, dict, ap) == -1) {
311 token = parser_context_pop_token(ctxt);
313 parse_error(ctxt, NULL, "premature EOI");
317 while (token->type != JSON_RCURLY) {
318 if (token->type != JSON_COMMA) {
319 parse_error(ctxt, token, "expected separator in dict");
323 if (parse_pair(ctxt, dict, ap) == -1) {
327 token = parser_context_pop_token(ctxt);
329 parse_error(ctxt, NULL, "premature EOI");
334 (void)parser_context_pop_token(ctxt);
337 return QOBJECT(dict);
344 static QObject *parse_array(JSONParserContext *ctxt, va_list *ap)
347 JSONToken *token, *peek;
349 token = parser_context_pop_token(ctxt);
350 assert(token && token->type == JSON_LSQUARE);
354 peek = parser_context_peek_token(ctxt);
356 parse_error(ctxt, NULL, "premature EOI");
360 if (peek->type != JSON_RSQUARE) {
363 obj = parse_value(ctxt, ap);
365 parse_error(ctxt, token, "expecting value");
369 qlist_append_obj(list, obj);
371 token = parser_context_pop_token(ctxt);
373 parse_error(ctxt, NULL, "premature EOI");
377 while (token->type != JSON_RSQUARE) {
378 if (token->type != JSON_COMMA) {
379 parse_error(ctxt, token, "expected separator in list");
383 obj = parse_value(ctxt, ap);
385 parse_error(ctxt, token, "expecting value");
389 qlist_append_obj(list, obj);
391 token = parser_context_pop_token(ctxt);
393 parse_error(ctxt, NULL, "premature EOI");
398 (void)parser_context_pop_token(ctxt);
401 return QOBJECT(list);
408 static QObject *parse_keyword(JSONParserContext *ctxt)
412 token = parser_context_pop_token(ctxt);
413 assert(token && token->type == JSON_KEYWORD);
415 if (!strcmp(token->str, "true")) {
416 return QOBJECT(qbool_from_bool(true));
417 } else if (!strcmp(token->str, "false")) {
418 return QOBJECT(qbool_from_bool(false));
419 } else if (!strcmp(token->str, "null")) {
420 return QOBJECT(qnull());
422 parse_error(ctxt, token, "invalid keyword '%s'", token->str);
426 static QObject *parse_escape(JSONParserContext *ctxt, va_list *ap)
434 token = parser_context_pop_token(ctxt);
435 assert(token && token->type == JSON_ESCAPE);
437 if (!strcmp(token->str, "%p")) {
438 return va_arg(*ap, QObject *);
439 } else if (!strcmp(token->str, "%i")) {
440 return QOBJECT(qbool_from_bool(va_arg(*ap, int)));
441 } else if (!strcmp(token->str, "%d")) {
442 return QOBJECT(qnum_from_int(va_arg(*ap, int)));
443 } else if (!strcmp(token->str, "%ld")) {
444 return QOBJECT(qnum_from_int(va_arg(*ap, long)));
445 } else if (!strcmp(token->str, "%lld") ||
446 !strcmp(token->str, "%I64d")) {
447 return QOBJECT(qnum_from_int(va_arg(*ap, long long)));
448 } else if (!strcmp(token->str, "%u")) {
449 return QOBJECT(qnum_from_uint(va_arg(*ap, unsigned int)));
450 } else if (!strcmp(token->str, "%lu")) {
451 return QOBJECT(qnum_from_uint(va_arg(*ap, unsigned long)));
452 } else if (!strcmp(token->str, "%llu") ||
453 !strcmp(token->str, "%I64u")) {
454 return QOBJECT(qnum_from_uint(va_arg(*ap, unsigned long long)));
455 } else if (!strcmp(token->str, "%s")) {
456 return QOBJECT(qstring_from_str(va_arg(*ap, const char *)));
457 } else if (!strcmp(token->str, "%f")) {
458 return QOBJECT(qnum_from_double(va_arg(*ap, double)));
463 static QObject *parse_literal(JSONParserContext *ctxt)
467 token = parser_context_pop_token(ctxt);
470 switch (token->type) {
472 return QOBJECT(parse_string(ctxt, token));
475 * Represent JSON_INTEGER as QNUM_I64 if possible, else as
476 * QNUM_U64, else as QNUM_DOUBLE. Note that qemu_strtoi64()
477 * and qemu_strtou64() fail with ERANGE when it's not
480 * qnum_get_int() will then work for any signed 64-bit
481 * JSON_INTEGER, qnum_get_uint() for any unsigned 64-bit
482 * integer, and qnum_get_double() both for any JSON_INTEGER
483 * and any JSON_FLOAT (with precision loss for integers beyond
490 ret = qemu_strtoi64(token->str, NULL, 10, &value);
492 return QOBJECT(qnum_from_int(value));
494 assert(ret == -ERANGE);
496 if (token->str[0] != '-') {
497 ret = qemu_strtou64(token->str, NULL, 10, &uvalue);
499 return QOBJECT(qnum_from_uint(uvalue));
501 assert(ret == -ERANGE);
503 /* fall through to JSON_FLOAT */
506 /* FIXME dependent on locale; a pervasive issue in QEMU */
507 /* FIXME our lexer matches RFC 7159 in forbidding Inf or NaN,
508 * but those might be useful extensions beyond JSON */
509 return QOBJECT(qnum_from_double(strtod(token->str, NULL)));
515 static QObject *parse_value(JSONParserContext *ctxt, va_list *ap)
519 token = parser_context_peek_token(ctxt);
521 parse_error(ctxt, NULL, "premature EOI");
525 switch (token->type) {
527 return parse_object(ctxt, ap);
529 return parse_array(ctxt, ap);
531 return parse_escape(ctxt, ap);
535 return parse_literal(ctxt);
537 return parse_keyword(ctxt);
539 parse_error(ctxt, token, "expecting value");
544 QObject *json_parser_parse(GQueue *tokens, va_list *ap, Error **errp)
546 JSONParserContext ctxt = { .buf = tokens };
553 result = parse_value(&ctxt, ap);
555 error_propagate(errp, ctxt.err);
557 while (!g_queue_is_empty(ctxt.buf)) {
558 parser_context_pop_token(&ctxt);
560 g_free(ctxt.current);
561 g_queue_free(ctxt.buf);