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

TOMOYO Linux Cross Reference
Linux/kernel/module.c

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

~ [ 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