Debian Codegraph @

src/libxml_reporter.c

raw symbols SCIP
1 #include <cgreen/breadcrumb.h>
2 #include <stdio.h>
3 #include <stdint.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <errno.h>
7 #include <inttypes.h>
8 #include <assert.h>
9
10 #include <libxml/xmlwriter.h>
11 #include <libxml/encoding.h>
12 #include <libxml/xmlIO.h>
13 #include <libxml/tree.h>
14
15 #include "libxml_reporter_internal.h"
16
17 #ifdef __ANDROID__
18 #include "cgreen/internal/android_headers/androidcompat.h"
19 #endif // #ifdef __ANDROID__
20
21 typedef struct {
22 XmlPrinter *printer;
23 int segment_count;
24 } XmlMemo;
25
26 #define XMLSTRING(x) (BAD_CAST x)
27
28 static void xml_reporter_start_suite(TestReporter *reporter, const char *name,
29 int count);
30 static void xml_reporter_start_test(TestReporter *reporter, const char *name);
31 static void xml_reporter_finish_test(TestReporter *reporter, const char *filename,
32 int line, const char *message);
33 static void xml_reporter_finish_suite(TestReporter *reporter, const char *filename,
34 int line);
35 static void xml_show_skip(TestReporter *reporter, const char *file, int line);
36 static void xml_show_fail(TestReporter *reporter, const char *file, int line,
37 const char *message, va_list arguments);
38 static void xml_show_incomplete(TestReporter *reporter, const char *filename,
39 int line, const char *message, va_list arguments);
40
41 static const char *file_prefix;
42
43 static int default_printer(xmlDocPtr doc);
44
45 void set_libxml_reporter_printer(TestReporter *reporter, XmlPrinter *printer)
46 {
47 XmlMemo *memo = (XmlMemo*)reporter->memo;
48 memo->printer = printer;
49 }
50
51 TestReporter *create_libxml_reporter(const char *prefix) {
52 TestReporter *reporter;
53 XmlMemo *memo;
54
55 reporter = create_reporter();
56 if (reporter == NULL) {
57 return NULL;
58 }
59
60 memo = (XmlMemo *) malloc(sizeof(XmlMemo));
61 if (memo == NULL) {
62 destroy_reporter(reporter);
63 return NULL;
64 }
65 reporter->memo = memo;
66 memo->printer = &default_printer;
67
68 file_prefix = prefix;
69 reporter->start_suite = &xml_reporter_start_suite;
70 reporter->start_test = &xml_reporter_start_test;
71 reporter->show_fail = &xml_show_fail;
72 reporter->show_skip = &xml_show_skip;
73 reporter->show_incomplete = &xml_show_incomplete;
74 reporter->finish_test = &xml_reporter_finish_test;
75 reporter->finish_suite = &xml_reporter_finish_suite;
76 return reporter;
77 }
78
79 #ifndef PATH_MAX
80 #define PATH_MAX 4096
81 #endif
82 static char suite_path[PATH_MAX];
83
84 static void print_path_separator_if_needed(int *more_segments) {
85 if (*more_segments > 0) {
86 strcat(suite_path, "/");
87 (*more_segments)--;
88 }
89 }
90
91 static void print_path_segment_walker(const char *segment, void *void_memo) {
92 XmlMemo *memo = (XmlMemo *)void_memo;
93
94 strncat(suite_path, segment, sizeof(suite_path)-strlen(suite_path)-1);
95 print_path_separator_if_needed(&memo->segment_count);
96 }
97
98 static void strcat_path_segment(const char *segment, void *more_segments) {
99 (void)more_segments;
100 if (suite_path[0] != '\0') strcat(suite_path, "-");
101 strncat(suite_path, segment, sizeof(suite_path)-strlen(suite_path)-1);
102 }
103
104 static void add_suite_name(const char *suite_name) {
105 if (suite_path[0] != '\0')
106 strcat(suite_path, "-");
107 strncat(suite_path, suite_name, sizeof(suite_path)-strlen(suite_path)-1);
108 }
109
110 #define NESTED_SUITE_MAX 100
111 struct xml_suite_context {
112 xmlDocPtr doc;
113 xmlNodePtr suite, curTest;
114 FILE* outFile;
115 uint32_t suite_duration;
116 };
117 static struct xml_suite_context context_stack[NESTED_SUITE_MAX];
118 static int context_stack_p = 0;
119
120 /*
121 * The table below is taken from the "Non-restricted characters" section of
122 * https://en.wikipedia.org/wiki/Valid_characters_in_XML
123 */
124 static bool isNonRestrictedXMLChar(unsigned int c) {
125 return (c == 0x09u || c == 0x0Au || c == 0x0Du ||
126 (c >= 0x20u && c <= 0x7Eu) || c == 0x85u ||
127 (c >= 0xA0u && c <= 0xD7FFu) ||
128 (c >= 0xE000u && c <= 0xFDCFu) ||
129 (c >= 0xFDF0u && c <= 0xFFFDu) ||
130 (c >= 0x10000u && c <= 0x1FFFDu) ||
131 (c >= 0x20000u && c <= 0x2FFFDu) ||
132 (c >= 0x30000u && c <= 0x3FFFDu) ||
133 (c >= 0x40000u && c <= 0x4FFFDu) ||
134 (c >= 0x50000u && c <= 0x5FFFDu) ||
135 (c >= 0x60000u && c <= 0x6FFFDu) ||
136 (c >= 0x70000u && c <= 0x7FFFDu) ||
137 (c >= 0x80000u && c <= 0x8FFFDu) ||
138 (c >= 0x90000u && c <= 0x9FFFDu) ||
139 (c >= 0xA0000u && c <= 0xAFFFDu) ||
140 (c >= 0xB0000u && c <= 0xBFFFDu) ||
141 (c >= 0xC0000u && c <= 0xCFFFDu) ||
142 (c >= 0xD0000u && c <= 0xDFFFDu) ||
143 (c >= 0xE0000u && c <= 0xEFFFDu) ||
144 (c >= 0xF0000u && c <= 0xFFFFDu) ||
145 (c >= 0x100000u && c <= 0x10FFFD));
146 }
147
148 static bool isOverlongUTF8(unsigned int ucs, int len)
149 {
150 return ((ucs <= 0x7f && len > 1) ||
151 (ucs <= 0x7ff && len > 2) ||
152 (ucs <= 0xffff && len > 3) ||
153 (ucs <= 0x10ffff && len > 4));
154 }
155
156 /*
157 * Return a copy of the argument prepared to be used as an attribute value.
158 * The produced result is not necessary convertable back to the original set
159 * of bytes.
160 */
161 static xmlChar* xmlEscapePropValue(const char *str) {
162 size_t len = strlen(str);
163 /*
164 * The worst-case length of the output is 4 times the input length (if
165 * every input byte has to be escaped) plus 1 for the terminating NUL
166 * character
167 */
168 size_t retLen = len * 4 + 1;
169 xmlChar* ret = xmlMalloc(retLen), *retPos = ret, *retEnd = ret + retLen;
170 if (!ret) {
171 fprintf(stderr, "memory allocation failure in %s\n", __func__);
172 exit(EXIT_FAILURE);
173 }
174
175 const unsigned char *it = (const unsigned char*)str;
176 const unsigned char *itEnd = it + len;
177 while (*it) {
178 int utfLen = itEnd - it;
179 int ucs = xmlGetUTF8Char(it, &utfLen);
180 if (ucs != -1) {
181 if (!isOverlongUTF8(ucs, utfLen)) {
182 if (isNonRestrictedXMLChar(ucs)) {
183 /* Valid UTF8 sequence of an allowed character */
184 while (utfLen--)
185 *retPos++ = *it++;
186 } else {
187 xmlStrPrintf(retPos, retEnd - retPos, "&x%x;", ucs);
188 }
189 } else {
190 /* Disallowed character or overlong UTF8, escape entire sequence */
191 for(int i = 0;i < utfLen;++i) {
192 xmlStrPrintf(retPos, retEnd-retPos, "\\x%.2" PRIx8, *it);
193 retPos += 4;
194 ++it;
195 }
196 }
197 } else {
198 /* Invalid UTF8, escape one byte then try to parse rest of input as UTF8 again */
199 xmlStrPrintf(retPos, retEnd-retPos, "\\x%.2" PRIx8, *it);
200 retPos += 4;
201 ++it;
202 }
203 }
204
205 *retPos = '\0';
206 return ret;
207 }
208
209 static void xml_reporter_start_suite(TestReporter *reporter, const char *suitename, int count) {
210 char filename[PATH_MAX];
211 int segment_decrementer = reporter->breadcrumb->depth;
212 XmlMemo *memo = (XmlMemo *)reporter->memo;
213 if (context_stack_p >= NESTED_SUITE_MAX)
214 abort();
215 struct xml_suite_context *ctx = &context_stack[context_stack_p++];
216
217 FILE *out;
218
219 (void)count; /* UNUSED */
220
221 reporter->passes = 0;
222 reporter->failures = 0;
223 reporter->skips = 0;
224 reporter->exceptions = 0;
225
226 suite_path[0] = '\0';
227 walk_breadcrumb(reporter->breadcrumb, strcat_path_segment, &segment_decrementer);
228 add_suite_name(suitename);
229
230 if (snprintf(filename, sizeof(filename), "%s-%s.xml", file_prefix, suite_path) >= (int)sizeof(filename)) {
231 fprintf(stderr, "filename truncated; exceeds PATH_MAX (= %d)\n", PATH_MAX);
232 exit(EXIT_FAILURE);
233 }
234 if (memo->printer == default_printer) {
235 // If we're really printing to files, then open one...
236 out = fopen(filename, "w");
237 if (!out) {
238 fprintf(stderr, "could not open %s: %s\r\n", filename, strerror(errno));
239 exit(EXIT_FAILURE);
240 }
241 ctx->outFile = out;
242 }
243
244 ctx->suite_duration = 0;
245 ctx->doc = xmlNewDoc(XMLSTRING("1.0"));
246 ctx->suite = xmlNewNode(NULL, XMLSTRING("testsuite"));
247 xmlChar *xml_suite_path = xmlEscapePropValue(suite_path);
248 xmlNewProp(ctx->suite, XMLSTRING("name"), xml_suite_path);
249 xmlFree(xml_suite_path);
250 xmlDocSetRootElement(ctx->doc, ctx->suite);
251
252 reporter_start_suite(reporter, suitename, 0);
253 }
254
255
256 /* Accumulate output from the actual test (the "<testcase>" nodes) in
257 a file since the tests usually are run in a child processes, so
258 there is no simple way to save output from it and then use it in
259 the parent (start_test() and finish_test() are run from parent) */
260
261 static FILE *child_output_tmpfile;
262 static xmlTextWriterPtr child_output_writer;
263
264 static void xml_reporter_start_test(TestReporter *reporter, const char *testname) {
265 XmlMemo *memo = (XmlMemo *)reporter->memo;
266 struct xml_suite_context *ctx = &context_stack[context_stack_p-1];
267
268 ctx->curTest = xmlNewChild(ctx->suite, NULL, XMLSTRING("testcase"), NULL);
269 xmlChar *xml_testname = xmlEscapePropValue(testname);
270 xmlNewProp(ctx->curTest, XMLSTRING("name"), xml_testname);
271 xmlFree(xml_testname);
272
273 memo->segment_count = reporter->breadcrumb->depth - 1;
274 suite_path[0] = '\0';
275 walk_breadcrumb(reporter->breadcrumb, print_path_segment_walker, memo);
276 xmlChar* xml_suite_path = xmlEscapePropValue(suite_path);
277 xmlNewProp(ctx->curTest, XMLSTRING("classname"), xml_suite_path);
278 xmlFree(xml_suite_path);
279
280 reporter_start_test(reporter, testname);
281
282 child_output_tmpfile = tmpfile();
283 xmlOutputBufferPtr tmpfileBuf
284 = xmlOutputBufferCreateFile(child_output_tmpfile,
285 xmlGetCharEncodingHandler(XML_CHAR_ENCODING_UTF8));
286 child_output_writer = xmlNewTextWriter(tmpfileBuf);
287 }
288
289
290 static void xml_show_skip(TestReporter *reporter, const char *file, int line) {
291 (void)file;
292 (void)line;
293 (void)reporter;
294
295 xmlTextWriterStartElement(child_output_writer, XMLSTRING("skipped"));
296 xmlTextWriterEndElement(child_output_writer); // </skipped>
297 xmlTextWriterFlush(child_output_writer);
298 }
299
300 static xmlChar* xml_secure_vprint(const char *format, va_list ap)
301 {
302 char buf[100];
303 char *msg = buf;
304 const size_t len = sizeof(buf);
305
306 va_list ap_store;
307 va_copy(ap_store, ap);
308 int res = vsnprintf(msg, len, format, ap_store);
309 va_end(ap_store);
310 if (res < 0) {
311 fprintf(stderr, "vsnprintf failed in xml_secure_vprint: %s\n", strerror(res));
312 exit(EXIT_FAILURE);
313 }
314
315 if ((unsigned)res >= len) {
316 size_t msglen = res+1;
317 msg = malloc(msglen);
318 if (!msg) {
319 fprintf(stderr, "memory allocation failure in xml_secure_vprint\n");
320 exit(EXIT_FAILURE);
321 }
322 res = vsnprintf(msg, msglen, format, ap);
323 if (res < 0) {
324 free(msg);
325 fprintf(stderr, "vsnprintf failed in xml_secure_vprint: %s\n", strerror(res));
326 exit(EXIT_FAILURE);
327 }
328 if ((unsigned)res >= msglen) {
329 // What? Did format get longer while allocating msg?
330 free(msg);
331 fprintf(stderr, "vsnprintf failed in xml_secure_vprint: nondeterministic message length\n");
332 exit(EXIT_FAILURE);
333 }
334 }
335
336 xmlChar *xml_msg = xmlEscapePropValue(msg);
337 if (msg != buf) free(msg);
338 return xml_msg;
339 }
340
341 static void xml_show_fail(TestReporter *reporter, const char *file, int line,
342 const char *message, va_list arguments) {
343 (void)reporter;
344
345 xmlTextWriterStartElement(child_output_writer, XMLSTRING("failure"));
346
347 xmlChar *xml_str = xml_secure_vprint(message, arguments);
348 xmlTextWriterWriteAttribute(child_output_writer, XMLSTRING("message"), xml_str);
349 xmlFree(xml_str);
350
351 xmlTextWriterStartElement(child_output_writer, XMLSTRING("location"));
352 xmlChar *xml_file = xmlEscapePropValue(file);
353 xmlTextWriterWriteAttribute(child_output_writer, XMLSTRING("file"), xml_file);
354 xmlFree(xml_file);
355 xmlTextWriterWriteFormatAttribute(child_output_writer, XMLSTRING("line"), "%d", line);
356 xmlTextWriterEndElement(child_output_writer); // </location>
357 xmlTextWriterEndElement(child_output_writer); // </failure>
358 xmlTextWriterFlush(child_output_writer);
359 }
360
361 static xmlAttrPtr xmlFormatProp(xmlNodePtr node, const xmlChar* name, const char *format, ...)
362 {
363 va_list vargs;
364 va_start(vargs, format);
365 xmlChar *xml_str = xml_secure_vprint(format, vargs);
366 va_end(vargs);
367
368 xmlAttrPtr attr = xmlNewProp(node, name, xml_str);
369 xmlFree(xml_str);
370
371 return attr;
372 }
373
374 static void xml_show_incomplete(TestReporter *reporter, const char *filename,
375 int line, const char *message, va_list arguments) {
376 (void)reporter;
377
378 struct xml_suite_context *ctx = &context_stack[context_stack_p-1];
379
380 xmlNodePtr errNode = xmlNewChild(ctx->curTest, NULL, XMLSTRING("error"), NULL);
381 xmlNewProp(errNode, XMLSTRING("type"), XMLSTRING("Fatal"));
382 if (message) {
383 xmlChar *xml_msg = xml_secure_vprint(message, arguments);
384 xmlNewProp(errNode, XMLSTRING("message"), xml_msg);
385 xmlFree(xml_msg);
386 } else {
387 xmlNewProp(errNode, XMLSTRING("message"),
388 XMLSTRING("Test terminated unexpectedly, likely from a non-standard exception or Posix signal"));
389 }
390 xmlNodePtr locNode = xmlNewChild(errNode, NULL, XMLSTRING("location"), NULL);
391 xmlChar *xml_filename = xmlEscapePropValue(filename);
392 xmlNewProp(locNode, XMLSTRING("file"), xml_filename);
393 xmlFree(xml_filename);
394 xmlFormatProp(locNode, XMLSTRING("line"), "%d", line);
395 }
396
397 static void insert_child_results(struct xml_suite_context *ctx) {
398 char childData[4096];
399 fseek(child_output_tmpfile, 0, SEEK_SET);
400
401 size_t pos = 0, ret;
402 while (!feof(child_output_tmpfile)) {
403 ret = fread(childData+pos, 1, sizeof(childData)-pos, child_output_tmpfile);
404 if (ferror(child_output_tmpfile)) {
405 abort();
406 }
407 pos += ret;
408 }
409
410 fclose(child_output_tmpfile);
411 if (pos > 0) {
412 childData[pos] = '\0';
413
414 xmlNodePtr childLst;
415 if (xmlParseBalancedChunkMemoryRecover(ctx->doc, NULL, NULL, 0, XMLSTRING(childData), &childLst, 1) != 0) {
416 xmlNodePtr errNode = xmlNewChild(ctx->curTest, NULL, XMLSTRING("error"), NULL);
417 xmlNewProp(errNode, XMLSTRING("type"), XMLSTRING("Fatal"));
418 xmlNewProp(errNode, XMLSTRING("message"),
419 XMLSTRING("Test result XML truncated or malformed, "
420 "likely from abnormal process termination"));
421 }
422
423 xmlAddChildList(ctx->curTest, childLst);
424 }
425 }
426
427 static void xml_reporter_finish_test(TestReporter *reporter, const char *filename,
428 int line, const char *message) {
429 struct xml_suite_context *ctx = &context_stack[context_stack_p-1];
430
431 reporter_finish_test(reporter, filename, line, message);
432 xmlFreeTextWriter(child_output_writer);
433
434 xmlFormatProp(ctx->curTest, XMLSTRING("time"),
435 "%.5f", (double)reporter->duration/(double)1000);
436
437 ctx->suite_duration += reporter->duration;
438 insert_child_results(ctx);
439 }
440
441 static void deleteEmpty(xmlNodePtr elem)
442 {
443 while (elem != NULL) {
444 xmlNodePtr next = elem->next;
445 if (xmlIsBlankNode(elem)) {
446 xmlUnlinkNode(elem);
447 xmlFreeNode(elem);
448 } else if (elem->children) {
449 deleteEmpty(elem->children);
450 }
451
452 elem = next;
453 }
454 }
455
456 static int default_printer(xmlDocPtr doc)
457 {
458 struct xml_suite_context *ctx = &context_stack[context_stack_p-1];
459 xmlOutputBufferPtr outBuf
460 = xmlOutputBufferCreateFile(ctx->outFile,
461 xmlGetCharEncodingHandler(XML_CHAR_ENCODING_UTF8));
462 xmlSaveFormatFileTo(outBuf, doc, "UTF-8", 1);
463
464 return 0;
465 }
466
467 static void xml_reporter_finish_suite(TestReporter *reporter, const char *filename, int line) {
468 XmlMemo *memo = (XmlMemo *)reporter->memo;
469 struct xml_suite_context *ctx = &context_stack[context_stack_p-1];
470
471 reporter_finish_suite(reporter, filename, line);
472
473 reporter->total_passes += reporter->passes;
474 reporter->total_failures += reporter->failures;
475 reporter->total_skips += reporter->skips;
476 reporter->total_exceptions += reporter->exceptions;
477
478 xmlFormatProp(ctx->suite, XMLSTRING("failures"), "%d", reporter->failures);
479 xmlFormatProp(ctx->suite, XMLSTRING("errors"), "%d", reporter->exceptions);
480 xmlFormatProp(ctx->suite, XMLSTRING("skipped"), "%d", reporter->skips);
481 xmlFormatProp(ctx->suite, XMLSTRING("time"), "%.5f", (double)ctx->suite_duration/(double)1000);
482
483 deleteEmpty(ctx->suite);
484 memo->printer(ctx->doc);
485 xmlFreeDoc(ctx->doc);
486 if (context_stack_p > 1) {
487 context_stack[context_stack_p-2].suite_duration += ctx->suite_duration;
488 }
489 --context_stack_p;
490 }