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