]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/plugin.cc
Update copyright years.
[thirdparty/gcc.git] / gcc / plugin.cc
CommitLineData
68a607d8 1/* Support for GCC plugin mechanism.
a945c346 2 Copyright (C) 2009-2024 Free Software Foundation, Inc.
68a607d8
DN
3
4This file is part of GCC.
5
6GCC is free software; you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
8the Free Software Foundation; either version 3, or (at your option)
9any later version.
10
11GCC is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with GCC; see the file COPYING3. If not see
18<http://www.gnu.org/licenses/>. */
19
20/* This file contains the support for GCC plugin mechanism based on the
21 APIs described in doc/plugin.texi. */
22
23#include "config.h"
24#include "system.h"
68a607d8 25#include "coretypes.h"
957060b5 26#include "options.h"
957060b5 27#include "tree-pass.h"
718f9c0f 28#include "diagnostic-core.h"
40e23961 29#include "flags.h"
68a607d8
DN
30#include "intl.h"
31#include "plugin.h"
ae2392a9 32
0acbbdb0 33#ifdef ENABLE_PLUGIN
0c463e16 34#include "plugin-version.h"
0acbbdb0 35#endif
68a607d8 36
8c7dbea9
BK
37#ifdef __MINGW32__
38#ifndef WIN32_LEAN_AND_MEAN
39#define WIN32_LEAN_AND_MEAN
40#endif
41#ifndef NOMINMAX
42#define NOMINMAX
43#endif
902c7559 44#define WIN32_LEAN_AND_MEAN
8c7dbea9
BK
45#include <windows.h>
46#endif
47
090fa0ab
GF
48#define GCC_PLUGIN_STRINGIFY0(X) #X
49#define GCC_PLUGIN_STRINGIFY1(X) GCC_PLUGIN_STRINGIFY0 (X)
50
68a607d8 51/* Event names as strings. Keep in sync with enum plugin_event. */
090fa0ab 52static const char *plugin_event_name_init[] =
68a607d8 53{
090fa0ab
GF
54# define DEFEVENT(NAME) GCC_PLUGIN_STRINGIFY1 (NAME),
55# include "plugin.def"
56# undef DEFEVENT
68a607d8
DN
57};
58
fdabb520 59/* A printf format large enough for the largest event above. */
090fa0ab
GF
60#define FMT_FOR_PLUGIN_EVENT "%-32s"
61
62const char **plugin_event_name = plugin_event_name_init;
63
4a8fb1a1
LC
64/* Event hashtable helpers. */
65
8d67ee55 66struct event_hasher : nofree_ptr_hash <const char *>
4a8fb1a1 67{
67f58944
TS
68 static inline hashval_t hash (const char **);
69 static inline bool equal (const char **, const char **);
4a8fb1a1
LC
70};
71
72/* Helper function for the event hash table that hashes the entry V. */
73
74inline hashval_t
67f58944 75event_hasher::hash (const char **v)
4a8fb1a1
LC
76{
77 return htab_hash_string (*v);
78}
79
80/* Helper function for the event hash table that compares the name of an
81 existing entry (S1) with the given string (S2). */
82
83inline bool
67f58944 84event_hasher::equal (const char **s1, const char **s2)
4a8fb1a1
LC
85{
86 return !strcmp (*s1, *s2);
87}
88
090fa0ab
GF
89/* A hash table to map event names to the position of the names in the
90 plugin_event_name table. */
c203e8a7 91static hash_table<event_hasher> *event_tab;
090fa0ab
GF
92
93/* Keep track of the limit of allocated events and space ready for
94 allocating events. */
95static int event_last = PLUGIN_EVENT_FIRST_DYNAMIC;
96static int event_horizon = PLUGIN_EVENT_FIRST_DYNAMIC;
fdabb520 97
68a607d8
DN
98/* Hash table for the plugin_name_args objects created during command-line
99 parsing. */
100static htab_t plugin_name_args_tab = NULL;
101
102/* List node for keeping track of plugin-registered callback. */
103struct callback_info
104{
105 const char *plugin_name; /* Name of plugin that registers the callback. */
106 plugin_callback_func func; /* Callback to be called. */
107 void *user_data; /* plugin-specified data. */
108 struct callback_info *next;
109};
110
111/* An array of lists of 'callback_info' objects indexed by the event id. */
090fa0ab
GF
112static struct callback_info *plugin_callbacks_init[PLUGIN_EVENT_FIRST_DYNAMIC];
113static struct callback_info **plugin_callbacks = plugin_callbacks_init;
68a607d8 114
efda3807
BH
115/* For invoke_plugin_callbacks(), see plugin.h. */
116bool flag_plugin_added = false;
68a607d8
DN
117
118#ifdef ENABLE_PLUGIN
119/* Each plugin should define an initialization function with exactly
120 this name. */
121static const char *str_plugin_init_func_name = "plugin_init";
fca5bb5c
DN
122
123/* Each plugin should define this symbol to assert that it is
124 distributed under a GPL-compatible license. */
125static const char *str_license = "plugin_is_GPL_compatible";
68a607d8
DN
126#endif
127
d5498d2f
BS
128/* Helper function for hashing the base_name of the plugin_name_args
129 structure to be inserted into the hash table. */
130
131static hashval_t
4b865081 132htab_hash_plugin (const void *p)
d5498d2f
BS
133{
134 const struct plugin_name_args *plugin = (const struct plugin_name_args *) p;
135 return htab_hash_string (plugin->base_name);
136 }
137
68a607d8
DN
138/* Helper function for the hash table that compares the base_name of the
139 existing entry (S1) with the given string (S2). */
140
141static int
142htab_str_eq (const void *s1, const void *s2)
143{
144 const struct plugin_name_args *plugin = (const struct plugin_name_args *) s1;
145 return !strcmp (plugin->base_name, (const char *) s2);
146}
147
148
149/* Given a plugin's full-path name FULL_NAME, e.g. /pass/to/NAME.so,
150 return NAME. */
151
152static char *
153get_plugin_base_name (const char *full_name)
154{
155 /* First get the base name part of the full-path name, i.e. NAME.so. */
156 char *base_name = xstrdup (lbasename (full_name));
157
8c7dbea9 158 /* Then get rid of the extension in the name, e.g., .so. */
68a607d8
DN
159 strip_off_ending (base_name, strlen (base_name));
160
161 return base_name;
162}
163
164
4adbd5dd
MK
165/* Create a plugin_name_args object for the given plugin and insert it
166 to the hash table. This function is called when
167 -fplugin=/path/to/NAME.so or -fplugin=NAME option is processed. */
68a607d8
DN
168
169void
170add_new_plugin (const char* plugin_name)
171{
172 struct plugin_name_args *plugin;
173 void **slot;
4adbd5dd
MK
174 char *base_name;
175 bool name_is_short;
176 const char *pc;
177
efda3807
BH
178 flag_plugin_added = true;
179
4adbd5dd
MK
180 /* Replace short names by their full path when relevant. */
181 name_is_short = !IS_ABSOLUTE_PATH (plugin_name);
182 for (pc = plugin_name; name_is_short && *pc; pc++)
183 if (*pc == '.' || IS_DIR_SEPARATOR (*pc))
184 name_is_short = false;
185
186 if (name_is_short)
187 {
188 base_name = CONST_CAST (char*, plugin_name);
8c7dbea9
BK
189
190#if defined(__MINGW32__)
191 static const char plugin_ext[] = ".dll";
192#elif defined(__APPLE__)
a335cf24 193 /* macOS has two types of libraries: dynamic libraries (.dylib) and
8c7dbea9
BK
194 plugins (.bundle). Both can be used with dlopen()/dlsym() but the
195 former cannot be linked at build time (i.e., with the -lfoo linker
a335cf24 196 option). A GCC plugin is therefore probably a macOS plugin but their
8c7dbea9
BK
197 use seems to be quite rare and the .bundle extension is more of a
198 recommendation rather than the rule. This raises the questions of how
199 well they are supported by tools (e.g., libtool). So to avoid
200 complications let's use the .dylib extension for now. In the future,
201 if this proves to be an issue, we can always check for both
202 extensions. */
203 static const char plugin_ext[] = ".dylib";
204#else
205 static const char plugin_ext[] = ".so";
206#endif
207
4adbd5dd 208 plugin_name = concat (default_plugin_dir_name (), "/",
8c7dbea9 209 plugin_name, plugin_ext, NULL);
4adbd5dd
MK
210 if (access (plugin_name, R_OK))
211 fatal_error
40fecdd6
JM
212 (input_location,
213 "inaccessible plugin file %s expanded from short plugin name %s: %m",
4adbd5dd
MK
214 plugin_name, base_name);
215 }
216 else
217 base_name = get_plugin_base_name (plugin_name);
68a607d8 218
b8698a0f 219 /* If this is the first -fplugin= option we encounter, create
68a607d8
DN
220 'plugin_name_args_tab' hash table. */
221 if (!plugin_name_args_tab)
d5498d2f 222 plugin_name_args_tab = htab_create (10, htab_hash_plugin, htab_str_eq,
68a607d8
DN
223 NULL);
224
d5498d2f
BS
225 slot = htab_find_slot_with_hash (plugin_name_args_tab, base_name,
226 htab_hash_string (base_name), INSERT);
68a607d8
DN
227
228 /* If the same plugin (name) has been specified earlier, either emit an
229 error or a warning message depending on if they have identical full
230 (path) names. */
231 if (*slot)
232 {
233 plugin = (struct plugin_name_args *) *slot;
234 if (strcmp (plugin->full_name, plugin_name))
a9c697b8 235 error ("plugin %qs was specified with different paths: %qs and %qs",
68a607d8
DN
236 plugin->base_name, plugin->full_name, plugin_name);
237 return;
238 }
239
240 plugin = XCNEW (struct plugin_name_args);
241 plugin->base_name = base_name;
242 plugin->full_name = plugin_name;
243
244 *slot = plugin;
245}
246
247
248/* Parse the -fplugin-arg-<name>-<key>[=<value>] option and create a
249 'plugin_argument' object for the parsed key-value pair. ARG is
250 the <name>-<key>[=<value>] part of the option. */
251
252void
253parse_plugin_arg_opt (const char *arg)
254{
255 size_t len = 0, name_len = 0, key_len = 0, value_len = 0;
256 const char *ptr, *name_start = arg, *key_start = NULL, *value_start = NULL;
257 char *name, *key, *value;
258 void **slot;
259 bool name_parsed = false, key_parsed = false;
260
261 /* Iterate over the ARG string and identify the starting character position
262 of 'name', 'key', and 'value' and their lengths. */
263 for (ptr = arg; *ptr; ++ptr)
264 {
265 /* Only the first '-' encountered is considered a separator between
266 'name' and 'key'. All the subsequent '-'s are considered part of
267 'key'. For example, given -fplugin-arg-foo-bar-primary-key=value,
268 the plugin name is 'foo' and the key is 'bar-primary-key'. */
269 if (*ptr == '-' && !name_parsed)
270 {
271 name_len = len;
272 len = 0;
273 key_start = ptr + 1;
274 name_parsed = true;
275 continue;
276 }
277 else if (*ptr == '=')
278 {
0a811e96
BS
279 if (!key_parsed)
280 {
281 key_len = len;
282 len = 0;
283 value_start = ptr + 1;
284 key_parsed = true;
285 }
68a607d8
DN
286 continue;
287 }
288 else
289 ++len;
290 }
291
292 if (!key_start)
293 {
a9c697b8
MS
294 error ("malformed option %<-fplugin-arg-%s%>: "
295 "missing %<-<key>[=<value>]%>",
68a607d8
DN
296 arg);
297 return;
298 }
299
300 /* If the option doesn't contain the 'value' part, LEN is the KEY_LEN.
301 Otherwise, it is the VALUE_LEN. */
302 if (!value_start)
303 key_len = len;
304 else
305 value_len = len;
306
307 name = XNEWVEC (char, name_len + 1);
308 strncpy (name, name_start, name_len);
309 name[name_len] = '\0';
310
311 /* Check if the named plugin has already been specified earlier in the
312 command-line. */
313 if (plugin_name_args_tab
d5498d2f
BS
314 && ((slot = htab_find_slot_with_hash (plugin_name_args_tab, name,
315 htab_hash_string (name), NO_INSERT))
68a607d8
DN
316 != NULL))
317 {
318 struct plugin_name_args *plugin = (struct plugin_name_args *) *slot;
319
320 key = XNEWVEC (char, key_len + 1);
321 strncpy (key, key_start, key_len);
322 key[key_len] = '\0';
323 if (value_start)
324 {
325 value = XNEWVEC (char, value_len + 1);
326 strncpy (value, value_start, value_len);
327 value[value_len] = '\0';
328 }
329 else
330 value = NULL;
331
332 /* Create a plugin_argument object for the parsed key-value pair.
333 If there are already arguments for this plugin, we will need to
334 adjust the argument array size by creating a new array and deleting
335 the old one. If the performance ever becomes an issue, we can
336 change the code by pre-allocating a larger array first. */
337 if (plugin->argc > 0)
338 {
339 struct plugin_argument *args = XNEWVEC (struct plugin_argument,
340 plugin->argc + 1);
341 memcpy (args, plugin->argv,
342 sizeof (struct plugin_argument) * plugin->argc);
343 XDELETEVEC (plugin->argv);
344 plugin->argv = args;
345 ++plugin->argc;
346 }
347 else
348 {
349 gcc_assert (plugin->argv == NULL);
350 plugin->argv = XNEWVEC (struct plugin_argument, 1);
351 plugin->argc = 1;
352 }
353
354 plugin->argv[plugin->argc - 1].key = key;
355 plugin->argv[plugin->argc - 1].value = value;
356 }
357 else
a3f9f006 358 error ("plugin %s should be specified before %<-fplugin-arg-%s%> "
68a607d8
DN
359 "in the command line", name, arg);
360
361 /* We don't need the plugin's name anymore. Just release it. */
362 XDELETEVEC (name);
363}
364
44e9f006
RAE
365/* Register additional plugin information. NAME is the name passed to
366 plugin_init. INFO is the information that should be registered. */
367
368static void
369register_plugin_info (const char* name, struct plugin_info *info)
370{
d5498d2f
BS
371 void **slot = htab_find_slot_with_hash (plugin_name_args_tab, name,
372 htab_hash_string (name), NO_INSERT);
b5300487
NC
373 struct plugin_name_args *plugin;
374
375 if (slot == NULL)
376 {
84671705 377 error ("unable to register info for plugin %qs - plugin name not found",
b5300487
NC
378 name);
379 return;
380 }
381 plugin = (struct plugin_name_args *) *slot;
44e9f006 382 plugin->version = info->version;
02e819ff 383 plugin->help = info->help;
44e9f006
RAE
384}
385
090fa0ab
GF
386/* Look up the event id for NAME. If the name is not found, return -1
387 if INSERT is NO_INSERT. */
388
389int
390get_named_event_id (const char *name, enum insert_option insert)
391{
4a8fb1a1 392 const char ***slot;
090fa0ab 393
c203e8a7 394 if (!event_tab)
090fa0ab
GF
395 {
396 int i;
397
c203e8a7 398 event_tab = new hash_table<event_hasher> (150);
8a8d675f 399 for (i = 0; i < event_last; i++)
090fa0ab 400 {
c203e8a7 401 slot = event_tab->find_slot (&plugin_event_name[i], INSERT);
090fa0ab
GF
402 gcc_assert (*slot == HTAB_EMPTY_ENTRY);
403 *slot = &plugin_event_name[i];
404 }
405 }
c203e8a7 406 slot = event_tab->find_slot (&name, insert);
090fa0ab
GF
407 if (slot == NULL)
408 return -1;
409 if (*slot != HTAB_EMPTY_ENTRY)
4a8fb1a1 410 return *slot - &plugin_event_name[0];
090fa0ab
GF
411
412 if (event_last >= event_horizon)
413 {
414 event_horizon = event_last * 2;
415 if (plugin_event_name == plugin_event_name_init)
416 {
417 plugin_event_name = XNEWVEC (const char *, event_horizon);
418 memcpy (plugin_event_name, plugin_event_name_init,
419 sizeof plugin_event_name_init);
420 plugin_callbacks = XNEWVEC (struct callback_info *, event_horizon);
421 memcpy (plugin_callbacks, plugin_callbacks_init,
422 sizeof plugin_callbacks_init);
423 }
424 else
425 {
426 plugin_event_name
427 = XRESIZEVEC (const char *, plugin_event_name, event_horizon);
428 plugin_callbacks = XRESIZEVEC (struct callback_info *,
429 plugin_callbacks, event_horizon);
430 }
431 /* All the pointers in the hash table will need to be updated. */
c203e8a7
TS
432 delete event_tab;
433 event_tab = NULL;
090fa0ab
GF
434 }
435 else
436 *slot = &plugin_event_name[event_last];
437 plugin_event_name[event_last] = name;
438 return event_last++;
439}
440
68a607d8
DN
441/* Called from the plugin's initialization code. Register a single callback.
442 This function can be called multiple times.
443
444 PLUGIN_NAME - display name for this plugin
445 EVENT - which event the callback is for
446 CALLBACK - the callback to be called at the event
447 USER_DATA - plugin-provided data */
448
449void
450register_callback (const char *plugin_name,
090fa0ab 451 int event,
68a607d8
DN
452 plugin_callback_func callback,
453 void *user_data)
454{
455 switch (event)
456 {
457 case PLUGIN_PASS_MANAGER_SETUP:
ae2392a9 458 gcc_assert (!callback);
b80b0fd9 459 register_pass ((struct register_pass_info *) user_data);
68a607d8 460 break;
44e9f006 461 case PLUGIN_INFO:
ae2392a9 462 gcc_assert (!callback);
44e9f006
RAE
463 register_plugin_info (plugin_name, (struct plugin_info *) user_data);
464 break;
ae2392a9
BS
465 case PLUGIN_REGISTER_GGC_ROOTS:
466 gcc_assert (!callback);
467 ggc_register_root_tab ((const struct ggc_root_tab*) user_data);
468 break;
090fa0ab
GF
469 case PLUGIN_EVENT_FIRST_DYNAMIC:
470 default:
471 if (event < PLUGIN_EVENT_FIRST_DYNAMIC || event >= event_last)
472 {
d8a07487 473 error ("unknown callback event registered by plugin %s",
090fa0ab
GF
474 plugin_name);
475 return;
476 }
477 /* Fall through. */
ea5b45b6
AT
478 case PLUGIN_START_PARSE_FUNCTION:
479 case PLUGIN_FINISH_PARSE_FUNCTION:
68a607d8 480 case PLUGIN_FINISH_TYPE:
4309e92c 481 case PLUGIN_FINISH_DECL:
78bf7bd0 482 case PLUGIN_START_UNIT:
68a607d8 483 case PLUGIN_FINISH_UNIT:
1c701f96 484 case PLUGIN_PRE_GENERICIZE:
ae2392a9
BS
485 case PLUGIN_GGC_START:
486 case PLUGIN_GGC_MARKING:
487 case PLUGIN_GGC_END:
d1c8e08a 488 case PLUGIN_ATTRIBUTES:
7ac8318c 489 case PLUGIN_PRAGMAS:
68a607d8 490 case PLUGIN_FINISH:
090fa0ab
GF
491 case PLUGIN_ALL_PASSES_START:
492 case PLUGIN_ALL_PASSES_END:
493 case PLUGIN_ALL_IPA_PASSES_START:
494 case PLUGIN_ALL_IPA_PASSES_END:
495 case PLUGIN_OVERRIDE_GATE:
496 case PLUGIN_PASS_EXECUTION:
497 case PLUGIN_EARLY_GIMPLE_PASSES_START:
498 case PLUGIN_EARLY_GIMPLE_PASSES_END:
499 case PLUGIN_NEW_PASS:
c34144fa 500 case PLUGIN_INCLUDE_FILE:
66dde7bc 501 case PLUGIN_ANALYZER_INIT:
68a607d8
DN
502 {
503 struct callback_info *new_callback;
504 if (!callback)
505 {
d8a07487 506 error ("plugin %s registered a null callback function "
68a607d8
DN
507 "for event %s", plugin_name, plugin_event_name[event]);
508 return;
509 }
510 new_callback = XNEW (struct callback_info);
511 new_callback->plugin_name = plugin_name;
512 new_callback->func = callback;
513 new_callback->user_data = user_data;
514 new_callback->next = plugin_callbacks[event];
515 plugin_callbacks[event] = new_callback;
516 }
517 break;
68a607d8
DN
518 }
519}
520
090fa0ab
GF
521/* Remove a callback for EVENT which has been registered with for a plugin
522 PLUGIN_NAME. Return PLUGEVT_SUCCESS if a matching callback was
523 found & removed, PLUGEVT_NO_CALLBACK if the event does not have a matching
524 callback, and PLUGEVT_NO_SUCH_EVENT if EVENT is invalid. */
525int
526unregister_callback (const char *plugin_name, int event)
527{
528 struct callback_info *callback, **cbp;
529
530 if (event >= event_last)
531 return PLUGEVT_NO_SUCH_EVENT;
532
533 for (cbp = &plugin_callbacks[event]; (callback = *cbp); cbp = &callback->next)
534 if (strcmp (callback->plugin_name, plugin_name) == 0)
535 {
536 *cbp = callback->next;
537 return PLUGEVT_SUCCESS;
538 }
539 return PLUGEVT_NO_CALLBACK;
540}
68a607d8 541
efda3807
BH
542/* Invoke all plugin callbacks registered with the specified event,
543 called from invoke_plugin_callbacks(). */
68a607d8 544
090fa0ab 545int
efda3807 546invoke_plugin_callbacks_full (int event, void *gcc_data)
68a607d8 547{
090fa0ab
GF
548 int retval = PLUGEVT_SUCCESS;
549
68a607d8
DN
550 timevar_push (TV_PLUGIN_RUN);
551
552 switch (event)
553 {
090fa0ab
GF
554 case PLUGIN_EVENT_FIRST_DYNAMIC:
555 default:
556 gcc_assert (event >= PLUGIN_EVENT_FIRST_DYNAMIC);
557 gcc_assert (event < event_last);
558 /* Fall through. */
ea5b45b6
AT
559 case PLUGIN_START_PARSE_FUNCTION:
560 case PLUGIN_FINISH_PARSE_FUNCTION:
68a607d8 561 case PLUGIN_FINISH_TYPE:
4309e92c 562 case PLUGIN_FINISH_DECL:
78bf7bd0 563 case PLUGIN_START_UNIT:
68a607d8 564 case PLUGIN_FINISH_UNIT:
1c701f96 565 case PLUGIN_PRE_GENERICIZE:
d1c8e08a 566 case PLUGIN_ATTRIBUTES:
7ac8318c 567 case PLUGIN_PRAGMAS:
68a607d8 568 case PLUGIN_FINISH:
ae2392a9
BS
569 case PLUGIN_GGC_START:
570 case PLUGIN_GGC_MARKING:
571 case PLUGIN_GGC_END:
090fa0ab
GF
572 case PLUGIN_ALL_PASSES_START:
573 case PLUGIN_ALL_PASSES_END:
574 case PLUGIN_ALL_IPA_PASSES_START:
575 case PLUGIN_ALL_IPA_PASSES_END:
576 case PLUGIN_OVERRIDE_GATE:
577 case PLUGIN_PASS_EXECUTION:
578 case PLUGIN_EARLY_GIMPLE_PASSES_START:
579 case PLUGIN_EARLY_GIMPLE_PASSES_END:
580 case PLUGIN_NEW_PASS:
c34144fa 581 case PLUGIN_INCLUDE_FILE:
66dde7bc 582 case PLUGIN_ANALYZER_INIT:
68a607d8
DN
583 {
584 /* Iterate over every callback registered with this event and
585 call it. */
586 struct callback_info *callback = plugin_callbacks[event];
090fa0ab
GF
587
588 if (!callback)
589 retval = PLUGEVT_NO_CALLBACK;
68a607d8
DN
590 for ( ; callback; callback = callback->next)
591 (*callback->func) (gcc_data, callback->user_data);
592 }
593 break;
594
595 case PLUGIN_PASS_MANAGER_SETUP:
ae2392a9 596 case PLUGIN_REGISTER_GGC_ROOTS:
68a607d8
DN
597 gcc_assert (false);
598 }
599
600 timevar_pop (TV_PLUGIN_RUN);
090fa0ab 601 return retval;
68a607d8
DN
602}
603
604#ifdef ENABLE_PLUGIN
8c7dbea9
BK
605
606/* Try to initialize PLUGIN. Return true if successful. */
607
608#ifdef __MINGW32__
609
610// Return a message string for last error or NULL if unknown. Must be freed
611// with LocalFree().
612static inline char *
613win32_error_msg ()
614{
615 char *msg;
616 return FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
617 FORMAT_MESSAGE_FROM_SYSTEM |
618 FORMAT_MESSAGE_IGNORE_INSERTS |
619 FORMAT_MESSAGE_MAX_WIDTH_MASK,
620 0,
621 GetLastError (),
622 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
623 (char*)&msg,
624 0,
625 0)
626 ? msg
627 : NULL;
628}
629
630static bool
631try_init_one_plugin (struct plugin_name_args *plugin)
632{
633 HMODULE dl_handle;
634 plugin_init_func plugin_init;
635
636 dl_handle = LoadLibrary (plugin->full_name);
637 if (!dl_handle)
638 {
639 char *err = win32_error_msg ();
640 error ("cannot load plugin %s\n%s", plugin->full_name, err);
641 LocalFree (err);
642 return false;
643 }
644
645 /* Check the plugin license. Unlike the name suggests, GetProcAddress()
646 can be used for both functions and variables. */
647 if (GetProcAddress (dl_handle, str_license) == NULL)
648 {
649 char *err = win32_error_msg ();
650 fatal_error (input_location,
651 "plugin %s is not licensed under a GPL-compatible license\n"
652 "%s", plugin->full_name, err);
653 }
654
655 /* Unlike dlsym(), GetProcAddress() returns a pointer to a function so we
656 can cast directly without union tricks. */
657 plugin_init = (plugin_init_func)
658 GetProcAddress (dl_handle, str_plugin_init_func_name);
659
660 if (plugin_init == NULL)
661 {
662 char *err = win32_error_msg ();
663 FreeLibrary (dl_handle);
664 error ("cannot find %s in plugin %s\n%s", str_plugin_init_func_name,
665 plugin->full_name, err);
666 LocalFree (err);
667 return false;
668 }
669
670 /* Call the plugin-provided initialization routine with the arguments. */
671 if ((*plugin_init) (plugin, &gcc_version))
672 {
673 FreeLibrary (dl_handle);
674 error ("fail to initialize plugin %s", plugin->full_name);
675 return false;
676 }
677 /* Leak dl_handle on purpose to ensure the plugin is loaded for the
678 entire run of the compiler. */
679 return true;
680}
681
682#else // POSIX-like with dlopen()/dlsym().
683
68a607d8
DN
684/* We need a union to cast dlsym return value to a function pointer
685 as ISO C forbids assignment between function pointer and 'void *'.
686 Use explicit union instead of __extension__(<union_cast>) for
687 portability. */
688#define PTR_UNION_TYPE(TOTYPE) union { void *_q; TOTYPE _nq; }
689#define PTR_UNION_AS_VOID_PTR(NAME) (NAME._q)
690#define PTR_UNION_AS_CAST_PTR(NAME) (NAME._nq)
691
44e9f006
RAE
692static bool
693try_init_one_plugin (struct plugin_name_args *plugin)
68a607d8 694{
68a607d8
DN
695 void *dl_handle;
696 plugin_init_func plugin_init;
57703d27 697 const char *err;
68a607d8
DN
698 PTR_UNION_TYPE (plugin_init_func) plugin_init_union;
699
8d4cf6d7
BS
700 /* We use RTLD_NOW to accelerate binding and detect any mismatch
701 between the API expected by the plugin and the GCC API; we use
702 RTLD_GLOBAL which is useful to plugins which themselves call
703 dlopen. */
704 dl_handle = dlopen (plugin->full_name, RTLD_NOW | RTLD_GLOBAL);
68a607d8
DN
705 if (!dl_handle)
706 {
a9c697b8 707 error ("cannot load plugin %s: %s", plugin->full_name, dlerror ());
44e9f006 708 return false;
68a607d8
DN
709 }
710
711 /* Clear any existing error. */
712 dlerror ();
713
fca5bb5c
DN
714 /* Check the plugin license. */
715 if (dlsym (dl_handle, str_license) == NULL)
40fecdd6 716 fatal_error (input_location,
a9c697b8 717 "plugin %s is not licensed under a GPL-compatible license"
f8cb8bcd 718 " %s", plugin->full_name, dlerror ());
fca5bb5c 719
f8cb8bcd
JJ
720 PTR_UNION_AS_VOID_PTR (plugin_init_union)
721 = dlsym (dl_handle, str_plugin_init_func_name);
68a607d8
DN
722 plugin_init = PTR_UNION_AS_CAST_PTR (plugin_init_union);
723
724 if ((err = dlerror ()) != NULL)
725 {
3fc5147b 726 dlclose(dl_handle);
a9c697b8 727 error ("cannot find %s in plugin %s: %s", str_plugin_init_func_name,
68a607d8 728 plugin->full_name, err);
44e9f006 729 return false;
68a607d8
DN
730 }
731
732 /* Call the plugin-provided initialization routine with the arguments. */
9fefa0aa 733 if ((*plugin_init) (plugin, &gcc_version))
68a607d8 734 {
3fc5147b 735 dlclose(dl_handle);
a9c697b8 736 error ("failed to initialize plugin %s", plugin->full_name);
44e9f006 737 return false;
68a607d8 738 }
3fc5147b
SL
739 /* leak dl_handle on purpose to ensure the plugin is loaded for the
740 entire run of the compiler. */
44e9f006
RAE
741 return true;
742}
8c7dbea9 743#endif
44e9f006
RAE
744
745/* Routine to dlopen and initialize one plugin. This function is passed to
746 (and called by) the hash table traverse routine. Return 1 for the
747 htab_traverse to continue scan, 0 to stop.
748
749 SLOT - slot of the hash table element
750 INFO - auxiliary pointer handed to hash table traverse routine
751 (unused in this function) */
68a607d8 752
44e9f006
RAE
753static int
754init_one_plugin (void **slot, void * ARG_UNUSED (info))
755{
756 struct plugin_name_args *plugin = (struct plugin_name_args *) *slot;
757 bool ok = try_init_one_plugin (plugin);
758 if (!ok)
759 {
d5498d2f
BS
760 htab_remove_elt_with_hash (plugin_name_args_tab, plugin->base_name,
761 htab_hash_string (plugin->base_name));
44e9f006
RAE
762 XDELETE (plugin);
763 }
68a607d8
DN
764 return 1;
765}
44e9f006 766
68a607d8
DN
767#endif /* ENABLE_PLUGIN */
768
769/* Main plugin initialization function. Called from compile_file() in
e53b6e56 770 toplev.cc. */
68a607d8
DN
771
772void
773initialize_plugins (void)
774{
775 /* If no plugin was specified in the command-line, simply return. */
776 if (!plugin_name_args_tab)
777 return;
778
779 timevar_push (TV_PLUGIN_INIT);
b8698a0f 780
68a607d8
DN
781#ifdef ENABLE_PLUGIN
782 /* Traverse and initialize each plugin specified in the command-line. */
783 htab_traverse_noresize (plugin_name_args_tab, init_one_plugin, NULL);
784#endif
785
44e9f006
RAE
786 timevar_pop (TV_PLUGIN_INIT);
787}
788
789/* Release memory used by one plugin. */
790
791static int
792finalize_one_plugin (void **slot, void * ARG_UNUSED (info))
793{
794 struct plugin_name_args *plugin = (struct plugin_name_args *) *slot;
795 XDELETE (plugin);
796 return 1;
797}
798
799/* Free memory allocated by the plugin system. */
800
801void
802finalize_plugins (void)
803{
804 if (!plugin_name_args_tab)
805 return;
806
807 /* We can now delete the plugin_name_args object as it will no longer
808 be used. Note that base_name and argv fields (both of which were also
809 dynamically allocated) are not freed as they could still be used by
810 the plugin code. */
811
812 htab_traverse_noresize (plugin_name_args_tab, finalize_one_plugin, NULL);
813
68a607d8
DN
814 /* PLUGIN_NAME_ARGS_TAB is no longer needed, just delete it. */
815 htab_delete (plugin_name_args_tab);
816 plugin_name_args_tab = NULL;
44e9f006 817}
68a607d8 818
6cf276dd
DM
819/* Implementation detail of for_each_plugin. */
820
821struct for_each_plugin_closure
822{
823 void (*cb) (const plugin_name_args *,
824 void *user_data);
825 void *user_data;
826};
827
828/* Implementation detail of for_each_plugin: callback for htab_traverse_noresize
829 that calls the user-provided callback. */
830
831static int
832for_each_plugin_cb (void **slot, void *info)
833{
834 struct plugin_name_args *plugin = (struct plugin_name_args *) *slot;
835 for_each_plugin_closure *c = (for_each_plugin_closure *)info;
836 c->cb (plugin, c->user_data);
837 return 1;
838}
839
840/* Call CB with USER_DATA on each plugin. */
841
842void
843for_each_plugin (void (*cb) (const plugin_name_args *,
844 void *user_data),
845 void *user_data)
846{
847 if (!plugin_name_args_tab)
848 return;
849
850 for_each_plugin_closure c;
851 c.cb = cb;
852 c.user_data = user_data;
853
854 htab_traverse_noresize (plugin_name_args_tab, for_each_plugin_cb, &c);
855}
856
44e9f006
RAE
857/* Used to pass options to htab_traverse callbacks. */
858
859struct print_options
860{
861 FILE *file;
862 const char *indent;
863};
864
865/* Print the version of one plugin. */
866
867static int
868print_version_one_plugin (void **slot, void *data)
869{
870 struct print_options *opt = (struct print_options *) data;
871 struct plugin_name_args *plugin = (struct plugin_name_args *) *slot;
872 const char *version = plugin->version ? plugin->version : "Unknown version.";
873
874 fprintf (opt->file, " %s%s: %s\n", opt->indent, plugin->base_name, version);
875 return 1;
876}
877
878/* Print the version of each plugin. */
879
880void
881print_plugins_versions (FILE *file, const char *indent)
882{
883 struct print_options opt;
884 opt.file = file;
885 opt.indent = indent;
886 if (!plugin_name_args_tab || htab_elements (plugin_name_args_tab) == 0)
887 return;
888
889 fprintf (file, "%sVersions of loaded plugins:\n", indent);
890 htab_traverse_noresize (plugin_name_args_tab, print_version_one_plugin, &opt);
68a607d8
DN
891}
892
02e819ff
RAE
893/* Print help for one plugin. SLOT is the hash table slot. DATA is the
894 argument to htab_traverse_noresize. */
895
896static int
897print_help_one_plugin (void **slot, void *data)
898{
899 struct print_options *opt = (struct print_options *) data;
900 struct plugin_name_args *plugin = (struct plugin_name_args *) *slot;
901 const char *help = plugin->help ? plugin->help : "No help available .";
902
903 char *dup = xstrdup (help);
904 char *p, *nl;
905 fprintf (opt->file, " %s%s:\n", opt->indent, plugin->base_name);
906
907 for (p = nl = dup; nl; p = nl)
908 {
909 nl = strchr (nl, '\n');
910 if (nl)
911 {
912 *nl = '\0';
913 nl++;
914 }
915 fprintf (opt->file, " %s %s\n", opt->indent, p);
916 }
917
918 free (dup);
919 return 1;
920}
921
922/* Print help for each plugin. The output goes to FILE and every line starts
923 with INDENT. */
924
925void
926print_plugins_help (FILE *file, const char *indent)
927{
928 struct print_options opt;
929 opt.file = file;
930 opt.indent = indent;
931 if (!plugin_name_args_tab || htab_elements (plugin_name_args_tab) == 0)
932 return;
933
934 fprintf (file, "%sHelp for the loaded plugins:\n", indent);
935 htab_traverse_noresize (plugin_name_args_tab, print_help_one_plugin, &opt);
936}
937
68a607d8
DN
938
939/* Return true if plugins have been loaded. */
940
941bool
942plugins_active_p (void)
943{
09639a83 944 int event;
68a607d8 945
090fa0ab 946 for (event = PLUGIN_PASS_MANAGER_SETUP; event < event_last; event++)
68a607d8
DN
947 if (plugin_callbacks[event])
948 return true;
949
950 return false;
951}
952
953
954/* Dump to FILE the names and associated events for all the active
955 plugins. */
956
24e47c76 957DEBUG_FUNCTION void
68a607d8
DN
958dump_active_plugins (FILE *file)
959{
09639a83 960 int event;
68a607d8
DN
961
962 if (!plugins_active_p ())
963 return;
964
fdabb520 965 fprintf (file, FMT_FOR_PLUGIN_EVENT " | %s\n", _("Event"), _("Plugins"));
090fa0ab 966 for (event = PLUGIN_PASS_MANAGER_SETUP; event < event_last; event++)
68a607d8
DN
967 if (plugin_callbacks[event])
968 {
969 struct callback_info *ci;
970
fdabb520 971 fprintf (file, FMT_FOR_PLUGIN_EVENT " |", plugin_event_name[event]);
68a607d8
DN
972
973 for (ci = plugin_callbacks[event]; ci; ci = ci->next)
fdabb520 974 fprintf (file, " %s", ci->plugin_name);
68a607d8 975
c3284718 976 putc ('\n', file);
68a607d8
DN
977 }
978}
979
980
981/* Dump active plugins to stderr. */
982
24e47c76 983DEBUG_FUNCTION void
68a607d8
DN
984debug_active_plugins (void)
985{
986 dump_active_plugins (stderr);
987}
cf8aba7f 988
a13812e2
JM
989/* Give a warning if plugins are present, before an ICE message asking
990 to submit a bug report. */
991
992void
993warn_if_plugins (void)
994{
995 if (plugins_active_p ())
996 {
997 fnotice (stderr, "*** WARNING *** there are active plugins, do not report"
998 " this as a bug unless you can reproduce it without enabling"
999 " any plugins.\n");
1000 dump_active_plugins (stderr);
1001 }
1002
1003}
1004
cf8aba7f
RAE
1005/* The default version check. Compares every field in VERSION. */
1006
1007bool
0c463e16
RAE
1008plugin_default_version_check (struct plugin_gcc_version *gcc_version,
1009 struct plugin_gcc_version *plugin_version)
cf8aba7f 1010{
0c463e16 1011 if (!gcc_version || !plugin_version)
cf8aba7f
RAE
1012 return false;
1013
0c463e16 1014 if (strcmp (gcc_version->basever, plugin_version->basever))
cf8aba7f 1015 return false;
0c463e16 1016 if (strcmp (gcc_version->datestamp, plugin_version->datestamp))
cf8aba7f 1017 return false;
0c463e16 1018 if (strcmp (gcc_version->devphase, plugin_version->devphase))
cf8aba7f 1019 return false;
0c463e16 1020 if (strcmp (gcc_version->revision, plugin_version->revision))
cf8aba7f 1021 return false;
0c463e16
RAE
1022 if (strcmp (gcc_version->configuration_arguments,
1023 plugin_version->configuration_arguments))
cf8aba7f
RAE
1024 return false;
1025 return true;
1026}
090fa0ab 1027
4adbd5dd 1028
090fa0ab
GF
1029/* Return the current value of event_last, so that plugins which provide
1030 additional functionality for events for the benefit of high-level plugins
1031 know how many valid entries plugin_event_name holds. */
1032
1033int
1034get_event_last (void)
1035{
1036 return event_last;
1037}
4adbd5dd
MK
1038
1039
1040/* Retrieve the default plugin directory. The gcc driver should have passed
073a8998 1041 it as -iplugindir <dir> to the cc1 program, and it is queriable through the
4adbd5dd
MK
1042 -print-file-name=plugin option to gcc. */
1043const char*
1044default_plugin_dir_name (void)
1045{
1046 if (!plugindir_string)
40fecdd6 1047 fatal_error (input_location,
93ecb25c 1048 "%<-iplugindir%> option not passed from the gcc driver");
4adbd5dd
MK
1049 return plugindir_string;
1050}