~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/kernel/module.c

Version: ~ [ linux-5.4-rc7 ] ~ [ linux-5.3.11 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.84 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.154 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.201 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.201 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.77 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-3.9.11 ] ~ [ linux-3.8.13 ] ~ [ linux-3.7.10 ] ~ [ linux-3.6.11 ] ~ [ linux-3.5.7 ] ~ [ linux-3.4.113 ] ~ [ linux-3.3.8 ] ~ [ linux-3.2.102 ] ~ [ linux-3.1.10 ] ~ [ linux-3.0.101 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 /*
  2    Copyright (C) 2002 Richard Henderson
  3    Copyright (C) 2001 Rusty Russell, 2002, 2010 Rusty Russell IBM.
  4 
  5     This program is free software; you can redistribute it and/or modify
  6     it under the terms of the GNU General Public License as published by
  7     the Free Software Foundation; either version 2 of the License, or
  8     (at your option) any later version.
  9 
 10     This program is distributed in the hope that it will be useful,
 11     but WITHOUT ANY WARRANTY; without even the implied warranty of
 12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 13     GNU General Public License for more details.
 14 
 15     You should have received a copy of the GNU General Public License
 16     along with this program; if not, write to the Free Software
 17     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 18 */
 19 #include <linux/export.h>
 20 #include <linux/moduleloader.h>
 21 #include <linux/ftrace_event.h>
 22 #include <linux/init.h>
 23 #include <linux/kallsyms.h>
 24 #include <linux/fs.h>
 25 #include <linux/sysfs.h>
 26 #include <linux/kernel.h>
 27 #include <linux/slab.h>
 28 #include <linux/vmalloc.h>
 29 #include <linux/elf.h>
 30 #include <linux/proc_fs.h>
 31 #include <linux/seq_file.h>
 32 #include <linux/syscalls.h>
 33 #include <linux/fcntl.h>
 34 #include <linux/rcupdate.h>
 35 #include <linux/capability.h>
 36 #include <linux/cpu.h>
 37 #include <linux/moduleparam.h>
 38 #include <linux/errno.h>
 39 #include <linux/err.h>
 40 #include <linux/vermagic.h>
 41 #include <linux/notifier.h>
 42 #include <linux/sched.h>
 43 #include <linux/stop_machine.h>
 44 #include <linux/device.h>
 45 #include <linux/string.h>
 46 #include <linux/mutex.h>
 47 #include <linux/rculist.h>
 48 #include <asm/uaccess.h>
 49 #include <asm/cacheflush.h>
 50 #include <asm/mmu_context.h>
 51 #include <linux/license.h>
 52 #include <asm/sections.h>
 53 #include <linux/tracepoint.h>
 54 #include <linux/ftrace.h>
 55 #include <linux/async.h>
 56 #include <linux/percpu.h>
 57 #include <linux/kmemleak.h>
 58 #include <linux/jump_label.h>
 59 #include <linux/pfn.h>
 60 #include <linux/bsearch.h>
 61 #include <linux/ccsecurity.h>
 62 
 63 #define CREATE_TRACE_POINTS
 64 #include <trace/events/module.h>
 65 
 66 #if 0
 67 #define DEBUGP printk
 68 #else
 69 #define DEBUGP(fmt , a...)
 70 #endif
 71 
 72 #ifndef ARCH_SHF_SMALL
 73 #define ARCH_SHF_SMALL 0
 74 #endif
 75 
 76 /*
 77  * Modules' sections will be aligned on page boundaries
 78  * to ensure complete separation of code and data, but
 79  * only when CONFIG_DEBUG_SET_MODULE_RONX=y
 80  */
 81 #ifdef CONFIG_DEBUG_SET_MODULE_RONX
 82 # define debug_align(X) ALIGN(X, PAGE_SIZE)
 83 #else
 84 # define debug_align(X) (X)
 85 #endif
 86 
 87 /*
 88  * Given BASE and SIZE this macro calculates the number of pages the
 89  * memory regions occupies
 90  */
 91 #define MOD_NUMBER_OF_PAGES(BASE, SIZE) (((SIZE) > 0) ?         \
 92                 (PFN_DOWN((unsigned long)(BASE) + (SIZE) - 1) - \
 93                          PFN_DOWN((unsigned long)BASE) + 1)     \
 94                 : (0UL))
 95 
 96 /* If this is set, the section belongs in the init part of the module */
 97 #define INIT_OFFSET_MASK (1UL << (BITS_PER_LONG-1))
 98 
 99 /*
100  * Mutex protects:
101  * 1) List of modules (also safely readable with preempt_disable),
102  * 2) module_use links,
103  * 3) module_addr_min/module_addr_max.
104  * (delete uses stop_machine/add uses RCU list operations). */
105 DEFINE_MUTEX(module_mutex);
106 EXPORT_SYMBOL_GPL(module_mutex);
107 static LIST_HEAD(modules);
108 #ifdef CONFIG_KGDB_KDB
109 struct list_head *kdb_modules = &modules; /* kdb needs the list of modules */
110 #endif /* CONFIG_KGDB_KDB */
111 
112 
113 /* Block module loading/unloading? */
114 int modules_disabled = 0;
115 
116 /* Waiting for a module to finish initializing? */
117 static DECLARE_WAIT_QUEUE_HEAD(module_wq);
118 
119 static BLOCKING_NOTIFIER_HEAD(module_notify_list);
120 
121 /* Bounds of module allocation, for speeding __module_address.
122  * Protected by module_mutex. */
123 static unsigned long module_addr_min = -1UL, module_addr_max = 0;
124 
125 int register_module_notifier(struct notifier_block * nb)
126 {
127         return blocking_notifier_chain_register(&module_notify_list, nb);
128 }
129 EXPORT_SYMBOL(register_module_notifier);
130 
131 int unregister_module_notifier(struct notifier_block * nb)
132 {
133         return blocking_notifier_chain_unregister(&module_notify_list, nb);
134 }
135 EXPORT_SYMBOL(unregister_module_notifier);
136 
137 struct load_info {
138         Elf_Ehdr *hdr;
139         unsigned long len;
140         Elf_Shdr *sechdrs;
141         char *secstrings, *strtab;
142         unsigned long *strmap;
143         unsigned long symoffs, stroffs;
144         struct _ddebug *debug;
145         unsigned int num_debug;
146         struct {
147                 unsigned int sym, str, mod, vers, info, pcpu;
148         } index;
149 };
150 
151 /* We require a truly strong try_module_get(): 0 means failure due to
152    ongoing or failed initialization etc. */
153 static inline int strong_try_module_get(struct module *mod)
154 {
155         if (mod && mod->state == MODULE_STATE_COMING)
156                 return -EBUSY;
157         if (try_module_get(mod))
158                 return 0;
159         else
160                 return -ENOENT;
161 }
162 
163 static inline void add_taint_module(struct module *mod, unsigned flag)
164 {
165         add_taint(flag);
166         mod->taints |= (1U << flag);
167 }
168 
169 /*
170  * A thread that wants to hold a reference to a module only while it
171  * is running can call this to safely exit.  nfsd and lockd use this.
172  */
173 void __module_put_and_exit(struct module *mod, long code)
174 {
175         module_put(mod);
176         do_exit(code);
177 }
178 EXPORT_SYMBOL(__module_put_and_exit);
179 
180 /* Find a module section: 0 means not found. */
181 static unsigned int find_sec(const struct load_info *info, const char *name)
182 {
183         unsigned int i;
184 
185         for (i = 1; i < info->hdr->e_shnum; i++) {
186                 Elf_Shdr *shdr = &info->sechdrs[i];
187                 /* Alloc bit cleared means "ignore it." */
188                 if ((shdr->sh_flags & SHF_ALLOC)
189                     && strcmp(info->secstrings + shdr->sh_name, name) == 0)
190                         return i;
191         }
192         return 0;
193 }
194 
195 /* Find a module section, or NULL. */
196 static void *section_addr(const struct load_info *info, const char *name)
197 {
198         /* Section 0 has sh_addr 0. */
199         return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
200 }
201 
202 /* Find a module section, or NULL.  Fill in number of "objects" in section. */
203 static void *section_objs(const struct load_info *info,
204                           const char *name,
205                           size_t object_size,
206                           unsigned int *num)
207 {
208         unsigned int sec = find_sec(info, name);
209 
210         /* Section 0 has sh_addr 0 and sh_size 0. */
211         *num = info->sechdrs[sec].sh_size / object_size;
212         return (void *)info->sechdrs[sec].sh_addr;
213 }
214 
215 /* Provided by the linker */
216 extern const struct kernel_symbol __start___ksymtab[];
217 extern const struct kernel_symbol __stop___ksymtab[];
218 extern const struct kernel_symbol __start___ksymtab_gpl[];
219 extern const struct kernel_symbol __stop___ksymtab_gpl[];
220 extern const struct kernel_symbol __start___ksymtab_gpl_future[];
221 extern const struct kernel_symbol __stop___ksymtab_gpl_future[];
222 extern const unsigned long __start___kcrctab[];
223 extern const unsigned long __start___kcrctab_gpl[];
224 extern const unsigned long __start___kcrctab_gpl_future[];
225 #ifdef CONFIG_UNUSED_SYMBOLS
226 extern const struct kernel_symbol __start___ksymtab_unused[];
227 extern const struct kernel_symbol __stop___ksymtab_unused[];
228 extern const struct kernel_symbol __start___ksymtab_unused_gpl[];
229 extern const struct kernel_symbol __stop___ksymtab_unused_gpl[];
230 extern const unsigned long __start___kcrctab_unused[];
231 extern const unsigned long __start___kcrctab_unused_gpl[];
232 #endif
233 
234 #ifndef CONFIG_MODVERSIONS
235 #define symversion(base, idx) NULL
236 #else
237 #define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
238 #endif
239 
240 static bool each_symbol_in_section(const struct symsearch *arr,
241                                    unsigned int arrsize,
242                                    struct module *owner,
243                                    bool (*fn)(const struct symsearch *syms,
244                                               struct module *owner,
245                                               void *data),
246                                    void *data)
247 {
248         unsigned int j;
249 
250         for (j = 0; j < arrsize; j++) {
251                 if (fn(&arr[j], owner, data))
252                         return true;
253         }
254 
255         return false;
256 }
257 
258 /* Returns true as soon as fn returns true, otherwise false. */
259 bool each_symbol_section(bool (*fn)(const struct symsearch *arr,
260                                     struct module *owner,
261                                     void *data),
262                          void *data)
263 {
264         struct module *mod;
265         static const struct symsearch arr[] = {
266                 { __start___ksymtab, __stop___ksymtab, __start___kcrctab,
267                   NOT_GPL_ONLY, false },
268                 { __start___ksymtab_gpl, __stop___ksymtab_gpl,
269                   __start___kcrctab_gpl,
270                   GPL_ONLY, false },
271                 { __start___ksymtab_gpl_future, __stop___ksymtab_gpl_future,
272                   __start___kcrctab_gpl_future,
273                   WILL_BE_GPL_ONLY, false },
274 #ifdef CONFIG_UNUSED_SYMBOLS
275                 { __start___ksymtab_unused, __stop___ksymtab_unused,
276                   __start___kcrctab_unused,
277                   NOT_GPL_ONLY, true },
278                 { __start___ksymtab_unused_gpl, __stop___ksymtab_unused_gpl,
279                   __start___kcrctab_unused_gpl,
280                   GPL_ONLY, true },
281 #endif
282         };
283 
284         if (each_symbol_in_section(arr, ARRAY_SIZE(arr), NULL, fn, data))
285                 return true;
286 
287         list_for_each_entry_rcu(mod, &modules, list) {
288                 struct symsearch arr[] = {
289                         { mod->syms, mod->syms + mod->num_syms, mod->crcs,
290                           NOT_GPL_ONLY, false },
291                         { mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
292                           mod->gpl_crcs,
293                           GPL_ONLY, false },
294                         { mod->gpl_future_syms,
295                           mod->gpl_future_syms + mod->num_gpl_future_syms,
296                           mod->gpl_future_crcs,
297                           WILL_BE_GPL_ONLY, false },
298 #ifdef CONFIG_UNUSED_SYMBOLS
299                         { mod->unused_syms,
300                           mod->unused_syms + mod->num_unused_syms,
301                           mod->unused_crcs,
302                           NOT_GPL_ONLY, true },
303                         { mod->unused_gpl_syms,
304                           mod->unused_gpl_syms + mod->num_unused_gpl_syms,
305                           mod->unused_gpl_crcs,
306                           GPL_ONLY, true },
307 #endif
308                 };
309 
310                 if (each_symbol_in_section(arr, ARRAY_SIZE(arr), mod, fn, data))
311                         return true;
312         }
313         return false;
314 }
315 EXPORT_SYMBOL_GPL(each_symbol_section);
316 
317 struct find_symbol_arg {
318         /* Input */
319         const char *name;
320         bool gplok;
321         bool warn;
322 
323         /* Output */
324         struct module *owner;
325         const unsigned long *crc;
326         const struct kernel_symbol *sym;
327 };
328 
329 static bool check_symbol(const struct symsearch *syms,
330                                  struct module *owner,
331                                  unsigned int symnum, void *data)
332 {
333         struct find_symbol_arg *fsa = data;
334 
335         if (!fsa->gplok) {
336                 if (syms->licence == GPL_ONLY)
337                         return false;
338                 if (syms->licence == WILL_BE_GPL_ONLY && fsa->warn) {
339                         printk(KERN_WARNING "Symbol %s is being used "
340                                "by a non-GPL module, which will not "
341                                "be allowed in the future\n", fsa->name);
342                         printk(KERN_WARNING "Please see the file "
343                                "Documentation/feature-removal-schedule.txt "
344                                "in the kernel source tree for more details.\n");
345                 }
346         }
347 
348 #ifdef CONFIG_UNUSED_SYMBOLS
349         if (syms->unused && fsa->warn) {
350                 printk(KERN_WARNING "Symbol %s is marked as UNUSED, "
351                        "however this module is using it.\n", fsa->name);
352                 printk(KERN_WARNING
353                        "This symbol will go away in the future.\n");
354                 printk(KERN_WARNING
355                        "Please evalute if this is the right api to use and if "
356                        "it really is, submit a report the linux kernel "
357                        "mailinglist together with submitting your code for "
358                        "inclusion.\n");
359         }
360 #endif
361 
362         fsa->owner = owner;
363         fsa->crc = symversion(syms->crcs, symnum);
364         fsa->sym = &syms->start[symnum];
365         return true;
366 }
367 
368 static int cmp_name(const void *va, const void *vb)
369 {
370         const char *a;
371         const struct kernel_symbol *b;
372         a = va; b = vb;
373         return strcmp(a, b->name);
374 }
375 
376 static bool find_symbol_in_section(const struct symsearch *syms,
377                                    struct module *owner,
378                                    void *data)
379 {
380         struct find_symbol_arg *fsa = data;
381         struct kernel_symbol *sym;
382 
383         sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
384                         sizeof(struct kernel_symbol), cmp_name);
385 
386         if (sym != NULL && check_symbol(syms, owner, sym - syms->start, data))
387                 return true;
388 
389         return false;
390 }
391 
392 /* Find a symbol and return it, along with, (optional) crc and
393  * (optional) module which owns it.  Needs preempt disabled or module_mutex. */
394 const struct kernel_symbol *find_symbol(const char *name,
395                                         struct module **owner,
396                                         const unsigned long **crc,
397                                         bool gplok,
398                                         bool warn)
399 {
400         struct find_symbol_arg fsa;
401 
402         fsa.name = name;
403         fsa.gplok = gplok;
404         fsa.warn = warn;
405 
406         if (each_symbol_section(find_symbol_in_section, &fsa)) {
407                 if (owner)
408                         *owner = fsa.owner;
409                 if (crc)
410                         *crc = fsa.crc;
411                 return fsa.sym;
412         }
413 
414         DEBUGP("Failed to find symbol %s\n", name);
415         return NULL;
416 }
417 EXPORT_SYMBOL_GPL(find_symbol);
418 
419 /* Search for module by name: must hold module_mutex. */
420 struct module *find_module(const char *name)
421 {
422         struct module *mod;
423 
424         list_for_each_entry(mod, &modules, list) {
425                 if (strcmp(mod->name, name) == 0)
426                         return mod;
427         }
428         return NULL;
429 }
430 EXPORT_SYMBOL_GPL(find_module);
431 
432 #ifdef CONFIG_SMP
433 
434 static inline void __percpu *mod_percpu(struct module *mod)
435 {
436         return mod->percpu;
437 }
438 
439 static int percpu_modalloc(struct module *mod,
440                            unsigned long size, unsigned long align)
441 {
442         if (align > PAGE_SIZE) {
443                 printk(KERN_WARNING "%s: per-cpu alignment %li > %li\n",
444                        mod->name, align, PAGE_SIZE);
445                 align = PAGE_SIZE;
446         }
447 
448         mod->percpu = __alloc_reserved_percpu(size, align);
449         if (!mod->percpu) {
450                 printk(KERN_WARNING
451                        "%s: Could not allocate %lu bytes percpu data\n",
452                        mod->name, size);
453                 return -ENOMEM;
454         }
455         mod->percpu_size = size;
456         return 0;
457 }
458 
459 static void percpu_modfree(struct module *mod)
460 {
461         free_percpu(mod->percpu);
462 }
463 
464 static unsigned int find_pcpusec(struct load_info *info)
465 {
466         return find_sec(info, ".data..percpu");
467 }
468 
469 static void percpu_modcopy(struct module *mod,
470                            const void *from, unsigned long size)
471 {
472         int cpu;
473 
474         for_each_possible_cpu(cpu)
475                 memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
476 }
477 
478 /**
479  * is_module_percpu_address - test whether address is from module static percpu
480  * @addr: address to test
481  *
482  * Test whether @addr belongs to module static percpu area.
483  *
484  * RETURNS:
485  * %true if @addr is from module static percpu area
486  */
487 bool is_module_percpu_address(unsigned long addr)
488 {
489         struct module *mod;
490         unsigned int cpu;
491 
492         preempt_disable();
493 
494         list_for_each_entry_rcu(mod, &modules, list) {
495                 if (!mod->percpu_size)
496                         continue;
497                 for_each_possible_cpu(cpu) {
498                         void *start = per_cpu_ptr(mod->percpu, cpu);
499 
500                         if ((void *)addr >= start &&
501                             (void *)addr < start + mod->percpu_size) {
502                                 preempt_enable();
503                                 return true;
504                         }
505                 }
506         }
507 
508         preempt_enable();
509         return false;
510 }
511 
512 #else /* ... !CONFIG_SMP */
513 
514 static inline void __percpu *mod_percpu(struct module *mod)
515 {
516         return NULL;
517 }
518 static inline int percpu_modalloc(struct module *mod,
519                                   unsigned long size, unsigned long align)
520 {
521         return -ENOMEM;
522 }
523 static inline void percpu_modfree(struct module *mod)
524 {
525 }
526 static unsigned int find_pcpusec(struct load_info *info)
527 {
528         return 0;
529 }
530 static inline void percpu_modcopy(struct module *mod,
531                                   const void *from, unsigned long size)
532 {
533         /* pcpusec should be 0, and size of that section should be 0. */
534         BUG_ON(size != 0);
535 }
536 bool is_module_percpu_address(unsigned long addr)
537 {
538         return false;
539 }
540 
541 #endif /* CONFIG_SMP */
542 
543 #define MODINFO_ATTR(field)     \
544 static void setup_modinfo_##field(struct module *mod, const char *s)  \
545 {                                                                     \
546         mod->field = kstrdup(s, GFP_KERNEL);                          \
547 }                                                                     \
548 static ssize_t show_modinfo_##field(struct module_attribute *mattr,   \
549                         struct module_kobject *mk, char *buffer)      \
550 {                                                                     \
551         return sprintf(buffer, "%s\n", mk->mod->field);               \
552 }                                                                     \
553 static int modinfo_##field##_exists(struct module *mod)               \
554 {                                                                     \
555         return mod->field != NULL;                                    \
556 }                                                                     \
557 static void free_modinfo_##field(struct module *mod)                  \
558 {                                                                     \
559         kfree(mod->field);                                            \
560         mod->field = NULL;                                            \
561 }                                                                     \
562 static struct module_attribute modinfo_##field = {                    \
563         .attr = { .name = __stringify(field), .mode = 0444 },         \
564         .show = show_modinfo_##field,                                 \
565         .setup = setup_modinfo_##field,                               \
566         .test = modinfo_##field##_exists,                             \
567         .free = free_modinfo_##field,                                 \
568 };
569 
570 MODINFO_ATTR(version);
571 MODINFO_ATTR(srcversion);
572 
573 static char last_unloaded_module[MODULE_NAME_LEN+1];
574 
575 #ifdef CONFIG_MODULE_UNLOAD
576 
577 EXPORT_TRACEPOINT_SYMBOL(module_get);
578 
579 /* Init the unload section of the module. */
580 static int module_unload_init(struct module *mod)
581 {
582         mod->refptr = alloc_percpu(struct module_ref);
583         if (!mod->refptr)
584                 return -ENOMEM;
585 
586         INIT_LIST_HEAD(&mod->source_list);
587         INIT_LIST_HEAD(&mod->target_list);
588 
589         /* Hold reference count during initialization. */
590         __this_cpu_write(mod->refptr->incs, 1);
591         /* Backwards compatibility macros put refcount during init. */
592         mod->waiter = current;
593 
594         return 0;
595 }
596 
597 /* Does a already use b? */
598 static int already_uses(struct module *a, struct module *b)
599 {
600         struct module_use *use;
601 
602         list_for_each_entry(use, &b->source_list, source_list) {
603                 if (use->source == a) {
604                         DEBUGP("%s uses %s!\n", a->name, b->name);
605                         return 1;
606                 }
607         }
608         DEBUGP("%s does not use %s!\n", a->name, b->name);
609         return 0;
610 }
611 
612 /*
613  * Module a uses b
614  *  - we add 'a' as a "source", 'b' as a "target" of module use
615  *  - the module_use is added to the list of 'b' sources (so
616  *    'b' can walk the list to see who sourced them), and of 'a'
617  *    targets (so 'a' can see what modules it targets).
618  */
619 static int add_module_usage(struct module *a, struct module *b)
620 {
621         struct module_use *use;
622 
623         DEBUGP("Allocating new usage for %s.\n", a->name);
624         use = kmalloc(sizeof(*use), GFP_ATOMIC);
625         if (!use) {
626                 printk(KERN_WARNING "%s: out of memory loading\n", a->name);
627                 return -ENOMEM;
628         }
629 
630         use->source = a;
631         use->target = b;
632         list_add(&use->source_list, &b->source_list);
633         list_add(&use->target_list, &a->target_list);
634         return 0;
635 }
636 
637 /* Module a uses b: caller needs module_mutex() */
638 int ref_module(struct module *a, struct module *b)
639 {
640         int err;
641 
642         if (b == NULL || already_uses(a, b))
643                 return 0;
644 
645         /* If module isn't available, we fail. */
646         err = strong_try_module_get(b);
647         if (err)
648                 return err;
649 
650         err = add_module_usage(a, b);
651         if (err) {
652                 module_put(b);
653                 return err;
654         }
655         return 0;
656 }
657 EXPORT_SYMBOL_GPL(ref_module);
658 
659 /* Clear the unload stuff of the module. */
660 static void module_unload_free(struct module *mod)
661 {
662         struct module_use *use, *tmp;
663 
664         mutex_lock(&module_mutex);
665         list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
666                 struct module *i = use->target;
667                 DEBUGP("%s unusing %s\n", mod->name, i->name);
668                 module_put(i);
669                 list_del(&use->source_list);
670                 list_del(&use->target_list);
671                 kfree(use);
672         }
673         mutex_unlock(&module_mutex);
674 
675         free_percpu(mod->refptr);
676 }
677 
678 #ifdef CONFIG_MODULE_FORCE_UNLOAD
679 static inline int try_force_unload(unsigned int flags)
680 {
681         int ret = (flags & O_TRUNC);
682         if (ret)
683                 add_taint(TAINT_FORCED_RMMOD);
684         return ret;
685 }
686 #else
687 static inline int try_force_unload(unsigned int flags)
688 {
689         return 0;
690 }
691 #endif /* CONFIG_MODULE_FORCE_UNLOAD */
692 
693 struct stopref
694 {
695         struct module *mod;
696         int flags;
697         int *forced;
698 };
699 
700 /* Whole machine is stopped with interrupts off when this runs. */
701 static int __try_stop_module(void *_sref)
702 {
703         struct stopref *sref = _sref;
704 
705         /* If it's not unused, quit unless we're forcing. */
706         if (module_refcount(sref->mod) != 0) {
707                 if (!(*sref->forced = try_force_unload(sref->flags)))
708                         return -EWOULDBLOCK;
709         }
710 
711         /* Mark it as dying. */
712         sref->mod->state = MODULE_STATE_GOING;
713         return 0;
714 }
715 
716 static int try_stop_module(struct module *mod, int flags, int *forced)
717 {
718         if (flags & O_NONBLOCK) {
719                 struct stopref sref = { mod, flags, forced };
720 
721                 return stop_machine(__try_stop_module, &sref, NULL);
722         } else {
723                 /* We don't need to stop the machine for this. */
724                 mod->state = MODULE_STATE_GOING;
725                 synchronize_sched();
726                 return 0;
727         }
728 }
729 
730 unsigned int module_refcount(struct module *mod)
731 {
732         unsigned int incs = 0, decs = 0;
733         int cpu;
734 
735         for_each_possible_cpu(cpu)
736                 decs += per_cpu_ptr(mod->refptr, cpu)->decs;
737         /*
738          * ensure the incs are added up after the decs.
739          * module_put ensures incs are visible before decs with smp_wmb.
740          *
741          * This 2-count scheme avoids the situation where the refcount
742          * for CPU0 is read, then CPU0 increments the module refcount,
743          * then CPU1 drops that refcount, then the refcount for CPU1 is
744          * read. We would record a decrement but not its corresponding
745          * increment so we would see a low count (disaster).
746          *
747          * Rare situation? But module_refcount can be preempted, and we
748          * might be tallying up 4096+ CPUs. So it is not impossible.
749          */
750         smp_rmb();
751         for_each_possible_cpu(cpu)
752                 incs += per_cpu_ptr(mod->refptr, cpu)->incs;
753         return incs - decs;
754 }
755 EXPORT_SYMBOL(module_refcount);
756 
757 /* This exists whether we can unload or not */
758 static void free_module(struct module *mod);
759 
760 static void wait_for_zero_refcount(struct module *mod)
761 {
762         /* Since we might sleep for some time, release the mutex first */
763         mutex_unlock(&module_mutex);
764         for (;;) {
765                 DEBUGP("Looking at refcount...\n");
766                 set_current_state(TASK_UNINTERRUPTIBLE);
767                 if (module_refcount(mod) == 0)
768                         break;
769                 schedule();
770         }
771         current->state = TASK_RUNNING;
772         mutex_lock(&module_mutex);
773 }
774 
775 SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
776                 unsigned int, flags)
777 {
778         struct module *mod;
779         char name[MODULE_NAME_LEN];
780         int ret, forced = 0;
781 
782         if (!capable(CAP_SYS_MODULE) || modules_disabled)
783                 return -EPERM;
784         if (!ccs_capable(CCS_USE_KERNEL_MODULE))
785                 return -EPERM;
786 
787         if (strncpy_from_user(name, name_user, MODULE_NAME_LEN-1) < 0)
788                 return -EFAULT;
789         name[MODULE_NAME_LEN-1] = '\0';
790 
791         if (mutex_lock_interruptible(&module_mutex) != 0)
792                 return -EINTR;
793 
794         mod = find_module(name);
795         if (!mod) {
796                 ret = -ENOENT;
797                 goto out;
798         }
799 
800         if (!list_empty(&mod->source_list)) {
801                 /* Other modules depend on us: get rid of them first. */
802                 ret = -EWOULDBLOCK;
803                 goto out;
804         }
805 
806         /* Doing init or already dying? */
807         if (mod->state != MODULE_STATE_LIVE) {
808                 /* FIXME: if (force), slam module count and wake up
809                    waiter --RR */
810                 DEBUGP("%s already dying\n", mod->name);
811                 ret = -EBUSY;
812                 goto out;
813         }
814 
815         /* If it has an init func, it must have an exit func to unload */
816         if (mod->init && !mod->exit) {
817                 forced = try_force_unload(flags);
818                 if (!forced) {
819                         /* This module can't be removed */
820                         ret = -EBUSY;
821                         goto out;
822                 }
823         }
824 
825         /* Set this up before setting mod->state */
826         mod->waiter = current;
827 
828         /* Stop the machine so refcounts can't move and disable module. */
829         ret = try_stop_module(mod, flags, &forced);
830         if (ret != 0)
831                 goto out;
832 
833         /* Never wait if forced. */
834         if (!forced && module_refcount(mod) != 0)
835                 wait_for_zero_refcount(mod);
836 
837         mutex_unlock(&module_mutex);
838         /* Final destruction now no one is using it. */
839         if (mod->exit != NULL)
840                 mod->exit();
841         blocking_notifier_call_chain(&module_notify_list,
842                                      MODULE_STATE_GOING, mod);
843         async_synchronize_full();
844 
845         /* Store the name of the last unloaded module for diagnostic purposes */
846         strlcpy(last_unloaded_module, mod->name, sizeof(last_unloaded_module));
847 
848         free_module(mod);
849         return 0;
850 out:
851         mutex_unlock(&module_mutex);
852         return ret;
853 }
854 
855 static inline void print_unload_info(struct seq_file *m, struct module *mod)
856 {
857         struct module_use *use;
858         int printed_something = 0;
859 
860         seq_printf(m, " %u ", module_refcount(mod));
861 
862         /* Always include a trailing , so userspace can differentiate
863            between this and the old multi-field proc format. */
864         list_for_each_entry(use, &mod->source_list, source_list) {
865                 printed_something = 1;
866                 seq_printf(m, "%s,", use->source->name);
867         }
868 
869         if (mod->init != NULL && mod->exit == NULL) {
870                 printed_something = 1;
871                 seq_printf(m, "[permanent],");
872         }
873 
874         if (!printed_something)
875                 seq_printf(m, "-");
876 }
877 
878 void __symbol_put(const char *symbol)
879 {
880         struct module *owner;
881 
882         preempt_disable();
883         if (!find_symbol(symbol, &owner, NULL, true, false))
884                 BUG();
885         module_put(owner);
886         preempt_enable();
887 }
888 EXPORT_SYMBOL(__symbol_put);
889 
890 /* Note this assumes addr is a function, which it currently always is. */
891 void symbol_put_addr(void *addr)
892 {
893         struct module *modaddr;
894         unsigned long a = (unsigned long)dereference_function_descriptor(addr);
895 
896         if (core_kernel_text(a))
897                 return;
898 
899         /*
900          * Even though we hold a reference on the module; we still need to
901          * disable preemption in order to safely traverse the data structure.
902          */
903         preempt_disable();
904         modaddr = __module_text_address(a);
905         BUG_ON(!modaddr);
906         module_put(modaddr);
907         preempt_enable();
908 }
909 EXPORT_SYMBOL_GPL(symbol_put_addr);
910 
911 static ssize_t show_refcnt(struct module_attribute *mattr,
912                            struct module_kobject *mk, char *buffer)
913 {
914         return sprintf(buffer, "%u\n", module_refcount(mk->mod));
915 }
916 
917 static struct module_attribute refcnt = {
918         .attr = { .name = "refcnt", .mode = 0444 },
919         .show = show_refcnt,
920 };
921 
922 void module_put(struct module *module)
923 {
924         if (module) {
925                 preempt_disable();
926                 smp_wmb(); /* see comment in module_refcount */
927                 __this_cpu_inc(module->refptr->decs);
928 
929                 trace_module_put(module, _RET_IP_);
930                 /* Maybe they're waiting for us to drop reference? */
931                 if (unlikely(!module_is_live(module)))
932                         wake_up_process(module->waiter);
933                 preempt_enable();
934         }
935 }
936 EXPORT_SYMBOL(module_put);
937 
938 #else /* !CONFIG_MODULE_UNLOAD */
939 static inline void print_unload_info(struct seq_file *m, struct module *mod)
940 {
941         /* We don't know the usage count, or what modules are using. */
942         seq_printf(m, " - -");
943 }
944 
945 static inline void module_unload_free(struct module *mod)
946 {
947 }
948 
949 int ref_module(struct module *a, struct module *b)
950 {
951         return strong_try_module_get(b);
952 }
953 EXPORT_SYMBOL_GPL(ref_module);
954 
955 static inline int module_unload_init(struct module *mod)
956 {
957         return 0;
958 }
959 #endif /* CONFIG_MODULE_UNLOAD */
960 
961 static ssize_t show_initstate(struct module_attribute *mattr,
962                               struct module_kobject *mk, char *buffer)
963 {
964         const char *state = "unknown";
965 
966         switch (mk->mod->state) {
967         case MODULE_STATE_LIVE:
968                 state = "live";
969                 break;
970         case MODULE_STATE_COMING:
971                 state = "coming";
972                 break;
973         case MODULE_STATE_GOING:
974                 state = "going";
975                 break;
976         }
977         return sprintf(buffer, "%s\n", state);
978 }
979 
980 static struct module_attribute initstate = {
981         .attr = { .name = "initstate", .mode = 0444 },
982         .show = show_initstate,
983 };
984 
985 static ssize_t store_uevent(struct module_attribute *mattr,
986                             struct module_kobject *mk,
987                             const char *buffer, size_t count)
988 {
989         enum kobject_action action;
990 
991         if (kobject_action_type(buffer, count, &action) == 0)
992                 kobject_uevent(&mk->kobj, action);
993         return count;
994 }
995 
996 struct module_attribute module_uevent = {
997         .attr = { .name = "uevent", .mode = 0200 },
998         .store = store_uevent,
999 };
1000 
1001 static struct module_attribute *modinfo_attrs[] = {
1002         &modinfo_version,
1003         &modinfo_srcversion,
1004         &initstate,
1005         &module_uevent,
1006 #ifdef CONFIG_MODULE_UNLOAD
1007         &refcnt,
1008 #endif
1009         NULL,
1010 };
1011 
1012 static const char vermagic[] = VERMAGIC_STRING;
1013 
1014 static int try_to_force_load(struct module *mod, const char *reason)
1015 {
1016 #ifdef CONFIG_MODULE_FORCE_LOAD
1017         if (!test_taint(TAINT_FORCED_MODULE))
1018                 printk(KERN_WARNING "%s: %s: kernel tainted.\n",
1019                        mod->name, reason);
1020         add_taint_module(mod, TAINT_FORCED_MODULE);
1021         return 0;
1022 #else
1023         return -ENOEXEC;
1024 #endif
1025 }
1026 
1027 #ifdef CONFIG_MODVERSIONS
1028 /* If the arch applies (non-zero) relocations to kernel kcrctab, unapply it. */
1029 static unsigned long maybe_relocated(unsigned long crc,
1030                                      const struct module *crc_owner)
1031 {
1032 #ifdef ARCH_RELOCATES_KCRCTAB
1033         if (crc_owner == NULL)
1034                 return crc - (unsigned long)reloc_start;
1035 #endif
1036         return crc;
1037 }
1038 
1039 static int check_version(Elf_Shdr *sechdrs,
1040                          unsigned int versindex,
1041                          const char *symname,
1042                          struct module *mod, 
1043                          const unsigned long *crc,
1044                          const struct module *crc_owner)
1045 {
1046         unsigned int i, num_versions;
1047         struct modversion_info *versions;
1048 
1049         /* Exporting module didn't supply crcs?  OK, we're already tainted. */
1050         if (!crc)
1051                 return 1;
1052 
1053         /* No versions at all?  modprobe --force does this. */
1054         if (versindex == 0)
1055                 return try_to_force_load(mod, symname) == 0;
1056 
1057         versions = (void *) sechdrs[versindex].sh_addr;
1058         num_versions = sechdrs[versindex].sh_size
1059                 / sizeof(struct modversion_info);
1060 
1061         for (i = 0; i < num_versions; i++) {
1062                 if (strcmp(versions[i].name, symname) != 0)
1063                         continue;
1064 
1065                 if (versions[i].crc == maybe_relocated(*crc, crc_owner))
1066                         return 1;
1067                 DEBUGP("Found checksum %lX vs module %lX\n",
1068                        maybe_relocated(*crc, crc_owner), versions[i].crc);
1069                 goto bad_version;
1070         }
1071 
1072         printk(KERN_WARNING "%s: no symbol version for %s\n",
1073                mod->name, symname);
1074         return 0;
1075 
1076 bad_version:
1077         printk("%s: disagrees about version of symbol %s\n",
1078                mod->name, symname);
1079         return 0;
1080 }
1081 
1082 static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1083                                           unsigned int versindex,
1084                                           struct module *mod)
1085 {
1086         const unsigned long *crc;
1087 
1088         /* Since this should be found in kernel (which can't be removed),
1089          * no locking is necessary. */
1090         if (!find_symbol(MODULE_SYMBOL_PREFIX "module_layout", NULL,
1091                          &crc, true, false))
1092                 BUG();
1093         return check_version(sechdrs, versindex, "module_layout", mod, crc,
1094                              NULL);
1095 }
1096 
1097 /* First part is kernel version, which we ignore if module has crcs. */
1098 static inline int same_magic(const char *amagic, const char *bmagic,
1099                              bool has_crcs)
1100 {
1101         if (has_crcs) {
1102                 amagic += strcspn(amagic, " ");
1103                 bmagic += strcspn(bmagic, " ");
1104         }
1105         return strcmp(amagic, bmagic) == 0;
1106 }
1107 #else
1108 static inline int check_version(Elf_Shdr *sechdrs,
1109                                 unsigned int versindex,
1110                                 const char *symname,
1111                                 struct module *mod, 
1112                                 const unsigned long *crc,
1113                                 const struct module *crc_owner)
1114 {
1115         return 1;
1116 }
1117 
1118 static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1119                                           unsigned int versindex,
1120                                           struct module *mod)
1121 {
1122         return 1;
1123 }
1124 
1125 static inline int same_magic(const char *amagic, const char *bmagic,
1126                              bool has_crcs)
1127 {
1128         return strcmp(amagic, bmagic) == 0;
1129 }
1130 #endif /* CONFIG_MODVERSIONS */
1131 
1132 /* Resolve a symbol for this module.  I.e. if we find one, record usage. */
1133 static const struct kernel_symbol *resolve_symbol(struct module *mod,
1134                                                   const struct load_info *info,
1135                                                   const char *name,
1136                                                   char ownername[])
1137 {
1138         struct module *owner;
1139         const struct kernel_symbol *sym;
1140         const unsigned long *crc;
1141         int err;
1142 
1143         mutex_lock(&module_mutex);
1144         sym = find_symbol(name, &owner, &crc,
1145                           !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)), true);
1146         if (!sym)
1147                 goto unlock;
1148 
1149         if (!check_version(info->sechdrs, info->index.vers, name, mod, crc,
1150                            owner)) {
1151                 sym = ERR_PTR(-EINVAL);
1152                 goto getname;
1153         }
1154 
1155         err = ref_module(mod, owner);
1156         if (err) {
1157                 sym = ERR_PTR(err);
1158                 goto getname;
1159         }
1160 
1161 getname:
1162         /* We must make copy under the lock if we failed to get ref. */
1163         strncpy(ownername, module_name(owner), MODULE_NAME_LEN);
1164 unlock:
1165         mutex_unlock(&module_mutex);
1166         return sym;
1167 }
1168 
1169 static const struct kernel_symbol *
1170 resolve_symbol_wait(struct module *mod,
1171                     const struct load_info *info,
1172                     const char *name)
1173 {
1174         const struct kernel_symbol *ksym;
1175         char owner[MODULE_NAME_LEN];
1176 
1177         if (wait_event_interruptible_timeout(module_wq,
1178                         !IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1179                         || PTR_ERR(ksym) != -EBUSY,
1180                                              30 * HZ) <= 0) {
1181                 printk(KERN_WARNING "%s: gave up waiting for init of module %s.\n",
1182                        mod->name, owner);
1183         }
1184         return ksym;
1185 }
1186 
1187 /*
1188  * /sys/module/foo/sections stuff
1189  * J. Corbet <corbet@lwn.net>
1190  */
1191 #ifdef CONFIG_SYSFS
1192 
1193 #ifdef CONFIG_KALLSYMS
1194 static inline bool sect_empty(const Elf_Shdr *sect)
1195 {
1196         return !(sect->sh_flags & SHF_ALLOC) || sect->sh_size == 0;
1197 }
1198 
1199 struct module_sect_attr
1200 {
1201         struct module_attribute mattr;
1202         char *name;
1203         unsigned long address;
1204 };
1205 
1206 struct module_sect_attrs
1207 {
1208         struct attribute_group grp;
1209         unsigned int nsections;
1210         struct module_sect_attr attrs[0];
1211 };
1212 
1213 static ssize_t module_sect_show(struct module_attribute *mattr,
1214                                 struct module_kobject *mk, char *buf)
1215 {
1216         struct module_sect_attr *sattr =
1217                 container_of(mattr, struct module_sect_attr, mattr);
1218         return sprintf(buf, "0x%pK\n", (void *)sattr->address);
1219 }
1220 
1221 static void free_sect_attrs(struct module_sect_attrs *sect_attrs)
1222 {
1223         unsigned int section;
1224 
1225         for (section = 0; section < sect_attrs->nsections; section++)
1226                 kfree(sect_attrs->attrs[section].name);
1227         kfree(sect_attrs);
1228 }
1229 
1230 static void add_sect_attrs(struct module *mod, const struct load_info *info)
1231 {
1232         unsigned int nloaded = 0, i, size[2];
1233         struct module_sect_attrs *sect_attrs;
1234         struct module_sect_attr *sattr;
1235         struct attribute **gattr;
1236 
1237         /* Count loaded sections and allocate structures */
1238         for (i = 0; i < info->hdr->e_shnum; i++)
1239                 if (!sect_empty(&info->sechdrs[i]))
1240                         nloaded++;
1241         size[0] = ALIGN(sizeof(*sect_attrs)
1242                         + nloaded * sizeof(sect_attrs->attrs[0]),
1243                         sizeof(sect_attrs->grp.attrs[0]));
1244         size[1] = (nloaded + 1) * sizeof(sect_attrs->grp.attrs[0]);
1245         sect_attrs = kzalloc(size[0] + size[1], GFP_KERNEL);
1246         if (sect_attrs == NULL)
1247                 return;
1248 
1249         /* Setup section attributes. */
1250         sect_attrs->grp.name = "sections";
1251         sect_attrs->grp.attrs = (void *)sect_attrs + size[0];
1252 
1253         sect_attrs->nsections = 0;
1254         sattr = &sect_attrs->attrs[0];
1255         gattr = &sect_attrs->grp.attrs[0];
1256         for (i = 0; i < info->hdr->e_shnum; i++) {
1257                 Elf_Shdr *sec = &info->sechdrs[i];
1258                 if (sect_empty(sec))
1259                         continue;
1260                 sattr->address = sec->sh_addr;
1261                 sattr->name = kstrdup(info->secstrings + sec->sh_name,
1262                                         GFP_KERNEL);
1263                 if (sattr->name == NULL)
1264                         goto out;
1265                 sect_attrs->nsections++;
1266                 sysfs_attr_init(&sattr->mattr.attr);
1267                 sattr->mattr.show = module_sect_show;
1268                 sattr->mattr.store = NULL;
1269                 sattr->mattr.attr.name = sattr->name;
1270                 sattr->mattr.attr.mode = S_IRUGO;
1271                 *(gattr++) = &(sattr++)->mattr.attr;
1272         }
1273         *gattr = NULL;
1274 
1275         if (sysfs_create_group(&mod->mkobj.kobj, &sect_attrs->grp))
1276                 goto out;
1277 
1278         mod->sect_attrs = sect_attrs;
1279         return;
1280   out:
1281         free_sect_attrs(sect_attrs);
1282 }
1283 
1284 static void remove_sect_attrs(struct module *mod)
1285 {
1286         if (mod->sect_attrs) {
1287                 sysfs_remove_group(&mod->mkobj.kobj,
1288                                    &mod->sect_attrs->grp);
1289                 /* We are positive that no one is using any sect attrs
1290                  * at this point.  Deallocate immediately. */
1291                 free_sect_attrs(mod->sect_attrs);
1292                 mod->sect_attrs = NULL;
1293         }
1294 }
1295 
1296 /*
1297  * /sys/module/foo/notes/.section.name gives contents of SHT_NOTE sections.
1298  */
1299 
1300 struct module_notes_attrs {
1301         struct kobject *dir;
1302         unsigned int notes;
1303         struct bin_attribute attrs[0];
1304 };
1305 
1306 static ssize_t module_notes_read(struct file *filp, struct kobject *kobj,
1307                                  struct bin_attribute *bin_attr,
1308                                  char *buf, loff_t pos, size_t count)
1309 {
1310         /*
1311          * The caller checked the pos and count against our size.
1312          */
1313         memcpy(buf, bin_attr->private + pos, count);
1314         return count;
1315 }
1316 
1317 static void free_notes_attrs(struct module_notes_attrs *notes_attrs,
1318                              unsigned int i)
1319 {
1320         if (notes_attrs->dir) {
1321                 while (i-- > 0)
1322                         sysfs_remove_bin_file(notes_attrs->dir,
1323                                               &notes_attrs->attrs[i]);
1324                 kobject_put(notes_attrs->dir);
1325         }
1326         kfree(notes_attrs);
1327 }
1328 
1329 static void add_notes_attrs(struct module *mod, const struct load_info *info)
1330 {
1331         unsigned int notes, loaded, i;
1332         struct module_notes_attrs *notes_attrs;
1333         struct bin_attribute *nattr;
1334 
1335         /* failed to create section attributes, so can't create notes */
1336         if (!mod->sect_attrs)
1337                 return;
1338 
1339         /* Count notes sections and allocate structures.  */
1340         notes = 0;
1341         for (i = 0; i < info->hdr->e_shnum; i++)
1342                 if (!sect_empty(&info->sechdrs[i]) &&
1343                     (info->sechdrs[i].sh_type == SHT_NOTE))
1344                         ++notes;
1345 
1346         if (notes == 0)
1347                 return;
1348 
1349         notes_attrs = kzalloc(sizeof(*notes_attrs)
1350                               + notes * sizeof(notes_attrs->attrs[0]),
1351                               GFP_KERNEL);
1352         if (notes_attrs == NULL)
1353                 return;
1354 
1355         notes_attrs->notes = notes;
1356         nattr = &notes_attrs->attrs[0];
1357         for (loaded = i = 0; i < info->hdr->e_shnum; ++i) {
1358                 if (sect_empty(&info->sechdrs[i]))
1359                         continue;
1360                 if (info->sechdrs[i].sh_type == SHT_NOTE) {
1361                         sysfs_bin_attr_init(nattr);
1362                         nattr->attr.name = mod->sect_attrs->attrs[loaded].name;
1363                         nattr->attr.mode = S_IRUGO;
1364                         nattr->size = info->sechdrs[i].sh_size;
1365                         nattr->private = (void *) info->sechdrs[i].sh_addr;
1366                         nattr->read = module_notes_read;
1367                         ++nattr;
1368                 }
1369                 ++loaded;
1370         }
1371 
1372         notes_attrs->dir = kobject_create_and_add("notes", &mod->mkobj.kobj);
1373         if (!notes_attrs->dir)
1374                 goto out;
1375 
1376         for (i = 0; i < notes; ++i)
1377                 if (sysfs_create_bin_file(notes_attrs->dir,
1378                                           &notes_attrs->attrs[i]))
1379                         goto out;
1380 
1381         mod->notes_attrs = notes_attrs;
1382         return;
1383 
1384   out:
1385         free_notes_attrs(notes_attrs, i);
1386 }
1387 
1388 static void remove_notes_attrs(struct module *mod)
1389 {
1390         if (mod->notes_attrs)
1391                 free_notes_attrs(mod->notes_attrs, mod->notes_attrs->notes);
1392 }
1393 
1394 #else
1395 
1396 static inline void add_sect_attrs(struct module *mod,
1397                                   const struct load_info *info)
1398 {
1399 }
1400 
1401 static inline void remove_sect_attrs(struct module *mod)
1402 {
1403 }
1404 
1405 static inline void add_notes_attrs(struct module *mod,
1406                                    const struct load_info *info)
1407 {
1408 }
1409 
1410 static inline void remove_notes_attrs(struct module *mod)
1411 {
1412 }
1413 #endif /* CONFIG_KALLSYMS */
1414 
1415 static void add_usage_links(struct module *mod)
1416 {
1417 #ifdef CONFIG_MODULE_UNLOAD
1418         struct module_use *use;
1419         int nowarn;
1420 
1421         mutex_lock(&module_mutex);
1422         list_for_each_entry(use, &mod->target_list, target_list) {
1423                 nowarn = sysfs_create_link(use->target->holders_dir,
1424                                            &mod->mkobj.kobj, mod->name);
1425         }
1426         mutex_unlock(&module_mutex);
1427 #endif
1428 }
1429 
1430 static void del_usage_links(struct module *mod)
1431 {
1432 #ifdef CONFIG_MODULE_UNLOAD
1433         struct module_use *use;
1434 
1435         mutex_lock(&module_mutex);
1436         list_for_each_entry(use, &mod->target_list, target_list)
1437                 sysfs_remove_link(use->target->holders_dir, mod->name);
1438         mutex_unlock(&module_mutex);
1439 #endif
1440 }
1441 
1442 static int module_add_modinfo_attrs(struct module *mod)
1443 {
1444         struct module_attribute *attr;
1445         struct module_attribute *temp_attr;
1446         int error = 0;
1447         int i;
1448 
1449         mod->modinfo_attrs = kzalloc((sizeof(struct module_attribute) *
1450                                         (ARRAY_SIZE(modinfo_attrs) + 1)),
1451                                         GFP_KERNEL);
1452         if (!mod->modinfo_attrs)
1453                 return -ENOMEM;
1454 
1455         temp_attr = mod->modinfo_attrs;
1456         for (i = 0; (attr = modinfo_attrs[i]) && !error; i++) {
1457                 if (!attr->test ||
1458                     (attr->test && attr->test(mod))) {
1459                         memcpy(temp_attr, attr, sizeof(*temp_attr));
1460                         sysfs_attr_init(&temp_attr->attr);
1461                         error = sysfs_create_file(&mod->mkobj.kobj,&temp_attr->attr);
1462                         ++temp_attr;
1463                 }
1464         }
1465         return error;
1466 }
1467 
1468 static void module_remove_modinfo_attrs(struct module *mod)
1469 {
1470         struct module_attribute *attr;
1471         int i;
1472 
1473         for (i = 0; (attr = &mod->modinfo_attrs[i]); i++) {
1474                 /* pick a field to test for end of list */
1475                 if (!attr->attr.name)
1476                         break;
1477                 sysfs_remove_file(&mod->mkobj.kobj,&attr->attr);
1478                 if (attr->free)
1479                         attr->free(mod);
1480         }
1481         kfree(mod->modinfo_attrs);
1482 }
1483 
1484 static int mod_sysfs_init(struct module *mod)
1485 {
1486         int err;
1487         struct kobject *kobj;
1488 
1489         if (!module_sysfs_initialized) {
1490                 printk(KERN_ERR "%s: module sysfs not initialized\n",
1491                        mod->name);
1492                 err = -EINVAL;
1493                 goto out;
1494         }
1495 
1496         kobj = kset_find_obj(module_kset, mod->name);
1497         if (kobj) {
1498                 printk(KERN_ERR "%s: module is already loaded\n", mod->name);
1499                 kobject_put(kobj);
1500                 err = -EINVAL;
1501                 goto out;
1502         }
1503 
1504         mod->mkobj.mod = mod;
1505 
1506         memset(&mod->mkobj.kobj, 0, sizeof(mod->mkobj.kobj));
1507         mod->mkobj.kobj.kset = module_kset;
1508         err = kobject_init_and_add(&mod->mkobj.kobj, &module_ktype, NULL,
1509                                    "%s", mod->name);
1510         if (err)
1511                 kobject_put(&mod->mkobj.kobj);
1512 
1513         /* delay uevent until full sysfs population */
1514 out:
1515         return err;
1516 }
1517 
1518 static int mod_sysfs_setup(struct module *mod,
1519                            const struct load_info *info,
1520                            struct kernel_param *kparam,
1521                            unsigned int num_params)
1522 {
1523         int err;
1524 
1525         err = mod_sysfs_init(mod);
1526         if (err)
1527                 goto out;
1528 
1529         mod->holders_dir = kobject_create_and_add("holders", &mod->mkobj.kobj);
1530         if (!mod->holders_dir) {
1531                 err = -ENOMEM;
1532                 goto out_unreg;
1533         }
1534 
1535         err = module_param_sysfs_setup(mod, kparam, num_params);
1536         if (err)
1537                 goto out_unreg_holders;
1538 
1539         err = module_add_modinfo_attrs(mod);
1540         if (err)
1541                 goto out_unreg_param;
1542 
1543         add_usage_links(mod);
1544         add_sect_attrs(mod, info);
1545         add_notes_attrs(mod, info);
1546 
1547         kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
1548         return 0;
1549 
1550 out_unreg_param:
1551         module_param_sysfs_remove(mod);
1552 out_unreg_holders:
1553         kobject_put(mod->holders_dir);
1554 out_unreg:
1555         kobject_put(&mod->mkobj.kobj);
1556 out:
1557         return err;
1558 }
1559 
1560 static void mod_sysfs_fini(struct module *mod)
1561 {
1562         remove_notes_attrs(mod);
1563         remove_sect_attrs(mod);
1564         kobject_put(&mod->mkobj.kobj);
1565 }
1566 
1567 #else /* !CONFIG_SYSFS */
1568 
1569 static int mod_sysfs_setup(struct module *mod,
1570                            const struct load_info *info,
1571                            struct kernel_param *kparam,
1572                            unsigned int num_params)
1573 {
1574         return 0;
1575 }
1576 
1577 static void mod_sysfs_fini(struct module *mod)
1578 {
1579 }
1580 
1581 static void module_remove_modinfo_attrs(struct module *mod)
1582 {
1583 }
1584 
1585 static void del_usage_links(struct module *mod)
1586 {
1587 }
1588 
1589 #endif /* CONFIG_SYSFS */
1590 
1591 static void mod_sysfs_teardown(struct module *mod)
1592 {
1593         del_usage_links(mod);
1594         module_remove_modinfo_attrs(mod);
1595         module_param_sysfs_remove(mod);
1596         kobject_put(mod->mkobj.drivers_dir);
1597         kobject_put(mod->holders_dir);
1598         mod_sysfs_fini(mod);
1599 }
1600 
1601 /*
1602  * unlink the module with the whole machine is stopped with interrupts off
1603  * - this defends against kallsyms not taking locks
1604  */
1605 static int __unlink_module(void *_mod)
1606 {
1607         struct module *mod = _mod;
1608         list_del(&mod->list);
1609         module_bug_cleanup(mod);
1610         return 0;
1611 }
1612 
1613 #ifdef CONFIG_DEBUG_SET_MODULE_RONX
1614 /*
1615  * LKM RO/NX protection: protect module's text/ro-data
1616  * from modification and any data from execution.
1617  */
1618 void set_page_attributes(void *start, void *end, int (*set)(unsigned long start, int num_pages))
1619 {
1620         unsigned long begin_pfn = PFN_DOWN((unsigned long)start);
1621         unsigned long end_pfn = PFN_DOWN((unsigned long)end);
1622 
1623         if (end_pfn > begin_pfn)
1624                 set(begin_pfn << PAGE_SHIFT, end_pfn - begin_pfn);
1625 }
1626 
1627 static void set_section_ro_nx(void *base,
1628                         unsigned long text_size,
1629                         unsigned long ro_size,
1630                         unsigned long total_size)
1631 {
1632         /* begin and end PFNs of the current subsection */
1633         unsigned long begin_pfn;
1634         unsigned long end_pfn;
1635 
1636         /*
1637          * Set RO for module text and RO-data:
1638          * - Always protect first page.
1639          * - Do not protect last partial page.
1640          */
1641         if (ro_size > 0)
1642                 set_page_attributes(base, base + ro_size, set_memory_ro);
1643 
1644         /*
1645          * Set NX permissions for module data:
1646          * - Do not protect first partial page.
1647          * - Always protect last page.
1648          */
1649         if (total_size > text_size) {
1650                 begin_pfn = PFN_UP((unsigned long)base + text_size);
1651                 end_pfn = PFN_UP((unsigned long)base + total_size);
1652                 if (end_pfn > begin_pfn)
1653                         set_memory_nx(begin_pfn << PAGE_SHIFT, end_pfn - begin_pfn);
1654         }
1655 }
1656 
1657 static void unset_module_core_ro_nx(struct module *mod)
1658 {
1659         set_page_attributes(mod->module_core + mod->core_text_size,
1660                 mod->module_core + mod->core_size,
1661                 set_memory_x);
1662         set_page_attributes(mod->module_core,
1663                 mod->module_core + mod->core_ro_size,
1664                 set_memory_rw);
1665 }
1666 
1667 static void unset_module_init_ro_nx(struct module *mod)
1668 {
1669         set_page_attributes(mod->module_init + mod->init_text_size,
1670                 mod->module_init + mod->init_size,
1671                 set_memory_x);
1672         set_page_attributes(mod->module_init,
1673                 mod->module_init + mod->init_ro_size,
1674                 set_memory_rw);
1675 }
1676 
1677 /* Iterate through all modules and set each module's text as RW */
1678 void set_all_modules_text_rw(void)
1679 {
1680         struct module *mod;
1681 
1682         mutex_lock(&module_mutex);
1683         list_for_each_entry_rcu(mod, &modules, list) {
1684                 if ((mod->module_core) && (mod->core_text_size)) {
1685                         set_page_attributes(mod->module_core,
1686                                                 mod->module_core + mod->core_text_size,
1687                                                 set_memory_rw);
1688                 }
1689                 if ((mod->module_init) && (mod->init_text_size)) {
1690                         set_page_attributes(mod->module_init,
1691                                                 mod->module_init + mod->init_text_size,
1692                                                 set_memory_rw);
1693                 }
1694         }
1695         mutex_unlock(&module_mutex);
1696 }
1697 
1698 /* Iterate through all modules and set each module's text as RO */
1699 void set_all_modules_text_ro(void)
1700 {
1701         struct module *mod;
1702 
1703         mutex_lock(&module_mutex);
1704         list_for_each_entry_rcu(mod, &modules, list) {
1705                 if ((mod->module_core) && (mod->core_text_size)) {
1706                         set_page_attributes(mod->module_core,
1707                                                 mod->module_core + mod->core_text_size,
1708                                                 set_memory_ro);
1709                 }
1710                 if ((mod->module_init) && (mod->init_text_size)) {
1711                         set_page_attributes(mod->module_init,
1712                                                 mod->module_init + mod->init_text_size,
1713                                                 set_memory_ro);
1714                 }
1715         }
1716         mutex_unlock(&module_mutex);
1717 }
1718 #else
1719 static inline void set_section_ro_nx(void *base, unsigned long text_size, unsigned long ro_size, unsigned long total_size) { }
1720 static void unset_module_core_ro_nx(struct module *mod) { }
1721 static void unset_module_init_ro_nx(struct module *mod) { }
1722 #endif
1723 
1724 void __weak module_free(struct module *mod, void *module_region)
1725 {
1726         vfree(module_region);
1727 }
1728 
1729 void __weak module_arch_cleanup(struct module *mod)
1730 {
1731 }
1732 
1733 /* Free a module, remove from lists, etc. */
1734 static void free_module(struct module *mod)
1735 {
1736         trace_module_free(mod);
1737 
1738         /* Delete from various lists */
1739         mutex_lock(&module_mutex);
1740         stop_machine(__unlink_module, mod, NULL);
1741         mutex_unlock(&module_mutex);
1742         mod_sysfs_teardown(mod);
1743 
1744         /* Remove dynamic debug info */
1745         ddebug_remove_module(mod->name);
1746 
1747         /* Arch-specific cleanup. */
1748         module_arch_cleanup(mod);
1749 
1750         /* Module unload stuff */
1751         module_unload_free(mod);
1752 
1753         /* Free any allocated parameters. */
1754         destroy_params(mod->kp, mod->num_kp);
1755 
1756         /* This may be NULL, but that's OK */
1757         unset_module_init_ro_nx(mod);
1758         module_free(mod, mod->module_init);
1759         kfree(mod->args);
1760         percpu_modfree(mod);
1761 
1762         /* Free lock-classes: */
1763         lockdep_free_key_range(mod->module_core, mod->core_size);
1764 
1765         /* Finally, free the core (containing the module structure) */
1766         unset_module_core_ro_nx(mod);
1767         module_free(mod, mod->module_core);
1768 
1769 #ifdef CONFIG_MPU
1770         update_protections(current->mm);
1771 #endif
1772 }
1773 
1774 void *__symbol_get(const char *symbol)
1775 {
1776         struct module *owner;
1777         const struct kernel_symbol *sym;
1778 
1779         preempt_disable();
1780         sym = find_symbol(symbol, &owner, NULL, true, true);
1781         if (sym && strong_try_module_get(owner))
1782                 sym = NULL;
1783         preempt_enable();
1784 
1785         return sym ? (void *)sym->value : NULL;
1786 }
1787 EXPORT_SYMBOL_GPL(__symbol_get);
1788 
1789 /*
1790  * Ensure that an exported symbol [global namespace] does not already exist
1791  * in the kernel or in some other module's exported symbol table.
1792  *
1793  * You must hold the module_mutex.
1794  */
1795 static int verify_export_symbols(struct module *mod)
1796 {
1797         unsigned int i;
1798         struct module *owner;
1799         const struct kernel_symbol *s;
1800         struct {
1801                 const struct kernel_symbol *sym;
1802                 unsigned int num;
1803         } arr[] = {
1804                 { mod->syms, mod->num_syms },
1805                 { mod->gpl_syms, mod->num_gpl_syms },
1806                 { mod->gpl_future_syms, mod->num_gpl_future_syms },
1807 #ifdef CONFIG_UNUSED_SYMBOLS
1808                 { mod->unused_syms, mod->num_unused_syms },
1809                 { mod->unused_gpl_syms, mod->num_unused_gpl_syms },
1810 #endif
1811         };
1812 
1813         for (i = 0; i < ARRAY_SIZE(arr); i++) {
1814                 for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
1815                         if (find_symbol(s->name, &owner, NULL, true, false)) {
1816                                 printk(KERN_ERR
1817                                        "%s: exports duplicate symbol %s"
1818                                        " (owned by %s)\n",
1819                                        mod->name, s->name, module_name(owner));
1820                                 return -ENOEXEC;
1821                         }
1822                 }
1823         }
1824         return 0;
1825 }
1826 
1827 /* Change all symbols so that st_value encodes the pointer directly. */
1828 static int simplify_symbols(struct module *mod, const struct load_info *info)
1829 {
1830         Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
1831         Elf_Sym *sym = (void *)symsec->sh_addr;
1832         unsigned long secbase;
1833         unsigned int i;
1834         int ret = 0;
1835         const struct kernel_symbol *ksym;
1836 
1837         for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
1838                 const char *name = info->strtab + sym[i].st_name;
1839 
1840                 switch (sym[i].st_shndx) {
1841                 case SHN_COMMON:
1842                         /* We compiled with -fno-common.  These are not
1843                            supposed to happen.  */
1844                         DEBUGP("Common symbol: %s\n", name);
1845                         printk("%s: please compile with -fno-common\n",
1846                                mod->name);
1847                         ret = -ENOEXEC;
1848                         break;
1849 
1850                 case SHN_ABS:
1851                         /* Don't need to do anything */
1852                         DEBUGP("Absolute symbol: 0x%08lx\n",
1853                                (long)sym[i].st_value);
1854                         break;
1855 
1856                 case SHN_UNDEF:
1857                         ksym = resolve_symbol_wait(mod, info, name);
1858                         /* Ok if resolved.  */
1859                         if (ksym && !IS_ERR(ksym)) {
1860                                 sym[i].st_value = ksym->value;
1861                                 break;
1862                         }
1863 
1864                         /* Ok if weak.  */
1865                         if (!ksym && ELF_ST_BIND(sym[i].st_info) == STB_WEAK)
1866                                 break;
1867 
1868                         printk(KERN_WARNING "%s: Unknown symbol %s (err %li)\n",
1869                                mod->name, name, PTR_ERR(ksym));
1870                         ret = PTR_ERR(ksym) ?: -ENOENT;
1871                         break;
1872 
1873                 default:
1874                         /* Divert to percpu allocation if a percpu var. */
1875                         if (sym[i].st_shndx == info->index.pcpu)
1876                                 secbase = (unsigned long)mod_percpu(mod);
1877                         else
1878                                 secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
1879                         sym[i].st_value += secbase;
1880                         break;
1881                 }
1882         }
1883 
1884         return ret;
1885 }
1886 
1887 int __weak apply_relocate(Elf_Shdr *sechdrs,
1888                           const char *strtab,
1889                           unsigned int symindex,
1890                           unsigned int relsec,
1891                           struct module *me)
1892 {
1893         pr_err("module %s: REL relocation unsupported\n", me->name);
1894         return -ENOEXEC;
1895 }
1896 
1897 int __weak apply_relocate_add(Elf_Shdr *sechdrs,
1898                               const char *strtab,
1899                               unsigned int symindex,
1900                               unsigned int relsec,
1901                               struct module *me)
1902 {
1903         pr_err("module %s: RELA relocation unsupported\n", me->name);
1904         return -ENOEXEC;
1905 }
1906 
1907 static int apply_relocations(struct module *mod, const struct load_info *info)
1908 {
1909         unsigned int i;
1910         int err = 0;
1911 
1912         /* Now do relocations. */
1913         for (i = 1; i < info->hdr->e_shnum; i++) {
1914                 unsigned int infosec = info->sechdrs[i].sh_info;
1915 
1916                 /* Not a valid relocation section? */
1917                 if (infosec >= info->hdr->e_shnum)
1918                         continue;
1919 
1920                 /* Don't bother with non-allocated sections */
1921                 if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
1922                         continue;
1923 
1924                 if (info->sechdrs[i].sh_type == SHT_REL)
1925                         err = apply_relocate(info->sechdrs, info->strtab,
1926                                              info->index.sym, i, mod);
1927                 else if (info->sechdrs[i].sh_type == SHT_RELA)
1928                         err = apply_relocate_add(info->sechdrs, info->strtab,
1929                                                  info->index.sym, i, mod);
1930                 if (err < 0)
1931                         break;
1932         }
1933         return err;
1934 }
1935 
1936 /* Additional bytes needed by arch in front of individual sections */
1937 unsigned int __weak arch_mod_section_prepend(struct module *mod,
1938                                              unsigned int section)
1939 {
1940         /* default implementation just returns zero */
1941         return 0;
1942 }
1943 
1944 /* Update size with this section: return offset. */
1945 static long get_offset(struct module *mod, unsigned int *size,
1946                        Elf_Shdr *sechdr, unsigned int section)
1947 {
1948         long ret;
1949 
1950         *size += arch_mod_section_prepend(mod, section);
1951         ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
1952         *size = ret + sechdr->sh_size;
1953         return ret;
1954 }
1955 
1956 /* Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
1957    might -- code, read-only data, read-write data, small data.  Tally
1958    sizes, and place the offsets into sh_entsize fields: high bit means it
1959    belongs in init. */
1960 static void layout_sections(struct module *mod, struct load_info *info)
1961 {
1962         static unsigned long const masks[][2] = {
1963                 /* NOTE: all executable code must be the first section
1964                  * in this array; otherwise modify the text_size
1965                  * finder in the two loops below */
1966                 { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
1967                 { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
1968                 { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
1969                 { ARCH_SHF_SMALL | SHF_ALLOC, 0 }
1970         };
1971         unsigned int m, i;
1972 
1973         for (i = 0; i < info->hdr->e_shnum; i++)
1974                 info->sechdrs[i].sh_entsize = ~0UL;
1975 
1976         DEBUGP("Core section allocation order:\n");
1977         for (m = 0; m < ARRAY_SIZE(masks); ++m) {
1978                 for (i = 0; i < info->hdr->e_shnum; ++i) {
1979                         Elf_Shdr *s = &info->sechdrs[i];
1980                         const char *sname = info->secstrings + s->sh_name;
1981 
1982                         if ((s->sh_flags & masks[m][0]) != masks[m][0]
1983                             || (s->sh_flags & masks[m][1])
1984                             || s->sh_entsize != ~0UL
1985                             || strstarts(sname, ".init"))
1986                                 continue;
1987                         s->sh_entsize = get_offset(mod, &mod->core_size, s, i);
1988                         DEBUGP("\t%s\n", name);
1989                 }
1990                 switch (m) {
1991                 case 0: /* executable */
1992                         mod->core_size = debug_align(mod->core_size);
1993                         mod->core_text_size = mod->core_size;
1994                         break;
1995                 case 1: /* RO: text and ro-data */
1996                         mod->core_size = debug_align(mod->core_size);
1997                         mod->core_ro_size = mod->core_size;
1998                         break;
1999                 case 3: /* whole core */
2000                         mod->core_size = debug_align(mod->core_size);
2001                         break;
2002                 }
2003         }
2004 
2005         DEBUGP("Init section allocation order:\n");
2006         for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2007                 for (i = 0; i < info->hdr->e_shnum; ++i) {
2008                         Elf_Shdr *s = &info->sechdrs[i];
2009                         const char *sname = info->secstrings + s->sh_name;
2010 
2011                         if ((s->sh_flags & masks[m][0]) != masks[m][0]
2012                             || (s->sh_flags & masks[m][1])
2013                             || s->sh_entsize != ~0UL
2014                             || !strstarts(sname, ".init"))
2015                                 continue;
2016                         s->sh_entsize = (get_offset(mod, &mod->init_size, s, i)
2017                                          | INIT_OFFSET_MASK);
2018                         DEBUGP("\t%s\n", sname);
2019                 }
2020                 switch (m) {
2021                 case 0: /* executable */
2022                         mod->init_size = debug_align(mod->init_size);
2023                         mod->init_text_size = mod->init_size;
2024                         break;
2025                 case 1: /* RO: text and ro-data */
2026                         mod->init_size = debug_align(mod->init_size);
2027                         mod->init_ro_size = mod->init_size;
2028                         break;
2029                 case 3: /* whole init */
2030                         mod->init_size = debug_align(mod->init_size);
2031                         break;
2032                 }
2033         }
2034 }
2035 
2036 static void set_license(struct module *mod, const char *license)
2037 {
2038         if (!license)
2039                 license = "unspecified";
2040 
2041         if (!license_is_gpl_compatible(license)) {
2042                 if (!test_taint(TAINT_PROPRIETARY_MODULE))
2043                         printk(KERN_WARNING "%s: module license '%s' taints "
2044                                 "kernel.\n", mod->name, license);
2045                 add_taint_module(mod, TAINT_PROPRIETARY_MODULE);
2046         }
2047 }
2048 
2049 /* Parse tag=value strings from .modinfo section */
2050 static char *next_string(char *string, unsigned long *secsize)
2051 {
2052         /* Skip non-zero chars */
2053         while (string[0]) {
2054                 string++;
2055                 if ((*secsize)-- <= 1)
2056                         return NULL;
2057         }
2058 
2059         /* Skip any zero padding. */
2060         while (!string[0]) {
2061                 string++;
2062                 if ((*secsize)-- <= 1)
2063                         return NULL;
2064         }
2065         return string;
2066 }
2067 
2068 static char *get_modinfo(struct load_info *info, const char *tag)
2069 {
2070         char *p;
2071         unsigned int taglen = strlen(tag);
2072         Elf_Shdr *infosec = &info->sechdrs[info->index.info];
2073         unsigned long size = infosec->sh_size;
2074 
2075         for (p = (char *)infosec->sh_addr; p; p = next_string(p, &size)) {
2076                 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
2077                         return p + taglen + 1;
2078         }
2079         return NULL;
2080 }
2081 
2082 static void setup_modinfo(struct module *mod, struct load_info *info)
2083 {
2084         struct module_attribute *attr;
2085         int i;
2086 
2087         for (i = 0; (attr = modinfo_attrs[i]); i++) {
2088                 if (attr->setup)
2089                         attr->setup(mod, get_modinfo(info, attr->attr.name));
2090         }
2091 }
2092 
2093 static void free_modinfo(struct module *mod)
2094 {
2095         struct module_attribute *attr;
2096         int i;
2097 
2098         for (i = 0; (attr = modinfo_attrs[i]); i++) {
2099                 if (attr->free)
2100                         attr->free(mod);
2101         }
2102 }
2103 
2104 #ifdef CONFIG_KALLSYMS
2105 
2106 /* lookup symbol in given range of kernel_symbols */
2107 static const struct kernel_symbol *lookup_symbol(const char *name,
2108         const struct kernel_symbol *start,
2109         const struct kernel_symbol *stop)
2110 {
2111         return bsearch(name, start, stop - start,
2112                         sizeof(struct kernel_symbol), cmp_name);
2113 }
2114 
2115 static int is_exported(const char *name, unsigned long value,
2116                        const struct module *mod)
2117 {
2118         const struct kernel_symbol *ks;
2119         if (!mod)
2120                 ks = lookup_symbol(name, __start___ksymtab, __stop___ksymtab);
2121         else
2122                 ks = lookup_symbol(name, mod->syms, mod->syms + mod->num_syms);
2123         return ks != NULL && ks->value == value;
2124 }
2125 
2126 /* As per nm */
2127 static char elf_type(const Elf_Sym *sym, const struct load_info *info)
2128 {
2129         const Elf_Shdr *sechdrs = info->sechdrs;
2130 
2131         if (ELF_ST_BIND(sym->st_info) == STB_WEAK) {
2132                 if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT)
2133                         return 'v';
2134                 else
2135                         return 'w';
2136         }
2137         if (sym->st_shndx == SHN_UNDEF)
2138                 return 'U';
2139         if (sym->st_shndx == SHN_ABS)
2140                 return 'a';
2141         if (sym->st_shndx >= SHN_LORESERVE)
2142                 return '?';
2143         if (sechdrs[sym->st_shndx].sh_flags & SHF_EXECINSTR)
2144                 return 't';
2145         if (sechdrs[sym->st_shndx].sh_flags & SHF_ALLOC
2146             && sechdrs[sym->st_shndx].sh_type != SHT_NOBITS) {
2147                 if (!(sechdrs[sym->st_shndx].sh_flags & SHF_WRITE))
2148                         return 'r';
2149                 else if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2150                         return 'g';
2151                 else
2152                         return 'd';
2153         }
2154         if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
2155                 if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2156                         return 's';
2157                 else
2158                         return 'b';
2159         }
2160         if (strstarts(info->secstrings + sechdrs[sym->st_shndx].sh_name,
2161                       ".debug")) {
2162                 return 'n';
2163         }
2164         return '?';
2165 }
2166 
2167 static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,
2168                            unsigned int shnum)
2169 {
2170         const Elf_Shdr *sec;
2171 
2172         if (src->st_shndx == SHN_UNDEF
2173             || src->st_shndx >= shnum
2174             || !src->st_name)
2175                 return false;
2176 
2177         sec = sechdrs + src->st_shndx;
2178         if (!(sec->sh_flags & SHF_ALLOC)
2179 #ifndef CONFIG_KALLSYMS_ALL
2180             || !(sec->sh_flags & SHF_EXECINSTR)
2181 #endif
2182             || (sec->sh_entsize & INIT_OFFSET_MASK))
2183                 return false;
2184 
2185         return true;
2186 }
2187 
2188 static void layout_symtab(struct module *mod, struct load_info *info)
2189 {
2190         Elf_Shdr *symsect = info->sechdrs + info->index.sym;
2191         Elf_Shdr *strsect = info->sechdrs + info->index.str;
2192         const Elf_Sym *src;
2193         unsigned int i, nsrc, ndst;
2194 
2195         /* Put symbol section at end of init part of module. */
2196         symsect->sh_flags |= SHF_ALLOC;
2197         symsect->sh_entsize = get_offset(mod, &mod->init_size, symsect,
2198                                          info->index.sym) | INIT_OFFSET_MASK;
2199         DEBUGP("\t%s\n", info->secstrings + symsect->sh_name);
2200 
2201         src = (void *)info->hdr + symsect->sh_offset;
2202         nsrc = symsect->sh_size / sizeof(*src);
2203         for (ndst = i = 0; i < nsrc; i++) {
2204                 if (i == 0 ||
2205                     is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum)) {
2206                         unsigned int j = src[i].st_name;
2207 
2208                         while (!__test_and_set_bit(j, info->strmap)
2209                                && info->strtab[j])
2210                                 ++j;
2211                         ++ndst;
2212                 }
2213         }
2214 
2215         /* Append room for core symbols at end of core part. */
2216         info->symoffs = ALIGN(mod->core_size, symsect->sh_addralign ?: 1);
2217         mod->core_size = info->symoffs + ndst * sizeof(Elf_Sym);
2218 
2219         /* Put string table section at end of init part of module. */
2220         strsect->sh_flags |= SHF_ALLOC;
2221         strsect->sh_entsize = get_offset(mod, &mod->init_size, strsect,
2222                                          info->index.str) | INIT_OFFSET_MASK;
2223         DEBUGP("\t%s\n", info->secstrings + strsect->sh_name);
2224 
2225         /* Append room for core symbols' strings at end of core part. */
2226         info->stroffs = mod->core_size;
2227         __set_bit(0, info->strmap);
2228         mod->core_size += bitmap_weight(info->strmap, strsect->sh_size);
2229 }
2230 
2231 static void add_kallsyms(struct module *mod, const struct load_info *info)
2232 {
2233         unsigned int i, ndst;
2234         const Elf_Sym *src;
2235         Elf_Sym *dst;
2236         char *s;
2237         Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2238 
2239         mod->symtab = (void *)symsec->sh_addr;
2240         mod->num_symtab = symsec->sh_size / sizeof(Elf_Sym);
2241         /* Make sure we get permanent strtab: don't use info->strtab. */
2242         mod->strtab = (void *)info->sechdrs[info->index.str].sh_addr;
2243 
2244         /* Set types up while we still have access to sections. */
2245         for (i = 0; i < mod->num_symtab; i++)
2246                 mod->symtab[i].st_info = elf_type(&mod->symtab[i], info);
2247 
2248         mod->core_symtab = dst = mod->module_core + info->symoffs;
2249         src = mod->symtab;
2250         for (ndst = i = 0; i < mod->num_symtab; i++) {
2251                 if (i == 0 ||
2252                     is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum)) {
2253                         dst[ndst] = src[i];
2254                         dst[ndst].st_name = bitmap_weight(info->strmap,
2255                                                           dst[ndst].st_name);
2256                         ++ndst;
2257                 }
2258         }
2259         mod->core_num_syms = ndst;
2260 
2261         mod->core_strtab = s = mod->module_core + info->stroffs;
2262         for (*s = 0, i = 1; i < info->sechdrs[info->index.str].sh_size; ++i)
2263                 if (test_bit(i, info->strmap))
2264                         *++s = mod->strtab[i];
2265 }
2266 #else
2267 static inline void layout_symtab(struct module *mod, struct load_info *info)
2268 {
2269 }
2270 
2271 static void add_kallsyms(struct module *mod, const struct load_info *info)
2272 {
2273 }
2274 #endif /* CONFIG_KALLSYMS */
2275 
2276 static void dynamic_debug_setup(struct _ddebug *debug, unsigned int num)
2277 {
2278         if (!debug)
2279                 return;
2280 #ifdef CONFIG_DYNAMIC_DEBUG
2281         if (ddebug_add_module(debug, num, debug->modname))
2282                 printk(KERN_ERR "dynamic debug error adding module: %s\n",
2283                                         debug->modname);
2284 #endif
2285 }
2286 
2287 static void dynamic_debug_remove(struct _ddebug *debug)
2288 {
2289         if (debug)
2290                 ddebug_remove_module(debug->modname);
2291 }
2292 
2293 void * __weak module_alloc(unsigned long size)
2294 {
2295         return size == 0 ? NULL : vmalloc_exec(size);
2296 }
2297 
2298 static void *module_alloc_update_bounds(unsigned long size)
2299 {
2300         void *ret = module_alloc(size);
2301 
2302         if (ret) {
2303                 mutex_lock(&module_mutex);
2304                 /* Update module bounds. */
2305                 if ((unsigned long)ret < module_addr_min)
2306                         module_addr_min = (unsigned long)ret;
2307                 if ((unsigned long)ret + size > module_addr_max)
2308                         module_addr_max = (unsigned long)ret + size;
2309                 mutex_unlock(&module_mutex);
2310         }
2311         return ret;
2312 }
2313 
2314 #ifdef CONFIG_DEBUG_KMEMLEAK
2315 static void kmemleak_load_module(const struct module *mod,
2316                                  const struct load_info *info)
2317 {
2318         unsigned int i;
2319 
2320         /* only scan the sections containing data */
2321         kmemleak_scan_area(mod, sizeof(struct module), GFP_KERNEL);
2322 
2323         for (i = 1; i < info->hdr->e_shnum; i++) {
2324                 const char *name = info->secstrings + info->sechdrs[i].sh_name;
2325                 if (!(info->sechdrs[i].sh_flags & SHF_ALLOC))
2326                         continue;
2327                 if (!strstarts(name, ".data") && !strstarts(name, ".bss"))
2328                         continue;
2329 
2330                 kmemleak_scan_area((void *)info->sechdrs[i].sh_addr,
2331                                    info->sechdrs[i].sh_size, GFP_KERNEL);
2332         }
2333 }
2334 #else
2335 static inline void kmemleak_load_module(const struct module *mod,
2336                                         const struct load_info *info)
2337 {
2338 }
2339 #endif
2340 
2341 static void check_modinfo_retpoline(struct module *mod, struct load_info *info)
2342 {
2343         if (retpoline_module_ok(get_modinfo(info, "retpoline")))
2344                 return;
2345 
2346         pr_warn("%s: loading module not compiled with retpoline compiler.\n",
2347                 mod->name);
2348 }
2349 
2350 /* Sets info->hdr and info->len. */
2351 static int copy_and_check(struct load_info *info,
2352                           const void __user *umod, unsigned long len,
2353                           const char __user *uargs)
2354 {
2355         int err;
2356         Elf_Ehdr *hdr;
2357 
2358         if (len < sizeof(*hdr))
2359                 return -ENOEXEC;
2360 
2361         /* Suck in entire file: we'll want most of it. */
2362         if ((hdr = vmalloc(len)) == NULL)
2363                 return -ENOMEM;
2364 
2365         if (copy_from_user(hdr, umod, len) != 0) {
2366                 err = -EFAULT;
2367                 goto free_hdr;
2368         }
2369 
2370         /* Sanity checks against insmoding binaries or wrong arch,
2371            weird elf version */
2372         if (memcmp(hdr->e_ident, ELFMAG, SELFMAG) != 0
2373             || hdr->e_type != ET_REL
2374             || !elf_check_arch(hdr)
2375             || hdr->e_shentsize != sizeof(Elf_Shdr)) {
2376                 err = -ENOEXEC;
2377                 goto free_hdr;
2378         }
2379 
2380         if (len < hdr->e_shoff + hdr->e_shnum * sizeof(Elf_Shdr)) {
2381                 err = -ENOEXEC;
2382                 goto free_hdr;
2383         }
2384 
2385         info->hdr = hdr;
2386         info->len = len;
2387         return 0;
2388 
2389 free_hdr:
2390         vfree(hdr);
2391         return err;
2392 }
2393 
2394 static void free_copy(struct load_info *info)
2395 {
2396         vfree(info->hdr);
2397 }
2398 
2399 static int rewrite_section_headers(struct load_info *info)
2400 {
2401         unsigned int i;
2402 
2403         /* This should always be true, but let's be sure. */
2404         info->sechdrs[0].sh_addr = 0;
2405 
2406         for (i = 1; i < info->hdr->e_shnum; i++) {
2407                 Elf_Shdr *shdr = &info->sechdrs[i];
2408                 if (shdr->sh_type != SHT_NOBITS
2409                     && info->len < shdr->sh_offset + shdr->sh_size) {
2410                         printk(KERN_ERR "Module len %lu truncated\n",
2411                                info->len);
2412                         return -ENOEXEC;
2413                 }
2414 
2415                 /* Mark all sections sh_addr with their address in the
2416                    temporary image. */
2417                 shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
2418 
2419 #ifndef CONFIG_MODULE_UNLOAD
2420                 /* Don't load .exit sections */
2421                 if (strstarts(info->secstrings+shdr->sh_name, ".exit"))
2422                         shdr->sh_flags &= ~(unsigned long)SHF_ALLOC;
2423 #endif
2424         }
2425 
2426         /* Track but don't keep modinfo and version sections. */
2427         info->index.vers = find_sec(info, "__versions");
2428         info->index.info = find_sec(info, ".modinfo");
2429         info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
2430         info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
2431         return 0;
2432 }
2433 
2434 /*
2435  * Set up our basic convenience variables (pointers to section headers,
2436  * search for module section index etc), and do some basic section
2437  * verification.
2438  *
2439  * Return the temporary module pointer (we'll replace it with the final
2440  * one when we move the module sections around).
2441  */
2442 static struct module *setup_load_info(struct load_info *info)
2443 {
2444         unsigned int i;
2445         int err;
2446         struct module *mod;
2447 
2448         /* Set up the convenience variables */
2449         info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
2450         info->secstrings = (void *)info->hdr
2451                 + info->sechdrs[info->hdr->e_shstrndx].sh_offset;
2452 
2453         err = rewrite_section_headers(info);
2454         if (err)
2455                 return ERR_PTR(err);
2456 
2457         /* Find internal symbols and strings. */
2458         for (i = 1; i < info->hdr->e_shnum; i++) {
2459                 if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
2460                         info->index.sym = i;
2461                         info->index.str = info->sechdrs[i].sh_link;
2462                         info->strtab = (char *)info->hdr
2463                                 + info->sechdrs[info->index.str].sh_offset;
2464                         break;
2465                 }
2466         }
2467 
2468         info->index.mod = find_sec(info, ".gnu.linkonce.this_module");
2469         if (!info->index.mod) {
2470                 printk(KERN_WARNING "No module found in object\n");
2471                 return ERR_PTR(-ENOEXEC);
2472         }
2473         /* This is temporary: point mod into copy of data. */
2474         mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2475 
2476         if (info->index.sym == 0) {
2477                 printk(KERN_WARNING "%s: module has no symbols (stripped?)\n",
2478                        mod->name);
2479                 return ERR_PTR(-ENOEXEC);
2480         }
2481 
2482         info->index.pcpu = find_pcpusec(info);
2483 
2484         /* Check module struct version now, before we try to use module. */
2485         if (!check_modstruct_version(info->sechdrs, info->index.vers, mod))
2486                 return ERR_PTR(-ENOEXEC);
2487 
2488         return mod;
2489 }
2490 
2491 static int check_modinfo(struct module *mod, struct load_info *info)
2492 {
2493         const char *modmagic = get_modinfo(info, "vermagic");
2494         int err;
2495 
2496         /* This is allowed: modprobe --force will invalidate it. */
2497         if (!modmagic) {
2498                 err = try_to_force_load(mod, "bad vermagic");
2499                 if (err)
2500                         return err;
2501         } else if (!same_magic(modmagic, vermagic, info->index.vers)) {
2502                 printk(KERN_ERR "%s: version magic '%s' should be '%s'\n",
2503                        mod->name, modmagic, vermagic);
2504                 return -ENOEXEC;
2505         }
2506 
2507         if (!get_modinfo(info, "intree"))
2508                 add_taint_module(mod, TAINT_OOT_MODULE);
2509 
2510         check_modinfo_retpoline(mod, info);
2511 
2512         if (get_modinfo(info, "staging")) {
2513                 add_taint_module(mod, TAINT_CRAP);
2514                 printk(KERN_WARNING "%s: module is from the staging directory,"
2515                        " the quality is unknown, you have been warned.\n",
2516                        mod->name);
2517         }
2518 
2519         /* Set up license info based on the info section */
2520         set_license(mod, get_modinfo(info, "license"));
2521 
2522         return 0;
2523 }
2524 
2525 static void find_module_sections(struct module *mod, struct load_info *info)
2526 {
2527         mod->kp = section_objs(info, "__param",
2528                                sizeof(*mod->kp), &mod->num_kp);
2529         mod->syms = section_objs(info, "__ksymtab",
2530                                  sizeof(*mod->syms), &mod->num_syms);
2531         mod->crcs = section_addr(info, "__kcrctab");
2532         mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
2533                                      sizeof(*mod->gpl_syms),
2534                                      &mod->num_gpl_syms);
2535         mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
2536         mod->gpl_future_syms = section_objs(info,
2537                                             "__ksymtab_gpl_future",
2538                                             sizeof(*mod->gpl_future_syms),
2539                                             &mod->num_gpl_future_syms);
2540         mod->gpl_future_crcs = section_addr(info, "__kcrctab_gpl_future");
2541 
2542 #ifdef CONFIG_UNUSED_SYMBOLS
2543         mod->unused_syms = section_objs(info, "__ksymtab_unused",
2544                                         sizeof(*mod->unused_syms),
2545                                         &mod->num_unused_syms);
2546         mod->unused_crcs = section_addr(info, "__kcrctab_unused");
2547         mod->unused_gpl_syms = section_objs(info, "__ksymtab_unused_gpl",
2548                                             sizeof(*mod->unused_gpl_syms),
2549                                             &mod->num_unused_gpl_syms);
2550         mod->unused_gpl_crcs = section_addr(info, "__kcrctab_unused_gpl");
2551 #endif
2552 #ifdef CONFIG_CONSTRUCTORS
2553         mod->ctors = section_objs(info, ".ctors",
2554                                   sizeof(*mod->ctors), &mod->num_ctors);
2555 #endif
2556 
2557 #ifdef CONFIG_TRACEPOINTS
2558         mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
2559                                              sizeof(*mod->tracepoints_ptrs),
2560                                              &mod->num_tracepoints);
2561 #endif
2562 #ifdef HAVE_JUMP_LABEL
2563         mod->jump_entries = section_objs(info, "__jump_table",
2564                                         sizeof(*mod->jump_entries),
2565                                         &mod->num_jump_entries);
2566 #endif
2567 #ifdef CONFIG_EVENT_TRACING
2568         mod->trace_events = section_objs(info, "_ftrace_events",
2569                                          sizeof(*mod->trace_events),
2570                                          &mod->num_trace_events);
2571         /*
2572          * This section contains pointers to allocated objects in the trace
2573          * code and not scanning it leads to false positives.
2574          */
2575         kmemleak_scan_area(mod->trace_events, sizeof(*mod->trace_events) *
2576                            mod->num_trace_events, GFP_KERNEL);
2577 #endif
2578 #ifdef CONFIG_TRACING
2579         mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
2580                                          sizeof(*mod->trace_bprintk_fmt_start),
2581                                          &mod->num_trace_bprintk_fmt);
2582         /*
2583          * This section contains pointers to allocated objects in the trace
2584          * code and not scanning it leads to false positives.
2585          */
2586         kmemleak_scan_area(mod->trace_bprintk_fmt_start,
2587                            sizeof(*mod->trace_bprintk_fmt_start) *
2588                            mod->num_trace_bprintk_fmt, GFP_KERNEL);
2589 #endif
2590 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
2591         /* sechdrs[0].sh_size is always zero */
2592         mod->ftrace_callsites = section_objs(info, "__mcount_loc",
2593                                              sizeof(*mod->ftrace_callsites),
2594                                              &mod->num_ftrace_callsites);
2595 #endif
2596 
2597         mod->extable = section_objs(info, "__ex_table",
2598                                     sizeof(*mod->extable), &mod->num_exentries);
2599 
2600         if (section_addr(info, "__obsparm"))
2601                 printk(KERN_WARNING "%s: Ignoring obsolete parameters\n",
2602                        mod->name);
2603 
2604         info->debug = section_objs(info, "__verbose",
2605                                    sizeof(*info->debug), &info->num_debug);
2606 }
2607 
2608 static int move_module(struct module *mod, struct load_info *info)
2609 {
2610         int i;
2611         void *ptr;
2612 
2613         /* Do the allocs. */
2614         ptr = module_alloc_update_bounds(mod->core_size);
2615         /*
2616          * The pointer to this block is stored in the module structure
2617          * which is inside the block. Just mark it as not being a
2618          * leak.
2619          */
2620         kmemleak_not_leak(ptr);
2621         if (!ptr)
2622                 return -ENOMEM;
2623 
2624         memset(ptr, 0, mod->core_size);
2625         mod->module_core = ptr;
2626 
2627         ptr = module_alloc_update_bounds(mod->init_size);
2628         /*
2629          * The pointer to this block is stored in the module structure
2630          * which is inside the block. This block doesn't need to be
2631          * scanned as it contains data and code that will be freed
2632          * after the module is initialized.
2633          */
2634         kmemleak_ignore(ptr);
2635         if (!ptr && mod->init_size) {
2636                 module_free(mod, mod->module_core);
2637                 return -ENOMEM;
2638         }
2639         memset(ptr, 0, mod->init_size);
2640         mod->module_init = ptr;
2641 
2642         /* Transfer each section which specifies SHF_ALLOC */
2643         DEBUGP("final section addresses:\n");
2644         for (i = 0; i < info->hdr->e_shnum; i++) {
2645                 void *dest;
2646                 Elf_Shdr *shdr = &info->sechdrs[i];
2647 
2648                 if (!(shdr->sh_flags & SHF_ALLOC))
2649                         continue;
2650 
2651                 if (shdr->sh_entsize & INIT_OFFSET_MASK)
2652                         dest = mod->module_init
2653                                 + (shdr->sh_entsize & ~INIT_OFFSET_MASK);
2654                 else
2655                         dest = mod->module_core + shdr->sh_entsize;
2656 
2657                 if (shdr->sh_type != SHT_NOBITS)
2658                         memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
2659                 /* Update sh_addr to point to copy in image. */
2660                 shdr->sh_addr = (unsigned long)dest;
2661                 DEBUGP("\t0x%lx %s\n",
2662                        shdr->sh_addr, info->secstrings + shdr->sh_name);
2663         }
2664 
2665         return 0;
2666 }
2667 
2668 static int check_module_license_and_versions(struct module *mod)
2669 {
2670         /*
2671          * ndiswrapper is under GPL by itself, but loads proprietary modules.
2672          * Don't use add_taint_module(), as it would prevent ndiswrapper from
2673          * using GPL-only symbols it needs.
2674          */
2675         if (strcmp(mod->name, "ndiswrapper") == 0)
2676                 add_taint(TAINT_PROPRIETARY_MODULE);
2677 
2678         /* driverloader was caught wrongly pretending to be under GPL */
2679         if (strcmp(mod->name, "driverloader") == 0)
2680                 add_taint_module(mod, TAINT_PROPRIETARY_MODULE);
2681 
2682         /* lve claims to be GPL but upstream won't provide source */
2683         if (strcmp(mod->name, "lve") == 0)
2684                 add_taint_module(mod, TAINT_PROPRIETARY_MODULE);
2685 
2686 #ifdef CONFIG_MODVERSIONS
2687         if ((mod->num_syms && !mod->crcs)
2688             || (mod->num_gpl_syms && !mod->gpl_crcs)
2689             || (mod->num_gpl_future_syms && !mod->gpl_future_crcs)
2690 #ifdef CONFIG_UNUSED_SYMBOLS
2691             || (mod->num_unused_syms && !mod->unused_crcs)
2692             || (mod->num_unused_gpl_syms && !mod->unused_gpl_crcs)
2693 #endif
2694                 ) {
2695                 return try_to_force_load(mod,
2696                                          "no versions for exported symbols");
2697         }
2698 #endif
2699         return 0;
2700 }
2701 
2702 static void flush_module_icache(const struct module *mod)
2703 {
2704         mm_segment_t old_fs;
2705 
2706         /* flush the icache in correct context */
2707         old_fs = get_fs();
2708         set_fs(KERNEL_DS);
2709 
2710         /*
2711          * Flush the instruction cache, since we've played with text.
2712          * Do it before processing of module parameters, so the module
2713          * can provide parameter accessor functions of its own.
2714          */
2715         if (mod->module_init)
2716                 flush_icache_range((unsigned long)mod->module_init,
2717                                    (unsigned long)mod->module_init
2718                                    + mod->init_size);
2719         flush_icache_range((unsigned long)mod->module_core,
2720                            (unsigned long)mod->module_core + mod->core_size);
2721 
2722         set_fs(old_fs);
2723 }
2724 
2725 int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
2726                                      Elf_Shdr *sechdrs,
2727                                      char *secstrings,
2728                                      struct module *mod)
2729 {
2730         return 0;
2731 }
2732 
2733 static struct module *layout_and_allocate(struct load_info *info)
2734 {
2735         /* Module within temporary copy. */
2736         struct module *mod;
2737         Elf_Shdr *pcpusec;
2738         int err;
2739 
2740         mod = setup_load_info(info);
2741         if (IS_ERR(mod))
2742                 return mod;
2743 
2744         err = check_modinfo(mod, info);
2745         if (err)
2746                 return ERR_PTR(err);
2747 
2748         /* Allow arches to frob section contents and sizes.  */
2749         err = module_frob_arch_sections(info->hdr, info->sechdrs,
2750                                         info->secstrings, mod);
2751         if (err < 0)
2752                 goto out;
2753 
2754         pcpusec = &info->sechdrs[info->index.pcpu];
2755         if (pcpusec->sh_size) {
2756                 /* We have a special allocation for this section. */
2757                 err = percpu_modalloc(mod,
2758                                       pcpusec->sh_size, pcpusec->sh_addralign);
2759                 if (err)
2760                         goto out;
2761                 pcpusec->sh_flags &= ~(unsigned long)SHF_ALLOC;
2762         }
2763 
2764         /* Determine total sizes, and put offsets in sh_entsize.  For now
2765            this is done generically; there doesn't appear to be any
2766            special cases for the architectures. */
2767         layout_sections(mod, info);
2768 
2769         info->strmap = kzalloc(BITS_TO_LONGS(info->sechdrs[info->index.str].sh_size)
2770                          * sizeof(long), GFP_KERNEL);
2771         if (!info->strmap) {
2772                 err = -ENOMEM;
2773                 goto free_percpu;
2774         }
2775         layout_symtab(mod, info);
2776 
2777         /* Allocate and move to the final place */
2778         err = move_module(mod, info);
2779         if (err)
2780                 goto free_strmap;
2781 
2782         /* Module has been copied to its final place now: return it. */
2783         mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2784         kmemleak_load_module(mod, info);
2785         return mod;
2786 
2787 free_strmap:
2788         kfree(info->strmap);
2789 free_percpu:
2790         percpu_modfree(mod);
2791 out:
2792         return ERR_PTR(err);
2793 }
2794 
2795 /* mod is no longer valid after this! */
2796 static void module_deallocate(struct module *mod, struct load_info *info)
2797 {
2798         kfree(info->strmap);
2799         percpu_modfree(mod);
2800         module_free(mod, mod->module_init);
2801         module_free(mod, mod->module_core);
2802 }
2803 
2804 int __weak module_finalize(const Elf_Ehdr *hdr,
2805                            const Elf_Shdr *sechdrs,
2806                            struct module *me)
2807 {
2808         return 0;
2809 }
2810 
2811 static int post_relocation(struct module *mod, const struct load_info *info)
2812 {
2813         /* Sort exception table now relocations are done. */
2814         sort_extable(mod->extable, mod->extable + mod->num_exentries);
2815 
2816         /* Copy relocated percpu area over. */
2817         percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
2818                        info->sechdrs[info->index.pcpu].sh_size);
2819 
2820         /* Setup kallsyms-specific fields. */
2821         add_kallsyms(mod, info);
2822 
2823         /* Arch-specific module finalizing. */
2824         return module_finalize(info->hdr, info->sechdrs, mod);
2825 }
2826 
2827 /* Allocate and load the module: note that size of section 0 is always
2828    zero, and we rely on this for optional sections. */
2829 static struct module *load_module(void __user *umod,
2830                                   unsigned long len,
2831                                   const char __user *uargs)
2832 {
2833         struct load_info info = { NULL, };
2834         struct module *mod;
2835         long err;
2836 
2837         DEBUGP("load_module: umod=%p, len=%lu, uargs=%p\n",
2838                umod, len, uargs);
2839 
2840         /* Copy in the blobs from userspace, check they are vaguely sane. */
2841         err = copy_and_check(&info, umod, len, uargs);
2842         if (err)
2843                 return ERR_PTR(err);
2844 
2845         /* Figure out module layout, and allocate all the memory. */
2846         mod = layout_and_allocate(&info);
2847         if (IS_ERR(mod)) {
2848                 err = PTR_ERR(mod);
2849                 goto free_copy;
2850         }
2851 
2852         /* Now module is in final location, initialize linked lists, etc. */
2853         err = module_unload_init(mod);
2854         if (err)
2855                 goto free_module;
2856 
2857         /* Now we've got everything in the final locations, we can
2858          * find optional sections. */
2859         find_module_sections(mod, &info);
2860 
2861         err = check_module_license_and_versions(mod);
2862         if (err)
2863                 goto free_unload;
2864 
2865         /* Set up MODINFO_ATTR fields */
2866         setup_modinfo(mod, &info);
2867 
2868         /* Fix up syms, so that st_value is a pointer to location. */
2869         err = simplify_symbols(mod, &info);
2870         if (err < 0)
2871                 goto free_modinfo;
2872 
2873         err = apply_relocations(mod, &info);
2874         if (err < 0)
2875                 goto free_modinfo;
2876 
2877         err = post_relocation(mod, &info);
2878         if (err < 0)
2879                 goto free_modinfo;
2880 
2881         flush_module_icache(mod);
2882 
2883         /* Now copy in args */
2884         mod->args = strndup_user(uargs, ~0UL >> 1);
2885         if (IS_ERR(mod->args)) {
2886                 err = PTR_ERR(mod->args);
2887                 goto free_arch_cleanup;
2888         }
2889 
2890         /* Mark state as coming so strong_try_module_get() ignores us. */
2891         mod->state = MODULE_STATE_COMING;
2892 
2893         /* Now sew it into the lists so we can get lockdep and oops
2894          * info during argument parsing.  No one should access us, since
2895          * strong_try_module_get() will fail.
2896          * lockdep/oops can run asynchronous, so use the RCU list insertion
2897          * function to insert in a way safe to concurrent readers.
2898          * The mutex protects against concurrent writers.
2899          */
2900         mutex_lock(&module_mutex);
2901         if (find_module(mod->name)) {
2902                 err = -EEXIST;
2903                 goto unlock;
2904         }
2905 
2906         /* This has to be done once we're sure module name is unique. */
2907         dynamic_debug_setup(info.debug, info.num_debug);
2908 
2909         /* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
2910         ftrace_module_init(mod);
2911 
2912         /* Find duplicate symbols */
2913         err = verify_export_symbols(mod);
2914         if (err < 0)
2915                 goto ddebug;
2916 
2917         module_bug_finalize(info.hdr, info.sechdrs, mod);
2918         list_add_rcu(&mod->list, &modules);
2919         mutex_unlock(&module_mutex);
2920 
2921         /* Module is ready to execute: parsing args may do that. */
2922         err = parse_args(mod->name, mod->args, mod->kp, mod->num_kp, NULL);
2923         if (err < 0)
2924                 goto unlink;
2925 
2926         /* Link in to syfs. */
2927         err = mod_sysfs_setup(mod, &info, mod->kp, mod->num_kp);
2928         if (err < 0)
2929                 goto unlink;
2930 
2931         /* Get rid of temporary copy and strmap. */
2932         kfree(info.strmap);
2933         free_copy(&info);
2934 
2935         /* Done! */
2936         trace_module_load(mod);
2937         return mod;
2938 
2939  unlink:
2940         mutex_lock(&module_mutex);
2941         /* Unlink carefully: kallsyms could be walking list. */
2942         list_del_rcu(&mod->list);
2943         module_bug_cleanup(mod);
2944 
2945  ddebug:
2946         dynamic_debug_remove(info.debug);
2947  unlock:
2948         mutex_unlock(&module_mutex);
2949         synchronize_sched();
2950         kfree(mod->args);
2951  free_arch_cleanup:
2952         module_arch_cleanup(mod);
2953  free_modinfo:
2954         free_modinfo(mod);
2955  free_unload:
2956         module_unload_free(mod);
2957  free_module:
2958         module_deallocate(mod, &info);
2959  free_copy:
2960         free_copy(&info);
2961         return ERR_PTR(err);
2962 }
2963 
2964 /* Call module constructors. */
2965 static void do_mod_ctors(struct module *mod)
2966 {
2967 #ifdef CONFIG_CONSTRUCTORS
2968         unsigned long i;
2969 
2970         for (i = 0; i < mod->num_ctors; i++)
2971                 mod->ctors[i]();
2972 #endif
2973 }
2974 
2975 /* This is where the real work happens */
2976 SYSCALL_DEFINE3(init_module, void __user *, umod,
2977                 unsigned long, len, const char __user *, uargs)
2978 {
2979         struct module *mod;
2980         int ret = 0;
2981 
2982         /* Must have permission */
2983         if (!capable(CAP_SYS_MODULE) || modules_disabled)
2984                 return -EPERM;
2985         if (!ccs_capable(CCS_USE_KERNEL_MODULE))
2986                 return -EPERM;
2987 
2988         /* Do all the hard work */
2989         mod = load_module(umod, len, uargs);
2990         if (IS_ERR(mod))
2991                 return PTR_ERR(mod);
2992 
2993         blocking_notifier_call_chain(&module_notify_list,
2994                         MODULE_STATE_COMING, mod);
2995 
2996         /* Set RO and NX regions for core */
2997         set_section_ro_nx(mod->module_core,
2998                                 mod->core_text_size,
2999                                 mod->core_ro_size,
3000                                 mod->core_size);
3001 
3002         /* Set RO and NX regions for init */
3003         set_section_ro_nx(mod->module_init,
3004                                 mod->init_text_size,
3005                                 mod->init_ro_size,
3006                                 mod->init_size);
3007 
3008         do_mod_ctors(mod);
3009         /* Start the module */
3010         if (mod->init != NULL)
3011                 ret = do_one_initcall(mod->init);
3012         if (ret < 0) {
3013                 /* Init routine failed: abort.  Try to protect us from
3014                    buggy refcounters. */
3015                 mod->state = MODULE_STATE_GOING;
3016                 synchronize_sched();
3017                 module_put(mod);
3018                 blocking_notifier_call_chain(&module_notify_list,
3019                                              MODULE_STATE_GOING, mod);
3020                 free_module(mod);
3021                 wake_up(&module_wq);
3022                 return ret;
3023         }
3024         if (ret > 0) {
3025                 printk(KERN_WARNING
3026 "%s: '%s'->init suspiciously returned %d, it should follow 0/-E convention\n"
3027 "%s: loading module anyway...\n",
3028                        __func__, mod->name, ret,
3029                        __func__);
3030                 dump_stack();
3031         }
3032 
3033         /* Now it's a first class citizen!  Wake up anyone waiting for it. */
3034         mod->state = MODULE_STATE_LIVE;
3035         wake_up(&module_wq);
3036         blocking_notifier_call_chain(&module_notify_list,
3037                                      MODULE_STATE_LIVE, mod);
3038 
3039         /* We need to finish all async code before the module init sequence is done */
3040         async_synchronize_full();
3041 
3042         mutex_lock(&module_mutex);
3043         /* Drop initial reference. */
3044         module_put(mod);
3045         trim_init_extable(mod);
3046 #ifdef CONFIG_KALLSYMS
3047         mod->num_symtab = mod->core_num_syms;
3048         mod->symtab = mod->core_symtab;
3049         mod->strtab = mod->core_strtab;
3050 #endif
3051         unset_module_init_ro_nx(mod);
3052         module_free(mod, mod->module_init);
3053         mod->module_init = NULL;
3054         mod->init_size = 0;
3055         mod->init_ro_size = 0;
3056         mod->init_text_size = 0;
3057         mutex_unlock(&module_mutex);
3058 
3059         return 0;
3060 }
3061 
3062 static inline int within(unsigned long addr, void *start, unsigned long size)
3063 {
3064         return ((void *)addr >= start && (void *)addr < start + size);
3065 }
3066 
3067 #ifdef CONFIG_KALLSYMS
3068 /*
3069  * This ignores the intensely annoying "mapping symbols" found
3070  * in ARM ELF files: $a, $t and $d.
3071  */
3072 static inline int is_arm_mapping_symbol(const char *str)
3073 {
3074         return str[0] == '$' && strchr("atd", str[1])
3075                && (str[2] == '\0' || str[2] == '.');
3076 }
3077 
3078 static const char *get_ksymbol(struct module *mod,
3079                                unsigned long addr,
3080                                unsigned long *size,
3081                                unsigned long *offset)
3082 {
3083         unsigned int i, best = 0;
3084         unsigned long nextval;
3085 
3086         /* At worse, next value is at end of module */
3087         if (within_module_init(addr, mod))
3088                 nextval = (unsigned long)mod->module_init+mod->init_text_size;
3089         else
3090                 nextval = (unsigned long)mod->module_core+mod->core_text_size;
3091 
3092         /* Scan for closest preceding symbol, and next symbol. (ELF
3093            starts real symbols at 1). */
3094         for (i = 1; i < mod->num_symtab; i++) {
3095                 if (mod->symtab[i].st_shndx == SHN_UNDEF)
3096                         continue;
3097 
3098                 /* We ignore unnamed symbols: they're uninformative
3099                  * and inserted at a whim. */
3100                 if (mod->symtab[i].st_value <= addr
3101                     && mod->symtab[i].st_value > mod->symtab[best].st_value
3102                     && *(mod->strtab + mod->symtab[i].st_name) != '\0'
3103                     && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
3104                         best = i;
3105                 if (mod->symtab[i].st_value > addr
3106                     && mod->symtab[i].st_value < nextval
3107                     && *(mod->strtab + mod->symtab[i].st_name) != '\0'
3108                     && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
3109                         nextval = mod->symtab[i].st_value;
3110         }
3111 
3112         if (!best)
3113                 return NULL;
3114 
3115         if (size)
3116                 *size = nextval - mod->symtab[best].st_value;
3117         if (offset)
3118                 *offset = addr - mod->symtab[best].st_value;
3119         return mod->strtab + mod->symtab[best].st_name;
3120 }
3121 
3122 /* For kallsyms to ask for address resolution.  NULL means not found.  Careful
3123  * not to lock to avoid deadlock on oopses, simply disable preemption. */
3124 const char *module_address_lookup(unsigned long addr,
3125                             unsigned long *size,
3126                             unsigned long *offset,
3127                             char **modname,
3128                             char *namebuf)
3129 {
3130         struct module *mod;
3131         const char *ret = NULL;
3132 
3133         preempt_disable();
3134         list_for_each_entry_rcu(mod, &modules, list) {
3135                 if (within_module_init(addr, mod) ||
3136                     within_module_core(addr, mod)) {
3137                         if (modname)
3138                                 *modname = mod->name;
3139                         ret = get_ksymbol(mod, addr, size, offset);
3140                         break;
3141                 }
3142         }
3143         /* Make a copy in here where it's safe */
3144         if (ret) {
3145                 strncpy(namebuf, ret, KSYM_NAME_LEN - 1);
3146                 ret = namebuf;
3147         }
3148         preempt_enable();
3149         return ret;
3150 }
3151 
3152 int lookup_module_symbol_name(unsigned long addr, char *symname)
3153 {
3154         struct module *mod;
3155 
3156         preempt_disable();
3157         list_for_each_entry_rcu(mod, &modules, list) {
3158                 if (within_module_init(addr, mod) ||
3159                     within_module_core(addr, mod)) {
3160                         const char *sym;
3161 
3162                         sym = get_ksymbol(mod, addr, NULL, NULL);
3163                         if (!sym)
3164                                 goto out;
3165                         strlcpy(symname, sym, KSYM_NAME_LEN);
3166                         preempt_enable();
3167                         return 0;
3168                 }
3169         }
3170 out:
3171         preempt_enable();
3172         return -ERANGE;
3173 }
3174 
3175 int lookup_module_symbol_attrs(unsigned long addr, unsigned long *size,
3176                         unsigned long *offset, char *modname, char *name)
3177 {
3178         struct module *mod;
3179 
3180         preempt_disable();
3181         list_for_each_entry_rcu(mod, &modules, list) {
3182                 if (within_module_init(addr, mod) ||
3183                     within_module_core(addr, mod)) {
3184                         const char *sym;
3185 
3186                         sym = get_ksymbol(mod, addr, size, offset);
3187                         if (!sym)
3188                                 goto out;
3189                         if (modname)
3190                                 strlcpy(modname, mod->name, MODULE_NAME_LEN);
3191                         if (name)
3192                                 strlcpy(name, sym, KSYM_NAME_LEN);
3193                         preempt_enable();
3194                         return 0;
3195                 }
3196         }
3197 out:
3198         preempt_enable();
3199         return -ERANGE;
3200 }
3201 
3202 int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
3203                         char *name, char *module_name, int *exported)
3204 {
3205         struct module *mod;
3206 
3207         preempt_disable();
3208         list_for_each_entry_rcu(mod, &modules, list) {
3209                 if (symnum < mod->num_symtab) {
3210                         *value = mod->symtab[symnum].st_value;
3211                         *type = mod->symtab[symnum].st_info;
3212                         strlcpy(name, mod->strtab + mod->symtab[symnum].st_name,
3213                                 KSYM_NAME_LEN);
3214                         strlcpy(module_name, mod->name, MODULE_NAME_LEN);
3215                         *exported = is_exported(name, *value, mod);
3216                         preempt_enable();
3217                         return 0;
3218                 }
3219                 symnum -= mod->num_symtab;
3220         }
3221         preempt_enable();
3222         return -ERANGE;
3223 }
3224 
3225 static unsigned long mod_find_symname(struct module *mod, const char *name)
3226 {
3227         unsigned int i;
3228 
3229         for (i = 0; i < mod->num_symtab; i++)
3230                 if (strcmp(name, mod->strtab+mod->symtab[i].st_name) == 0 &&
3231                     mod->symtab[i].st_info != 'U')
3232                         return mod->symtab[i].st_value;
3233         return 0;
3234 }
3235 
3236 /* Look for this name: can be of form module:name. */
3237 unsigned long module_kallsyms_lookup_name(const char *name)
3238 {
3239         struct module *mod;
3240         char *colon;
3241         unsigned long ret = 0;
3242 
3243         /* Don't lock: we're in enough trouble already. */
3244         preempt_disable();
3245         if ((colon = strchr(name, ':')) != NULL) {
3246                 *colon = '\0';
3247                 if ((mod = find_module(name)) != NULL)
3248                         ret = mod_find_symname(mod, colon+1);
3249                 *colon = ':';
3250         } else {
3251                 list_for_each_entry_rcu(mod, &modules, list)
3252                         if ((ret = mod_find_symname(mod, name)) != 0)
3253                                 break;
3254         }
3255         preempt_enable();
3256         return ret;
3257 }
3258 
3259 int module_kallsyms_on_each_symbol(int (*fn)(void *, const char *,
3260                                              struct module *, unsigned long),
3261                                    void *data)
3262 {
3263         struct module *mod;
3264         unsigned int i;
3265         int ret;
3266 
3267         list_for_each_entry(mod, &modules, list) {
3268                 for (i = 0; i < mod->num_symtab; i++) {
3269                         ret = fn(data, mod->strtab + mod->symtab[i].st_name,
3270                                  mod, mod->symtab[i].st_value);
3271                         if (ret != 0)
3272                                 return ret;
3273                 }
3274         }
3275         return 0;
3276 }
3277 #endif /* CONFIG_KALLSYMS */
3278 
3279 static char *module_flags(struct module *mod, char *buf)
3280 {
3281         int bx = 0;
3282 
3283         if (mod->taints ||
3284             mod->state == MODULE_STATE_GOING ||
3285             mod->state == MODULE_STATE_COMING) {
3286                 buf[bx++] = '(';
3287                 if (mod->taints & (1 << TAINT_PROPRIETARY_MODULE))
3288                         buf[bx++] = 'P';
3289                 else if (mod->taints & (1 << TAINT_OOT_MODULE))
3290                         buf[bx++] = 'O';
3291                 if (mod->taints & (1 << TAINT_FORCED_MODULE))
3292                         buf[bx++] = 'F';
3293                 if (mod->taints & (1 << TAINT_CRAP))
3294                         buf[bx++] = 'C';
3295                 /*
3296                  * TAINT_FORCED_RMMOD: could be added.
3297                  * TAINT_UNSAFE_SMP, TAINT_MACHINE_CHECK, TAINT_BAD_PAGE don't
3298                  * apply to modules.
3299                  */
3300 
3301                 /* Show a - for module-is-being-unloaded */
3302                 if (mod->state == MODULE_STATE_GOING)
3303                         buf[bx++] = '-';
3304                 /* Show a + for module-is-being-loaded */
3305                 if (mod->state == MODULE_STATE_COMING)
3306                         buf[bx++] = '+';
3307                 buf[bx++] = ')';
3308         }
3309         buf[bx] = '\0';
3310 
3311         return buf;
3312 }
3313 
3314 #ifdef CONFIG_PROC_FS
3315 /* Called by the /proc file system to return a list of modules. */
3316 static void *m_start(struct seq_file *m, loff_t *pos)
3317 {
3318         mutex_lock(&module_mutex);
3319         return seq_list_start(&modules, *pos);
3320 }
3321 
3322 static void *m_next(struct seq_file *m, void *p, loff_t *pos)
3323 {
3324         return seq_list_next(p, &modules, pos);
3325 }
3326 
3327 static void m_stop(struct seq_file *m, void *p)
3328 {
3329         mutex_unlock(&module_mutex);
3330 }
3331 
3332 static int m_show(struct seq_file *m, void *p)
3333 {
3334         struct module *mod = list_entry(p, struct module, list);
3335         char buf[8];
3336 
3337         seq_printf(m, "%s %u",
3338                    mod->name, mod->init_size + mod->core_size);
3339         print_unload_info(m, mod);
3340 
3341         /* Informative for users. */
3342         seq_printf(m, " %s",
3343                    mod->state == MODULE_STATE_GOING ? "Unloading":
3344                    mod->state == MODULE_STATE_COMING ? "Loading":
3345                    "Live");
3346         /* Used by oprofile and other similar tools. */
3347         seq_printf(m, " 0x%pK", mod->module_core);
3348 
3349         /* Taints info */
3350         if (mod->taints)
3351                 seq_printf(m, " %s", module_flags(mod, buf));
3352 
3353         seq_printf(m, "\n");
3354         return 0;
3355 }
3356 
3357 /* Format: modulename size refcount deps address
3358 
3359    Where refcount is a number or -, and deps is a comma-separated list
3360    of depends or -.
3361 */
3362 static const struct seq_operations modules_op = {
3363         .start  = m_start,
3364         .next   = m_next,
3365         .stop   = m_stop,
3366         .show   = m_show
3367 };
3368 
3369 static int modules_open(struct inode *inode, struct file *file)
3370 {
3371         return seq_open(file, &modules_op);
3372 }
3373 
3374 static const struct file_operations proc_modules_operations = {
3375         .open           = modules_open,
3376         .read           = seq_read,
3377         .llseek         = seq_lseek,
3378         .release        = seq_release,
3379 };
3380 
3381 static int __init proc_modules_init(void)
3382 {
3383         proc_create("modules", 0, NULL, &proc_modules_operations);
3384         return 0;
3385 }
3386 module_init(proc_modules_init);
3387 #endif
3388 
3389 /* Given an address, look for it in the module exception tables. */
3390 const struct exception_table_entry *search_module_extables(unsigned long addr)
3391 {
3392         const struct exception_table_entry *e = NULL;
3393         struct module *mod;
3394 
3395         preempt_disable();
3396         list_for_each_entry_rcu(mod, &modules, list) {
3397                 if (mod->num_exentries == 0)
3398                         continue;
3399 
3400                 e = search_extable(mod->extable,
3401                                    mod->extable + mod->num_exentries - 1,
3402                                    addr);
3403                 if (e)
3404                         break;
3405         }
3406         preempt_enable();
3407 
3408         /* Now, if we found one, we are running inside it now, hence
3409            we cannot unload the module, hence no refcnt needed. */
3410         return e;
3411 }
3412 
3413 /*
3414  * is_module_address - is this address inside a module?
3415  * @addr: the address to check.
3416  *
3417  * See is_module_text_address() if you simply want to see if the address
3418  * is code (not data).
3419  */
3420 bool is_module_address(unsigned long addr)
3421 {
3422         bool ret;
3423 
3424         preempt_disable();
3425         ret = __module_address(addr) != NULL;
3426         preempt_enable();
3427 
3428         return ret;
3429 }
3430 
3431 /*
3432  * __module_address - get the module which contains an address.
3433  * @addr: the address.
3434  *
3435  * Must be called with preempt disabled or module mutex held so that
3436  * module doesn't get freed during this.
3437  */
3438 struct module *__module_address(unsigned long addr)
3439 {
3440         struct module *mod;
3441 
3442         if (addr < module_addr_min || addr > module_addr_max)
3443                 return NULL;
3444 
3445         list_for_each_entry_rcu(mod, &modules, list)
3446                 if (within_module_core(addr, mod)
3447                     || within_module_init(addr, mod))
3448                         return mod;
3449         return NULL;
3450 }
3451 EXPORT_SYMBOL_GPL(__module_address);
3452 
3453 /*
3454  * is_module_text_address - is this address inside module code?
3455  * @addr: the address to check.
3456  *
3457  * See is_module_address() if you simply want to see if the address is
3458  * anywhere in a module.  See kernel_text_address() for testing if an
3459  * address corresponds to kernel or module code.
3460  */
3461 bool is_module_text_address(unsigned long addr)
3462 {
3463         bool ret;
3464 
3465         preempt_disable();
3466         ret = __module_text_address(addr) != NULL;
3467         preempt_enable();
3468 
3469         return ret;
3470 }
3471 
3472 /*
3473  * __module_text_address - get the module whose code contains an address.
3474  * @addr: the address.
3475  *
3476  * Must be called with preempt disabled or module mutex held so that
3477  * module doesn't get freed during this.
3478  */
3479 struct module *__module_text_address(unsigned long addr)
3480 {
3481         struct module *mod = __module_address(addr);
3482         if (mod) {
3483                 /* Make sure it's within the text section. */
3484                 if (!within(addr, mod->module_init, mod->init_text_size)
3485                     && !within(addr, mod->module_core, mod->core_text_size))
3486                         mod = NULL;
3487         }
3488         return mod;
3489 }
3490 EXPORT_SYMBOL_GPL(__module_text_address);
3491 
3492 /* Don't grab lock, we're oopsing. */
3493 void print_modules(void)
3494 {
3495         struct module *mod;
3496         char buf[8];
3497 
3498         printk(KERN_DEFAULT "Modules linked in:");
3499         /* Most callers should already have preempt disabled, but make sure */
3500         preempt_disable();
3501         list_for_each_entry_rcu(mod, &modules, list)
3502                 printk(" %s%s", mod->name, module_flags(mod, buf));
3503         preempt_enable();
3504         if (last_unloaded_module[0])
3505                 printk(" [last unloaded: %s]", last_unloaded_module);
3506         printk("\n");
3507 }
3508 
3509 #ifdef CONFIG_MODVERSIONS
3510 /* Generate the signature for all relevant module structures here.
3511  * If these change, we don't want to try to parse the module. */
3512 void module_layout(struct module *mod,
3513                    struct modversion_info *ver,
3514                    struct kernel_param *kp,
3515                    struct kernel_symbol *ks,
3516                    struct tracepoint * const *tp)
3517 {
3518 }
3519 EXPORT_SYMBOL(module_layout);
3520 #endif
3521 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp