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