json-parser.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. /*
  2. * JSON Parser
  3. *
  4. * Copyright IBM, Corp. 2009
  5. *
  6. * Authors:
  7. * Anthony Liguori <aliguori@us.ibm.com>
  8. *
  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.
  11. *
  12. */
  13. #include <stdarg.h>
  14. #include "qemu-common.h"
  15. #include "qapi/qmp/qstring.h"
  16. #include "qapi/qmp/qint.h"
  17. #include "qapi/qmp/qdict.h"
  18. #include "qapi/qmp/qlist.h"
  19. #include "qapi/qmp/qfloat.h"
  20. #include "qapi/qmp/qbool.h"
  21. #include "qapi/qmp/json-parser.h"
  22. #include "qapi/qmp/json-lexer.h"
  23. typedef struct JSONParserContext
  24. {
  25. Error *err;
  26. struct {
  27. QObject **buf;
  28. size_t pos;
  29. size_t count;
  30. } tokens;
  31. } JSONParserContext;
  32. #define BUG_ON(cond) assert(!(cond))
  33. /**
  34. * TODO
  35. *
  36. * 0) make errors meaningful again
  37. * 1) add geometry information to tokens
  38. * 3) should we return a parsed size?
  39. * 4) deal with premature EOI
  40. */
  41. static QObject *parse_value(JSONParserContext *ctxt, va_list *ap);
  42. /**
  43. * Token manipulators
  44. *
  45. * tokens are dictionaries that contain a type, a string value, and geometry information
  46. * about a token identified by the lexer. These are routines that make working with
  47. * these objects a bit easier.
  48. */
  49. static const char *token_get_value(QObject *obj)
  50. {
  51. return qdict_get_str(qobject_to_qdict(obj), "token");
  52. }
  53. static JSONTokenType token_get_type(QObject *obj)
  54. {
  55. return qdict_get_int(qobject_to_qdict(obj), "type");
  56. }
  57. static int token_is_operator(QObject *obj, char op)
  58. {
  59. const char *val;
  60. if (token_get_type(obj) != JSON_OPERATOR) {
  61. return 0;
  62. }
  63. val = token_get_value(obj);
  64. return (val[0] == op) && (val[1] == 0);
  65. }
  66. static int token_is_keyword(QObject *obj, const char *value)
  67. {
  68. if (token_get_type(obj) != JSON_KEYWORD) {
  69. return 0;
  70. }
  71. return strcmp(token_get_value(obj), value) == 0;
  72. }
  73. static int token_is_escape(QObject *obj, const char *value)
  74. {
  75. if (token_get_type(obj) != JSON_ESCAPE) {
  76. return 0;
  77. }
  78. return (strcmp(token_get_value(obj), value) == 0);
  79. }
  80. /**
  81. * Error handler
  82. */
  83. static void GCC_FMT_ATTR(3, 4) parse_error(JSONParserContext *ctxt,
  84. QObject *token, const char *msg, ...)
  85. {
  86. va_list ap;
  87. char message[1024];
  88. va_start(ap, msg);
  89. vsnprintf(message, sizeof(message), msg, ap);
  90. va_end(ap);
  91. if (ctxt->err) {
  92. error_free(ctxt->err);
  93. ctxt->err = NULL;
  94. }
  95. error_setg(&ctxt->err, "JSON parse error, %s", message);
  96. }
  97. /**
  98. * String helpers
  99. *
  100. * These helpers are used to unescape strings.
  101. */
  102. static void wchar_to_utf8(uint16_t wchar, char *buffer, size_t buffer_length)
  103. {
  104. if (wchar <= 0x007F) {
  105. BUG_ON(buffer_length < 2);
  106. buffer[0] = wchar & 0x7F;
  107. buffer[1] = 0;
  108. } else if (wchar <= 0x07FF) {
  109. BUG_ON(buffer_length < 3);
  110. buffer[0] = 0xC0 | ((wchar >> 6) & 0x1F);
  111. buffer[1] = 0x80 | (wchar & 0x3F);
  112. buffer[2] = 0;
  113. } else {
  114. BUG_ON(buffer_length < 4);
  115. buffer[0] = 0xE0 | ((wchar >> 12) & 0x0F);
  116. buffer[1] = 0x80 | ((wchar >> 6) & 0x3F);
  117. buffer[2] = 0x80 | (wchar & 0x3F);
  118. buffer[3] = 0;
  119. }
  120. }
  121. static int hex2decimal(char ch)
  122. {
  123. if (ch >= '0' && ch <= '9') {
  124. return (ch - '0');
  125. } else if (ch >= 'a' && ch <= 'f') {
  126. return 10 + (ch - 'a');
  127. } else if (ch >= 'A' && ch <= 'F') {
  128. return 10 + (ch - 'A');
  129. }
  130. return -1;
  131. }
  132. /**
  133. * parse_string(): Parse a json string and return a QObject
  134. *
  135. * string
  136. * ""
  137. * " chars "
  138. * chars
  139. * char
  140. * char chars
  141. * char
  142. * any-Unicode-character-
  143. * except-"-or-\-or-
  144. * control-character
  145. * \"
  146. * \\
  147. * \/
  148. * \b
  149. * \f
  150. * \n
  151. * \r
  152. * \t
  153. * \u four-hex-digits
  154. */
  155. static QString *qstring_from_escaped_str(JSONParserContext *ctxt, QObject *token)
  156. {
  157. const char *ptr = token_get_value(token);
  158. QString *str;
  159. int double_quote = 1;
  160. if (*ptr == '"') {
  161. double_quote = 1;
  162. } else {
  163. double_quote = 0;
  164. }
  165. ptr++;
  166. str = qstring_new();
  167. while (*ptr &&
  168. ((double_quote && *ptr != '"') || (!double_quote && *ptr != '\''))) {
  169. if (*ptr == '\\') {
  170. ptr++;
  171. switch (*ptr) {
  172. case '"':
  173. qstring_append(str, "\"");
  174. ptr++;
  175. break;
  176. case '\'':
  177. qstring_append(str, "'");
  178. ptr++;
  179. break;
  180. case '\\':
  181. qstring_append(str, "\\");
  182. ptr++;
  183. break;
  184. case '/':
  185. qstring_append(str, "/");
  186. ptr++;
  187. break;
  188. case 'b':
  189. qstring_append(str, "\b");
  190. ptr++;
  191. break;
  192. case 'f':
  193. qstring_append(str, "\f");
  194. ptr++;
  195. break;
  196. case 'n':
  197. qstring_append(str, "\n");
  198. ptr++;
  199. break;
  200. case 'r':
  201. qstring_append(str, "\r");
  202. ptr++;
  203. break;
  204. case 't':
  205. qstring_append(str, "\t");
  206. ptr++;
  207. break;
  208. case 'u': {
  209. uint16_t unicode_char = 0;
  210. char utf8_char[4];
  211. int i = 0;
  212. ptr++;
  213. for (i = 0; i < 4; i++) {
  214. if (qemu_isxdigit(*ptr)) {
  215. unicode_char |= hex2decimal(*ptr) << ((3 - i) * 4);
  216. } else {
  217. parse_error(ctxt, token,
  218. "invalid hex escape sequence in string");
  219. goto out;
  220. }
  221. ptr++;
  222. }
  223. wchar_to_utf8(unicode_char, utf8_char, sizeof(utf8_char));
  224. qstring_append(str, utf8_char);
  225. } break;
  226. default:
  227. parse_error(ctxt, token, "invalid escape sequence in string");
  228. goto out;
  229. }
  230. } else {
  231. char dummy[2];
  232. dummy[0] = *ptr++;
  233. dummy[1] = 0;
  234. qstring_append(str, dummy);
  235. }
  236. }
  237. return str;
  238. out:
  239. QDECREF(str);
  240. return NULL;
  241. }
  242. static QObject *parser_context_pop_token(JSONParserContext *ctxt)
  243. {
  244. QObject *token;
  245. g_assert(ctxt->tokens.pos < ctxt->tokens.count);
  246. token = ctxt->tokens.buf[ctxt->tokens.pos];
  247. ctxt->tokens.pos++;
  248. return token;
  249. }
  250. /* Note: parser_context_{peek|pop}_token do not increment the
  251. * token object's refcount. In both cases the references will continue
  252. * to be tracked and cleaned up in parser_context_free(), so do not
  253. * attempt to free the token object.
  254. */
  255. static QObject *parser_context_peek_token(JSONParserContext *ctxt)
  256. {
  257. QObject *token;
  258. g_assert(ctxt->tokens.pos < ctxt->tokens.count);
  259. token = ctxt->tokens.buf[ctxt->tokens.pos];
  260. return token;
  261. }
  262. static JSONParserContext parser_context_save(JSONParserContext *ctxt)
  263. {
  264. JSONParserContext saved_ctxt = {0};
  265. saved_ctxt.tokens.pos = ctxt->tokens.pos;
  266. saved_ctxt.tokens.count = ctxt->tokens.count;
  267. saved_ctxt.tokens.buf = ctxt->tokens.buf;
  268. return saved_ctxt;
  269. }
  270. static void parser_context_restore(JSONParserContext *ctxt,
  271. JSONParserContext saved_ctxt)
  272. {
  273. ctxt->tokens.pos = saved_ctxt.tokens.pos;
  274. ctxt->tokens.count = saved_ctxt.tokens.count;
  275. ctxt->tokens.buf = saved_ctxt.tokens.buf;
  276. }
  277. static void tokens_append_from_iter(QObject *obj, void *opaque)
  278. {
  279. JSONParserContext *ctxt = opaque;
  280. g_assert(ctxt->tokens.pos < ctxt->tokens.count);
  281. ctxt->tokens.buf[ctxt->tokens.pos++] = obj;
  282. qobject_incref(obj);
  283. }
  284. static JSONParserContext *parser_context_new(QList *tokens)
  285. {
  286. JSONParserContext *ctxt;
  287. size_t count;
  288. if (!tokens) {
  289. return NULL;
  290. }
  291. count = qlist_size(tokens);
  292. if (count == 0) {
  293. return NULL;
  294. }
  295. ctxt = g_malloc0(sizeof(JSONParserContext));
  296. ctxt->tokens.pos = 0;
  297. ctxt->tokens.count = count;
  298. ctxt->tokens.buf = g_malloc(count * sizeof(QObject *));
  299. qlist_iter(tokens, tokens_append_from_iter, ctxt);
  300. ctxt->tokens.pos = 0;
  301. return ctxt;
  302. }
  303. /* to support error propagation, ctxt->err must be freed separately */
  304. static void parser_context_free(JSONParserContext *ctxt)
  305. {
  306. int i;
  307. if (ctxt) {
  308. for (i = 0; i < ctxt->tokens.count; i++) {
  309. qobject_decref(ctxt->tokens.buf[i]);
  310. }
  311. g_free(ctxt->tokens.buf);
  312. g_free(ctxt);
  313. }
  314. }
  315. /**
  316. * Parsing rules
  317. */
  318. static int parse_pair(JSONParserContext *ctxt, QDict *dict, va_list *ap)
  319. {
  320. QObject *key = NULL, *token = NULL, *value, *peek;
  321. JSONParserContext saved_ctxt = parser_context_save(ctxt);
  322. peek = parser_context_peek_token(ctxt);
  323. if (peek == NULL) {
  324. parse_error(ctxt, NULL, "premature EOI");
  325. goto out;
  326. }
  327. key = parse_value(ctxt, ap);
  328. if (!key || qobject_type(key) != QTYPE_QSTRING) {
  329. parse_error(ctxt, peek, "key is not a string in object");
  330. goto out;
  331. }
  332. token = parser_context_pop_token(ctxt);
  333. if (token == NULL) {
  334. parse_error(ctxt, NULL, "premature EOI");
  335. goto out;
  336. }
  337. if (!token_is_operator(token, ':')) {
  338. parse_error(ctxt, token, "missing : in object pair");
  339. goto out;
  340. }
  341. value = parse_value(ctxt, ap);
  342. if (value == NULL) {
  343. parse_error(ctxt, token, "Missing value in dict");
  344. goto out;
  345. }
  346. qdict_put_obj(dict, qstring_get_str(qobject_to_qstring(key)), value);
  347. qobject_decref(key);
  348. return 0;
  349. out:
  350. parser_context_restore(ctxt, saved_ctxt);
  351. qobject_decref(key);
  352. return -1;
  353. }
  354. static QObject *parse_object(JSONParserContext *ctxt, va_list *ap)
  355. {
  356. QDict *dict = NULL;
  357. QObject *token, *peek;
  358. JSONParserContext saved_ctxt = parser_context_save(ctxt);
  359. token = parser_context_pop_token(ctxt);
  360. if (token == NULL) {
  361. goto out;
  362. }
  363. if (!token_is_operator(token, '{')) {
  364. goto out;
  365. }
  366. dict = qdict_new();
  367. peek = parser_context_peek_token(ctxt);
  368. if (peek == NULL) {
  369. parse_error(ctxt, NULL, "premature EOI");
  370. goto out;
  371. }
  372. if (!token_is_operator(peek, '}')) {
  373. if (parse_pair(ctxt, dict, ap) == -1) {
  374. goto out;
  375. }
  376. token = parser_context_pop_token(ctxt);
  377. if (token == NULL) {
  378. parse_error(ctxt, NULL, "premature EOI");
  379. goto out;
  380. }
  381. while (!token_is_operator(token, '}')) {
  382. if (!token_is_operator(token, ',')) {
  383. parse_error(ctxt, token, "expected separator in dict");
  384. goto out;
  385. }
  386. if (parse_pair(ctxt, dict, ap) == -1) {
  387. goto out;
  388. }
  389. token = parser_context_pop_token(ctxt);
  390. if (token == NULL) {
  391. parse_error(ctxt, NULL, "premature EOI");
  392. goto out;
  393. }
  394. }
  395. } else {
  396. (void)parser_context_pop_token(ctxt);
  397. }
  398. return QOBJECT(dict);
  399. out:
  400. parser_context_restore(ctxt, saved_ctxt);
  401. QDECREF(dict);
  402. return NULL;
  403. }
  404. static QObject *parse_array(JSONParserContext *ctxt, va_list *ap)
  405. {
  406. QList *list = NULL;
  407. QObject *token, *peek;
  408. JSONParserContext saved_ctxt = parser_context_save(ctxt);
  409. token = parser_context_pop_token(ctxt);
  410. if (token == NULL) {
  411. goto out;
  412. }
  413. if (!token_is_operator(token, '[')) {
  414. goto out;
  415. }
  416. list = qlist_new();
  417. peek = parser_context_peek_token(ctxt);
  418. if (peek == NULL) {
  419. parse_error(ctxt, NULL, "premature EOI");
  420. goto out;
  421. }
  422. if (!token_is_operator(peek, ']')) {
  423. QObject *obj;
  424. obj = parse_value(ctxt, ap);
  425. if (obj == NULL) {
  426. parse_error(ctxt, token, "expecting value");
  427. goto out;
  428. }
  429. qlist_append_obj(list, obj);
  430. token = parser_context_pop_token(ctxt);
  431. if (token == NULL) {
  432. parse_error(ctxt, NULL, "premature EOI");
  433. goto out;
  434. }
  435. while (!token_is_operator(token, ']')) {
  436. if (!token_is_operator(token, ',')) {
  437. parse_error(ctxt, token, "expected separator in list");
  438. goto out;
  439. }
  440. obj = parse_value(ctxt, ap);
  441. if (obj == NULL) {
  442. parse_error(ctxt, token, "expecting value");
  443. goto out;
  444. }
  445. qlist_append_obj(list, obj);
  446. token = parser_context_pop_token(ctxt);
  447. if (token == NULL) {
  448. parse_error(ctxt, NULL, "premature EOI");
  449. goto out;
  450. }
  451. }
  452. } else {
  453. (void)parser_context_pop_token(ctxt);
  454. }
  455. return QOBJECT(list);
  456. out:
  457. parser_context_restore(ctxt, saved_ctxt);
  458. QDECREF(list);
  459. return NULL;
  460. }
  461. static QObject *parse_keyword(JSONParserContext *ctxt)
  462. {
  463. QObject *token, *ret;
  464. JSONParserContext saved_ctxt = parser_context_save(ctxt);
  465. token = parser_context_pop_token(ctxt);
  466. if (token == NULL) {
  467. goto out;
  468. }
  469. if (token_get_type(token) != JSON_KEYWORD) {
  470. goto out;
  471. }
  472. if (token_is_keyword(token, "true")) {
  473. ret = QOBJECT(qbool_from_bool(true));
  474. } else if (token_is_keyword(token, "false")) {
  475. ret = QOBJECT(qbool_from_bool(false));
  476. } else if (token_is_keyword(token, "null")) {
  477. ret = qnull();
  478. } else {
  479. parse_error(ctxt, token, "invalid keyword `%s'", token_get_value(token));
  480. goto out;
  481. }
  482. return ret;
  483. out:
  484. parser_context_restore(ctxt, saved_ctxt);
  485. return NULL;
  486. }
  487. static QObject *parse_escape(JSONParserContext *ctxt, va_list *ap)
  488. {
  489. QObject *token = NULL, *obj;
  490. JSONParserContext saved_ctxt = parser_context_save(ctxt);
  491. if (ap == NULL) {
  492. goto out;
  493. }
  494. token = parser_context_pop_token(ctxt);
  495. if (token == NULL) {
  496. goto out;
  497. }
  498. if (token_is_escape(token, "%p")) {
  499. obj = va_arg(*ap, QObject *);
  500. } else if (token_is_escape(token, "%i")) {
  501. obj = QOBJECT(qbool_from_bool(va_arg(*ap, int)));
  502. } else if (token_is_escape(token, "%d")) {
  503. obj = QOBJECT(qint_from_int(va_arg(*ap, int)));
  504. } else if (token_is_escape(token, "%ld")) {
  505. obj = QOBJECT(qint_from_int(va_arg(*ap, long)));
  506. } else if (token_is_escape(token, "%lld") ||
  507. token_is_escape(token, "%I64d")) {
  508. obj = QOBJECT(qint_from_int(va_arg(*ap, long long)));
  509. } else if (token_is_escape(token, "%s")) {
  510. obj = QOBJECT(qstring_from_str(va_arg(*ap, const char *)));
  511. } else if (token_is_escape(token, "%f")) {
  512. obj = QOBJECT(qfloat_from_double(va_arg(*ap, double)));
  513. } else {
  514. goto out;
  515. }
  516. return obj;
  517. out:
  518. parser_context_restore(ctxt, saved_ctxt);
  519. return NULL;
  520. }
  521. static QObject *parse_literal(JSONParserContext *ctxt)
  522. {
  523. QObject *token, *obj;
  524. JSONParserContext saved_ctxt = parser_context_save(ctxt);
  525. token = parser_context_pop_token(ctxt);
  526. if (token == NULL) {
  527. goto out;
  528. }
  529. switch (token_get_type(token)) {
  530. case JSON_STRING:
  531. obj = QOBJECT(qstring_from_escaped_str(ctxt, token));
  532. break;
  533. case JSON_INTEGER: {
  534. /* A possibility exists that this is a whole-valued float where the
  535. * fractional part was left out due to being 0 (.0). It's not a big
  536. * deal to treat these as ints in the parser, so long as users of the
  537. * resulting QObject know to expect a QInt in place of a QFloat in
  538. * cases like these.
  539. *
  540. * However, in some cases these values will overflow/underflow a
  541. * QInt/int64 container, thus we should assume these are to be handled
  542. * as QFloats/doubles rather than silently changing their values.
  543. *
  544. * strtoll() indicates these instances by setting errno to ERANGE
  545. */
  546. int64_t value;
  547. errno = 0; /* strtoll doesn't set errno on success */
  548. value = strtoll(token_get_value(token), NULL, 10);
  549. if (errno != ERANGE) {
  550. obj = QOBJECT(qint_from_int(value));
  551. break;
  552. }
  553. /* fall through to JSON_FLOAT */
  554. }
  555. case JSON_FLOAT:
  556. /* FIXME dependent on locale */
  557. obj = QOBJECT(qfloat_from_double(strtod(token_get_value(token), NULL)));
  558. break;
  559. default:
  560. goto out;
  561. }
  562. return obj;
  563. out:
  564. parser_context_restore(ctxt, saved_ctxt);
  565. return NULL;
  566. }
  567. static QObject *parse_value(JSONParserContext *ctxt, va_list *ap)
  568. {
  569. QObject *obj;
  570. obj = parse_object(ctxt, ap);
  571. if (obj == NULL) {
  572. obj = parse_array(ctxt, ap);
  573. }
  574. if (obj == NULL) {
  575. obj = parse_escape(ctxt, ap);
  576. }
  577. if (obj == NULL) {
  578. obj = parse_keyword(ctxt);
  579. }
  580. if (obj == NULL) {
  581. obj = parse_literal(ctxt);
  582. }
  583. return obj;
  584. }
  585. QObject *json_parser_parse(QList *tokens, va_list *ap)
  586. {
  587. return json_parser_parse_err(tokens, ap, NULL);
  588. }
  589. QObject *json_parser_parse_err(QList *tokens, va_list *ap, Error **errp)
  590. {
  591. JSONParserContext *ctxt = parser_context_new(tokens);
  592. QObject *result;
  593. if (!ctxt) {
  594. return NULL;
  595. }
  596. result = parse_value(ctxt, ap);
  597. error_propagate(errp, ctxt->err);
  598. parser_context_free(ctxt);
  599. return result;
  600. }