4 * Copyright IBM, Corp. 2009
7 * Anthony Liguori <aliguori@us.ibm.com>
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 "json-parser-int.h"
34 typedef struct JSONParserContext
42 #define BUG_ON(cond) assert(!(cond))
47 * 0) make errors meaningful again
48 * 1) add geometry information to tokens
49 * 3) should we return a parsed size?
50 * 4) deal with premature EOI
53 static QObject
*parse_value(JSONParserContext
*ctxt
);
58 static void GCC_FMT_ATTR(3, 4) parse_error(JSONParserContext
*ctxt
,
59 JSONToken
*token
, const char *msg
, ...)
68 vsnprintf(message
, sizeof(message
), msg
, ap
);
70 error_setg(&ctxt
->err
, "JSON parse error, %s", message
);
73 static int cvt4hex(const char *s
)
78 for (i
= 0; i
< 4; i
++) {
79 if (!qemu_isxdigit(s
[i
])) {
83 if (s
[i
] >= '0' && s
[i
] <= '9') {
85 } else if (s
[i
] >= 'a' && s
[i
] <= 'f') {
86 cp
|= 10 + s
[i
] - 'a';
87 } else if (s
[i
] >= 'A' && s
[i
] <= 'F') {
88 cp
|= 10 + s
[i
] - 'A';
97 * parse_string(): Parse a JSON string
99 * From RFC 8259 "The JavaScript Object Notation (JSON) Data
100 * Interchange Format":
104 * %x22 / ; " quotation mark U+0022
105 * %x5C / ; \ reverse solidus U+005C
106 * %x2F / ; / solidus U+002F
107 * %x62 / ; b backspace U+0008
108 * %x66 / ; f form feed U+000C
109 * %x6E / ; n line feed U+000A
110 * %x72 / ; r carriage return U+000D
111 * %x74 / ; t tab U+0009
112 * %x75 4HEXDIG ) ; uXXXX U+XXXX
114 * quotation-mark = %x22 ; "
115 * unescaped = %x20-21 / %x23-5B / %x5D-10FFFF
117 * Extensions over RFC 8259:
118 * - Extra escape sequence in strings:
119 * 0x27 (apostrophe) is recognized after escape, too
120 * - Single-quoted strings:
121 * Like double-quoted strings, except they're delimited by %x27
122 * (apostrophe) instead of %x22 (quotation mark), and can't contain
123 * unescaped apostrophe, but can contain unescaped quotation mark.
126 * - Encoding is modified UTF-8.
127 * - Invalid Unicode characters are rejected.
128 * - Control characters \x00..\x1F are rejected by the lexer.
130 static QString
*parse_string(JSONParserContext
*ctxt
, JSONToken
*token
)
132 const char *ptr
= token
->str
;
141 assert(*ptr
== '"' || *ptr
== '\'');
145 while (*ptr
!= quote
) {
152 qstring_append_chr(str
, '"');
155 qstring_append_chr(str
, '\'');
158 qstring_append_chr(str
, '\\');
161 qstring_append_chr(str
, '/');
164 qstring_append_chr(str
, '\b');
167 qstring_append_chr(str
, '\f');
170 qstring_append_chr(str
, '\n');
173 qstring_append_chr(str
, '\r');
176 qstring_append_chr(str
, '\t');
182 /* handle surrogate pairs */
183 if (cp
>= 0xD800 && cp
<= 0xDBFF
184 && ptr
[0] == '\\' && ptr
[1] == 'u') {
185 /* leading surrogate followed by \u */
186 cp
= 0x10000 + ((cp
& 0x3FF) << 10);
187 trailing
= cvt4hex(ptr
+ 2);
188 if (trailing
>= 0xDC00 && trailing
<= 0xDFFF) {
189 /* followed by trailing surrogate */
190 cp
|= trailing
& 0x3FF;
193 cp
= -1; /* invalid */
197 if (mod_utf8_encode(utf8_buf
, sizeof(utf8_buf
), cp
) < 0) {
198 parse_error(ctxt
, token
,
199 "%.*s is not a valid Unicode character",
200 (int)(ptr
- beg
), beg
);
203 qstring_append(str
, utf8_buf
);
206 parse_error(ctxt
, token
, "invalid escape sequence in string");
211 if (ctxt
->ap
&& ptr
[1] != '%') {
212 parse_error(ctxt
, token
, "can't interpolate into string");
218 cp
= mod_utf8_codepoint(ptr
, 6, &end
);
220 parse_error(ctxt
, token
, "invalid UTF-8 sequence in string");
224 len
= mod_utf8_encode(utf8_buf
, sizeof(utf8_buf
), cp
);
226 qstring_append(str
, utf8_buf
);
237 /* Note: the token object returned by parser_context_peek_token or
238 * parser_context_pop_token is deleted as soon as parser_context_pop_token
241 static JSONToken
*parser_context_pop_token(JSONParserContext
*ctxt
)
243 g_free(ctxt
->current
);
244 ctxt
->current
= g_queue_pop_head(ctxt
->buf
);
245 return ctxt
->current
;
248 static JSONToken
*parser_context_peek_token(JSONParserContext
*ctxt
)
250 return g_queue_peek_head(ctxt
->buf
);
256 static int parse_pair(JSONParserContext
*ctxt
, QDict
*dict
)
260 JSONToken
*peek
, *token
;
262 peek
= parser_context_peek_token(ctxt
);
264 parse_error(ctxt
, NULL
, "premature EOI");
268 key
= qobject_to(QString
, parse_value(ctxt
));
270 parse_error(ctxt
, peek
, "key is not a string in object");
274 token
= parser_context_pop_token(ctxt
);
276 parse_error(ctxt
, NULL
, "premature EOI");
280 if (token
->type
!= JSON_COLON
) {
281 parse_error(ctxt
, token
, "missing : in object pair");
285 value
= parse_value(ctxt
);
287 parse_error(ctxt
, token
, "Missing value in dict");
291 if (qdict_haskey(dict
, qstring_get_str(key
))) {
292 parse_error(ctxt
, token
, "duplicate key");
296 qdict_put_obj(dict
, qstring_get_str(key
), value
);
308 static QObject
*parse_object(JSONParserContext
*ctxt
)
311 JSONToken
*token
, *peek
;
313 token
= parser_context_pop_token(ctxt
);
314 assert(token
&& token
->type
== JSON_LCURLY
);
318 peek
= parser_context_peek_token(ctxt
);
320 parse_error(ctxt
, NULL
, "premature EOI");
324 if (peek
->type
!= JSON_RCURLY
) {
325 if (parse_pair(ctxt
, dict
) == -1) {
329 token
= parser_context_pop_token(ctxt
);
331 parse_error(ctxt
, NULL
, "premature EOI");
335 while (token
->type
!= JSON_RCURLY
) {
336 if (token
->type
!= JSON_COMMA
) {
337 parse_error(ctxt
, token
, "expected separator in dict");
341 if (parse_pair(ctxt
, dict
) == -1) {
345 token
= parser_context_pop_token(ctxt
);
347 parse_error(ctxt
, NULL
, "premature EOI");
352 (void)parser_context_pop_token(ctxt
);
355 return QOBJECT(dict
);
362 static QObject
*parse_array(JSONParserContext
*ctxt
)
365 JSONToken
*token
, *peek
;
367 token
= parser_context_pop_token(ctxt
);
368 assert(token
&& token
->type
== JSON_LSQUARE
);
372 peek
= parser_context_peek_token(ctxt
);
374 parse_error(ctxt
, NULL
, "premature EOI");
378 if (peek
->type
!= JSON_RSQUARE
) {
381 obj
= parse_value(ctxt
);
383 parse_error(ctxt
, token
, "expecting value");
387 qlist_append_obj(list
, obj
);
389 token
= parser_context_pop_token(ctxt
);
391 parse_error(ctxt
, NULL
, "premature EOI");
395 while (token
->type
!= JSON_RSQUARE
) {
396 if (token
->type
!= JSON_COMMA
) {
397 parse_error(ctxt
, token
, "expected separator in list");
401 obj
= parse_value(ctxt
);
403 parse_error(ctxt
, token
, "expecting value");
407 qlist_append_obj(list
, obj
);
409 token
= parser_context_pop_token(ctxt
);
411 parse_error(ctxt
, NULL
, "premature EOI");
416 (void)parser_context_pop_token(ctxt
);
419 return QOBJECT(list
);
426 static QObject
*parse_keyword(JSONParserContext
*ctxt
)
430 token
= parser_context_pop_token(ctxt
);
431 assert(token
&& token
->type
== JSON_KEYWORD
);
433 if (!strcmp(token
->str
, "true")) {
434 return QOBJECT(qbool_from_bool(true));
435 } else if (!strcmp(token
->str
, "false")) {
436 return QOBJECT(qbool_from_bool(false));
437 } else if (!strcmp(token
->str
, "null")) {
438 return QOBJECT(qnull());
440 parse_error(ctxt
, token
, "invalid keyword '%s'", token
->str
);
444 static QObject
*parse_interpolation(JSONParserContext
*ctxt
)
448 token
= parser_context_pop_token(ctxt
);
449 assert(token
&& token
->type
== JSON_INTERP
);
451 if (!strcmp(token
->str
, "%p")) {
452 return va_arg(*ctxt
->ap
, QObject
*);
453 } else if (!strcmp(token
->str
, "%i")) {
454 return QOBJECT(qbool_from_bool(va_arg(*ctxt
->ap
, int)));
455 } else if (!strcmp(token
->str
, "%d")) {
456 return QOBJECT(qnum_from_int(va_arg(*ctxt
->ap
, int)));
457 } else if (!strcmp(token
->str
, "%ld")) {
458 return QOBJECT(qnum_from_int(va_arg(*ctxt
->ap
, long)));
459 } else if (!strcmp(token
->str
, "%lld")) {
460 return QOBJECT(qnum_from_int(va_arg(*ctxt
->ap
, long long)));
461 } else if (!strcmp(token
->str
, "%" PRId64
)) {
462 return QOBJECT(qnum_from_int(va_arg(*ctxt
->ap
, int64_t)));
463 } else if (!strcmp(token
->str
, "%u")) {
464 return QOBJECT(qnum_from_uint(va_arg(*ctxt
->ap
, unsigned int)));
465 } else if (!strcmp(token
->str
, "%lu")) {
466 return QOBJECT(qnum_from_uint(va_arg(*ctxt
->ap
, unsigned long)));
467 } else if (!strcmp(token
->str
, "%llu")) {
468 return QOBJECT(qnum_from_uint(va_arg(*ctxt
->ap
, unsigned long long)));
469 } else if (!strcmp(token
->str
, "%" PRIu64
)) {
470 return QOBJECT(qnum_from_uint(va_arg(*ctxt
->ap
, uint64_t)));
471 } else if (!strcmp(token
->str
, "%s")) {
472 return QOBJECT(qstring_from_str(va_arg(*ctxt
->ap
, const char *)));
473 } else if (!strcmp(token
->str
, "%f")) {
474 return QOBJECT(qnum_from_double(va_arg(*ctxt
->ap
, double)));
476 parse_error(ctxt
, token
, "invalid interpolation '%s'", token
->str
);
480 static QObject
*parse_literal(JSONParserContext
*ctxt
)
484 token
= parser_context_pop_token(ctxt
);
487 switch (token
->type
) {
489 return QOBJECT(parse_string(ctxt
, token
));
492 * Represent JSON_INTEGER as QNUM_I64 if possible, else as
493 * QNUM_U64, else as QNUM_DOUBLE. Note that qemu_strtoi64()
494 * and qemu_strtou64() fail with ERANGE when it's not
497 * qnum_get_int() will then work for any signed 64-bit
498 * JSON_INTEGER, qnum_get_uint() for any unsigned 64-bit
499 * integer, and qnum_get_double() both for any JSON_INTEGER
500 * and any JSON_FLOAT (with precision loss for integers beyond
507 ret
= qemu_strtoi64(token
->str
, NULL
, 10, &value
);
509 return QOBJECT(qnum_from_int(value
));
511 assert(ret
== -ERANGE
);
513 if (token
->str
[0] != '-') {
514 ret
= qemu_strtou64(token
->str
, NULL
, 10, &uvalue
);
516 return QOBJECT(qnum_from_uint(uvalue
));
518 assert(ret
== -ERANGE
);
520 /* fall through to JSON_FLOAT */
523 /* FIXME dependent on locale; a pervasive issue in QEMU */
524 /* FIXME our lexer matches RFC 8259 in forbidding Inf or NaN,
525 * but those might be useful extensions beyond JSON */
526 return QOBJECT(qnum_from_double(strtod(token
->str
, NULL
)));
532 static QObject
*parse_value(JSONParserContext
*ctxt
)
536 token
= parser_context_peek_token(ctxt
);
538 parse_error(ctxt
, NULL
, "premature EOI");
542 switch (token
->type
) {
544 return parse_object(ctxt
);
546 return parse_array(ctxt
);
548 return parse_interpolation(ctxt
);
552 return parse_literal(ctxt
);
554 return parse_keyword(ctxt
);
556 parse_error(ctxt
, token
, "expecting value");
561 JSONToken
*json_token(JSONTokenType type
, int x
, int y
, GString
*tokstr
)
563 JSONToken
*token
= g_malloc(sizeof(JSONToken
) + tokstr
->len
+ 1);
566 memcpy(token
->str
, tokstr
->str
, tokstr
->len
);
567 token
->str
[tokstr
->len
] = 0;
573 QObject
*json_parser_parse(GQueue
*tokens
, va_list *ap
, Error
**errp
)
575 JSONParserContext ctxt
= { .buf
= tokens
, .ap
= ap
};
578 result
= parse_value(&ctxt
);
579 assert(ctxt
.err
|| g_queue_is_empty(ctxt
.buf
));
581 error_propagate(errp
, ctxt
.err
);
583 while (!g_queue_is_empty(ctxt
.buf
)) {
584 parser_context_pop_token(&ctxt
);
586 g_free(ctxt
.current
);