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