Debian Codegraph @

gcc/diagnostic-format-sarif.cc

raw
1 /* SARIF output for diagnostics
2 Copyright (C) 2018-2025 Free Software Foundation, Inc.
3 Contributed by David Malcolm <[email protected]>.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
20
21
22 #include "config.h"
23 #define INCLUDE_LIST
24 #define INCLUDE_MAP
25 #define INCLUDE_STRING
26 #define INCLUDE_VECTOR
27 #include "system.h"
28 #include "coretypes.h"
29 #include "diagnostic.h"
30 #include "diagnostic-metadata.h"
31 #include "diagnostic-path.h"
32 #include "diagnostic-format.h"
33 #include "diagnostic-buffer.h"
34 #include "json.h"
35 #include "cpplib.h"
36 #include "logical-location.h"
37 #include "diagnostic-client-data-hooks.h"
38 #include "diagnostic-diagram.h"
39 #include "text-art/canvas.h"
40 #include "diagnostic-format-sarif.h"
41 #include "diagnostic-format-text.h"
42 #include "ordered-hash-map.h"
43 #include "sbitmap.h"
44 #include "make-unique.h"
45 #include "selftest.h"
46 #include "selftest-diagnostic.h"
47 #include "selftest-diagnostic-show-locus.h"
48 #include "selftest-json.h"
49 #include "text-range-label.h"
50 #include "pretty-print-format-impl.h"
51 #include "pretty-print-urlifier.h"
52 #include "demangle.h"
53 #include "backtrace.h"
54
55 /* Forward decls. */
56 class sarif_builder;
57 class content_renderer;
58 class escape_nonascii_renderer;
59
60 /* Subclasses of sarif_object.
61 Keep these in order of their descriptions in the specification. */
62 class sarif_artifact_content; // 3.3
63 class sarif_artifact_location; // 3.4
64 class sarif_message; // 3.11
65 class sarif_multiformat_message_string; // 3.12
66 class sarif_log; // 3.13
67 class sarif_run; // 3.14
68 class sarif_tool; // 3.18
69 class sarif_tool_component; // 3.19
70 class sarif_invocation; // 3.20
71 class sarif_artifact; // 3.24
72 class sarif_location_manager; // not in the spec
73 class sarif_result; // 3.27
74 class sarif_location; // 3.28
75 class sarif_physical_location; // 3.29
76 class sarif_region; // 3.30
77 class sarif_logical_location; // 3.33
78 class sarif_location_relationship; // 3.34
79 class sarif_code_flow; // 3.36
80 class sarif_thread_flow; // 3.37
81 class sarif_thread_flow_location; // 3.38
82 class sarif_reporting_descriptor; // 3.49
83 class sarif_reporting_descriptor_reference; // 3.53
84 class sarif_tool_component_reference; // 3.54
85 class sarif_fix; // 3.55
86 class sarif_artifact_change; // 3.56
87 class sarif_replacement; // 3.57
88 class sarif_ice_notification; // 3.58
89
90 // Valid values for locationRelationship's "kinds" property (3.34.3)
91
92 enum class location_relationship_kind
93 {
94 includes,
95 is_included_by,
96 relevant,
97
98 NUM_KINDS
99 };
100
101 /* Declarations of subclasses of sarif_object.
102 Keep these in order of their descriptions in the specification. */
103
104 /* Subclass of sarif_object for SARIF "artifactContent" objects
105 (SARIF v2.1.0 section 3.3). */
106
107 class sarif_artifact_content : public sarif_object {};
108
109 /* Subclass of sarif_object for SARIF "artifactLocation" objects
110 (SARIF v2.1.0 section 3.4). */
111
112 class sarif_artifact_location : public sarif_object {};
113
114 /* Subclass of sarif_object for SARIF "message" objects
115 (SARIF v2.1.0 section 3.11). */
116
117 class sarif_message : public sarif_object {};
118
119 /* Subclass of sarif_object for SARIF "multiformatMessageString" objects
120 (SARIF v2.1.0 section 3.12). */
121
122 class sarif_multiformat_message_string : public sarif_object {};
123
124 /* Subclass of sarif_object for SARIF "log" objects
125 (SARIF v2.1.0 section 3.13). */
126
127 class sarif_log : public sarif_object {};
128
129 /* Subclass of sarif_object for SARIF "run" objects
130 (SARIF v2.1.0 section 3.14). */
131
132 class sarif_run : public sarif_object {};
133
134 /* Subclass of sarif_object for SARIF "tool" objects
135 (SARIF v2.1.0 section 3.18). */
136
137 class sarif_tool : public sarif_object {};
138
139 /* Subclass of sarif_object for SARIF "toolComponent" objects
140 (SARIF v2.1.0 section 3.19). */
141
142 class sarif_tool_component : public sarif_object {};
143
144 /* Make a JSON string for the current date and time.
145 See SARIF v2.1.0 section 3.9 "Date/time properties".
146 Given that we don't run at the very beginning/end of the
147 process, it doesn't make sense to be more accurate than
148 the current second. */
149
150 static std::unique_ptr<json::string>
151 make_date_time_string_for_current_time ()
152 {
153 time_t t = time (nullptr);
154 struct tm *tm = gmtime (&t);
155 char buf[256];
156 snprintf (buf, sizeof (buf) - 1,
157 ("%04i-%02i-%02iT"
158 "%02i:%02i:%02iZ"),
159 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
160 tm->tm_hour, tm->tm_min, tm->tm_sec);
161 return ::make_unique<json::string> (buf);
162 }
163
164 /* Subclass of sarif_object for SARIF "invocation" objects
165 (SARIF v2.1.0 section 3.20). */
166
167 class sarif_invocation : public sarif_object
168 {
169 public:
170 sarif_invocation (sarif_builder &builder,
171 const char * const *original_argv);
172
173 void add_notification_for_ice (const diagnostic_info &diagnostic,
174 sarif_builder &builder,
175 std::unique_ptr<json::object> backtrace);
176 void prepare_to_flush (sarif_builder &builder);
177
178 private:
179 std::unique_ptr<json::array> m_notifications_arr;
180 bool m_success;
181 };
182
183 /* Corresponds to values for the SARIF artifact objects "roles" property.
184 (SARIF v2.1.0 section 3.24.6). */
185
186 enum class diagnostic_artifact_role
187 {
188 analysis_target, /* "analysisTarget". */
189 debug_output_file, /* "debugOutputFile". */
190 result_file, /* "resultFile". */
191
192 /* "scannedFile" added in 2.2;
193 see https://github.com/oasis-tcs/sarif-spec/issues/459 */
194 scanned_file,
195
196 traced_file, /* "tracedFile". */
197
198 NUM_ROLES
199 };
200
201 /* Subclass of sarif_object for SARIF artifact objects
202 (SARIF v2.1.0 section 3.24). */
203
204 class sarif_artifact : public sarif_object
205 {
206 public:
207 sarif_artifact (const char *filename)
208 : m_filename (filename),
209 m_roles ((unsigned)diagnostic_artifact_role::NUM_ROLES),
210 m_embed_contents (false)
211 {
212 bitmap_clear (m_roles);
213 }
214
215 void add_role (enum diagnostic_artifact_role role,
216 bool embed_contents);
217
218 bool embed_contents_p () const { return m_embed_contents; }
219 void populate_contents (sarif_builder &builder);
220 void populate_roles ();
221
222 private:
223 const char *m_filename;
224 auto_sbitmap m_roles;
225
226 /* Flag to track whether this artifact should have a "contents" property
227 (SARIF v2.1.0 section 3.24.8).
228 We only add the contents for those artifacts that have a location
229 referencing them (so that a consumer might want to quote the source). */
230 bool m_embed_contents;
231 };
232
233 /* A class for sarif_objects that own a "namespace" of numeric IDs for
234 managing location objects within them. Currently (SARIF v2.1.0)
235 this is just for sarif_result (section 3.28.2), but it will likely
236 eventually also be for notification objects; see
237 https://github.com/oasis-tcs/sarif-spec/issues/540
238
239 Consider locations with chains of include information e.g.
240
241 > include-chain-1.c:
242 > #include "include-chain-1.h"
243
244 include-chain-1.h:
245 | // First set of decls, which will be referenced in notes
246 | #include "include-chain-1-1.h"
247 |
248 | // Second set of decls, which will trigger the errors
249 | #include "include-chain-1-2.h"
250
251 include-chain-1-1.h:
252 | int p;
253 | int q;
254
255 include-chain-1-1.h:
256 | char p;
257 | char q;
258
259 GCC's textual output emits:
260 | In file included from PATH/include-chain-1.h:5,
261 | from PATH/include-chain-1.c:30:
262 | PATH/include-chain-1-2.h:1:6: error: conflicting types for 'p'; have 'char'
263 | 1 | char p;
264 | | ^
265 | In file included from PATH/include-chain-1.h:2:
266 | PATH/include-chain-1-1.h:1:5: note: previous declaration of 'p' with type 'int'
267 | 1 | int p;
268 | | ^
269 | PATH/include-chain-1-2.h:2:6: error: conflicting types for 'q'; have 'char'
270 | 2 | char q;
271 | | ^
272 | PATH/include-chain-1-1.h:2:5: note: previous declaration of 'q' with type 'int'
273 | 2 | int q;
274 | | ^
275
276 Whenever a SARIF location is added for a location_t that
277 was #included from somewhere, we queue up the creation of a SARIF
278 location for the location of the #include. The worklist of queued
279 locations is flushed when the result is finished, which lazily creates
280 any additional related locations for the include chain, and the
281 relationships between the locations. Doing so can lead to further
282 include locations being processed. The worklist approach allows us
283 to lazily explore the relevant part of the directed graph of location_t
284 values implicit in our line_maps structure, replicating it as a directed
285 graph of SARIF locations within the SARIF result object, like this:
286
287 [0]: error in include-chain-1-2.h ("conflicting types for 'p'; have 'char'")
288 [1]: #include "include-chain-1-2.h" in include-chain-1.h
289 [2]: note in include-chain-1-2.h ("previous declaration of 'p' with type 'int'")
290 [3]: #include "include-chain-1-1.h" in include-chain-1.h
291 [4]: #include "include-chain-1.h" in include-chain-1.c
292
293 where we want to capture this "includes" graph in SARIF form:
294 . +-----------------------------------+ +----------------------------------+
295 . |"id": 0 | |"id": 2 |
296 . | error: "conflicting types for 'p';| | note: previous declaration of 'p'|
297 . | have 'char'"| | | with type 'int'") |
298 . | in include-chain-1-2.h | | in include-chain-1-1.h |
299 . +-----------------------------------+ +----------------------------------+
300 . ^ | ^ |
301 . includes | | included-by includes | | included-by
302 . | V | V
303 . +--------------------------------+ +--------------------------------+
304 . |"id": 1 | |"id": 3 |
305 . | #include "include-chain-1-2.h" | | #include "include-chain-1-1.h" |
306 . | in include-chain-1.h | | in include-chain-1.h |
307 . +--------------------------------+ +--------------------------------+
308 . ^ | ^ |
309 . includes | | included-by includes | | included-by
310 . | V | V
311 . +------------------------------------+
312 . |"id": 4 |
313 . | The #include "include-chain-1.h" |
314 . | in include-chain-1.c |
315 . +------------------------------------+
316 */
317
318 class sarif_location_manager : public sarif_object
319 {
320 public:
321 /* A worklist of pending actions needed to fully process this object.
322
323 This lets us lazily walk our data structures to build the
324 directed graph of locations, whilst keeping "notes" at the top
325 of the "relatedLocations" array, and avoiding the need for
326 recursion. */
327 struct worklist_item
328 {
329 enum class kind
330 {
331 /* Process a #include relationship where m_location_obj
332 was #included-d at m_where. */
333 included_from,
334
335 /* Process a location_t that was added as a secondary location
336 to a rich_location without a label. */
337 unlabelled_secondary_location
338 };
339
340 worklist_item (sarif_location &location_obj,
341 enum kind kind,
342 location_t where)
343 : m_location_obj (location_obj),
344 m_kind (kind),
345 m_where (where)
346 {
347 }
348
349 sarif_location &m_location_obj;
350 enum kind m_kind;
351 location_t m_where;
352 };
353
354 sarif_location_manager ()
355 : m_related_locations_arr (nullptr),
356 m_next_location_id (0)
357 {
358 }
359
360 unsigned allocate_location_id ()
361 {
362 return m_next_location_id++;
363 }
364
365 virtual void
366 add_related_location (std::unique_ptr<sarif_location> location_obj,
367 sarif_builder &builder);
368
369 void
370 add_relationship_to_worklist (sarif_location &location_obj,
371 enum worklist_item::kind kind,
372 location_t where);
373
374 void
375 process_worklist (sarif_builder &builder);
376
377 void
378 process_worklist_item (sarif_builder &builder,
379 const worklist_item &item);
380 private:
381 json::array *m_related_locations_arr; // borrowed
382 unsigned m_next_location_id;
383
384 std::list<worklist_item> m_worklist;
385 std::map<location_t, sarif_location *> m_included_from_locations;
386 std::map<location_t, sarif_location *> m_unlabelled_secondary_locations;
387 };
388
389 /* Subclass of sarif_object for SARIF "result" objects
390 (SARIF v2.1.0 section 3.27).
391 Each SARIF result object has its own "namespace" of numeric IDs for
392 managing location objects (SARIF v2.1.0 section 3.28.2). */
393
394 class sarif_result : public sarif_location_manager
395 {
396 public:
397 sarif_result (unsigned idx_within_parent)
398 : m_idx_within_parent (idx_within_parent)
399 {}
400
401 unsigned get_index_within_parent () const { return m_idx_within_parent; }
402
403 void
404 on_nested_diagnostic (const diagnostic_info &diagnostic,
405 diagnostic_t orig_diag_kind,
406 sarif_builder &builder);
407 void on_diagram (const diagnostic_diagram &diagram,
408 sarif_builder &builder);
409
410 private:
411 const unsigned m_idx_within_parent;
412 };
413
414 /* Subclass of sarif_object for SARIF "location" objects
415 (SARIF v2.1.0 section 3.28).
416 A location object can have an "id" which must be unique within
417 the enclosing result, if any (see SARIF v2.1.0 section 3.28.2). */
418
419 class sarif_location : public sarif_object
420 {
421 public:
422 long lazily_add_id (sarif_location_manager &loc_mgr);
423 long get_id () const;
424
425 void lazily_add_relationship (sarif_location &target,
426 enum location_relationship_kind kind,
427 sarif_location_manager &loc_mgr);
428
429 private:
430 sarif_location_relationship &
431 lazily_add_relationship_object (sarif_location &target,
432 sarif_location_manager &loc_mgr);
433
434 json::array &lazily_add_relationships_array ();
435
436 std::map<sarif_location *,
437 sarif_location_relationship *> m_relationships_map;
438 };
439
440 /* Subclass of sarif_object for SARIF "physicalLocation" objects
441 (SARIF v2.1.0 section 3.29). */
442
443 class sarif_physical_location : public sarif_object {};
444
445 /* Subclass of sarif_object for SARIF "region" objects
446 (SARIF v2.1.0 section 3.30). */
447
448 class sarif_region : public sarif_object {};
449
450 /* Subclass of sarif_object for SARIF "locationRelationship" objects
451 (SARIF v2.1.0 section 3.34). */
452
453 class sarif_location_relationship : public sarif_object
454 {
455 public:
456 sarif_location_relationship (sarif_location &target,
457 sarif_location_manager &loc_mgr);
458
459 long get_target_id () const;
460
461 void lazily_add_kind (enum location_relationship_kind kind);
462
463 private:
464 auto_sbitmap m_kinds;
465 };
466
467 /* Subclass of sarif_object for SARIF "codeFlow" objects
468 (SARIF v2.1.0 section 3.36). */
469
470 class sarif_code_flow : public sarif_object
471 {
472 public:
473 sarif_code_flow (sarif_result &parent,
474 unsigned idx_within_parent);
475
476 sarif_result &get_parent () const { return m_parent; }
477 unsigned get_index_within_parent () const { return m_idx_within_parent; }
478
479 sarif_thread_flow &
480 get_or_append_thread_flow (const diagnostic_thread &thread,
481 diagnostic_thread_id_t thread_id);
482
483 sarif_thread_flow &
484 get_thread_flow (diagnostic_thread_id_t thread_id);
485
486 void add_location (sarif_thread_flow_location &);
487
488 sarif_thread_flow_location &
489 get_thread_flow_loc_obj (diagnostic_event_id_t event_id) const;
490
491 private:
492 sarif_result &m_parent;
493 const unsigned m_idx_within_parent;
494
495 hash_map<int_hash<diagnostic_thread_id_t, -1, -2>,
496 sarif_thread_flow *> m_thread_id_map; // borrowed ptr
497 json::array *m_thread_flows_arr; // borrowed
498
499 /* Vec of borrowed ptr, allowing for going easily from
500 an event_id to the corresponding threadFlowLocation object. */
501 std::vector<sarif_thread_flow_location *> m_all_tfl_objs;
502 };
503
504 /* Subclass of sarif_object for SARIF "threadFlow" objects
505 (SARIF v2.1.0 section 3.37). */
506
507 class sarif_thread_flow : public sarif_object
508 {
509 public:
510 sarif_thread_flow (sarif_code_flow &parent,
511 const diagnostic_thread &thread,
512 unsigned idx_within_parent);
513
514 sarif_code_flow &get_parent () const { return m_parent; }
515 unsigned get_index_within_parent () const { return m_idx_within_parent; }
516
517 sarif_thread_flow_location &add_location ();
518
519 private:
520 sarif_code_flow &m_parent;
521 json::array *m_locations_arr; // borrowed
522 const unsigned m_idx_within_parent;
523 };
524
525 /* Subclass of sarif_object for SARIF "threadFlowLocation" objects
526 (SARIF v2.1.0 section 3.38). */
527
528 class sarif_thread_flow_location : public sarif_object
529 {
530 public:
531 sarif_thread_flow_location (sarif_thread_flow &parent,
532 unsigned idx_within_parent)
533 : m_parent (parent),
534 m_idx_within_parent (idx_within_parent)
535 {
536 }
537
538 sarif_thread_flow &get_parent () const { return m_parent; }
539 unsigned get_index_within_parent () const { return m_idx_within_parent; }
540
541 private:
542 sarif_thread_flow &m_parent;
543 const unsigned m_idx_within_parent;
544 };
545
546 /* Subclass of sarif_object for SARIF "reportingDescriptor" objects
547 (SARIF v2.1.0 section 3.49). */
548
549 class sarif_reporting_descriptor : public sarif_object {};
550
551 /* Subclass of sarif_object for SARIF "reportingDescriptorReference" objects
552 (SARIF v2.1.0 section 3.53). */
553
554 class sarif_reporting_descriptor_reference : public sarif_object {};
555
556 /* Subclass of sarif_object for SARIF "toolComponentReference" objects
557 (SARIF v2.1.0 section 3.54). */
558
559 class sarif_tool_component_reference : public sarif_object {};
560
561 /* Subclass of sarif_object for SARIF "fix" objects
562 (SARIF v2.1.0 section 3.55). */
563
564 class sarif_fix : public sarif_object {};
565
566 /* Subclass of sarif_object for SARIF "artifactChange" objects
567 (SARIF v2.1.0 section 3.56). */
568
569 class sarif_artifact_change : public sarif_object {};
570
571 /* Subclass of sarif_object for SARIF "replacement" objects
572 (SARIF v2.1.0 section 3.57). */
573
574 class sarif_replacement : public sarif_object {};
575
576 /* Subclass of sarif_object for SARIF "notification" objects
577 (SARIF v2.1.0 section 3.58).
578
579 This subclass is specifically for notifying when an
580 internal compiler error occurs. */
581
582 class sarif_ice_notification : public sarif_location_manager
583 {
584 public:
585 sarif_ice_notification (const diagnostic_info &diagnostic,
586 sarif_builder &builder,
587 std::unique_ptr<json::object> backtrace);
588
589 void
590 add_related_location (std::unique_ptr<sarif_location> location_obj,
591 sarif_builder &builder) final override;
592 };
593
594 /* Abstract base class for use when making an "artifactContent"
595 object (SARIF v2.1.0 section 3.3): generate a value for the
596 3.3.4 "rendered" property.
597 Can return nullptr, for "no property". */
598
599 class content_renderer
600 {
601 public:
602 virtual ~content_renderer () {}
603
604 virtual std::unique_ptr<sarif_multiformat_message_string>
605 render (const sarif_builder &builder) const = 0;
606 };
607
608 /* Concrete buffering implementation subclass for JSON output. */
609
610 class diagnostic_sarif_format_buffer : public diagnostic_per_format_buffer
611 {
612 public:
613 friend class sarif_output_format;
614
615 diagnostic_sarif_format_buffer (sarif_builder &builder)
616 : m_builder (builder)
617 {}
618
619 void dump (FILE *out, int indent) const final override;
620 bool empty_p () const final override;
621 void move_to (diagnostic_per_format_buffer &dest) final override;
622 void clear () final override;
623 void flush () final override;
624
625 void add_result (std::unique_ptr<sarif_result> result)
626 {
627 m_results.push_back (std::move (result));
628 }
629
630 size_t num_results () const { return m_results.size (); }
631 sarif_result &get_result (size_t idx) { return *m_results[idx]; }
632
633 private:
634 sarif_builder &m_builder;
635 std::vector<std::unique_ptr<sarif_result>> m_results;
636 };
637
638 /* A class for managing SARIF output (for -fdiagnostics-format=sarif-stderr
639 and -fdiagnostics-format=sarif-file).
640
641 As diagnostics occur, we build "result" JSON objects, and
642 accumulate state:
643 - which source files are referenced
644 - which warnings are emitted
645 - which CWEs are used
646
647 At the end of the compile, we use the above to build the full SARIF
648 object tree, adding the result objects to the correct place, and
649 creating objects for the various source files, warnings and CWEs
650 referenced.
651
652 Implemented:
653 - fix-it hints
654 - CWE metadata
655 - diagnostic groups (see limitations below)
656 - logical locations (e.g. cfun)
657 - labelled ranges (as annotations)
658 - secondary ranges without labels (as related locations)
659
660 Known limitations:
661 - GCC supports nesting of diagnostics (one-deep nesting via
662 auto_diagnostic_group, and arbitrary nesting via
663 auto_diagnostic_nesting_level). These are captured in the SARIF
664 as related locations, and so we only capture location and message
665 information from such nested diagnostics (e.g. we ignore fix-it
666 hints on them). Diagnostics within an auto_diagnostic_nesting_level
667 have their nesting level captured as a property.
668 - although we capture command-line arguments (section 3.20.2), we don't
669 yet capture response files.
670 - doesn't capture "artifact.encoding" property
671 (SARIF v2.1.0 section 3.24.9).
672 - doesn't capture hashes of the source files
673 ("artifact.hashes" property (SARIF v2.1.0 section 3.24.11).
674 - doesn't capture the "analysisTarget" property
675 (SARIF v2.1.0 section 3.27.13).
676 - doesn't capture -Werror cleanly
677 - doesn't capture inlining information (can SARIF handle this?)
678 - doesn't capture macro expansion information (can SARIF handle this?).
679 - doesn't capture any diagnostic_metadata::rules associated with
680 a diagnostic. */
681
682 class sarif_builder
683 {
684 public:
685 friend class diagnostic_sarif_format_buffer;
686
687 sarif_builder (diagnostic_context &context,
688 pretty_printer &printer,
689 const line_maps *line_maps,
690 const char *main_input_filename_,
691 bool formatted,
692 enum sarif_version version);
693 ~sarif_builder ();
694
695 void set_printer (pretty_printer &printer)
696 {
697 m_printer = &printer;
698 }
699
700 void on_report_diagnostic (const diagnostic_info &diagnostic,
701 diagnostic_t orig_diag_kind,
702 diagnostic_sarif_format_buffer *buffer);
703 void emit_diagram (const diagnostic_diagram &diagram);
704 void end_group ();
705
706 std::unique_ptr<sarif_result> take_current_result ()
707 {
708 return std::move (m_cur_group_result);
709 }
710
711 std::unique_ptr<sarif_log> flush_to_object ();
712 void flush_to_file (FILE *outf);
713
714 std::unique_ptr<json::array>
715 make_locations_arr (sarif_location_manager &loc_mgr,
716 const diagnostic_info &diagnostic,
717 enum diagnostic_artifact_role role);
718 std::unique_ptr<sarif_location>
719 make_location_object (sarif_location_manager &loc_mgr,
720 const rich_location &rich_loc,
721 const logical_location *logical_loc,
722 enum diagnostic_artifact_role role);
723 std::unique_ptr<sarif_location>
724 make_location_object (sarif_location_manager &loc_mgr,
725 location_t where,
726 enum diagnostic_artifact_role role);
727 std::unique_ptr<sarif_message>
728 make_message_object (const char *msg) const;
729 std::unique_ptr<sarif_message>
730 make_message_object_for_diagram (const diagnostic_diagram &diagram);
731 std::unique_ptr<sarif_artifact_content>
732 maybe_make_artifact_content_object (const char *filename) const;
733
734 std::unique_ptr<sarif_artifact_location>
735 make_artifact_location_object (const char *filename);
736
737 const sarif_code_flow *
738 get_code_flow_for_event_ids () const
739 {
740 return m_current_code_flow;
741 }
742
743 diagnostic_context &get_context () const { return m_context; }
744 pretty_printer *get_printer () const { return m_printer; }
745 token_printer &get_token_printer () { return m_token_printer; }
746 enum sarif_version get_version () const { return m_version; }
747
748 size_t num_results () const { return m_results_array->size (); }
749 sarif_result &get_result (size_t idx)
750 {
751 auto element = (*m_results_array)[idx];
752 gcc_assert (element);
753 return *static_cast<sarif_result *> (element);
754 }
755
756 private:
757 class sarif_token_printer : public token_printer
758 {
759 public:
760 sarif_token_printer (sarif_builder &builder)
761 : m_builder (builder)
762 {
763 }
764 void print_tokens (pretty_printer *pp,
765 const pp_token_list &tokens) final override;
766 private:
767 sarif_builder &m_builder;
768 };
769
770 std::unique_ptr<sarif_result>
771 make_result_object (const diagnostic_info &diagnostic,
772 diagnostic_t orig_diag_kind,
773 unsigned idx_within_parent);
774 void
775 add_any_include_chain (sarif_location_manager &loc_mgr,
776 sarif_location &location_obj,
777 location_t where);
778 void
779 set_any_logical_locs_arr (sarif_location &location_obj,
780 const logical_location *logical_loc);
781 std::unique_ptr<sarif_location>
782 make_location_object (sarif_location_manager &loc_mgr,
783 const diagnostic_event &event,
784 enum diagnostic_artifact_role role);
785 std::unique_ptr<sarif_code_flow>
786 make_code_flow_object (sarif_result &result,
787 unsigned idx_within_parent,
788 const diagnostic_path &path);
789 void
790 populate_thread_flow_location_object (sarif_result &result,
791 sarif_thread_flow_location &thread_flow_loc_obj,
792 const diagnostic_event &event,
793 int event_execution_idx);
794 std::unique_ptr<json::array>
795 maybe_make_kinds_array (diagnostic_event::meaning m) const;
796 std::unique_ptr<sarif_physical_location>
797 maybe_make_physical_location_object (location_t loc,
798 enum diagnostic_artifact_role role,
799 int column_override,
800 const content_renderer *snippet_renderer);
801 std::unique_ptr<sarif_artifact_location>
802 make_artifact_location_object (location_t loc);
803 std::unique_ptr<sarif_artifact_location>
804 make_artifact_location_object_for_pwd () const;
805 std::unique_ptr<sarif_region>
806 maybe_make_region_object (location_t loc,
807 int column_override) const;
808 std::unique_ptr<sarif_region>
809 maybe_make_region_object_for_context (location_t loc,
810 const content_renderer *snippet_renderer) const;
811 std::unique_ptr<sarif_region>
812 make_region_object_for_hint (const fixit_hint &hint) const;
813 std::unique_ptr<sarif_multiformat_message_string>
814 make_multiformat_message_string (const char *msg) const;
815 std::unique_ptr<sarif_log>
816 make_top_level_object (std::unique_ptr<sarif_invocation> invocation_obj,
817 std::unique_ptr<json::array> results);
818 std::unique_ptr<sarif_run>
819 make_run_object (std::unique_ptr<sarif_invocation> invocation_obj,
820 std::unique_ptr<json::array> results);
821 std::unique_ptr<sarif_tool>
822 make_tool_object ();
823 std::unique_ptr<sarif_tool_component>
824 make_driver_tool_component_object ();
825 std::unique_ptr<json::array> maybe_make_taxonomies_array () const;
826 std::unique_ptr<sarif_tool_component>
827 maybe_make_cwe_taxonomy_object () const;
828 std::unique_ptr<sarif_tool_component_reference>
829 make_tool_component_reference_object_for_cwe () const;
830 std::unique_ptr<sarif_reporting_descriptor>
831 make_reporting_descriptor_object_for_warning (const diagnostic_info &diagnostic,
832 diagnostic_t orig_diag_kind,
833 const char *option_text);
834 std::unique_ptr<sarif_reporting_descriptor>
835 make_reporting_descriptor_object_for_cwe_id (int cwe_id) const;
836 std::unique_ptr<sarif_reporting_descriptor_reference>
837 make_reporting_descriptor_reference_object_for_cwe_id (int cwe_id);
838 sarif_artifact &
839 get_or_create_artifact (const char *filename,
840 enum diagnostic_artifact_role role,
841 bool embed_contents);
842 char *
843 get_source_lines (const char *filename,
844 int start_line,
845 int end_line) const;
846 std::unique_ptr<sarif_artifact_content>
847 maybe_make_artifact_content_object (const char *filename,
848 int start_line,
849 int end_line,
850 const content_renderer *r) const;
851 std::unique_ptr<sarif_fix>
852 make_fix_object (const rich_location &rich_loc);
853 std::unique_ptr<sarif_artifact_change>
854 make_artifact_change_object (const rich_location &richloc);
855 std::unique_ptr<sarif_replacement>
856 make_replacement_object (const fixit_hint &hint) const;
857 std::unique_ptr<sarif_artifact_content>
858 make_artifact_content_object (const char *text) const;
859 int get_sarif_column (expanded_location exploc) const;
860
861 std::unique_ptr<json::object>
862 make_stack_from_backtrace ();
863
864 diagnostic_context &m_context;
865 pretty_printer *m_printer;
866 const line_maps *m_line_maps;
867 sarif_token_printer m_token_printer;
868 enum sarif_version m_version;
869
870 /* The JSON object for the invocation object. */
871 std::unique_ptr<sarif_invocation> m_invocation_obj;
872
873 /* The JSON array of pending diagnostics. */
874 std::unique_ptr<json::array> m_results_array;
875
876 /* The JSON object for the result object (if any) in the current
877 diagnostic group. */
878 std::unique_ptr<sarif_result> m_cur_group_result;
879
880 /* Ideally we'd use std::unique_ptr<sarif_artifact> here, but I had
881 trouble getting this to work when building with GCC 4.8. */
882 ordered_hash_map <nofree_string_hash,
883 sarif_artifact *> m_filename_to_artifact_map;
884
885 bool m_seen_any_relative_paths;
886 hash_set <free_string_hash> m_rule_id_set;
887 std::unique_ptr<json::array> m_rules_arr;
888
889 /* The set of all CWE IDs we've seen, if any. */
890 hash_set <int_hash <int, 0, 1> > m_cwe_id_set;
891
892 int m_tabstop;
893
894 bool m_formatted;
895
896 unsigned m_next_result_idx;
897 sarif_code_flow *m_current_code_flow;
898 };
899
900 /* class sarif_object : public json::object. */
901
902 sarif_property_bag &
903 sarif_object::get_or_create_properties ()
904 {
905 json::value *properties_val = get ("properties");
906 if (properties_val)
907 {
908 if (properties_val->get_kind () == json::JSON_OBJECT)
909 return *static_cast <sarif_property_bag *> (properties_val);
910 }
911
912 sarif_property_bag *bag = new sarif_property_bag ();
913 set ("properties", bag);
914 return *bag;
915 }
916
917 /* class sarif_invocation : public sarif_object. */
918
919 sarif_invocation::sarif_invocation (sarif_builder &builder,
920 const char * const *original_argv)
921 : m_notifications_arr (::make_unique<json::array> ()),
922 m_success (true)
923 {
924 // "arguments" property (SARIF v2.1.0 section 3.20.2)
925 if (original_argv)
926 {
927 auto arguments_arr = ::make_unique<json::array> ();
928 for (size_t i = 0; original_argv[i]; ++i)
929 arguments_arr->append_string (original_argv[i]);
930 set<json::array> ("arguments", std::move (arguments_arr));
931 }
932
933 // "workingDirectory" property (SARIF v2.1.0 section 3.20.19)
934 if (const char *pwd = getpwd ())
935 set<sarif_artifact_location> ("workingDirectory",
936 builder.make_artifact_location_object (pwd));
937
938 // "startTimeUtc" property (SARIF v2.1.0 section 3.20.7)
939 set<json::string> ("startTimeUtc",
940 make_date_time_string_for_current_time ());
941 }
942
943 /* Handle an internal compiler error DIAGNOSTIC.
944 Add an object representing the ICE to the notifications array. */
945
946 void
947 sarif_invocation::add_notification_for_ice (const diagnostic_info &diagnostic,
948 sarif_builder &builder,
949 std::unique_ptr<json::object> backtrace)
950 {
951 m_success = false;
952
953 auto notification
954 = ::make_unique<sarif_ice_notification> (diagnostic,
955 builder,
956 std::move (backtrace));
957
958 /* Support for related locations within a notification was added
959 in SARIF 2.2; see https://github.com/oasis-tcs/sarif-spec/issues/540 */
960 if (builder.get_version () >= sarif_version::v2_2_prerelease_2024_08_08)
961 notification->process_worklist (builder);
962
963 m_notifications_arr->append<sarif_ice_notification>
964 (std::move (notification));
965 }
966
967 void
968 sarif_invocation::prepare_to_flush (sarif_builder &builder)
969 {
970 const diagnostic_context &context = builder.get_context ();
971
972 /* "executionSuccessful" property (SARIF v2.1.0 section 3.20.14). */
973 if (context.execution_failed_p ())
974 m_success = false;
975 set_bool ("executionSuccessful", m_success);
976
977 /* "toolExecutionNotifications" property (SARIF v2.1.0 section 3.20.21). */
978 set ("toolExecutionNotifications", std::move (m_notifications_arr));
979
980 /* Call client hook, allowing it to create a custom property bag for
981 this object (SARIF v2.1.0 section 3.8) e.g. for recording time vars. */
982 if (auto client_data_hooks = context.get_client_data_hooks ())
983 client_data_hooks->add_sarif_invocation_properties (*this);
984
985 // "endTimeUtc" property (SARIF v2.1.0 section 3.20.8);
986 set<json::string> ("endTimeUtc",
987 make_date_time_string_for_current_time ());
988 }
989
990 /* class sarif_artifact : public sarif_object. */
991
992 /* Add ROLE to this artifact's roles.
993 If EMBED_CONTENTS is true, then flag that we will attempt to embed the
994 contents of this artifact when writing it out. */
995
996 void
997 sarif_artifact::add_role (enum diagnostic_artifact_role role,
998 bool embed_contents)
999 {
1000 /* TODO(SARIF 2.2): "scannedFile" is to be added as a role in SARIF 2.2;
1001 see https://github.com/oasis-tcs/sarif-spec/issues/459
1002
1003 For now, skip them.
1004 Ultimately, we probably shouldn't bother embedding the contents
1005 of such artifacts, just the snippets. */
1006 if (role == diagnostic_artifact_role::scanned_file)
1007 return;
1008
1009 if (embed_contents)
1010 m_embed_contents = true;
1011
1012 /* In SARIF v2.1.0 section 3.24.6 "roles" property:
1013 "resultFile" is for an artifact
1014 "which the analysis tool was not explicitly instructed to scan",
1015 whereas "analysisTarget" is for one where the
1016 "analysis tool was instructed to scan this artifact".
1017 Hence the latter excludes the former. */
1018 if (role == diagnostic_artifact_role::result_file)
1019 if (bitmap_bit_p (m_roles, (int)diagnostic_artifact_role::analysis_target))
1020 return;
1021
1022 bitmap_set_bit (m_roles, (int)role);
1023 }
1024
1025 /* Populate the "contents" property (SARIF v2.1.0 section 3.24.8).
1026 We do this after initialization to
1027 (a) ensure that any charset options have been set
1028 (b) only populate it for artifacts that are referenced by a location. */
1029
1030 void
1031 sarif_artifact::populate_contents (sarif_builder &builder)
1032 {
1033 if (auto artifact_content_obj
1034 = builder.maybe_make_artifact_content_object (m_filename))
1035 set<sarif_artifact_content> ("contents", std::move (artifact_content_obj));
1036 }
1037
1038 /* Get a string for ROLE corresponding to the
1039 SARIF v2.1.0 section 3.24.6 "roles" property. */
1040
1041 static const char *
1042 get_artifact_role_string (enum diagnostic_artifact_role role)
1043 {
1044 switch (role)
1045 {
1046 default:
1047 gcc_unreachable ();
1048 case diagnostic_artifact_role::analysis_target:
1049 return "analysisTarget";
1050 case diagnostic_artifact_role::debug_output_file:
1051 return "debugOutputFile";
1052 case diagnostic_artifact_role::result_file:
1053 return "resultFile";
1054 case diagnostic_artifact_role::scanned_file:
1055 return "scannedFile";
1056 case diagnostic_artifact_role::traced_file:
1057 return "tracedFile";
1058 }
1059 }
1060
1061 /* Populate the "roles" property of this sarif_artifact with a new
1062 json::array for the artifact.roles property (SARIF v2.1.0 section 3.24.6)
1063 containing strings such as "analysisTarget", "resultFile"
1064 and/or "tracedFile". */
1065
1066 void
1067 sarif_artifact::populate_roles ()
1068 {
1069 if (bitmap_empty_p (m_roles))
1070 return;
1071 auto roles_arr (::make_unique<json::array> ());
1072 for (int i = 0; i < (int)diagnostic_artifact_role::NUM_ROLES; i++)
1073 if (bitmap_bit_p (m_roles, i))
1074 {
1075 enum diagnostic_artifact_role role = (enum diagnostic_artifact_role)i;
1076 roles_arr->append_string (get_artifact_role_string (role));
1077 }
1078 set<json::array> ("roles", std::move (roles_arr));
1079 }
1080
1081 /* class sarif_location_manager : public sarif_object. */
1082
1083 /* Base implementation of sarif_location_manager::add_related_location vfunc.
1084
1085 Add LOCATION_OBJ to this object's "relatedLocations" array,
1086 creating it if it doesn't yet exist. */
1087
1088 void
1089 sarif_location_manager::
1090 add_related_location (std::unique_ptr<sarif_location> location_obj,
1091 sarif_builder &)
1092 {
1093 if (!m_related_locations_arr)
1094 {
1095 m_related_locations_arr = new json::array ();
1096 /* Give ownership of m_related_locations_arr to json::object;
1097 keep a borrowed ptr. */
1098 set ("relatedLocations", m_related_locations_arr);
1099 }
1100 m_related_locations_arr->append (std::move (location_obj));
1101 }
1102
1103 void
1104 sarif_location_manager::
1105 add_relationship_to_worklist (sarif_location &location_obj,
1106 enum worklist_item::kind kind,
1107 location_t where)
1108 {
1109 m_worklist.push_back (worklist_item (location_obj,
1110 kind,
1111 where));
1112 }
1113
1114 /* Process all items in this result's worklist.
1115 Doing so may temporarily add new items to the end
1116 of the worklist.
1117 Handling any item should be "lazy", and thus we should
1118 eventually drain the queue and terminate. */
1119
1120 void
1121 sarif_location_manager::process_worklist (sarif_builder &builder)
1122 {
1123 while (!m_worklist.empty ())
1124 {
1125 const worklist_item &item = m_worklist.front ();
1126 process_worklist_item (builder, item);
1127 m_worklist.pop_front ();
1128 }
1129 }
1130
1131 /* Process one item in this result's worklist, potentially
1132 adding new items to the end of the worklist. */
1133
1134 void
1135 sarif_location_manager::process_worklist_item (sarif_builder &builder,
1136 const worklist_item &item)
1137 {
1138 switch (item.m_kind)
1139 {
1140 default:
1141 gcc_unreachable ();
1142 case worklist_item::kind::included_from:
1143 {
1144 sarif_location &included_loc_obj = item.m_location_obj;
1145 sarif_location *includer_loc_obj = nullptr;
1146 auto iter = m_included_from_locations.find (item.m_where);
1147 if (iter != m_included_from_locations.end ())
1148 includer_loc_obj = iter->second;
1149 else
1150 {
1151 std::unique_ptr<sarif_location> new_loc_obj
1152 = builder.make_location_object
1153 (*this,
1154 item.m_where,
1155 diagnostic_artifact_role::scanned_file);
1156 includer_loc_obj = new_loc_obj.get ();
1157 add_related_location (std::move (new_loc_obj), builder);
1158 auto kv
1159 = std::pair<location_t, sarif_location *> (item.m_where,
1160 includer_loc_obj);
1161 m_included_from_locations.insert (kv);
1162 }
1163
1164 includer_loc_obj->lazily_add_relationship
1165 (included_loc_obj,
1166 location_relationship_kind::includes,
1167 *this);
1168 included_loc_obj.lazily_add_relationship
1169 (*includer_loc_obj,
1170 location_relationship_kind::is_included_by,
1171 *this);
1172 }
1173 break;
1174 case worklist_item::kind::unlabelled_secondary_location:
1175 {
1176 sarif_location &primary_loc_obj = item.m_location_obj;
1177 sarif_location *secondary_loc_obj = nullptr;
1178 auto iter = m_unlabelled_secondary_locations.find (item.m_where);
1179 if (iter != m_unlabelled_secondary_locations.end ())
1180 secondary_loc_obj = iter->second;
1181 else
1182 {
1183 std::unique_ptr<sarif_location> new_loc_obj
1184 = builder.make_location_object
1185 (*this,
1186 item.m_where,
1187 diagnostic_artifact_role::scanned_file);
1188 secondary_loc_obj = new_loc_obj.get ();
1189 add_related_location (std::move (new_loc_obj), builder);
1190 auto kv
1191 = std::pair<location_t, sarif_location *> (item.m_where,
1192 secondary_loc_obj);
1193 m_unlabelled_secondary_locations.insert (kv);
1194 }
1195 gcc_assert (secondary_loc_obj);
1196 primary_loc_obj.lazily_add_relationship
1197 (*secondary_loc_obj,
1198 location_relationship_kind::relevant,
1199 *this);
1200 }
1201 break;
1202 }
1203 }
1204
1205 /* class sarif_result : public sarif_location_manager. */
1206
1207 /* Handle secondary diagnostics that occur within a diagnostic group.
1208 The closest SARIF seems to have to nested diagnostics is the
1209 "relatedLocations" property of result objects (SARIF v2.1.0 section 3.27.22),
1210 so we lazily set this property and populate the array if and when
1211 secondary diagnostics occur (such as notes to a warning). */
1212
1213 void
1214 sarif_result::on_nested_diagnostic (const diagnostic_info &diagnostic,
1215 diagnostic_t /*orig_diag_kind*/,
1216 sarif_builder &builder)
1217 {
1218 /* We don't yet generate meaningful logical locations for notes;
1219 sometimes these will related to current_function_decl, but
1220 often they won't. */
1221 auto location_obj
1222 = builder.make_location_object (*this, *diagnostic.richloc, nullptr,
1223 diagnostic_artifact_role::result_file);
1224 auto message_obj
1225 = builder.make_message_object (pp_formatted_text (builder.get_printer ()));
1226 pp_clear_output_area (builder.get_printer ());
1227 location_obj->set<sarif_message> ("message", std::move (message_obj));
1228
1229 /* Add nesting level, as per "P3358R0 SARIF for Structured Diagnostics"
1230 https://wg21.link/P3358R0 */
1231 sarif_property_bag &bag = location_obj->get_or_create_properties ();
1232 bag.set_integer ("nestingLevel",
1233 builder.get_context ().get_diagnostic_nesting_level ());
1234
1235 add_related_location (std::move (location_obj), builder);
1236 }
1237
1238 /* Handle diagrams that occur within a diagnostic group.
1239 The closest thing in SARIF seems to be to add a location to the
1240 "releatedLocations" property (SARIF v2.1.0 section 3.27.22),
1241 and to put the diagram into the "message" property of that location
1242 (SARIF v2.1.0 section 3.28.5). */
1243
1244 void
1245 sarif_result::on_diagram (const diagnostic_diagram &diagram,
1246 sarif_builder &builder)
1247 {
1248 auto location_obj = ::make_unique<sarif_location> ();
1249 auto message_obj = builder.make_message_object_for_diagram (diagram);
1250 location_obj->set<sarif_message> ("message", std::move (message_obj));
1251
1252 add_related_location (std::move (location_obj), builder);
1253 }
1254
1255 /* class sarif_location : public sarif_object. */
1256
1257 /* Ensure this location has an "id" and return it.
1258 Use LOC_MGR if an id needs to be allocated.
1259
1260 See the "id" property (3.28.2).
1261
1262 We use this to only assign ids to locations that are
1263 referenced by another sarif object; others have no "id". */
1264
1265 long
1266 sarif_location::lazily_add_id (sarif_location_manager &loc_mgr)
1267 {
1268 long id = get_id ();
1269 if (id != -1)
1270 return id;
1271 id = loc_mgr.allocate_location_id ();
1272 set_integer ("id", id);
1273 gcc_assert (id != -1);
1274 return id;
1275 }
1276
1277 /* Get the id of this location, or -1 if it doesn't have one. */
1278
1279 long
1280 sarif_location::get_id () const
1281 {
1282 json::value *id = get ("id");
1283 if (!id)
1284 return -1;
1285 gcc_assert (id->get_kind () == json::JSON_INTEGER);
1286 return static_cast <json::integer_number *> (id)->get ();
1287 }
1288
1289 // 3.34.3 kinds property
1290 static const char *
1291 get_string_for_location_relationship_kind (enum location_relationship_kind kind)
1292 {
1293 switch (kind)
1294 {
1295 default:
1296 gcc_unreachable ();
1297 case location_relationship_kind::includes:
1298 return "includes";
1299 case location_relationship_kind::is_included_by:
1300 return "isIncludedBy";
1301 case location_relationship_kind::relevant:
1302 return "relevant";
1303 }
1304 }
1305
1306 /* Lazily populate this location's "relationships" property (3.28.7)
1307 with the relationship of KIND to TARGET, creating objects
1308 as necessary.
1309 Use LOC_MGR for any locations that need "id" values. */
1310
1311 void
1312 sarif_location::lazily_add_relationship (sarif_location &target,
1313 enum location_relationship_kind kind,
1314 sarif_location_manager &loc_mgr)
1315 {
1316 sarif_location_relationship &relationship_obj
1317 = lazily_add_relationship_object (target, loc_mgr);
1318
1319 relationship_obj.lazily_add_kind (kind);
1320 }
1321
1322 /* Lazily populate this location's "relationships" property (3.28.7)
1323 with a location_relationship to TARGET, creating objects
1324 as necessary.
1325 Use LOC_MGR for any locations that need "id" values. */
1326
1327 sarif_location_relationship &
1328 sarif_location::lazily_add_relationship_object (sarif_location &target,
1329 sarif_location_manager &loc_mgr)
1330 {
1331 /* See if THIS already has a locationRelationship referencing TARGET. */
1332 auto iter = m_relationships_map.find (&target);
1333 if (iter != m_relationships_map.end ())
1334 {
1335 /* We already have a locationRelationship from THIS to TARGET. */
1336 sarif_location_relationship *relationship = iter->second;
1337 gcc_assert (relationship->get_target_id() == target.get_id ());
1338 return *relationship;
1339 }
1340
1341 // Ensure that THIS has a "relationships" property (3.28.7).
1342 json::array &relationships_arr = lazily_add_relationships_array ();
1343
1344 /* No existing locationRelationship from THIS to TARGET; make one,
1345 record it, and add it to the "relationships" array. */
1346 auto relationship_obj
1347 = ::make_unique<sarif_location_relationship> (target, loc_mgr);
1348 sarif_location_relationship *relationship = relationship_obj.get ();
1349 auto kv
1350 = std::pair<sarif_location *,
1351 sarif_location_relationship *> (&target, relationship);
1352 m_relationships_map.insert (kv);
1353
1354 relationships_arr.append (std::move (relationship_obj));
1355
1356 return *relationship;
1357 }
1358
1359 /* Ensure this location has a "relationships" array (3.28.7). */
1360
1361 json::array &
1362 sarif_location::lazily_add_relationships_array ()
1363 {
1364 const char *const property_name = "relationships";
1365 if (json::value *relationships = get (property_name))
1366 {
1367 gcc_assert (relationships->get_kind () == json::JSON_ARRAY);
1368 return *static_cast <json::array *> (relationships);
1369 }
1370 json::array *relationships_arr = new json::array ();
1371 set (property_name, relationships_arr);
1372 return *relationships_arr;
1373 }
1374
1375 /* class sarif_ice_notification : public sarif_location_manager. */
1376
1377 /* sarif_ice_notification's ctor.
1378 DIAGNOSTIC is an internal compiler error. */
1379
1380 sarif_ice_notification::
1381 sarif_ice_notification (const diagnostic_info &diagnostic,
1382 sarif_builder &builder,
1383 std::unique_ptr<json::object> backtrace)
1384 {
1385 /* "locations" property (SARIF v2.1.0 section 3.58.4). */
1386 auto locations_arr
1387 = builder.make_locations_arr (*this,
1388 diagnostic,
1389 diagnostic_artifact_role::result_file);
1390 set<json::array> ("locations", std::move (locations_arr));
1391
1392 /* "message" property (SARIF v2.1.0 section 3.85.5). */
1393 auto message_obj
1394 = builder.make_message_object (pp_formatted_text (builder.get_printer ()));
1395 pp_clear_output_area (builder.get_printer ());
1396 set<sarif_message> ("message", std::move (message_obj));
1397
1398 /* "level" property (SARIF v2.1.0 section 3.58.6). */
1399 set_string ("level", "error");
1400
1401 /* If we have backtrace information, add it as part of a property bag. */
1402 if (backtrace)
1403 {
1404 sarif_property_bag &bag = get_or_create_properties ();
1405 bag.set ("gcc/backtrace", std::move (backtrace));
1406 }
1407 }
1408
1409 /* Implementation of sarif_location_manager::add_related_location vfunc
1410 for notifications. */
1411
1412 void
1413 sarif_ice_notification::
1414 add_related_location (std::unique_ptr<sarif_location> location_obj,
1415 sarif_builder &builder)
1416 {
1417 /* Support for related locations within a notification was added
1418 in SARIF 2.2; see https://github.com/oasis-tcs/sarif-spec/issues/540 */
1419 if (builder.get_version () >= sarif_version::v2_2_prerelease_2024_08_08)
1420 sarif_location_manager::add_related_location (std::move (location_obj),
1421 builder);
1422 /* Otherwise implicitly discard LOCATION_OBJ. */
1423 }
1424
1425 /* class sarif_location_relationship : public sarif_object. */
1426
1427 sarif_location_relationship::
1428 sarif_location_relationship (sarif_location &target,
1429 sarif_location_manager &loc_mgr)
1430 : m_kinds ((unsigned)location_relationship_kind::NUM_KINDS)
1431 {
1432 bitmap_clear (m_kinds);
1433 set_integer ("target", target.lazily_add_id (loc_mgr));
1434 }
1435
1436 long
1437 sarif_location_relationship::get_target_id () const
1438 {
1439 json::value *id = get ("id");
1440 gcc_assert (id);
1441 return static_cast <json::integer_number *> (id)->get ();
1442 }
1443
1444 void
1445 sarif_location_relationship::
1446 lazily_add_kind (enum location_relationship_kind kind)
1447 {
1448 if (bitmap_bit_p (m_kinds, (int)kind))
1449 return; // already have this kind
1450 bitmap_set_bit (m_kinds, (int)kind);
1451
1452 // 3.34.3 kinds property
1453 json::array *kinds_arr = nullptr;
1454 if (json::value *kinds_val = get ("kinds"))
1455 {
1456 gcc_assert (kinds_val->get_kind () == json::JSON_ARRAY);
1457 }
1458 else
1459 {
1460 kinds_arr = new json::array ();
1461 set ("kinds", kinds_arr);
1462 }
1463 const char *kind_str = get_string_for_location_relationship_kind (kind);
1464 kinds_arr->append_string (kind_str);
1465 }
1466
1467 /* class sarif_code_flow : public sarif_object. */
1468
1469 sarif_code_flow::sarif_code_flow (sarif_result &parent,
1470 unsigned idx_within_parent)
1471 : m_parent (parent),
1472 m_idx_within_parent (idx_within_parent)
1473 {
1474 /* "threadFlows" property (SARIF v2.1.0 section 3.36.3). */
1475 auto thread_flows_arr = ::make_unique<json::array> ();
1476 m_thread_flows_arr = thread_flows_arr.get (); // borrowed
1477 set<json::array> ("threadFlows", std::move (thread_flows_arr));
1478 }
1479
1480 sarif_thread_flow &
1481 sarif_code_flow::get_or_append_thread_flow (const diagnostic_thread &thread,
1482 diagnostic_thread_id_t thread_id)
1483 {
1484 sarif_thread_flow **slot = m_thread_id_map.get (thread_id);
1485 if (slot)
1486 return **slot;
1487
1488 unsigned next_thread_flow_idx = m_thread_flows_arr->size ();
1489 auto thread_flow_obj
1490 = ::make_unique<sarif_thread_flow> (*this, thread, next_thread_flow_idx);
1491 m_thread_id_map.put (thread_id, thread_flow_obj.get ()); // borrowed
1492 sarif_thread_flow *result = thread_flow_obj.get ();
1493 m_thread_flows_arr->append<sarif_thread_flow> (std::move (thread_flow_obj));
1494 return *result;
1495 }
1496
1497 sarif_thread_flow &
1498 sarif_code_flow::get_thread_flow (diagnostic_thread_id_t thread_id)
1499 {
1500 sarif_thread_flow **slot = m_thread_id_map.get (thread_id);
1501 gcc_assert (slot); // it must already have one
1502 return **slot;
1503 }
1504
1505 void
1506 sarif_code_flow::add_location (sarif_thread_flow_location &tfl_obj)
1507 {
1508 m_all_tfl_objs.push_back (&tfl_obj);
1509 }
1510
1511 sarif_thread_flow_location &
1512 sarif_code_flow::get_thread_flow_loc_obj (diagnostic_event_id_t event_id) const
1513 {
1514 gcc_assert (event_id.known_p ());
1515 gcc_assert ((size_t)event_id.zero_based () < m_all_tfl_objs.size ());
1516 sarif_thread_flow_location *tfl_obj = m_all_tfl_objs[event_id.zero_based ()];
1517 gcc_assert (tfl_obj);
1518 return *tfl_obj;
1519 }
1520
1521 /* class sarif_thread_flow : public sarif_object. */
1522
1523 sarif_thread_flow::sarif_thread_flow (sarif_code_flow &parent,
1524 const diagnostic_thread &thread,
1525 unsigned idx_within_parent)
1526 : m_parent (parent),
1527 m_idx_within_parent (idx_within_parent)
1528 {
1529 /* "id" property (SARIF v2.1.0 section 3.37.2). */
1530 label_text name (thread.get_name (false));
1531 set_string ("id", name.get ());
1532
1533 /* "locations" property (SARIF v2.1.0 section 3.37.6). */
1534 m_locations_arr = new json::array ();
1535
1536 /* Give ownership of m_locations_arr to json::object;
1537 keep a borrowed ptr. */
1538 set ("locations", m_locations_arr);
1539 }
1540
1541 /* Add a sarif_thread_flow_location to this threadFlow object, but
1542 don't populate it yet. */
1543
1544 sarif_thread_flow_location &
1545 sarif_thread_flow::add_location ()
1546 {
1547 const unsigned thread_flow_location_idx = m_locations_arr->size ();
1548 sarif_thread_flow_location *thread_flow_loc_obj
1549 = new sarif_thread_flow_location (*this, thread_flow_location_idx);
1550 m_locations_arr->append (thread_flow_loc_obj);
1551 m_parent.add_location (*thread_flow_loc_obj);
1552 return *thread_flow_loc_obj;
1553 }
1554
1555 /* class sarif_builder. */
1556
1557 /* sarif_builder's ctor. */
1558
1559 sarif_builder::sarif_builder (diagnostic_context &context,
1560 pretty_printer &printer,
1561 const line_maps *line_maps,
1562 const char *main_input_filename_,
1563 bool formatted,
1564 enum sarif_version version)
1565 : m_context (context),
1566 m_printer (&printer),
1567 m_line_maps (line_maps),
1568 m_token_printer (*this),
1569 m_version (version),
1570 m_invocation_obj
1571 (::make_unique<sarif_invocation> (*this,
1572 context.get_original_argv ())),
1573 m_results_array (new json::array ()),
1574 m_cur_group_result (nullptr),
1575 m_seen_any_relative_paths (false),
1576 m_rule_id_set (),
1577 m_rules_arr (new json::array ()),
1578 m_tabstop (context.m_tabstop),
1579 m_formatted (formatted),
1580 m_next_result_idx (0),
1581 m_current_code_flow (nullptr)
1582 {
1583 gcc_assert (m_line_maps);
1584
1585 /* Mark MAIN_INPUT_FILENAME_ as the artifact that the tool was
1586 instructed to scan.
1587 Only quote the contents if it gets referenced by physical locations,
1588 since otherwise the "no diagnostics" case would quote the main input
1589 file, and doing so noticeably bloated the output seen in analyzer
1590 integration testing (build directory went from 20G -> 21G). */
1591 if (main_input_filename_)
1592 get_or_create_artifact (main_input_filename_,
1593 diagnostic_artifact_role::analysis_target,
1594 false);
1595 }
1596
1597 sarif_builder::~sarif_builder ()
1598 {
1599 /* Normally m_filename_to_artifact_map will have been emptied as part
1600 of make_run_object, but this isn't run by all the selftests.
1601 Ensure the artifact objects are cleaned up for such cases. */
1602 for (auto iter : m_filename_to_artifact_map)
1603 {
1604 sarif_artifact *artifact_obj = iter.second;
1605 delete artifact_obj;
1606 }
1607 }
1608
1609 /* Functions at which to stop the backtrace print. It's not
1610 particularly helpful to print the callers of these functions. */
1611
1612 static const char * const bt_stop[] =
1613 {
1614 "main",
1615 "toplev::main",
1616 "execute_one_pass",
1617 "compile_file",
1618 };
1619
1620 struct bt_closure
1621 {
1622 bt_closure (sarif_builder &builder,
1623 json::array *frames_arr)
1624 : m_builder (builder),
1625 m_frames_arr (frames_arr)
1626 {
1627 }
1628
1629 sarif_builder &m_builder;
1630 json::array *m_frames_arr;
1631 };
1632
1633 /* A callback function passed to the backtrace_full function. */
1634
1635 static int
1636 bt_callback (void *data, uintptr_t pc, const char *filename, int lineno,
1637 const char *function)
1638 {
1639 bt_closure *closure = (bt_closure *)data;
1640
1641 /* If we don't have any useful information, don't print
1642 anything. */
1643 if (filename == NULL && function == NULL)
1644 return 0;
1645
1646 /* Skip functions in diagnostic.cc or diagnostic-global-context.cc. */
1647 if (closure->m_frames_arr->size () == 0
1648 && filename != NULL
1649 && (strcmp (lbasename (filename), "diagnostic.cc") == 0
1650 || strcmp (lbasename (filename),
1651 "diagnostic-global-context.cc") == 0))
1652 return 0;
1653
1654 /* Print up to 20 functions. We could make this a --param, but
1655 since this is only for debugging just use a constant for now. */
1656 if (closure->m_frames_arr->size () >= 20)
1657 {
1658 /* Returning a non-zero value stops the backtrace. */
1659 return 1;
1660 }
1661
1662 char *alc = NULL;
1663 if (function != NULL)
1664 {
1665 char *str = cplus_demangle_v3 (function,
1666 (DMGL_VERBOSE | DMGL_ANSI
1667 | DMGL_GNU_V3 | DMGL_PARAMS));
1668 if (str != NULL)
1669 {
1670 alc = str;
1671 function = str;
1672 }
1673
1674 for (size_t i = 0; i < ARRAY_SIZE (bt_stop); ++i)
1675 {
1676 size_t len = strlen (bt_stop[i]);
1677 if (strncmp (function, bt_stop[i], len) == 0
1678 && (function[len] == '\0' || function[len] == '('))
1679 {
1680 if (alc != NULL)
1681 free (alc);
1682 /* Returning a non-zero value stops the backtrace. */
1683 return 1;
1684 }
1685 }
1686 }
1687
1688 auto frame_obj = ::make_unique<json::object> ();
1689
1690 /* I tried using sarifStack and sarifStackFrame for this
1691 but it's not a good fit e.g. PC information. */
1692 char buf[128];
1693 snprintf (buf, sizeof (buf) - 1, "0x%lx", (unsigned long)pc);
1694 frame_obj->set_string ("pc", buf);
1695 if (function)
1696 frame_obj->set_string ("function", function);
1697 if (filename)
1698 frame_obj->set_string ("filename", filename);
1699 frame_obj->set_integer ("lineno", lineno);
1700 closure->m_frames_arr->append (std::move (frame_obj));
1701
1702 if (alc != NULL)
1703 free (alc);
1704
1705 return 0;
1706 }
1707
1708 /* Attempt to generate a JSON object representing a backtrace,
1709 for adding to ICE notifications. */
1710
1711 std::unique_ptr<json::object>
1712 sarif_builder::make_stack_from_backtrace ()
1713 {
1714 auto frames_arr = ::make_unique<json::array> ();
1715
1716 backtrace_state *state = nullptr;
1717 state = backtrace_create_state (nullptr, 0, nullptr, nullptr);
1718 bt_closure closure (*this, frames_arr.get ());
1719 const int frames_to_skip = 5;
1720 if (state != nullptr)
1721 backtrace_full (state, frames_to_skip, bt_callback, nullptr,
1722 (void *) &closure);
1723
1724 if (frames_arr->size () == 0)
1725 return nullptr;
1726
1727 auto stack = ::make_unique<json::object> ();
1728 stack->set ("frames", std::move (frames_arr));
1729 return stack;
1730 }
1731
1732 /* Implementation of "on_report_diagnostic" for SARIF output. */
1733
1734 void
1735 sarif_builder::on_report_diagnostic (const diagnostic_info &diagnostic,
1736 diagnostic_t orig_diag_kind,
1737 diagnostic_sarif_format_buffer *buffer)
1738 {
1739 pp_output_formatted_text (m_printer, m_context.get_urlifier ());
1740
1741 if (diagnostic.kind == DK_ICE || diagnostic.kind == DK_ICE_NOBT)
1742 {
1743 std::unique_ptr<json::object> stack = make_stack_from_backtrace ();
1744 m_invocation_obj->add_notification_for_ice (diagnostic, *this,
1745 std::move (stack));
1746
1747 /* Print a header for the remaining output to stderr, and
1748 return, attempting to print the usual ICE messages to
1749 stderr. Hopefully this will be helpful to the user in
1750 indicating what's gone wrong (also for DejaGnu, for pruning
1751 those messages). */
1752 fnotice (stderr, "Internal compiler error:\n");
1753
1754 return;
1755 }
1756
1757 if (buffer)
1758 {
1759 /* When buffering, we can only handle top-level results. */
1760 gcc_assert (!m_cur_group_result);
1761 buffer->add_result (make_result_object (diagnostic, orig_diag_kind,
1762 m_next_result_idx++));
1763 return;
1764 }
1765
1766 if (m_cur_group_result)
1767 /* Nested diagnostic. */
1768 m_cur_group_result->on_nested_diagnostic (diagnostic,
1769 orig_diag_kind,
1770 *this);
1771 else
1772 {
1773 /* Top-level diagnostic. */
1774 m_cur_group_result = make_result_object (diagnostic, orig_diag_kind,
1775 m_next_result_idx++);
1776 }
1777 }
1778
1779 /* Implementation of diagnostic_context::m_diagrams.m_emission_cb
1780 for SARIF output. */
1781
1782 void
1783 sarif_builder::emit_diagram (const diagnostic_diagram &diagram)
1784 {
1785 /* We must be within the emission of a top-level diagnostic. */
1786 gcc_assert (m_cur_group_result);
1787 m_cur_group_result->on_diagram (diagram, *this);
1788 }
1789
1790 /* Implementation of "end_group_cb" for SARIF output. */
1791
1792 void
1793 sarif_builder::end_group ()
1794 {
1795 if (m_cur_group_result)
1796 {
1797 m_cur_group_result->process_worklist (*this);
1798 m_results_array->append<sarif_result> (std::move (m_cur_group_result));
1799 }
1800 }
1801
1802 /* Create a top-level object, and add it to all the results
1803 (and other entities) we've seen so far, moving ownership
1804 to the object. */
1805
1806 std::unique_ptr<sarif_log>
1807 sarif_builder::flush_to_object ()
1808 {
1809 m_invocation_obj->prepare_to_flush (*this);
1810 std::unique_ptr<sarif_log> top
1811 = make_top_level_object (std::move (m_invocation_obj),
1812 std::move (m_results_array));
1813 return top;
1814 }
1815
1816 /* Create a top-level object, and add it to all the results
1817 (and other entities) we've seen so far.
1818
1819 Flush it all to OUTF. */
1820
1821 void
1822 sarif_builder::flush_to_file (FILE *outf)
1823 {
1824 std::unique_ptr<sarif_log> top = flush_to_object ();
1825 top->dump (outf, m_formatted);
1826 fprintf (outf, "\n");
1827 }
1828
1829 /* Attempt to convert DIAG_KIND to a suitable value for the "level"
1830 property (SARIF v2.1.0 section 3.27.10).
1831
1832 Return nullptr if there isn't one. */
1833
1834 static const char *
1835 maybe_get_sarif_level (diagnostic_t diag_kind)
1836 {
1837 switch (diag_kind)
1838 {
1839 case DK_WARNING:
1840 return "warning";
1841 case DK_FATAL:
1842 case DK_ERROR:
1843 return "error";
1844 case DK_NOTE:
1845 case DK_ANACHRONISM:
1846 return "note";
1847 default:
1848 return nullptr;
1849 }
1850 }
1851
1852 /* Make a string for DIAG_KIND suitable for use a ruleId
1853 (SARIF v2.1.0 section 3.27.5) as a fallback for when we don't
1854 have anything better to use. */
1855
1856 static char *
1857 make_rule_id_for_diagnostic_kind (diagnostic_t diag_kind)
1858 {
1859 /* Lose the trailing ": ". */
1860 const char *kind_text = get_diagnostic_kind_text (diag_kind);
1861 size_t len = strlen (kind_text);
1862 gcc_assert (len > 2);
1863 gcc_assert (kind_text[len - 2] == ':');
1864 gcc_assert (kind_text[len - 1] == ' ');
1865 char *rstrip = xstrdup (kind_text);
1866 rstrip[len - 2] = '\0';
1867 return rstrip;
1868 }
1869
1870 /* Make a "result" object (SARIF v2.1.0 section 3.27) for DIAGNOSTIC. */
1871
1872 std::unique_ptr<sarif_result>
1873 sarif_builder::make_result_object (const diagnostic_info &diagnostic,
1874 diagnostic_t orig_diag_kind,
1875 unsigned idx_within_parent)
1876 {
1877 auto result_obj = ::make_unique<sarif_result> (idx_within_parent);
1878
1879 /* "ruleId" property (SARIF v2.1.0 section 3.27.5). */
1880 /* Ideally we'd have an option_name for these. */
1881 if (char *option_text
1882 = m_context.make_option_name (diagnostic.option_id,
1883 orig_diag_kind, diagnostic.kind))
1884 {
1885 /* Lazily create reportingDescriptor objects for and add to m_rules_arr.
1886 Set ruleId referencing them. */
1887 result_obj->set_string ("ruleId", option_text);
1888 if (m_rule_id_set.contains (option_text))
1889 free (option_text);
1890 else
1891 {
1892 /* This is the first time we've seen this ruleId. */
1893 /* Add to set, taking ownership. */
1894 m_rule_id_set.add (option_text);
1895
1896 m_rules_arr->append<sarif_reporting_descriptor>
1897 (make_reporting_descriptor_object_for_warning (diagnostic,
1898 orig_diag_kind,
1899 option_text));
1900 }
1901 }
1902 else
1903 {
1904 /* Otherwise, we have an "error" or a stray "note"; use the
1905 diagnostic kind as the ruleId, so that the result object at least
1906 has a ruleId.
1907 We don't bother creating reportingDescriptor objects for these. */
1908 char *rule_id = make_rule_id_for_diagnostic_kind (orig_diag_kind);
1909 result_obj->set_string ("ruleId", rule_id);
1910 free (rule_id);
1911 }
1912
1913 if (diagnostic.metadata)
1914 {
1915 /* "taxa" property (SARIF v2.1.0 section 3.27.8). */
1916 if (int cwe_id = diagnostic.metadata->get_cwe ())
1917 {
1918 auto taxa_arr = ::make_unique<json::array> ();
1919 taxa_arr->append<sarif_reporting_descriptor_reference>
1920 (make_reporting_descriptor_reference_object_for_cwe_id (cwe_id));
1921 result_obj->set<json::array> ("taxa", std::move (taxa_arr));
1922 }
1923
1924 diagnostic.metadata->maybe_add_sarif_properties (*result_obj);
1925
1926 /* We don't yet support diagnostic_metadata::rule. */
1927 }
1928
1929 /* "level" property (SARIF v2.1.0 section 3.27.10). */
1930 if (const char *sarif_level = maybe_get_sarif_level (diagnostic.kind))
1931 result_obj->set_string ("level", sarif_level);
1932
1933 /* "message" property (SARIF v2.1.0 section 3.27.11). */
1934 auto message_obj
1935 = make_message_object (pp_formatted_text (m_printer));
1936 pp_clear_output_area (m_printer);
1937 result_obj->set<sarif_message> ("message", std::move (message_obj));
1938
1939 /* "locations" property (SARIF v2.1.0 section 3.27.12). */
1940 result_obj->set<json::array>
1941 ("locations",
1942 make_locations_arr (*result_obj.get (),
1943 diagnostic,
1944 diagnostic_artifact_role::result_file));
1945
1946 /* "codeFlows" property (SARIF v2.1.0 section 3.27.18). */
1947 if (const diagnostic_path *path = diagnostic.richloc->get_path ())
1948 {
1949 auto code_flows_arr = ::make_unique<json::array> ();
1950 const unsigned code_flow_index = 0;
1951 code_flows_arr->append<sarif_code_flow>
1952 (make_code_flow_object (*result_obj.get (),
1953 code_flow_index,
1954 *path));
1955 result_obj->set<json::array> ("codeFlows", std::move (code_flows_arr));
1956 }
1957
1958 /* The "relatedLocations" property (SARIF v2.1.0 section 3.27.22) is
1959 set up later, if any nested diagnostics occur within this diagnostic
1960 group. */
1961
1962 /* "fixes" property (SARIF v2.1.0 section 3.27.30). */
1963 const rich_location *richloc = diagnostic.richloc;
1964 if (richloc->get_num_fixit_hints ())
1965 {
1966 auto fix_arr = ::make_unique<json::array> ();
1967 fix_arr->append<sarif_fix> (make_fix_object (*richloc));
1968 result_obj->set<json::array> ("fixes", std::move (fix_arr));
1969 }
1970
1971 return result_obj;
1972 }
1973
1974 /* Make a "reportingDescriptor" object (SARIF v2.1.0 section 3.49)
1975 for a GCC warning. */
1976
1977 std::unique_ptr<sarif_reporting_descriptor>
1978 sarif_builder::
1979 make_reporting_descriptor_object_for_warning (const diagnostic_info &diagnostic,
1980 diagnostic_t /*orig_diag_kind*/,
1981 const char *option_text)
1982 {
1983 auto reporting_desc = ::make_unique<sarif_reporting_descriptor> ();
1984
1985 /* "id" property (SARIF v2.1.0 section 3.49.3). */
1986 reporting_desc->set_string ("id", option_text);
1987
1988 /* We don't implement "name" property (SARIF v2.1.0 section 3.49.7), since
1989 it seems redundant compared to "id". */
1990
1991 /* "helpUri" property (SARIF v2.1.0 section 3.49.12). */
1992 if (char *option_url = m_context.make_option_url (diagnostic.option_id))
1993 {
1994 reporting_desc->set_string ("helpUri", option_url);
1995 free (option_url);
1996 }
1997
1998 return reporting_desc;
1999 }
2000
2001 /* Make a "reportingDescriptor" object (SARIF v2.1.0 section 3.49)
2002 for CWE_ID, for use within the CWE taxa array. */
2003
2004 std::unique_ptr<sarif_reporting_descriptor>
2005 sarif_builder::make_reporting_descriptor_object_for_cwe_id (int cwe_id) const
2006 {
2007 auto reporting_desc = ::make_unique<sarif_reporting_descriptor> ();
2008
2009 /* "id" property (SARIF v2.1.0 section 3.49.3). */
2010 {
2011 pretty_printer pp;
2012 pp_printf (&pp, "%i", cwe_id);
2013 reporting_desc->set_string ("id", pp_formatted_text (&pp));
2014 }
2015
2016 /* "helpUri" property (SARIF v2.1.0 section 3.49.12). */
2017 {
2018 char *url = get_cwe_url (cwe_id);
2019 reporting_desc->set_string ("helpUri", url);
2020 free (url);
2021 }
2022
2023 return reporting_desc;
2024 }
2025
2026 /* Make a "reportingDescriptorReference" object (SARIF v2.1.0 section 3.52)
2027 referencing CWE_ID, for use within a result object.
2028 Also, add CWE_ID to m_cwe_id_set. */
2029
2030 std::unique_ptr<sarif_reporting_descriptor_reference>
2031 sarif_builder::
2032 make_reporting_descriptor_reference_object_for_cwe_id (int cwe_id)
2033 {
2034 auto desc_ref_obj = ::make_unique<sarif_reporting_descriptor_reference> ();
2035
2036 /* "id" property (SARIF v2.1.0 section 3.52.4). */
2037 {
2038 pretty_printer pp;
2039 pp_printf (&pp, "%i", cwe_id);
2040 desc_ref_obj->set_string ("id", pp_formatted_text (&pp));
2041 }
2042
2043 /* "toolComponent" property (SARIF v2.1.0 section 3.52.7). */
2044 desc_ref_obj->set<sarif_tool_component_reference>
2045 ("toolComponent", make_tool_component_reference_object_for_cwe ());
2046
2047 /* Add CWE_ID to our set. */
2048 gcc_assert (cwe_id > 0);
2049 m_cwe_id_set.add (cwe_id);
2050
2051 return desc_ref_obj;
2052 }
2053
2054 /* Make a "toolComponentReference" object (SARIF v2.1.0 section 3.54) that
2055 references the CWE taxonomy. */
2056
2057 std::unique_ptr<sarif_tool_component_reference>
2058 sarif_builder::
2059 make_tool_component_reference_object_for_cwe () const
2060 {
2061 auto comp_ref_obj = ::make_unique<sarif_tool_component_reference> ();
2062
2063 /* "name" property (SARIF v2.1.0 section 3.54.3). */
2064 comp_ref_obj->set_string ("name", "cwe");
2065
2066 return comp_ref_obj;
2067 }
2068
2069 /* Make an array suitable for use as the "locations" property of:
2070 - a "result" object (SARIF v2.1.0 section 3.27.12), or
2071 - a "notification" object (SARIF v2.1.0 section 3.58.4).
2072 Use LOC_MGR for any locations that need "id" values. */
2073
2074 std::unique_ptr<json::array>
2075 sarif_builder::make_locations_arr (sarif_location_manager &loc_mgr,
2076 const diagnostic_info &diagnostic,
2077 enum diagnostic_artifact_role role)
2078 {
2079 auto locations_arr = ::make_unique<json::array> ();
2080 const logical_location *logical_loc = nullptr;
2081 if (auto client_data_hooks = m_context.get_client_data_hooks ())
2082 logical_loc = client_data_hooks->get_current_logical_location ();
2083
2084 auto location_obj
2085 = make_location_object (loc_mgr, *diagnostic.richloc, logical_loc, role);
2086 /* Don't add entirely empty location objects to the array. */
2087 if (!location_obj->is_empty ())
2088 locations_arr->append<sarif_location> (std::move (location_obj));
2089
2090 return locations_arr;
2091 }
2092
2093 /* If LOGICAL_LOC is non-null, use it to create a "logicalLocations" property
2094 within LOCATION_OBJ (SARIF v2.1.0 section 3.28.4). */
2095
2096 void
2097 sarif_builder::
2098 set_any_logical_locs_arr (sarif_location &location_obj,
2099 const logical_location *logical_loc)
2100 {
2101 if (!logical_loc)
2102 return;
2103 auto location_locs_arr = ::make_unique<json::array> ();
2104 location_locs_arr->append<sarif_logical_location>
2105 (make_sarif_logical_location_object (*logical_loc));
2106 location_obj.set<json::array> ("logicalLocations",
2107 std::move (location_locs_arr));
2108 }
2109
2110 /* Make a "location" object (SARIF v2.1.0 section 3.28) for RICH_LOC
2111 and LOGICAL_LOC.
2112 Use LOC_MGR for any locations that need "id" values, and for
2113 any worklist items. */
2114
2115 std::unique_ptr<sarif_location>
2116 sarif_builder::make_location_object (sarif_location_manager &loc_mgr,
2117 const rich_location &rich_loc,
2118 const logical_location *logical_loc,
2119 enum diagnostic_artifact_role role)
2120 {
2121 class escape_nonascii_renderer : public content_renderer
2122 {
2123 public:
2124 escape_nonascii_renderer (const rich_location &richloc,
2125 enum diagnostics_escape_format escape_format)
2126 : m_richloc (richloc),
2127 m_escape_format (escape_format)
2128 {}
2129
2130 std::unique_ptr<sarif_multiformat_message_string>
2131 render (const sarif_builder &builder) const final override
2132 {
2133 diagnostic_context dc;
2134 diagnostic_initialize (&dc, 0);
2135 dc.m_source_printing.enabled = true;
2136 dc.m_source_printing.colorize_source_p = false;
2137 dc.m_source_printing.show_labels_p = true;
2138 dc.m_source_printing.show_line_numbers_p = true;
2139
2140 rich_location my_rich_loc (m_richloc);
2141 my_rich_loc.set_escape_on_output (true);
2142
2143 diagnostic_source_print_policy source_policy (dc);
2144 dc.set_escape_format (m_escape_format);
2145 diagnostic_text_output_format text_output (dc);
2146 source_policy.print (*text_output.get_printer (),
2147 my_rich_loc, DK_ERROR, nullptr);
2148
2149 const char *buf = pp_formatted_text (text_output.get_printer ());
2150 std::unique_ptr<sarif_multiformat_message_string> result
2151 = builder.make_multiformat_message_string (buf);
2152
2153 diagnostic_finish (&dc);
2154
2155 return result;
2156 }
2157 private:
2158 const rich_location &m_richloc;
2159 enum diagnostics_escape_format m_escape_format;
2160 } the_renderer (rich_loc,
2161 m_context.get_escape_format ());
2162
2163 auto location_obj = ::make_unique<sarif_location> ();
2164
2165 /* Get primary loc from RICH_LOC. */
2166 location_t loc = rich_loc.get_loc ();
2167
2168 /* "physicalLocation" property (SARIF v2.1.0 section 3.28.3). */
2169 const content_renderer *snippet_renderer
2170 = rich_loc.escape_on_output_p () ? &the_renderer : nullptr;
2171 if (auto phs_loc_obj
2172 = maybe_make_physical_location_object (loc, role,
2173 rich_loc.get_column_override (),
2174 snippet_renderer))
2175 location_obj->set<sarif_physical_location> ("physicalLocation",
2176 std::move (phs_loc_obj));
2177
2178 /* "logicalLocations" property (SARIF v2.1.0 section 3.28.4). */
2179 set_any_logical_locs_arr (*location_obj, logical_loc);
2180
2181 /* Handle labelled ranges and/or secondary locations. */
2182 {
2183 std::unique_ptr<json::array> annotations_arr = nullptr;
2184 for (unsigned int i = 0; i < rich_loc.get_num_locations (); i++)
2185 {
2186 const location_range *range = rich_loc.get_range (i);
2187 bool handled = false;
2188 if (const range_label *label = range->m_label)
2189 {
2190 label_text text = label->get_text (i);
2191 if (text.get ())
2192 {
2193 /* Create annotations for any labelled ranges. */
2194 location_t range_loc = rich_loc.get_loc (i);
2195 auto region
2196 = maybe_make_region_object (range_loc,
2197 rich_loc.get_column_override ());
2198 if (region)
2199 {
2200 if (!annotations_arr)
2201 annotations_arr = ::make_unique<json::array> ();
2202 region->set<sarif_message>
2203 ("message", make_message_object (text.get ()));
2204 annotations_arr->append<sarif_region> (std::move (region));
2205 handled = true;
2206 }
2207 }
2208 }
2209
2210 /* Add related locations for any secondary locations in RICH_LOC
2211 that don't have labels (and thus aren't added to "annotations"). */
2212 if (i > 0 && !handled)
2213 loc_mgr.add_relationship_to_worklist
2214 (*location_obj.get (),
2215 sarif_location_manager::worklist_item::kind::unlabelled_secondary_location,
2216 range->m_loc);
2217 }
2218 if (annotations_arr)
2219 /* "annotations" property (SARIF v2.1.0 section 3.28.6). */
2220 location_obj->set<json::array> ("annotations",
2221 std::move (annotations_arr));
2222 }
2223
2224 add_any_include_chain (loc_mgr, *location_obj.get (), loc);
2225
2226 /* A flag for hinting that the diagnostic involves issues at the
2227 level of character encodings (such as homoglyphs, or misleading
2228 bidirectional control codes), and thus that it will be helpful
2229 to the user if we show some representation of
2230 how the characters in the pertinent source lines are encoded. */
2231 if (rich_loc.escape_on_output_p ())
2232 {
2233 sarif_property_bag &bag = location_obj->get_or_create_properties ();
2234 bag.set_bool ("gcc/escapeNonAscii", rich_loc.escape_on_output_p ());
2235 }
2236
2237 return location_obj;
2238 }
2239
2240 /* If WHERE was #included from somewhere, add a worklist item
2241 to LOC_MGR to lazily add a location for the #include location,
2242 and relationships between it and the LOCATION_OBJ.
2243 Compare with diagnostic_context::report_current_module, but rather
2244 than iterating the current chain, we add the next edge and iterate
2245 in the worklist, so that edges are only added once. */
2246
2247 void
2248 sarif_builder::add_any_include_chain (sarif_location_manager &loc_mgr,
2249 sarif_location &location_obj,
2250 location_t where)
2251 {
2252 if (where <= BUILTINS_LOCATION)
2253 return;
2254
2255 const line_map_ordinary *map = nullptr;
2256 linemap_resolve_location (m_line_maps, where,
2257 LRK_MACRO_DEFINITION_LOCATION,
2258 &map);
2259
2260 if (!map)
2261 return;
2262
2263 location_t include_loc = linemap_included_from (map);
2264 map = linemap_included_from_linemap (m_line_maps, map);
2265 if (!map)
2266 return;
2267 loc_mgr.add_relationship_to_worklist
2268 (location_obj,
2269 sarif_result::worklist_item::kind::included_from,
2270 include_loc);
2271 }
2272
2273 /* Make a "location" object (SARIF v2.1.0 section 3.28) for WHERE
2274 within an include chain. */
2275
2276 std::unique_ptr<sarif_location>
2277 sarif_builder::make_location_object (sarif_location_manager &loc_mgr,
2278 location_t loc,
2279 enum diagnostic_artifact_role role)
2280 {
2281 auto location_obj = ::make_unique<sarif_location> ();
2282
2283 /* "physicalLocation" property (SARIF v2.1.0 section 3.28.3). */
2284 if (auto phs_loc_obj
2285 = maybe_make_physical_location_object (loc, role, 0, nullptr))
2286 location_obj->set<sarif_physical_location> ("physicalLocation",
2287 std::move (phs_loc_obj));
2288
2289 add_any_include_chain (loc_mgr, *location_obj.get (), loc);
2290
2291 return location_obj;
2292 }
2293
2294 /* Make a "location" object (SARIF v2.1.0 section 3.28) for EVENT
2295 within a diagnostic_path. */
2296
2297 std::unique_ptr<sarif_location>
2298 sarif_builder::make_location_object (sarif_location_manager &loc_mgr,
2299 const diagnostic_event &event,
2300 enum diagnostic_artifact_role role)
2301 {
2302 auto location_obj = ::make_unique<sarif_location> ();
2303
2304 /* "physicalLocation" property (SARIF v2.1.0 section 3.28.3). */
2305 location_t loc = event.get_location ();
2306 if (auto phs_loc_obj
2307 = maybe_make_physical_location_object (loc, role, 0, nullptr))
2308 location_obj->set<sarif_physical_location> ("physicalLocation",
2309 std::move (phs_loc_obj));
2310
2311 /* "logicalLocations" property (SARIF v2.1.0 section 3.28.4). */
2312 const logical_location *logical_loc = event.get_logical_location ();
2313 set_any_logical_locs_arr (*location_obj, logical_loc);
2314
2315 /* "message" property (SARIF v2.1.0 section 3.28.5). */
2316 std::unique_ptr<pretty_printer> pp = get_printer ()->clone ();
2317 event.print_desc (*pp);
2318 location_obj->set<sarif_message>
2319 ("message",
2320 make_message_object (pp_formatted_text (pp.get ())));
2321
2322 add_any_include_chain (loc_mgr, *location_obj.get (), loc);
2323
2324 return location_obj;
2325 }
2326
2327 /* Make a "physicalLocation" object (SARIF v2.1.0 section 3.29) for LOC.
2328
2329 If COLUMN_OVERRIDE is non-zero, then use it as the column number
2330 if LOC has no column information.
2331
2332 Ensure that we have an artifact object for the file, adding ROLE to it,
2333 and flagging that we will attempt to embed the contents of the artifact
2334 when writing it out. */
2335
2336 std::unique_ptr<sarif_physical_location>
2337 sarif_builder::
2338 maybe_make_physical_location_object (location_t loc,
2339 enum diagnostic_artifact_role role,
2340 int column_override,
2341 const content_renderer *snippet_renderer)
2342 {
2343 if (loc <= BUILTINS_LOCATION || LOCATION_FILE (loc) == nullptr)
2344 return nullptr;
2345
2346 auto phys_loc_obj = ::make_unique<sarif_physical_location> ();
2347
2348 /* "artifactLocation" property (SARIF v2.1.0 section 3.29.3). */
2349 phys_loc_obj->set<sarif_artifact_location>
2350 ("artifactLocation", make_artifact_location_object (loc));
2351 get_or_create_artifact (LOCATION_FILE (loc), role, true);
2352
2353 /* "region" property (SARIF v2.1.0 section 3.29.4). */
2354 if (auto region_obj = maybe_make_region_object (loc, column_override))
2355 phys_loc_obj->set<sarif_region> ("region", std::move (region_obj));
2356
2357 /* "contextRegion" property (SARIF v2.1.0 section 3.29.5). */
2358 if (auto context_region_obj
2359 = maybe_make_region_object_for_context (loc, snippet_renderer))
2360 phys_loc_obj->set<sarif_region> ("contextRegion",
2361 std::move (context_region_obj));
2362
2363 /* Instead, we add artifacts to the run as a whole,
2364 with artifact.contents.
2365 Could do both, though. */
2366
2367 return phys_loc_obj;
2368 }
2369
2370 /* Make an "artifactLocation" object (SARIF v2.1.0 section 3.4) for LOC,
2371 or return nullptr. */
2372
2373 std::unique_ptr<sarif_artifact_location>
2374 sarif_builder::make_artifact_location_object (location_t loc)
2375 {
2376 return make_artifact_location_object (LOCATION_FILE (loc));
2377 }
2378
2379 /* The ID value for use in "uriBaseId" properties (SARIF v2.1.0 section 3.4.4)
2380 for when we need to express paths relative to PWD. */
2381
2382 #define PWD_PROPERTY_NAME ("PWD")
2383
2384 /* Make an "artifactLocation" object (SARIF v2.1.0 section 3.4) for FILENAME,
2385 or return nullptr. */
2386
2387 std::unique_ptr<sarif_artifact_location>
2388 sarif_builder::make_artifact_location_object (const char *filename)
2389 {
2390 auto artifact_loc_obj = ::make_unique<sarif_artifact_location> ();
2391
2392 /* "uri" property (SARIF v2.1.0 section 3.4.3). */
2393 artifact_loc_obj->set_string ("uri", filename);
2394
2395 if (filename[0] != '/')
2396 {
2397 /* If we have a relative path, set the "uriBaseId" property
2398 (SARIF v2.1.0 section 3.4.4). */
2399 artifact_loc_obj->set_string ("uriBaseId", PWD_PROPERTY_NAME);
2400 m_seen_any_relative_paths = true;
2401 }
2402
2403 return artifact_loc_obj;
2404 }
2405
2406 /* Get the PWD, or nullptr, as an absolute file-based URI,
2407 adding a trailing forward slash (as required by SARIF v2.1.0
2408 section 3.14.14). */
2409
2410 static char *
2411 make_pwd_uri_str ()
2412 {
2413 /* The prefix of a file-based URI, up to, but not including the path. */
2414 #define FILE_PREFIX ("file://")
2415
2416 const char *pwd = getpwd ();
2417 if (!pwd)
2418 return nullptr;
2419 size_t len = strlen (pwd);
2420 if (len == 0 || pwd[len - 1] != '/')
2421 return concat (FILE_PREFIX, pwd, "/", nullptr);
2422 else
2423 {
2424 gcc_assert (pwd[len - 1] == '/');
2425 return concat (FILE_PREFIX, pwd, nullptr);
2426 }
2427 }
2428
2429 /* Make an "artifactLocation" object (SARIF v2.1.0 section 3.4) for the pwd,
2430 for use in the "run.originalUriBaseIds" property (SARIF v2.1.0
2431 section 3.14.14) when we have any relative paths. */
2432
2433 std::unique_ptr<sarif_artifact_location>
2434 sarif_builder::make_artifact_location_object_for_pwd () const
2435 {
2436 auto artifact_loc_obj = ::make_unique<sarif_artifact_location> ();
2437
2438 /* "uri" property (SARIF v2.1.0 section 3.4.3). */
2439 if (char *pwd = make_pwd_uri_str ())
2440 {
2441 gcc_assert (strlen (pwd) > 0);
2442 gcc_assert (pwd[strlen (pwd) - 1] == '/');
2443 artifact_loc_obj->set_string ("uri", pwd);
2444 free (pwd);
2445 }
2446
2447 return artifact_loc_obj;
2448 }
2449
2450 /* Get the column number within EXPLOC. */
2451
2452 int
2453 sarif_builder::get_sarif_column (expanded_location exploc) const
2454 {
2455 cpp_char_column_policy policy (m_tabstop, cpp_wcwidth);
2456 return location_compute_display_column (m_context.get_file_cache (),
2457 exploc, policy);
2458 }
2459
2460 /* Make a "region" object (SARIF v2.1.0 section 3.30) for LOC,
2461 or return nullptr.
2462
2463 If COLUMN_OVERRIDE is non-zero, then use it as the column number
2464 if LOC has no column information.
2465
2466 We only support text properties of regions ("text regions"),
2467 not binary properties ("binary regions"); see 3.30.1. */
2468
2469 std::unique_ptr<sarif_region>
2470 sarif_builder::maybe_make_region_object (location_t loc,
2471 int column_override) const
2472 {
2473 location_t caret_loc = get_pure_location (loc);
2474
2475 if (caret_loc <= BUILTINS_LOCATION)
2476 return nullptr;
2477
2478 location_t start_loc = get_start (loc);
2479 location_t finish_loc = get_finish (loc);
2480
2481 expanded_location exploc_caret = expand_location (caret_loc);
2482 expanded_location exploc_start = expand_location (start_loc);
2483 expanded_location exploc_finish = expand_location (finish_loc);
2484
2485 if (exploc_start.file !=exploc_caret.file)
2486 return nullptr;
2487 if (exploc_finish.file !=exploc_caret.file)
2488 return nullptr;
2489
2490 /* We can have line == 0 in the presence of "#" lines.
2491 SARIF requires lines > 0, so if we hit this case we don't have a
2492 way of validly representing the region as SARIF; bail out. */
2493 if (exploc_start.line <= 0)
2494 return nullptr;
2495
2496 auto region_obj = ::make_unique<sarif_region> ();
2497
2498 /* "startLine" property (SARIF v2.1.0 section 3.30.5) */
2499 region_obj->set_integer ("startLine", exploc_start.line);
2500
2501 /* "startColumn" property (SARIF v2.1.0 section 3.30.6).
2502
2503 We use column == 0 to mean the whole line, so omit the column
2504 information for this case, unless COLUMN_OVERRIDE is non-zero,
2505 (for handling certain awkward lexer diagnostics) */
2506
2507 if (exploc_start.column == 0 && column_override)
2508 /* Use the provided column number. */
2509 exploc_start.column = column_override;
2510
2511 if (exploc_start.column > 0)
2512 {
2513 int start_column = get_sarif_column (exploc_start);
2514 region_obj->set_integer ("startColumn", start_column);
2515 }
2516
2517 /* "endLine" property (SARIF v2.1.0 section 3.30.7) */
2518 if (exploc_finish.line != exploc_start.line
2519 && exploc_finish.line > 0)
2520 region_obj->set_integer ("endLine", exploc_finish.line);
2521
2522 /* "endColumn" property (SARIF v2.1.0 section 3.30.8).
2523 This expresses the column immediately beyond the range.
2524
2525 We use column == 0 to mean the whole line, so omit the column
2526 information for this case. */
2527 if (exploc_finish.column > 0)
2528 {
2529 int next_column = get_sarif_column (exploc_finish) + 1;
2530 region_obj->set_integer ("endColumn", next_column);
2531 }
2532
2533 return region_obj;
2534 }
2535
2536 /* Make a "region" object (SARIF v2.1.0 section 3.30) for the "contextRegion"
2537 property (SARIF v2.1.0 section 3.29.5) of a "physicalLocation".
2538
2539 This is similar to maybe_make_region_object, but ignores column numbers,
2540 covering the line(s) as a whole, and including a "snippet" property
2541 embedding those source lines, making it easier for consumers to show
2542 the pertinent source. */
2543
2544 std::unique_ptr<sarif_region>
2545 sarif_builder::
2546 maybe_make_region_object_for_context (location_t loc,
2547 const content_renderer *snippet_renderer)
2548 const
2549 {
2550 location_t caret_loc = get_pure_location (loc);
2551
2552 if (caret_loc <= BUILTINS_LOCATION)
2553 return nullptr;
2554
2555 location_t start_loc = get_start (loc);
2556 location_t finish_loc = get_finish (loc);
2557
2558 expanded_location exploc_caret = expand_location (caret_loc);
2559 expanded_location exploc_start = expand_location (start_loc);
2560 expanded_location exploc_finish = expand_location (finish_loc);
2561
2562 if (exploc_start.file !=exploc_caret.file)
2563 return nullptr;
2564 if (exploc_finish.file !=exploc_caret.file)
2565 return nullptr;
2566
2567 /* We can have line == 0 in the presence of "#" lines.
2568 SARIF requires lines > 0, so if we hit this case we don't have a
2569 way of validly representing the region as SARIF; bail out. */
2570 if (exploc_start.line <= 0)
2571 return nullptr;
2572
2573 auto region_obj = ::make_unique<sarif_region> ();
2574
2575 /* "startLine" property (SARIF v2.1.0 section 3.30.5) */
2576 region_obj->set_integer ("startLine", exploc_start.line);
2577
2578 /* "endLine" property (SARIF v2.1.0 section 3.30.7) */
2579 if (exploc_finish.line != exploc_start.line
2580 && exploc_finish.line > 0)
2581 region_obj->set_integer ("endLine", exploc_finish.line);
2582
2583 /* "snippet" property (SARIF v2.1.0 section 3.30.13). */
2584 if (auto artifact_content_obj
2585 = maybe_make_artifact_content_object (exploc_start.file,
2586 exploc_start.line,
2587 exploc_finish.line,
2588 snippet_renderer))
2589 region_obj->set<sarif_artifact_content> ("snippet",
2590 std::move (artifact_content_obj));
2591
2592 return region_obj;
2593 }
2594
2595 /* Make a "region" object (SARIF v2.1.0 section 3.30) for the deletion region
2596 of HINT (as per SARIF v2.1.0 section 3.57.3). */
2597
2598 std::unique_ptr<sarif_region>
2599 sarif_builder::make_region_object_for_hint (const fixit_hint &hint) const
2600 {
2601 location_t start_loc = hint.get_start_loc ();
2602 location_t next_loc = hint.get_next_loc ();
2603
2604 expanded_location exploc_start = expand_location (start_loc);
2605 expanded_location exploc_next = expand_location (next_loc);
2606
2607 auto region_obj = ::make_unique<sarif_region> ();
2608
2609 /* "startLine" property (SARIF v2.1.0 section 3.30.5) */
2610 region_obj->set_integer ("startLine", exploc_start.line);
2611
2612 /* "startColumn" property (SARIF v2.1.0 section 3.30.6) */
2613 int start_col = get_sarif_column (exploc_start);
2614 region_obj->set_integer ("startColumn", start_col);
2615
2616 /* "endLine" property (SARIF v2.1.0 section 3.30.7) */
2617 if (exploc_next.line != exploc_start.line)
2618 region_obj->set_integer ("endLine", exploc_next.line);
2619
2620 /* "endColumn" property (SARIF v2.1.0 section 3.30.8).
2621 This expresses the column immediately beyond the range. */
2622 int next_col = get_sarif_column (exploc_next);
2623 region_obj->set_integer ("endColumn", next_col);
2624
2625 return region_obj;
2626 }
2627
2628 /* Attempt to get a string for a logicalLocation's "kind" property
2629 (SARIF v2.1.0 section 3.33.7).
2630 Return nullptr if unknown. */
2631
2632 static const char *
2633 maybe_get_sarif_kind (enum logical_location_kind kind)
2634 {
2635 switch (kind)
2636 {
2637 default:
2638 gcc_unreachable ();
2639 case LOGICAL_LOCATION_KIND_UNKNOWN:
2640 return nullptr;
2641
2642 case LOGICAL_LOCATION_KIND_FUNCTION:
2643 return "function";
2644 case LOGICAL_LOCATION_KIND_MEMBER:
2645 return "member";
2646 case LOGICAL_LOCATION_KIND_MODULE:
2647 return "module";
2648 case LOGICAL_LOCATION_KIND_NAMESPACE:
2649 return "namespace";
2650 case LOGICAL_LOCATION_KIND_TYPE:
2651 return "type";
2652 case LOGICAL_LOCATION_KIND_RETURN_TYPE:
2653 return "returnType";
2654 case LOGICAL_LOCATION_KIND_PARAMETER:
2655 return "parameter";
2656 case LOGICAL_LOCATION_KIND_VARIABLE:
2657 return "variable";
2658 }
2659 }
2660
2661 /* Make a "logicalLocation" object (SARIF v2.1.0 section 3.33) for LOGICAL_LOC,
2662 or return nullptr. */
2663
2664 std::unique_ptr<sarif_logical_location>
2665 make_sarif_logical_location_object (const logical_location &logical_loc)
2666 {
2667 auto logical_loc_obj = ::make_unique<sarif_logical_location> ();
2668
2669 /* "name" property (SARIF v2.1.0 section 3.33.4). */
2670 if (const char *short_name = logical_loc.get_short_name ())
2671 logical_loc_obj->set_string ("name", short_name);
2672
2673 /* "fullyQualifiedName" property (SARIF v2.1.0 section 3.33.5). */
2674 if (const char *name_with_scope = logical_loc.get_name_with_scope ())
2675 logical_loc_obj->set_string ("fullyQualifiedName", name_with_scope);
2676
2677 /* "decoratedName" property (SARIF v2.1.0 section 3.33.6). */
2678 if (const char *internal_name = logical_loc.get_internal_name ())
2679 logical_loc_obj->set_string ("decoratedName", internal_name);
2680
2681 /* "kind" property (SARIF v2.1.0 section 3.33.7). */
2682 enum logical_location_kind kind = logical_loc.get_kind ();
2683 if (const char *sarif_kind_str = maybe_get_sarif_kind (kind))
2684 logical_loc_obj->set_string ("kind", sarif_kind_str);
2685
2686 return logical_loc_obj;
2687 }
2688
2689 label_text
2690 make_sarif_url_for_event (const sarif_code_flow *code_flow,
2691 diagnostic_event_id_t event_id)
2692 {
2693 gcc_assert (event_id.known_p ());
2694
2695 if (!code_flow)
2696 return label_text ();
2697
2698 const sarif_thread_flow_location &tfl_obj
2699 = code_flow->get_thread_flow_loc_obj (event_id);
2700 const int location_idx = tfl_obj.get_index_within_parent ();
2701
2702 const sarif_thread_flow &thread_flow_obj = tfl_obj.get_parent ();
2703 const int thread_flow_idx = thread_flow_obj.get_index_within_parent ();
2704
2705 const sarif_code_flow &code_flow_obj = thread_flow_obj.get_parent ();
2706 const int code_flow_idx = code_flow_obj.get_index_within_parent ();
2707
2708 const sarif_result &result_obj = code_flow_obj.get_parent ();
2709 const int result_idx = result_obj.get_index_within_parent ();
2710
2711 /* We only support a single run object in the log. */
2712 const int run_idx = 0;
2713
2714 char *buf = xasprintf
2715 ("sarif:/runs/%i/results/%i/codeFlows/%i/threadFlows/%i/locations/%i",
2716 run_idx, result_idx, code_flow_idx, thread_flow_idx, location_idx);
2717 return label_text::take (buf);
2718 }
2719
2720 /* Make a "codeFlow" object (SARIF v2.1.0 section 3.36) for PATH. */
2721
2722 std::unique_ptr<sarif_code_flow>
2723 sarif_builder::make_code_flow_object (sarif_result &result,
2724 unsigned idx_within_parent,
2725 const diagnostic_path &path)
2726 {
2727 auto code_flow_obj
2728 = ::make_unique <sarif_code_flow> (result, idx_within_parent);
2729
2730 /* First pass:
2731 Create threadFlows and threadFlowLocation objects within them,
2732 effectively recording a mapping from event_id to threadFlowLocation
2733 so that we can later go from an event_id to a URI within the
2734 SARIF file. */
2735 for (unsigned i = 0; i < path.num_events (); i++)
2736 {
2737 const diagnostic_event &event = path.get_event (i);
2738 const diagnostic_thread_id_t thread_id = event.get_thread_id ();
2739
2740 sarif_thread_flow &thread_flow_obj
2741 = code_flow_obj->get_or_append_thread_flow (path.get_thread (thread_id),
2742 thread_id);
2743 thread_flow_obj.add_location ();
2744 }
2745
2746 /* Second pass: walk the events, populating the tfl objs. */
2747 m_current_code_flow = code_flow_obj.get ();
2748 for (unsigned i = 0; i < path.num_events (); i++)
2749 {
2750 const diagnostic_event &event = path.get_event (i);
2751 sarif_thread_flow_location &thread_flow_loc_obj
2752 = code_flow_obj->get_thread_flow_loc_obj (i);
2753 populate_thread_flow_location_object (result,
2754 thread_flow_loc_obj,
2755 event,
2756 i);
2757 }
2758 m_current_code_flow = nullptr;
2759
2760 return code_flow_obj;
2761 }
2762
2763 /* Populate TFL_OBJ, a "threadFlowLocation" object (SARIF v2.1.0 section 3.38)
2764 based on EVENT. */
2765
2766 void
2767 sarif_builder::
2768 populate_thread_flow_location_object (sarif_result &result,
2769 sarif_thread_flow_location &tfl_obj,
2770 const diagnostic_event &ev,
2771 int event_execution_idx)
2772 {
2773 /* Give diagnostic_event subclasses a chance to add custom properties
2774 via a property bag. */
2775 ev.maybe_add_sarif_properties (tfl_obj);
2776
2777 /* "location" property (SARIF v2.1.0 section 3.38.3). */
2778 tfl_obj.set<sarif_location>
2779 ("location",
2780 make_location_object (result, ev, diagnostic_artifact_role::traced_file));
2781
2782 /* "kinds" property (SARIF v2.1.0 section 3.38.8). */
2783 diagnostic_event::meaning m = ev.get_meaning ();
2784 if (auto kinds_arr = maybe_make_kinds_array (m))
2785 tfl_obj.set<json::array> ("kinds", std::move (kinds_arr));
2786
2787 /* "nestingLevel" property (SARIF v2.1.0 section 3.38.10). */
2788 tfl_obj.set_integer ("nestingLevel", ev.get_stack_depth ());
2789
2790 /* "executionOrder" property (SARIF v2.1.0 3.38.11).
2791 Offset by 1 to match the human-readable values emitted by %@. */
2792 tfl_obj.set_integer ("executionOrder", event_execution_idx + 1);
2793
2794 /* It might be nice to eventually implement the following for -fanalyzer:
2795 - the "stack" property (SARIF v2.1.0 section 3.38.5)
2796 - the "state" property (SARIF v2.1.0 section 3.38.9)
2797 - the "importance" property (SARIF v2.1.0 section 3.38.13). */
2798 }
2799
2800 /* If M has any known meaning, make a json array suitable for the "kinds"
2801 property of a "threadFlowLocation" object (SARIF v2.1.0 section 3.38.8).
2802
2803 Otherwise, return nullptr. */
2804
2805 std::unique_ptr<json::array>
2806 sarif_builder::maybe_make_kinds_array (diagnostic_event::meaning m) const
2807 {
2808 if (m.m_verb == diagnostic_event::VERB_unknown
2809 && m.m_noun == diagnostic_event::NOUN_unknown
2810 && m.m_property == diagnostic_event::PROPERTY_unknown)
2811 return nullptr;
2812
2813 auto kinds_arr = ::make_unique<json::array> ();
2814 if (const char *verb_str
2815 = diagnostic_event::meaning::maybe_get_verb_str (m.m_verb))
2816 kinds_arr->append_string (verb_str);
2817 if (const char *noun_str
2818 = diagnostic_event::meaning::maybe_get_noun_str (m.m_noun))
2819 kinds_arr->append_string (noun_str);
2820 if (const char *property_str
2821 = diagnostic_event::meaning::maybe_get_property_str (m.m_property))
2822 kinds_arr->append_string (property_str);
2823 return kinds_arr;
2824 }
2825
2826 /* In "3.11.5 Messages with placeholders":
2827 "Within both plain text and formatted message strings, the characters
2828 "{" and "}" SHALL be represented by the character sequences
2829 "{{" and "}}" respectively." */
2830
2831 static std::string
2832 escape_braces (const char *text)
2833 {
2834 std::string result;
2835 while (char ch = *text++)
2836 switch (ch)
2837 {
2838 case '{':
2839 case '}':
2840 result += ch;
2841 /* Fall through. */
2842 default:
2843 result += ch;
2844 break;
2845 }
2846 return result;
2847 }
2848
2849 static void
2850 set_string_property_escaping_braces (json::object &obj,
2851 const char *property_name,
2852 const char *value)
2853 {
2854 std::string escaped (escape_braces (value));
2855 obj.set_string (property_name, escaped.c_str ());
2856 }
2857
2858 /* Make a "message" object (SARIF v2.1.0 section 3.11) for MSG. */
2859
2860 std::unique_ptr<sarif_message>
2861 sarif_builder::make_message_object (const char *msg) const
2862 {
2863 auto message_obj = ::make_unique<sarif_message> ();
2864
2865 /* "text" property (SARIF v2.1.0 section 3.11.8). */
2866 set_string_property_escaping_braces (*message_obj,
2867 "text", msg);
2868
2869 return message_obj;
2870 }
2871
2872 /* Make a "message" object (SARIF v2.1.0 section 3.11) for DIAGRAM.
2873 We emit the diagram as a code block within the Markdown part
2874 of the message. */
2875
2876 std::unique_ptr<sarif_message>
2877 sarif_builder::make_message_object_for_diagram (const diagnostic_diagram &diagram)
2878 {
2879 auto message_obj = ::make_unique<sarif_message> ();
2880
2881 /* "text" property (SARIF v2.1.0 section 3.11.8). */
2882 set_string_property_escaping_braces (*message_obj,
2883 "text", diagram.get_alt_text ());
2884
2885 pretty_printer *const pp = m_printer;
2886 char *saved_prefix = pp_take_prefix (pp);
2887 pp_set_prefix (pp, nullptr);
2888
2889 /* "To produce a code block in Markdown, simply indent every line of
2890 the block by at least 4 spaces or 1 tab."
2891 Here we use 4 spaces. */
2892 diagram.get_canvas ().print_to_pp (pp, " ");
2893 pp_set_prefix (pp, saved_prefix);
2894
2895 /* "markdown" property (SARIF v2.1.0 section 3.11.9). */
2896 set_string_property_escaping_braces (*message_obj,
2897 "markdown", pp_formatted_text (pp));
2898
2899 pp_clear_output_area (pp);
2900
2901 return message_obj;
2902 }
2903
2904 /* Make a "multiformatMessageString object" (SARIF v2.1.0 section 3.12)
2905 for MSG. */
2906
2907 std::unique_ptr<sarif_multiformat_message_string>
2908 sarif_builder::make_multiformat_message_string (const char *msg) const
2909 {
2910 auto message_obj = ::make_unique<sarif_multiformat_message_string> ();
2911
2912 /* "text" property (SARIF v2.1.0 section 3.12.3). */
2913 set_string_property_escaping_braces (*message_obj,
2914 "text", msg);
2915
2916 return message_obj;
2917 }
2918
2919 /* Convert VERSION to a value for the "$schema" property
2920 of a "sarifLog" object (SARIF v2.1.0 section 3.13.3). */
2921
2922 static const char *
2923 sarif_version_to_url (enum sarif_version version)
2924 {
2925 switch (version)
2926 {
2927 default:
2928 gcc_unreachable ();
2929 case sarif_version::v2_1_0:
2930 return "https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json";
2931 case sarif_version::v2_2_prerelease_2024_08_08:
2932 return "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/refs/tags/2.2-prerelease-2024-08-08/sarif-2.2/schema/sarif-2-2.schema.json";
2933 }
2934 }
2935
2936 /* Convert VERSION to a value for the "version" property
2937 of a "sarifLog" object (SARIF v2.1.0 section 3.13.2). */
2938
2939 static const char *
2940 sarif_version_to_property (enum sarif_version version)
2941 {
2942 switch (version)
2943 {
2944 default:
2945 gcc_unreachable ();
2946 case sarif_version::v2_1_0:
2947 return "2.1.0";
2948 case sarif_version::v2_2_prerelease_2024_08_08:
2949 /* I would have used "2.2-prerelease-2024-08-08",
2950 but the schema only accepts "2.2". */
2951 return "2.2";
2952 }
2953 }
2954
2955 /* Make a top-level "sarifLog" object (SARIF v2.1.0 section 3.13). */
2956
2957 std::unique_ptr<sarif_log>
2958 sarif_builder::
2959 make_top_level_object (std::unique_ptr<sarif_invocation> invocation_obj,
2960 std::unique_ptr<json::array> results)
2961 {
2962 auto log_obj = ::make_unique<sarif_log> ();
2963
2964 /* "$schema" property (SARIF v2.1.0 section 3.13.3) . */
2965 log_obj->set_string ("$schema", sarif_version_to_url (m_version));
2966
2967 /* "version" property (SARIF v2.1.0 section 3.13.2). */
2968 log_obj->set_string ("version", sarif_version_to_property (m_version));
2969
2970 /* "runs" property (SARIF v2.1.0 section 3.13.4). */
2971 auto run_arr = ::make_unique<json::array> ();
2972 auto run_obj = make_run_object (std::move (invocation_obj),
2973 std::move (results));
2974 run_arr->append<sarif_run> (std::move (run_obj));
2975 log_obj->set<json::array> ("runs", std::move (run_arr));
2976
2977 return log_obj;
2978 }
2979
2980 /* Make a "run" object (SARIF v2.1.0 section 3.14). */
2981
2982 std::unique_ptr<sarif_run>
2983 sarif_builder::
2984 make_run_object (std::unique_ptr<sarif_invocation> invocation_obj,
2985 std::unique_ptr<json::array> results)
2986 {
2987 auto run_obj = ::make_unique<sarif_run> ();
2988
2989 /* "tool" property (SARIF v2.1.0 section 3.14.6). */
2990 run_obj->set<sarif_tool> ("tool", make_tool_object ());
2991
2992 /* "taxonomies" property (SARIF v2.1.0 section 3.14.8). */
2993 if (auto taxonomies_arr = maybe_make_taxonomies_array ())
2994 run_obj->set<json::array> ("taxonomies", std::move (taxonomies_arr));
2995
2996 /* "invocations" property (SARIF v2.1.0 section 3.14.11). */
2997 {
2998 auto invocations_arr = ::make_unique<json::array> ();
2999 invocations_arr->append (std::move (invocation_obj));
3000 run_obj->set<json::array> ("invocations", std::move (invocations_arr));
3001 }
3002
3003 /* "originalUriBaseIds (SARIF v2.1.0 section 3.14.14). */
3004 if (m_seen_any_relative_paths)
3005 {
3006 auto orig_uri_base_ids = ::make_unique<json::object> ();
3007 orig_uri_base_ids->set<sarif_artifact_location>
3008 (PWD_PROPERTY_NAME, make_artifact_location_object_for_pwd ());
3009 run_obj->set<json::object> ("originalUriBaseIds",
3010 std::move (orig_uri_base_ids));
3011 }
3012
3013 /* "artifacts" property (SARIF v2.1.0 section 3.14.15). */
3014 auto artifacts_arr = ::make_unique<json::array> ();
3015 for (auto iter : m_filename_to_artifact_map)
3016 {
3017 sarif_artifact *artifact_obj = iter.second;
3018 if (artifact_obj->embed_contents_p ())
3019 artifact_obj->populate_contents (*this);
3020 artifact_obj->populate_roles ();
3021 artifacts_arr->append (artifact_obj);
3022 }
3023 run_obj->set<json::array> ("artifacts", std::move (artifacts_arr));
3024 m_filename_to_artifact_map.empty ();
3025
3026 /* "results" property (SARIF v2.1.0 section 3.14.23). */
3027 run_obj->set<json::array> ("results", std::move (results));
3028
3029 return run_obj;
3030 }
3031
3032 /* Make a "tool" object (SARIF v2.1.0 section 3.18). */
3033
3034 std::unique_ptr<sarif_tool>
3035 sarif_builder::make_tool_object ()
3036 {
3037 auto tool_obj = ::make_unique<sarif_tool> ();
3038
3039 /* "driver" property (SARIF v2.1.0 section 3.18.2). */
3040 tool_obj->set<sarif_tool_component> ("driver",
3041 make_driver_tool_component_object ());
3042
3043 /* Report plugins via the "extensions" property
3044 (SARIF v2.1.0 section 3.18.3). */
3045 if (auto client_data_hooks = m_context.get_client_data_hooks ())
3046 if (const client_version_info *vinfo
3047 = client_data_hooks->get_any_version_info ())
3048 {
3049 class my_plugin_visitor : public client_version_info :: plugin_visitor
3050 {
3051 public:
3052 void on_plugin (const diagnostic_client_plugin_info &p) final override
3053 {
3054 /* Create a "toolComponent" object (SARIF v2.1.0 section 3.19)
3055 for the plugin. */
3056 auto plugin_obj = ::make_unique<sarif_tool_component> ();
3057
3058 /* "name" property (SARIF v2.1.0 section 3.19.8). */
3059 if (const char *short_name = p.get_short_name ())
3060 plugin_obj->set_string ("name", short_name);
3061
3062 /* "fullName" property (SARIF v2.1.0 section 3.19.9). */
3063 if (const char *full_name = p.get_full_name ())
3064 plugin_obj->set_string ("fullName", full_name);
3065
3066 /* "version" property (SARIF v2.1.0 section 3.19.13). */
3067 if (const char *version = p.get_version ())
3068 plugin_obj->set_string ("version", version);
3069
3070 m_plugin_objs.push_back (std::move (plugin_obj));
3071 }
3072 std::vector<std::unique_ptr<sarif_tool_component>> m_plugin_objs;
3073 };
3074 my_plugin_visitor v;
3075 vinfo->for_each_plugin (v);
3076 if (v.m_plugin_objs.size () > 0)
3077 {
3078 auto extensions_arr = ::make_unique<json::array> ();
3079 for (auto &iter : v.m_plugin_objs)
3080 extensions_arr->append<sarif_tool_component> (std::move (iter));
3081 tool_obj->set<json::array> ("extensions",
3082 std::move (extensions_arr));
3083 }
3084 }
3085
3086 /* Perhaps we could also show GMP, MPFR, MPC, isl versions as other
3087 "extensions" (see toplev.cc: print_version). */
3088
3089 return tool_obj;
3090 }
3091
3092 /* Make a "toolComponent" object (SARIF v2.1.0 section 3.19) for what SARIF
3093 calls the "driver" (see SARIF v2.1.0 section 3.18.1). */
3094
3095 std::unique_ptr<sarif_tool_component>
3096 sarif_builder::make_driver_tool_component_object ()
3097 {
3098 auto driver_obj = ::make_unique<sarif_tool_component> ();
3099
3100 if (auto client_data_hooks = m_context.get_client_data_hooks ())
3101 if (const client_version_info *vinfo
3102 = client_data_hooks->get_any_version_info ())
3103 {
3104 /* "name" property (SARIF v2.1.0 section 3.19.8). */
3105 if (const char *name = vinfo->get_tool_name ())
3106 driver_obj->set_string ("name", name);
3107
3108 /* "fullName" property (SARIF v2.1.0 section 3.19.9). */
3109 if (char *full_name = vinfo->maybe_make_full_name ())
3110 {
3111 driver_obj->set_string ("fullName", full_name);
3112 free (full_name);
3113 }
3114
3115 /* "version" property (SARIF v2.1.0 section 3.19.13). */
3116 if (const char *version = vinfo->get_version_string ())
3117 driver_obj->set_string ("version", version);
3118
3119 /* "informationUri" property (SARIF v2.1.0 section 3.19.17). */
3120 if (char *version_url = vinfo->maybe_make_version_url ())
3121 {
3122 driver_obj->set_string ("informationUri", version_url);
3123 free (version_url);
3124 }
3125 }
3126
3127 /* "rules" property (SARIF v2.1.0 section 3.19.23). */
3128 driver_obj->set<json::array> ("rules", std::move (m_rules_arr));
3129
3130 return driver_obj;
3131 }
3132
3133 /* If we've seen any CWE IDs, make an array for the "taxonomies" property
3134 (SARIF v2.1.0 section 3.14.8) of a run object, containing a single
3135 "toolComponent" (3.19) as per 3.19.3, representing the CWE.
3136
3137 Otherwise return nullptr. */
3138
3139 std::unique_ptr<json::array>
3140 sarif_builder::maybe_make_taxonomies_array () const
3141 {
3142 auto cwe_obj = maybe_make_cwe_taxonomy_object ();
3143 if (!cwe_obj)
3144 return nullptr;
3145
3146 /* "taxonomies" property (SARIF v2.1.0 section 3.14.8). */
3147 auto taxonomies_arr = ::make_unique<json::array> ();
3148 taxonomies_arr->append<sarif_tool_component> (std::move (cwe_obj));
3149 return taxonomies_arr;
3150 }
3151
3152 /* If we've seen any CWE IDs, make a "toolComponent" object
3153 (SARIF v2.1.0 section 3.19) representing the CWE taxonomy, as per 3.19.3.
3154 Populate the "taxa" property with all of the CWE IDs in m_cwe_id_set.
3155
3156 Otherwise return nullptr. */
3157
3158 std::unique_ptr<sarif_tool_component>
3159 sarif_builder::maybe_make_cwe_taxonomy_object () const
3160 {
3161 if (m_cwe_id_set.is_empty ())
3162 return nullptr;
3163
3164 auto taxonomy_obj = ::make_unique<sarif_tool_component> ();
3165
3166 /* "name" property (SARIF v2.1.0 section 3.19.8). */
3167 taxonomy_obj->set_string ("name", "CWE");
3168
3169 /* "version" property (SARIF v2.1.0 section 3.19.13). */
3170 taxonomy_obj->set_string ("version", "4.7");
3171
3172 /* "organization" property (SARIF v2.1.0 section 3.19.18). */
3173 taxonomy_obj->set_string ("organization", "MITRE");
3174
3175 /* "shortDescription" property (SARIF v2.1.0 section 3.19.19). */
3176 taxonomy_obj->set<sarif_multiformat_message_string>
3177 ("shortDescription",
3178 make_multiformat_message_string ("The MITRE"
3179 " Common Weakness Enumeration"));
3180
3181 /* "taxa" property (SARIF v2.1.0 3.section 3.19.25). */
3182 auto taxa_arr = ::make_unique<json::array> ();
3183 for (auto cwe_id : m_cwe_id_set)
3184 taxa_arr->append<sarif_reporting_descriptor>
3185 (make_reporting_descriptor_object_for_cwe_id (cwe_id));
3186 taxonomy_obj->set<json::array> ("taxa", std::move (taxa_arr));
3187
3188 return taxonomy_obj;
3189 }
3190
3191 /* Ensure that we have an "artifact" object (SARIF v2.1.0 section 3.24)
3192 for FILENAME, adding it to m_filename_to_artifact_map if not already
3193 found, and adding ROLE to it.
3194 If EMBED_CONTENTS is true, then flag that we will attempt to embed the
3195 contents of this artifact when writing it out. */
3196
3197 sarif_artifact &
3198 sarif_builder::get_or_create_artifact (const char *filename,
3199 enum diagnostic_artifact_role role,
3200 bool embed_contents)
3201 {
3202 if (auto *slot = m_filename_to_artifact_map.get (filename))
3203 {
3204 (*slot)->add_role (role, embed_contents);
3205 return **slot;
3206 }
3207
3208 sarif_artifact *artifact_obj = new sarif_artifact (filename);
3209 artifact_obj->add_role (role, embed_contents);
3210 m_filename_to_artifact_map.put (filename, artifact_obj);
3211
3212 /* "location" property (SARIF v2.1.0 section 3.24.2). */
3213 artifact_obj->set<sarif_artifact_location>
3214 ("location", make_artifact_location_object (filename));
3215
3216 /* "sourceLanguage" property (SARIF v2.1.0 section 3.24.10). */
3217 switch (role)
3218 {
3219 default:
3220 gcc_unreachable ();
3221 case diagnostic_artifact_role::analysis_target:
3222 case diagnostic_artifact_role::result_file:
3223 case diagnostic_artifact_role::scanned_file:
3224 case diagnostic_artifact_role::traced_file:
3225 /* Assume that these are in the source language. */
3226 if (auto client_data_hooks = m_context.get_client_data_hooks ())
3227 if (const char *source_lang
3228 = client_data_hooks->maybe_get_sarif_source_language (filename))
3229 artifact_obj->set_string ("sourceLanguage", source_lang);
3230 break;
3231
3232 case diagnostic_artifact_role::debug_output_file:
3233 /* Assume that these are not in the source language. */
3234 break;
3235 }
3236
3237 return *artifact_obj;
3238 }
3239
3240 /* Make an "artifactContent" object (SARIF v2.1.0 section 3.3) for the
3241 full contents of FILENAME. */
3242
3243 std::unique_ptr<sarif_artifact_content>
3244 sarif_builder::maybe_make_artifact_content_object (const char *filename) const
3245 {
3246 /* Let input.cc handle any charset conversion. */
3247 char_span utf8_content
3248 = m_context.get_file_cache ().get_source_file_content (filename);
3249 if (!utf8_content)
3250 return nullptr;
3251
3252 /* Don't add it if it's not valid UTF-8. */
3253 if (!cpp_valid_utf8_p(utf8_content.get_buffer (), utf8_content.length ()))
3254 return nullptr;
3255
3256 auto artifact_content_obj = ::make_unique<sarif_artifact_content> ();
3257 artifact_content_obj->set<json::string>
3258 ("text",
3259 ::make_unique <json::string> (utf8_content.get_buffer (),
3260 utf8_content.length ()));
3261 return artifact_content_obj;
3262 }
3263
3264 /* Attempt to read the given range of lines from FILENAME; return
3265 a freshly-allocated 0-terminated buffer containing them, or nullptr. */
3266
3267 char *
3268 sarif_builder::get_source_lines (const char *filename,
3269 int start_line,
3270 int end_line) const
3271 {
3272 auto_vec<char> result;
3273
3274 for (int line = start_line; line <= end_line; line++)
3275 {
3276 char_span line_content
3277 = m_context.get_file_cache ().get_source_line (filename, line);
3278 if (!line_content.get_buffer ())
3279 return nullptr;
3280 result.reserve (line_content.length () + 1);
3281 for (size_t i = 0; i < line_content.length (); i++)
3282 result.quick_push (line_content[i]);
3283 result.quick_push ('\n');
3284 }
3285 result.safe_push ('\0');
3286
3287 return xstrdup (result.address ());
3288 }
3289
3290 /* Make an "artifactContent" object (SARIF v2.1.0 section 3.3) for the given
3291 run of lines within FILENAME (including the endpoints).
3292 If R is non-NULL, use it to potentially set the "rendered"
3293 property (3.3.4). */
3294
3295 std::unique_ptr<sarif_artifact_content>
3296 sarif_builder::
3297 maybe_make_artifact_content_object (const char *filename,
3298 int start_line,
3299 int end_line,
3300 const content_renderer *r) const
3301 {
3302 char *text_utf8 = get_source_lines (filename, start_line, end_line);
3303
3304 if (!text_utf8)
3305 return nullptr;
3306
3307 /* Don't add it if it's not valid UTF-8. */
3308 if (!cpp_valid_utf8_p(text_utf8, strlen(text_utf8)))
3309 {
3310 free (text_utf8);
3311 return nullptr;
3312 }
3313
3314 auto artifact_content_obj = ::make_unique<sarif_artifact_content> ();
3315 artifact_content_obj->set_string ("text", text_utf8);
3316 free (text_utf8);
3317
3318 /* 3.3.4 "rendered" property. */
3319 if (r)
3320 if (std::unique_ptr<sarif_multiformat_message_string> rendered
3321 = r->render (*this))
3322 artifact_content_obj->set ("rendered", std::move (rendered));
3323
3324 return artifact_content_obj;
3325 }
3326
3327 /* Make a "fix" object (SARIF v2.1.0 section 3.55) for RICHLOC. */
3328
3329 std::unique_ptr<sarif_fix>
3330 sarif_builder::make_fix_object (const rich_location &richloc)
3331 {
3332 auto fix_obj = ::make_unique<sarif_fix> ();
3333
3334 /* "artifactChanges" property (SARIF v2.1.0 section 3.55.3). */
3335 /* We assume that all fix-it hints in RICHLOC affect the same file. */
3336 auto artifact_change_arr = ::make_unique<json::array> ();
3337 artifact_change_arr->append<sarif_artifact_change>
3338 (make_artifact_change_object (richloc));
3339 fix_obj->set<json::array> ("artifactChanges",
3340 std::move (artifact_change_arr));
3341
3342 return fix_obj;
3343 }
3344
3345 /* Make an "artifactChange" object (SARIF v2.1.0 section 3.56) for RICHLOC. */
3346
3347 std::unique_ptr<sarif_artifact_change>
3348 sarif_builder::make_artifact_change_object (const rich_location &richloc)
3349 {
3350 auto artifact_change_obj = ::make_unique<sarif_artifact_change> ();
3351
3352 /* "artifactLocation" property (SARIF v2.1.0 section 3.56.2). */
3353 artifact_change_obj->set<sarif_artifact_location>
3354 ("artifactLocation",
3355 make_artifact_location_object (richloc.get_loc ()));
3356
3357 /* "replacements" property (SARIF v2.1.0 section 3.56.3). */
3358 auto replacement_arr = ::make_unique<json::array> ();
3359 for (unsigned int i = 0; i < richloc.get_num_fixit_hints (); i++)
3360 {
3361 const fixit_hint *hint = richloc.get_fixit_hint (i);
3362 replacement_arr->append<sarif_replacement>
3363 (make_replacement_object (*hint));
3364 }
3365 artifact_change_obj->set<json::array> ("replacements",
3366 std::move (replacement_arr));
3367
3368 return artifact_change_obj;
3369 }
3370
3371 /* Make a "replacement" object (SARIF v2.1.0 section 3.57) for HINT. */
3372
3373 std::unique_ptr<sarif_replacement>
3374 sarif_builder::make_replacement_object (const fixit_hint &hint) const
3375 {
3376 auto replacement_obj = ::make_unique<sarif_replacement> ();
3377
3378 /* "deletedRegion" property (SARIF v2.1.0 section 3.57.3). */
3379 replacement_obj->set<sarif_region> ("deletedRegion",
3380 make_region_object_for_hint (hint));
3381
3382 /* "insertedContent" property (SARIF v2.1.0 section 3.57.4). */
3383 replacement_obj->set<sarif_artifact_content>
3384 ("insertedContent",
3385 make_artifact_content_object (hint.get_string ()));
3386
3387 return replacement_obj;
3388 }
3389
3390 /* Make an "artifactContent" object (SARIF v2.1.0 section 3.3) for TEXT. */
3391
3392 std::unique_ptr<sarif_artifact_content>
3393 sarif_builder::make_artifact_content_object (const char *text) const
3394 {
3395 auto content_obj = ::make_unique<sarif_artifact_content> ();
3396
3397 /* "text" property (SARIF v2.1.0 section 3.3.2). */
3398 content_obj->set_string ("text", text);
3399
3400 return content_obj;
3401 }
3402
3403 /* class diagnostic_sarif_format_buffer : public diagnostic_per_format_buffer. */
3404
3405 void
3406 diagnostic_sarif_format_buffer::dump (FILE *out, int indent) const
3407 {
3408 fprintf (out, "%*sdiagnostic_sarif_format_buffer:\n", indent, "");
3409 int idx = 0;
3410 for (auto &result : m_results)
3411 {
3412 fprintf (out, "%*sresult[%i]:\n", indent + 2, "", idx);
3413 result->dump (out, true);
3414 fprintf (out, "\n");
3415 ++idx;
3416 }
3417 }
3418
3419 bool
3420 diagnostic_sarif_format_buffer::empty_p () const
3421 {
3422 return m_results.empty ();
3423 }
3424
3425 void
3426 diagnostic_sarif_format_buffer::move_to (diagnostic_per_format_buffer &base)
3427 {
3428 diagnostic_sarif_format_buffer &dest
3429 = static_cast<diagnostic_sarif_format_buffer &> (base);
3430 for (auto &&result : m_results)
3431 dest.m_results.push_back (std::move (result));
3432 m_results.clear ();
3433 }
3434
3435 void
3436 diagnostic_sarif_format_buffer::clear ()
3437 {
3438 m_results.clear ();
3439 }
3440
3441 void
3442 diagnostic_sarif_format_buffer::flush ()
3443 {
3444 for (auto &&result : m_results)
3445 {
3446 result->process_worklist (m_builder);
3447 m_builder.m_results_array->append<sarif_result> (std::move (result));
3448 }
3449 m_results.clear ();
3450 }
3451
3452 class sarif_output_format : public diagnostic_output_format
3453 {
3454 public:
3455 ~sarif_output_format ()
3456 {
3457 /* Any sarifResult objects should have been handled by now.
3458 If not, then something's gone wrong with diagnostic
3459 groupings. */
3460 std::unique_ptr<sarif_result> pending_result
3461 = m_builder.take_current_result ();
3462 gcc_assert (!pending_result);
3463 }
3464
3465 void dump (FILE *out, int indent) const override
3466 {
3467 fprintf (out, "%*ssarif_output_format\n", indent, "");
3468 diagnostic_output_format::dump (out, indent);
3469 }
3470
3471 std::unique_ptr<diagnostic_per_format_buffer>
3472 make_per_format_buffer () final override
3473 {
3474 return ::make_unique<diagnostic_sarif_format_buffer> (m_builder);
3475 }
3476 void set_buffer (diagnostic_per_format_buffer *base_buffer) final override
3477 {
3478 diagnostic_sarif_format_buffer *buffer
3479 = static_cast<diagnostic_sarif_format_buffer *> (base_buffer);
3480 m_buffer = buffer;
3481 }
3482
3483 bool follows_reference_printer_p () const final override
3484 {
3485 return false;
3486 }
3487
3488 void update_printer () final override
3489 {
3490 m_printer = m_context.clone_printer ();
3491
3492 /* Don't colorize the text. */
3493 pp_show_color (m_printer.get ()) = false;
3494
3495 /* No textual URLs. */
3496 m_printer->set_url_format (URL_FORMAT_NONE);
3497
3498 /* Use builder's token printer. */
3499 get_printer ()->set_token_printer (&m_builder.get_token_printer ());
3500
3501 /* Update the builder to use the new printer. */
3502 m_builder.set_printer (*get_printer ());
3503 }
3504
3505 void on_begin_group () final override
3506 {
3507 /* No-op, */
3508 }
3509 void on_end_group () final override
3510 {
3511 m_builder.end_group ();
3512 }
3513 void
3514 on_report_diagnostic (const diagnostic_info &diagnostic,
3515 diagnostic_t orig_diag_kind) final override
3516 {
3517 m_builder.on_report_diagnostic (diagnostic, orig_diag_kind, m_buffer);
3518 }
3519 void on_diagram (const diagnostic_diagram &diagram) final override
3520 {
3521 m_builder.emit_diagram (diagram);
3522 }
3523 void after_diagnostic (const diagnostic_info &) final override
3524 {
3525 /* No-op. */
3526 }
3527
3528 sarif_builder &get_builder () { return m_builder; }
3529
3530 size_t num_results () const { return m_builder.num_results (); }
3531 sarif_result &get_result (size_t idx) { return m_builder.get_result (idx); }
3532
3533 protected:
3534 sarif_output_format (diagnostic_context &context,
3535 const line_maps *line_maps,
3536 const char *main_input_filename_,
3537 bool formatted,
3538 enum sarif_version version)
3539 : diagnostic_output_format (context),
3540 m_builder (context, *get_printer (), line_maps, main_input_filename_,
3541 formatted, version),
3542 m_buffer (nullptr)
3543 {}
3544
3545 sarif_builder m_builder;
3546 diagnostic_sarif_format_buffer *m_buffer;
3547 };
3548
3549 class sarif_stream_output_format : public sarif_output_format
3550 {
3551 public:
3552 sarif_stream_output_format (diagnostic_context &context,
3553 const line_maps *line_maps,
3554 const char *main_input_filename_,
3555 bool formatted,
3556 enum sarif_version version,
3557 FILE *stream)
3558 : sarif_output_format (context, line_maps, main_input_filename_,
3559 formatted, version),
3560 m_stream (stream)
3561 {
3562 }
3563 ~sarif_stream_output_format ()
3564 {
3565 m_builder.flush_to_file (m_stream);
3566 }
3567 bool machine_readable_stderr_p () const final override
3568 {
3569 return m_stream == stderr;
3570 }
3571 private:
3572 FILE *m_stream;
3573 };
3574
3575 class sarif_file_output_format : public sarif_output_format
3576 {
3577 public:
3578 sarif_file_output_format (diagnostic_context &context,
3579 const line_maps *line_maps,
3580 const char *main_input_filename_,
3581 bool formatted,
3582 enum sarif_version version,
3583 diagnostic_output_file output_file)
3584 : sarif_output_format (context, line_maps, main_input_filename_,
3585 formatted, version),
3586 m_output_file (std::move (output_file))
3587 {
3588 gcc_assert (m_output_file.get_open_file ());
3589 gcc_assert (m_output_file.get_filename ());
3590 }
3591 ~sarif_file_output_format ()
3592 {
3593 m_builder.flush_to_file (m_output_file.get_open_file ());
3594 }
3595 void dump (FILE *out, int indent) const override
3596 {
3597 fprintf (out, "%*ssarif_file_output_format: %s\n",
3598 indent, "",
3599 m_output_file.get_filename ());
3600 diagnostic_output_format::dump (out, indent);
3601 }
3602 bool machine_readable_stderr_p () const final override
3603 {
3604 return false;
3605 }
3606
3607 private:
3608 diagnostic_output_file m_output_file;
3609 };
3610
3611 /* Print the start of an embedded link to PP, as per 3.11.6. */
3612
3613 static void
3614 sarif_begin_embedded_link (pretty_printer *pp)
3615 {
3616 pp_character (pp, '[');
3617 }
3618
3619 /* Print the end of an embedded link to PP, as per 3.11.6. */
3620
3621 static void
3622 sarif_end_embedded_link (pretty_printer *pp,
3623 const char *url)
3624 {
3625 pp_string (pp, "](");
3626 /* TODO: does the URI need escaping?
3627 See https://github.com/oasis-tcs/sarif-spec/issues/657 */
3628 pp_string (pp, url);
3629 pp_character (pp, ')');
3630 }
3631
3632 /* class sarif_token_printer : public token_printer. */
3633
3634 /* Implementation of pretty_printer::token_printer for SARIF output.
3635 Emit URLs as per 3.11.6 ("Messages with embedded links"). */
3636
3637 void
3638 sarif_builder::sarif_token_printer::print_tokens (pretty_printer *pp,
3639 const pp_token_list &tokens)
3640 {
3641 /* Convert to text, possibly with colorization, URLs, etc. */
3642 label_text current_url;
3643 for (auto iter = tokens.m_first; iter; iter = iter->m_next)
3644 switch (iter->m_kind)
3645 {
3646 default:
3647 gcc_unreachable ();
3648
3649 case pp_token::kind::text:
3650 {
3651 const pp_token_text *sub = as_a <const pp_token_text *> (iter);
3652 const char * const str = sub->m_value.get ();
3653 if (current_url.get ())
3654 {
3655 /* Write iter->m_value, but escaping any
3656 escaped link characters as per 3.11.6. */
3657 for (const char *ptr = str; *ptr; ptr++)
3658 {
3659 const char ch = *ptr;
3660 switch (ch)
3661 {
3662 default:
3663 pp_character (pp, ch);
3664 break;
3665 case '\\':
3666 case '[':
3667 case ']':
3668 pp_character (pp, '\\');
3669 pp_character (pp, ch);
3670 break;
3671 }
3672 }
3673 }
3674 else
3675 /* TODO: is other escaping needed? (e.g. of '[')
3676 See https://github.com/oasis-tcs/sarif-spec/issues/658 */
3677 pp_string (pp, str);
3678 }
3679 break;
3680
3681 case pp_token::kind::begin_color:
3682 case pp_token::kind::end_color:
3683 /* These are no-ops. */
3684 break;
3685
3686 case pp_token::kind::begin_quote:
3687 pp_begin_quote (pp, pp_show_color (pp));
3688 break;
3689 case pp_token::kind::end_quote:
3690 pp_end_quote (pp, pp_show_color (pp));
3691 break;
3692
3693 /* Emit URLs as per 3.11.6 ("Messages with embedded links"). */
3694 case pp_token::kind::begin_url:
3695 {
3696 pp_token_begin_url *sub = as_a <pp_token_begin_url *> (iter);
3697 sarif_begin_embedded_link (pp);
3698 current_url = std::move (sub->m_value);
3699 }
3700 break;
3701 case pp_token::kind::end_url:
3702 gcc_assert (current_url.get ());
3703 sarif_end_embedded_link (pp, current_url.get ());
3704 current_url = label_text::borrow (nullptr);
3705 break;
3706
3707 case pp_token::kind::event_id:
3708 {
3709 pp_token_event_id *sub = as_a <pp_token_event_id *> (iter);
3710 gcc_assert (sub->m_event_id.known_p ());
3711 const sarif_code_flow *code_flow
3712 = m_builder.get_code_flow_for_event_ids ();
3713 label_text url = make_sarif_url_for_event (code_flow,
3714 sub->m_event_id);
3715 if (url.get ())
3716 sarif_begin_embedded_link (pp);
3717 pp_character (pp, '(');
3718 pp_decimal_int (pp, sub->m_event_id.one_based ());
3719 pp_character (pp, ')');
3720 if (url.get ())
3721 sarif_end_embedded_link (pp, url.get ());
3722 }
3723 break;
3724 }
3725 }
3726
3727 /* Populate CONTEXT in preparation for SARIF output (either to stderr, or
3728 to a file). */
3729
3730 static void
3731 diagnostic_output_format_init_sarif (diagnostic_context &context,
3732 std::unique_ptr<sarif_output_format> fmt)
3733 {
3734 fmt->update_printer ();
3735
3736 context.set_output_format (std::move (fmt));
3737 }
3738
3739 /* Populate CONTEXT in preparation for SARIF output to stderr. */
3740
3741 void
3742 diagnostic_output_format_init_sarif_stderr (diagnostic_context &context,
3743 const line_maps *line_maps,
3744 const char *main_input_filename_,
3745 bool formatted,
3746 enum sarif_version version)
3747 {
3748 gcc_assert (line_maps);
3749 diagnostic_output_format_init_sarif
3750 (context,
3751 ::make_unique<sarif_stream_output_format> (context,
3752 line_maps,
3753 main_input_filename_,
3754 formatted,
3755 version,
3756 stderr));
3757 }
3758
3759 /* Attempt to open BASE_FILE_NAME.sarif for writing.
3760 Return a non-null diagnostic_output_file,
3761 or return a null diagnostic_output_file and complain to CONTEXT
3762 using LINE_MAPS. */
3763
3764 diagnostic_output_file
3765 diagnostic_output_format_open_sarif_file (diagnostic_context &context,
3766 line_maps *line_maps,
3767 const char *base_file_name)
3768 {
3769 if (!base_file_name)
3770 {
3771 rich_location richloc (line_maps, UNKNOWN_LOCATION);
3772 context.emit_diagnostic_with_group
3773 (DK_ERROR, richloc, nullptr, 0,
3774 "unable to determine filename for SARIF output");
3775 return diagnostic_output_file ();
3776 }
3777
3778 label_text filename = label_text::take (concat (base_file_name,
3779 ".sarif",
3780 nullptr));
3781 FILE *outf = fopen (filename.get (), "w");
3782 if (!outf)
3783 {
3784 rich_location richloc (line_maps, UNKNOWN_LOCATION);
3785 context.emit_diagnostic_with_group
3786 (DK_ERROR, richloc, nullptr, 0,
3787 "unable to open %qs for SARIF output: %m",
3788 filename.get ());
3789 return diagnostic_output_file ();
3790 }
3791 return diagnostic_output_file (outf, true, std::move (filename));
3792 }
3793
3794 /* Populate CONTEXT in preparation for SARIF output to a file named
3795 BASE_FILE_NAME.sarif. */
3796
3797 void
3798 diagnostic_output_format_init_sarif_file (diagnostic_context &context,
3799 line_maps *line_maps,
3800 const char *main_input_filename_,
3801 bool formatted,
3802 enum sarif_version version,
3803 const char *base_file_name)
3804 {
3805 gcc_assert (line_maps);
3806
3807 diagnostic_output_file output_file
3808 = diagnostic_output_format_open_sarif_file (context,
3809 line_maps,
3810 base_file_name);
3811
3812 diagnostic_output_format_init_sarif
3813 (context,
3814 ::make_unique<sarif_file_output_format> (context,
3815 line_maps,
3816 main_input_filename_,
3817 formatted,
3818 version,
3819 std::move (output_file)));
3820 }
3821
3822 /* Populate CONTEXT in preparation for SARIF output to STREAM. */
3823
3824 void
3825 diagnostic_output_format_init_sarif_stream (diagnostic_context &context,
3826 const line_maps *line_maps,
3827 const char *main_input_filename_,
3828 bool formatted,
3829 enum sarif_version version,
3830 FILE *stream)
3831 {
3832 gcc_assert (line_maps);
3833 diagnostic_output_format_init_sarif
3834 (context,
3835 ::make_unique<sarif_stream_output_format> (context,
3836 line_maps,
3837 main_input_filename_,
3838 formatted,
3839 version,
3840 stream));
3841 }
3842
3843 std::unique_ptr<diagnostic_output_format>
3844 make_sarif_sink (diagnostic_context &context,
3845 const line_maps &line_maps,
3846 const char *main_input_filename_,
3847 enum sarif_version version,
3848 diagnostic_output_file output_file)
3849 {
3850 auto sink = ::make_unique<sarif_file_output_format> (context,
3851 &line_maps,
3852 main_input_filename_,
3853 true,
3854 version,
3855 std::move (output_file));
3856 sink->update_printer ();
3857 return sink;
3858 }
3859
3860 #if CHECKING_P
3861
3862 namespace selftest {
3863
3864 /* A subclass of sarif_output_format for writing selftests.
3865 The JSON output is cached internally, rather than written
3866 out to a file. */
3867
3868 class test_sarif_diagnostic_context : public test_diagnostic_context
3869 {
3870 public:
3871 test_sarif_diagnostic_context (const char *main_input_filename,
3872 enum sarif_version version)
3873 {
3874 auto format = ::make_unique<buffered_output_format> (*this,
3875 line_table,
3876 main_input_filename,
3877 true,
3878 version);
3879 m_format = format.get (); // borrowed
3880 diagnostic_output_format_init_sarif (*this, std::move (format));
3881 }
3882
3883 std::unique_ptr<sarif_log> flush_to_object ()
3884 {
3885 return m_format->flush_to_object ();
3886 }
3887
3888 size_t num_results () const { return m_format->num_results (); }
3889 sarif_result &get_result (size_t idx) { return m_format->get_result (idx); }
3890
3891 private:
3892 class buffered_output_format : public sarif_output_format
3893 {
3894 public:
3895 buffered_output_format (diagnostic_context &context,
3896 const line_maps *line_maps,
3897 const char *main_input_filename_,
3898 bool formatted,
3899 enum sarif_version version)
3900 : sarif_output_format (context, line_maps, main_input_filename_,
3901 formatted, version)
3902 {
3903 }
3904 bool machine_readable_stderr_p () const final override
3905 {
3906 return false;
3907 }
3908 std::unique_ptr<sarif_log> flush_to_object ()
3909 {
3910 return m_builder.flush_to_object ();
3911 }
3912 };
3913
3914 buffered_output_format *m_format; // borrowed
3915 };
3916
3917 /* Test making a sarif_location for a complex rich_location
3918 with labels and escape-on-output. */
3919
3920 static void
3921 test_make_location_object (const line_table_case &case_,
3922 enum sarif_version version)
3923 {
3924 diagnostic_show_locus_fixture_one_liner_utf8 f (case_);
3925 location_t line_end = linemap_position_for_column (line_table, 31);
3926
3927 /* Don't attempt to run the tests if column data might be unavailable. */
3928 if (line_end > LINE_MAP_MAX_LOCATION_WITH_COLS)
3929 return;
3930
3931 test_diagnostic_context dc;
3932 pretty_printer pp;
3933 sarif_builder builder (dc, pp, line_table, "MAIN_INPUT_FILENAME",
3934 true, version);
3935
3936 /* These "columns" are byte offsets, whereas later on the columns
3937 in the generated SARIF use sarif_builder::get_sarif_column and
3938 thus respect tabs, encoding. */
3939 const location_t foo
3940 = make_location (linemap_position_for_column (line_table, 1),
3941 linemap_position_for_column (line_table, 1),
3942 linemap_position_for_column (line_table, 8));
3943 const location_t bar
3944 = make_location (linemap_position_for_column (line_table, 12),
3945 linemap_position_for_column (line_table, 12),
3946 linemap_position_for_column (line_table, 17));
3947 const location_t field
3948 = make_location (linemap_position_for_column (line_table, 19),
3949 linemap_position_for_column (line_table, 19),
3950 linemap_position_for_column (line_table, 30));
3951
3952 text_range_label label0 ("label0");
3953 text_range_label label1 ("label1");
3954 text_range_label label2 ("label2");
3955
3956 rich_location richloc (line_table, foo, &label0, nullptr);
3957 richloc.add_range (bar, SHOW_RANGE_WITHOUT_CARET, &label1);
3958 richloc.add_range (field, SHOW_RANGE_WITHOUT_CARET, &label2);
3959 richloc.set_escape_on_output (true);
3960
3961 sarif_result result (0);
3962
3963 std::unique_ptr<sarif_location> location_obj
3964 = builder.make_location_object
3965 (result, richloc, nullptr, diagnostic_artifact_role::analysis_target);
3966 ASSERT_NE (location_obj, nullptr);
3967
3968 auto physical_location
3969 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (location_obj.get (),
3970 "physicalLocation");
3971 {
3972 auto region
3973 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (physical_location, "region");
3974 ASSERT_JSON_INT_PROPERTY_EQ (region, "startLine", 1);
3975 ASSERT_JSON_INT_PROPERTY_EQ (region, "startColumn", 1);
3976 ASSERT_JSON_INT_PROPERTY_EQ (region, "endColumn", 7);
3977 }
3978 {
3979 auto context_region
3980 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (physical_location,
3981 "contextRegion");
3982 ASSERT_JSON_INT_PROPERTY_EQ (context_region, "startLine", 1);
3983
3984 {
3985 auto snippet
3986 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (context_region, "snippet");
3987
3988 /* We expect the snippet's "text" to be a copy of the content. */
3989 ASSERT_JSON_STRING_PROPERTY_EQ (snippet, "text", f.m_content);
3990
3991 /* We expect the snippet to have a "rendered" whose "text" has a
3992 pure ASCII escaped copy of the line (with labels, etc). */
3993 {
3994 auto rendered
3995 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (snippet, "rendered");
3996 ASSERT_JSON_STRING_PROPERTY_EQ
3997 (rendered, "text",
3998 "1 | <U+1F602>_foo = <U+03C0>_bar.<U+1F602>_field<U+03C0>;\n"
3999 " | ^~~~~~~~~~~~~ ~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~\n"
4000 " | | | |\n"
4001 " | label0 label1 label2\n");
4002 }
4003 }
4004 }
4005 auto annotations
4006 = EXPECT_JSON_OBJECT_WITH_ARRAY_PROPERTY (location_obj.get (),
4007 "annotations");
4008 ASSERT_EQ (annotations->size (), 3);
4009 {
4010 {
4011 auto a0 = (*annotations)[0];
4012 ASSERT_JSON_INT_PROPERTY_EQ (a0, "startLine", 1);
4013 ASSERT_JSON_INT_PROPERTY_EQ (a0, "startColumn", 1);
4014 ASSERT_JSON_INT_PROPERTY_EQ (a0, "endColumn", 7);
4015 auto message
4016 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (a0, "message");
4017 ASSERT_JSON_STRING_PROPERTY_EQ (message, "text", "label0");
4018 }
4019 {
4020 auto a1 = (*annotations)[1];
4021 ASSERT_JSON_INT_PROPERTY_EQ (a1, "startLine", 1);
4022 ASSERT_JSON_INT_PROPERTY_EQ (a1, "startColumn", 10);
4023 ASSERT_JSON_INT_PROPERTY_EQ (a1, "endColumn", 15);
4024 auto message
4025 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (a1, "message");
4026 ASSERT_JSON_STRING_PROPERTY_EQ (message, "text", "label1");
4027 }
4028 {
4029 auto a2 = (*annotations)[2];
4030 ASSERT_JSON_INT_PROPERTY_EQ (a2, "startLine", 1);
4031 ASSERT_JSON_INT_PROPERTY_EQ (a2, "startColumn", 16);
4032 ASSERT_JSON_INT_PROPERTY_EQ (a2, "endColumn", 25);
4033 auto message
4034 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (a2, "message");
4035 ASSERT_JSON_STRING_PROPERTY_EQ (message, "text", "label2");
4036 }
4037 }
4038 }
4039
4040 /* Test of reporting a diagnostic at UNKNOWN_LOCATION to a
4041 diagnostic_context and examining the generated sarif_log.
4042 Verify various basic properties. */
4043
4044 static void
4045 test_simple_log (enum sarif_version version)
4046 {
4047 test_sarif_diagnostic_context dc ("MAIN_INPUT_FILENAME", version);
4048
4049 rich_location richloc (line_table, UNKNOWN_LOCATION);
4050 dc.report (DK_ERROR, richloc, nullptr, 0, "this is a test: %i", 42);
4051
4052 auto log_ptr = dc.flush_to_object ();
4053
4054 // 3.13 sarifLog:
4055 auto log = log_ptr.get ();
4056 ASSERT_JSON_STRING_PROPERTY_EQ (log, "$schema",
4057 sarif_version_to_url (version));
4058 ASSERT_JSON_STRING_PROPERTY_EQ (log, "version",
4059 sarif_version_to_property (version));
4060
4061 auto runs = EXPECT_JSON_OBJECT_WITH_ARRAY_PROPERTY (log, "runs"); // 3.13.4
4062 ASSERT_EQ (runs->size (), 1);
4063
4064 // 3.14 "run" object:
4065 auto run = (*runs)[0];
4066
4067 {
4068 // 3.14.6:
4069 auto tool = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (run, "tool");
4070
4071 EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (tool, "driver"); // 3.18.2
4072 }
4073
4074 {
4075 // 3.14.11
4076 auto invocations
4077 = EXPECT_JSON_OBJECT_WITH_ARRAY_PROPERTY (run, "invocations");
4078 ASSERT_EQ (invocations->size (), 1);
4079
4080 {
4081 // 3.20 "invocation" object:
4082 auto invocation = (*invocations)[0];
4083
4084 // 3.20.3 arguments property
4085
4086 // 3.20.7 startTimeUtc property
4087 EXPECT_JSON_OBJECT_WITH_STRING_PROPERTY (invocation, "startTimeUtc");
4088
4089 // 3.20.8 endTimeUtc property
4090 EXPECT_JSON_OBJECT_WITH_STRING_PROPERTY (invocation, "endTimeUtc");
4091
4092 // 3.20.19 workingDirectory property
4093 {
4094 auto wd_obj
4095 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (invocation,
4096 "workingDirectory");
4097 EXPECT_JSON_OBJECT_WITH_STRING_PROPERTY (wd_obj, "uri");
4098 }
4099
4100 // 3.20.21 toolExecutionNotifications property
4101 auto notifications
4102 = EXPECT_JSON_OBJECT_WITH_ARRAY_PROPERTY
4103 (invocation, "toolExecutionNotifications");
4104 ASSERT_EQ (notifications->size (), 0);
4105 }
4106 }
4107
4108 {
4109 // 3.14.15:
4110 auto artifacts = EXPECT_JSON_OBJECT_WITH_ARRAY_PROPERTY (run, "artifacts");
4111 ASSERT_EQ (artifacts->size (), 1);
4112
4113 {
4114 // 3.24 "artifact" object:
4115 auto artifact = (*artifacts)[0];
4116
4117 // 3.24.2:
4118 auto location
4119 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (artifact, "location");
4120 ASSERT_JSON_STRING_PROPERTY_EQ (location, "uri", "MAIN_INPUT_FILENAME");
4121
4122 // 3.24.6:
4123 auto roles = EXPECT_JSON_OBJECT_WITH_ARRAY_PROPERTY (artifact, "roles");
4124 ASSERT_EQ (roles->size (), 1);
4125 {
4126 auto role = (*roles)[0];
4127 ASSERT_JSON_STRING_EQ (role, "analysisTarget");
4128 }
4129 }
4130 }
4131
4132 {
4133 // 3.14.23:
4134 auto results = EXPECT_JSON_OBJECT_WITH_ARRAY_PROPERTY (run, "results");
4135 ASSERT_EQ (results->size (), 1);
4136
4137 {
4138 // 3.27 "result" object:
4139 auto result = (*results)[0];
4140 ASSERT_JSON_STRING_PROPERTY_EQ (result, "ruleId", "error");
4141 ASSERT_JSON_STRING_PROPERTY_EQ (result, "level", "error"); // 3.27.10
4142
4143 {
4144 // 3.27.11:
4145 auto message
4146 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (result, "message");
4147 ASSERT_JSON_STRING_PROPERTY_EQ (message, "text",
4148 "this is a test: 42");
4149 }
4150
4151 // 3.27.12:
4152 auto locations
4153 = EXPECT_JSON_OBJECT_WITH_ARRAY_PROPERTY (result, "locations");
4154 ASSERT_EQ (locations->size (), 0);
4155 }
4156 }
4157 }
4158
4159 /* As above, but with a "real" location_t. */
4160
4161 static void
4162 test_simple_log_2 (const line_table_case &case_,
4163 enum sarif_version version)
4164 {
4165 auto_fix_quotes fix_quotes;
4166
4167 const char *const content
4168 /* 000000000111111
4169 123456789012345. */
4170 = "unsinged int i;\n";
4171 diagnostic_show_locus_fixture f (case_, content);
4172 location_t line_end = linemap_position_for_column (line_table, 31);
4173
4174 /* Don't attempt to run the tests if column data might be unavailable. */
4175 if (line_end > LINE_MAP_MAX_LOCATION_WITH_COLS)
4176 return;
4177
4178 test_sarif_diagnostic_context dc (f.get_filename (), version);
4179
4180 const location_t typo_loc
4181 = make_location (linemap_position_for_column (line_table, 1),
4182 linemap_position_for_column (line_table, 1),
4183 linemap_position_for_column (line_table, 8));
4184
4185 rich_location richloc (line_table, typo_loc);
4186 dc.report (DK_ERROR, richloc, nullptr, 0,
4187 "did you misspell %qs again?",
4188 "unsigned");
4189
4190 auto log_ptr = dc.flush_to_object ();
4191
4192 // 3.13 sarifLog:
4193 auto log = log_ptr.get ();
4194
4195 auto runs = EXPECT_JSON_OBJECT_WITH_ARRAY_PROPERTY (log, "runs"); // 3.13.4
4196 ASSERT_EQ (runs->size (), 1);
4197
4198 // 3.14 "run" object:
4199 auto run = (*runs)[0];
4200
4201 {
4202 // 3.14.23:
4203 auto results = EXPECT_JSON_OBJECT_WITH_ARRAY_PROPERTY (run, "results");
4204 ASSERT_EQ (results->size (), 1);
4205
4206 {
4207 // 3.27 "result" object:
4208 auto result = (*results)[0];
4209 ASSERT_JSON_STRING_PROPERTY_EQ (result, "ruleId", "error");
4210 ASSERT_JSON_STRING_PROPERTY_EQ (result, "level", "error"); // 3.27.10
4211
4212 {
4213 // 3.27.11:
4214 auto message
4215 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (result, "message");
4216 ASSERT_JSON_STRING_PROPERTY_EQ (message, "text",
4217 "did you misspell `unsigned' again?");
4218 }
4219
4220 // 3.27.12:
4221 auto locations
4222 = EXPECT_JSON_OBJECT_WITH_ARRAY_PROPERTY (result, "locations");
4223 ASSERT_EQ (locations->size (), 1);
4224
4225 {
4226 // 3.28 "location" object:
4227 auto location = (*locations)[0];
4228
4229 auto physical_location
4230 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (location,
4231 "physicalLocation");
4232 {
4233 auto region
4234 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (physical_location,
4235 "region");
4236 ASSERT_JSON_INT_PROPERTY_EQ (region, "startLine", 1);
4237 ASSERT_JSON_INT_PROPERTY_EQ (region, "startColumn", 1);
4238 ASSERT_JSON_INT_PROPERTY_EQ (region, "endColumn", 9);
4239 }
4240 {
4241 auto context_region
4242 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (physical_location,
4243 "contextRegion");
4244 ASSERT_JSON_INT_PROPERTY_EQ (context_region, "startLine", 1);
4245
4246 {
4247 auto snippet
4248 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (context_region,
4249 "snippet");
4250
4251 /* We expect the snippet's "text" to be a copy of the content. */
4252 ASSERT_JSON_STRING_PROPERTY_EQ (snippet, "text", f.m_content);
4253 }
4254 }
4255 }
4256 }
4257 }
4258 }
4259
4260 /* Assuming that a single diagnostic has been emitted within
4261 LOG, get a json::object for the result object. */
4262
4263 static const json::object *
4264 get_result_from_log (const sarif_log *log)
4265 {
4266 auto runs = EXPECT_JSON_OBJECT_WITH_ARRAY_PROPERTY (log, "runs"); // 3.13.4
4267 ASSERT_EQ (runs->size (), 1);
4268
4269 // 3.14 "run" object:
4270 auto run = (*runs)[0];
4271
4272 // 3.14.23:
4273 auto results = EXPECT_JSON_OBJECT_WITH_ARRAY_PROPERTY (run, "results");
4274 ASSERT_EQ (results->size (), 1);
4275
4276 // 3.27 "result" object:
4277 auto result = (*results)[0];
4278 return expect_json_object (SELFTEST_LOCATION, result);
4279 }
4280
4281 static const json::object *
4282 get_message_from_result (const sarif_result &result)
4283 {
4284 // 3.27.11:
4285 auto message_obj
4286 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (&result, "message");
4287 return message_obj;
4288 }
4289
4290 /* Assuming that a single diagnostic has been emitted to
4291 DC, get a json::object for the messsage object within
4292 the result. */
4293
4294 static const json::object *
4295 get_message_from_log (const sarif_log *log)
4296 {
4297 auto result_obj = get_result_from_log (log);
4298
4299 // 3.27.11:
4300 auto message_obj
4301 = EXPECT_JSON_OBJECT_WITH_OBJECT_PROPERTY (result_obj, "message");
4302 return message_obj;
4303 }
4304
4305 /* Tests of messages with embedded links; see SARIF v2.1.0 3.11.6. */
4306
4307 static void
4308 test_message_with_embedded_link (enum sarif_version version)
4309 {
4310 auto_fix_quotes fix_quotes;
4311 {
4312 test_sarif_diagnostic_context dc ("test.c", version);
4313 rich_location richloc (line_table, UNKNOWN_LOCATION);
4314 dc.report (DK_ERROR, richloc, nullptr, 0,
4315 "before %{text%} after",
4316 "http://example.com");
4317 std::unique_ptr<sarif_log> log = dc.flush_to_object ();
4318
4319 auto message_obj = get_message_from_log (log.get ());
4320 ASSERT_JSON_STRING_PROPERTY_EQ
4321 (message_obj, "text",
4322 "before [text](http://example.com) after");
4323 }
4324
4325 /* Escaping in message text.
4326 This is "EXAMPLE 1" from 3.11.6. */
4327 {
4328 test_sarif_diagnostic_context dc ("test.c", version);
4329 rich_location richloc (line_table, UNKNOWN_LOCATION);
4330
4331 /* Disable "unquoted sequence of 2 consecutive punctuation
4332 characters `]\' in format" warning. */
4333 #if __GNUC__ >= 10
4334 # pragma GCC diagnostic push
4335 # pragma GCC diagnostic ignored "-Wformat-diag"
4336 #endif
4337 dc.report (DK_ERROR, richloc, nullptr, 0,
4338 "Prohibited term used in %{para[0]\\spans[2]%}.",
4339 "1");
4340 #if __GNUC__ >= 10
4341 # pragma GCC diagnostic pop
4342 #endif
4343
4344 std::unique_ptr<sarif_log> log = dc.flush_to_object ();
4345
4346 auto message_obj = get_message_from_log (log.get ());
4347 ASSERT_JSON_STRING_PROPERTY_EQ
4348 (message_obj, "text",
4349 "Prohibited term used in [para\\[0\\]\\\\spans\\[2\\]](1).");
4350 /* This isn't exactly what EXAMPLE 1 of the spec has; reported as
4351 https://github.com/oasis-tcs/sarif-spec/issues/656 */
4352 }
4353
4354 /* Urlifier. */
4355 {
4356 class test_urlifier : public urlifier
4357 {
4358 public:
4359 char *
4360 get_url_for_quoted_text (const char *p, size_t sz) const final override
4361 {
4362 if (!strncmp (p, "-foption", sz))
4363 return xstrdup ("http://example.com");
4364 return nullptr;
4365 }
4366 };
4367
4368 test_sarif_diagnostic_context dc ("test.c", version);
4369 dc.push_owned_urlifier (::make_unique<test_urlifier> ());
4370 rich_location richloc (line_table, UNKNOWN_LOCATION);
4371 dc.report (DK_ERROR, richloc, nullptr, 0,
4372 "foo %<-foption%> %<unrecognized%> bar");
4373 std::unique_ptr<sarif_log> log = dc.flush_to_object ();
4374
4375 auto message_obj = get_message_from_log (log.get ());
4376 ASSERT_JSON_STRING_PROPERTY_EQ
4377 (message_obj, "text",
4378 "foo `[-foption](http://example.com)' `unrecognized' bar");
4379 }
4380 }
4381
4382 /* Verify that braces in messages get escaped, as per
4383 3.11.5 ("Messages with placeholders"). */
4384
4385 static void
4386 test_message_with_braces (enum sarif_version version)
4387 {
4388 auto_fix_quotes fix_quotes;
4389 {
4390 test_sarif_diagnostic_context dc ("test.c", version);
4391 rich_location richloc (line_table, UNKNOWN_LOCATION);
4392 dc.report (DK_ERROR, richloc, nullptr, 0,
4393 "open brace: %qs close brace: %qs",
4394 "{", "}");
4395 std::unique_ptr<sarif_log> log = dc.flush_to_object ();
4396
4397 auto message_obj = get_message_from_log (log.get ());
4398 ASSERT_JSON_STRING_PROPERTY_EQ
4399 (message_obj, "text",
4400 "open brace: `{{' close brace: `}}'");
4401 }
4402 }
4403
4404 static void
4405 test_buffering (enum sarif_version version)
4406 {
4407 test_sarif_diagnostic_context dc ("test.c", version);
4408
4409 diagnostic_buffer buf_a (dc);
4410 diagnostic_buffer buf_b (dc);
4411
4412 rich_location rich_loc (line_table, UNKNOWN_LOCATION);
4413
4414 ASSERT_EQ (dc.diagnostic_count (DK_ERROR), 0);
4415 ASSERT_EQ (buf_a.diagnostic_count (DK_ERROR), 0);
4416 ASSERT_EQ (buf_b.diagnostic_count (DK_ERROR), 0);
4417 ASSERT_EQ (dc.num_results (), 0);
4418 ASSERT_TRUE (buf_a.empty_p ());
4419 ASSERT_TRUE (buf_b.empty_p ());
4420
4421 /* Unbuffered diagnostic. */
4422 {
4423 dc.report (DK_ERROR, rich_loc, nullptr, 0,
4424 "message 1");
4425
4426 ASSERT_EQ (dc.diagnostic_count (DK_ERROR), 1);
4427 ASSERT_EQ (buf_a.diagnostic_count (DK_ERROR), 0);
4428 ASSERT_EQ (buf_b.diagnostic_count (DK_ERROR), 0);
4429 ASSERT_EQ (dc.num_results (), 1);
4430 sarif_result &result_obj = dc.get_result (0);
4431 auto message_obj = get_message_from_result (result_obj);
4432 ASSERT_JSON_STRING_PROPERTY_EQ (message_obj, "text",
4433 "message 1");
4434 ASSERT_TRUE (buf_a.empty_p ());
4435 ASSERT_TRUE (buf_b.empty_p ());
4436 }
4437
4438 /* Buffer diagnostic into buffer A. */
4439 {
4440 dc.set_diagnostic_buffer (&buf_a);
4441 dc.report (DK_ERROR, rich_loc, nullptr, 0,
4442 "message in buffer a");
4443 ASSERT_EQ (dc.diagnostic_count (DK_ERROR), 1);
4444 ASSERT_EQ (buf_a.diagnostic_count (DK_ERROR), 1);
4445 ASSERT_EQ (buf_b.diagnostic_count (DK_ERROR), 0);
4446 ASSERT_EQ (dc.num_results (), 1);
4447 ASSERT_FALSE (buf_a.empty_p ());
4448 ASSERT_TRUE (buf_b.empty_p ());
4449 }
4450
4451 /* Buffer diagnostic into buffer B. */
4452 {
4453 dc.set_diagnostic_buffer (&buf_b);
4454 dc.report (DK_ERROR, rich_loc, nullptr, 0,
4455 "message in buffer b");
4456 ASSERT_EQ (dc.diagnostic_count (DK_ERROR), 1);
4457 ASSERT_EQ (buf_a.diagnostic_count (DK_ERROR), 1);
4458 ASSERT_EQ (buf_b.diagnostic_count (DK_ERROR), 1);
4459 ASSERT_EQ (dc.num_results (), 1);
4460 ASSERT_FALSE (buf_a.empty_p ());
4461 ASSERT_FALSE (buf_b.empty_p ());
4462 }
4463
4464 /* Flush buffer B to dc. */
4465 {
4466 dc.flush_diagnostic_buffer (buf_b);
4467 ASSERT_EQ (dc.diagnostic_count (DK_ERROR), 2);
4468 ASSERT_EQ (buf_a.diagnostic_count (DK_ERROR), 1);
4469 ASSERT_EQ (buf_b.diagnostic_count (DK_ERROR), 0);
4470 ASSERT_EQ (dc.num_results (), 2);
4471 sarif_result &result_1_obj = dc.get_result (1);
4472 auto message_1_obj = get_message_from_result (result_1_obj);
4473 ASSERT_JSON_STRING_PROPERTY_EQ (message_1_obj, "text",
4474 "message in buffer b");
4475 ASSERT_FALSE (buf_a.empty_p ());
4476 ASSERT_TRUE (buf_b.empty_p ());
4477 }
4478
4479 /* Clear buffer A. */
4480 {
4481 dc.clear_diagnostic_buffer (buf_a);
4482 ASSERT_EQ (dc.diagnostic_count (DK_ERROR), 2);
4483 ASSERT_EQ (buf_a.diagnostic_count (DK_ERROR), 0);
4484 ASSERT_EQ (buf_b.diagnostic_count (DK_ERROR), 0);
4485 ASSERT_EQ (dc.num_results (), 2);
4486 ASSERT_TRUE (buf_a.empty_p ());
4487 ASSERT_TRUE (buf_b.empty_p ());
4488 }
4489 }
4490
4491 static void
4492 run_tests_per_version (const line_table_case &case_)
4493 {
4494 for (int version_idx = 0;
4495 version_idx < (int)sarif_version::num_versions;
4496 ++version_idx)
4497 {
4498 enum sarif_version version
4499 = static_cast<enum sarif_version> (version_idx);
4500
4501 test_make_location_object (case_, version);
4502 test_simple_log_2 (case_, version);
4503 }
4504 }
4505
4506 /* Run all of the selftests within this file. */
4507
4508 void
4509 diagnostic_format_sarif_cc_tests ()
4510 {
4511 for (int version_idx = 0;
4512 version_idx < (int)sarif_version::num_versions;
4513 ++version_idx)
4514 {
4515 enum sarif_version version
4516 = static_cast<enum sarif_version> (version_idx);
4517
4518 test_simple_log (version);
4519 test_message_with_embedded_link (version);
4520 test_message_with_braces (version);
4521 test_buffering (version);
4522 }
4523
4524 /* Run tests per (line-table-case, SARIF version) pair. */
4525 for_each_line_table_case (run_tests_per_version);
4526 }
4527
4528 } // namespace selftest
4529
4530 #endif /* CHECKING_P */