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

TOMOYO Linux Cross Reference
Linux/kernel/module.c

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

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