main.c 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * Copyright (C) 2002 Richard Henderson
  4. * Copyright (C) 2001 Rusty Russell, 2002, 2010 Rusty Russell IBM.
  5. * Copyright (C) 2023 Luis Chamberlain <mcgrof@kernel.org>
  6. */
  7. #define INCLUDE_VERMAGIC
  8. #include <linux/export.h>
  9. #include <linux/extable.h>
  10. #include <linux/moduleloader.h>
  11. #include <linux/module_signature.h>
  12. #include <linux/trace_events.h>
  13. #include <linux/init.h>
  14. #include <linux/kallsyms.h>
  15. #include <linux/buildid.h>
  16. #include <linux/fs.h>
  17. #include <linux/kernel.h>
  18. #include <linux/kernel_read_file.h>
  19. #include <linux/kstrtox.h>
  20. #include <linux/slab.h>
  21. #include <linux/vmalloc.h>
  22. #include <linux/elf.h>
  23. #include <linux/seq_file.h>
  24. #include <linux/syscalls.h>
  25. #include <linux/fcntl.h>
  26. #include <linux/rcupdate.h>
  27. #include <linux/capability.h>
  28. #include <linux/cpu.h>
  29. #include <linux/moduleparam.h>
  30. #include <linux/errno.h>
  31. #include <linux/err.h>
  32. #include <linux/vermagic.h>
  33. #include <linux/notifier.h>
  34. #include <linux/sched.h>
  35. #include <linux/device.h>
  36. #include <linux/string.h>
  37. #include <linux/mutex.h>
  38. #include <linux/rculist.h>
  39. #include <linux/uaccess.h>
  40. #include <asm/cacheflush.h>
  41. #include <linux/set_memory.h>
  42. #include <asm/mmu_context.h>
  43. #include <linux/license.h>
  44. #include <asm/sections.h>
  45. #include <linux/tracepoint.h>
  46. #include <linux/ftrace.h>
  47. #include <linux/livepatch.h>
  48. #include <linux/async.h>
  49. #include <linux/percpu.h>
  50. #include <linux/kmemleak.h>
  51. #include <linux/jump_label.h>
  52. #include <linux/pfn.h>
  53. #include <linux/bsearch.h>
  54. #include <linux/dynamic_debug.h>
  55. #include <linux/audit.h>
  56. #include <linux/cfi.h>
  57. #include <linux/codetag.h>
  58. #include <linux/debugfs.h>
  59. #include <linux/execmem.h>
  60. #include <uapi/linux/module.h>
  61. #include "internal.h"
  62. #define CREATE_TRACE_POINTS
  63. #include <trace/events/module.h>
  64. /*
  65. * Mutex protects:
  66. * 1) List of modules (also safely readable with preempt_disable),
  67. * 2) module_use links,
  68. * 3) mod_tree.addr_min/mod_tree.addr_max.
  69. * (delete and add uses RCU list operations).
  70. */
  71. DEFINE_MUTEX(module_mutex);
  72. LIST_HEAD(modules);
  73. /* Work queue for freeing init sections in success case */
  74. static void do_free_init(struct work_struct *w);
  75. static DECLARE_WORK(init_free_wq, do_free_init);
  76. static LLIST_HEAD(init_free_list);
  77. struct mod_tree_root mod_tree __cacheline_aligned = {
  78. .addr_min = -1UL,
  79. };
  80. struct symsearch {
  81. const struct kernel_symbol *start, *stop;
  82. const s32 *crcs;
  83. enum mod_license license;
  84. };
  85. /*
  86. * Bounds of module memory, for speeding up __module_address.
  87. * Protected by module_mutex.
  88. */
  89. static void __mod_update_bounds(enum mod_mem_type type __maybe_unused, void *base,
  90. unsigned int size, struct mod_tree_root *tree)
  91. {
  92. unsigned long min = (unsigned long)base;
  93. unsigned long max = min + size;
  94. #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
  95. if (mod_mem_type_is_core_data(type)) {
  96. if (min < tree->data_addr_min)
  97. tree->data_addr_min = min;
  98. if (max > tree->data_addr_max)
  99. tree->data_addr_max = max;
  100. return;
  101. }
  102. #endif
  103. if (min < tree->addr_min)
  104. tree->addr_min = min;
  105. if (max > tree->addr_max)
  106. tree->addr_max = max;
  107. }
  108. static void mod_update_bounds(struct module *mod)
  109. {
  110. for_each_mod_mem_type(type) {
  111. struct module_memory *mod_mem = &mod->mem[type];
  112. if (mod_mem->size)
  113. __mod_update_bounds(type, mod_mem->base, mod_mem->size, &mod_tree);
  114. }
  115. }
  116. /* Block module loading/unloading? */
  117. int modules_disabled;
  118. core_param(nomodule, modules_disabled, bint, 0);
  119. /* Waiting for a module to finish initializing? */
  120. static DECLARE_WAIT_QUEUE_HEAD(module_wq);
  121. static BLOCKING_NOTIFIER_HEAD(module_notify_list);
  122. int register_module_notifier(struct notifier_block *nb)
  123. {
  124. return blocking_notifier_chain_register(&module_notify_list, nb);
  125. }
  126. EXPORT_SYMBOL(register_module_notifier);
  127. int unregister_module_notifier(struct notifier_block *nb)
  128. {
  129. return blocking_notifier_chain_unregister(&module_notify_list, nb);
  130. }
  131. EXPORT_SYMBOL(unregister_module_notifier);
  132. /*
  133. * We require a truly strong try_module_get(): 0 means success.
  134. * Otherwise an error is returned due to ongoing or failed
  135. * initialization etc.
  136. */
  137. static inline int strong_try_module_get(struct module *mod)
  138. {
  139. BUG_ON(mod && mod->state == MODULE_STATE_UNFORMED);
  140. if (mod && mod->state == MODULE_STATE_COMING)
  141. return -EBUSY;
  142. if (try_module_get(mod))
  143. return 0;
  144. else
  145. return -ENOENT;
  146. }
  147. static inline void add_taint_module(struct module *mod, unsigned flag,
  148. enum lockdep_ok lockdep_ok)
  149. {
  150. add_taint(flag, lockdep_ok);
  151. set_bit(flag, &mod->taints);
  152. }
  153. /*
  154. * A thread that wants to hold a reference to a module only while it
  155. * is running can call this to safely exit.
  156. */
  157. void __noreturn __module_put_and_kthread_exit(struct module *mod, long code)
  158. {
  159. module_put(mod);
  160. kthread_exit(code);
  161. }
  162. EXPORT_SYMBOL(__module_put_and_kthread_exit);
  163. /* Find a module section: 0 means not found. */
  164. static unsigned int find_sec(const struct load_info *info, const char *name)
  165. {
  166. unsigned int i;
  167. for (i = 1; i < info->hdr->e_shnum; i++) {
  168. Elf_Shdr *shdr = &info->sechdrs[i];
  169. /* Alloc bit cleared means "ignore it." */
  170. if ((shdr->sh_flags & SHF_ALLOC)
  171. && strcmp(info->secstrings + shdr->sh_name, name) == 0)
  172. return i;
  173. }
  174. return 0;
  175. }
  176. /* Find a module section, or NULL. */
  177. static void *section_addr(const struct load_info *info, const char *name)
  178. {
  179. /* Section 0 has sh_addr 0. */
  180. return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
  181. }
  182. /* Find a module section, or NULL. Fill in number of "objects" in section. */
  183. static void *section_objs(const struct load_info *info,
  184. const char *name,
  185. size_t object_size,
  186. unsigned int *num)
  187. {
  188. unsigned int sec = find_sec(info, name);
  189. /* Section 0 has sh_addr 0 and sh_size 0. */
  190. *num = info->sechdrs[sec].sh_size / object_size;
  191. return (void *)info->sechdrs[sec].sh_addr;
  192. }
  193. /* Find a module section: 0 means not found. Ignores SHF_ALLOC flag. */
  194. static unsigned int find_any_sec(const struct load_info *info, const char *name)
  195. {
  196. unsigned int i;
  197. for (i = 1; i < info->hdr->e_shnum; i++) {
  198. Elf_Shdr *shdr = &info->sechdrs[i];
  199. if (strcmp(info->secstrings + shdr->sh_name, name) == 0)
  200. return i;
  201. }
  202. return 0;
  203. }
  204. /*
  205. * Find a module section, or NULL. Fill in number of "objects" in section.
  206. * Ignores SHF_ALLOC flag.
  207. */
  208. static __maybe_unused void *any_section_objs(const struct load_info *info,
  209. const char *name,
  210. size_t object_size,
  211. unsigned int *num)
  212. {
  213. unsigned int sec = find_any_sec(info, name);
  214. /* Section 0 has sh_addr 0 and sh_size 0. */
  215. *num = info->sechdrs[sec].sh_size / object_size;
  216. return (void *)info->sechdrs[sec].sh_addr;
  217. }
  218. #ifndef CONFIG_MODVERSIONS
  219. #define symversion(base, idx) NULL
  220. #else
  221. #define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
  222. #endif
  223. static const char *kernel_symbol_name(const struct kernel_symbol *sym)
  224. {
  225. #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
  226. return offset_to_ptr(&sym->name_offset);
  227. #else
  228. return sym->name;
  229. #endif
  230. }
  231. static const char *kernel_symbol_namespace(const struct kernel_symbol *sym)
  232. {
  233. #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
  234. if (!sym->namespace_offset)
  235. return NULL;
  236. return offset_to_ptr(&sym->namespace_offset);
  237. #else
  238. return sym->namespace;
  239. #endif
  240. }
  241. int cmp_name(const void *name, const void *sym)
  242. {
  243. return strcmp(name, kernel_symbol_name(sym));
  244. }
  245. static bool find_exported_symbol_in_section(const struct symsearch *syms,
  246. struct module *owner,
  247. struct find_symbol_arg *fsa)
  248. {
  249. struct kernel_symbol *sym;
  250. if (!fsa->gplok && syms->license == GPL_ONLY)
  251. return false;
  252. sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
  253. sizeof(struct kernel_symbol), cmp_name);
  254. if (!sym)
  255. return false;
  256. fsa->owner = owner;
  257. fsa->crc = symversion(syms->crcs, sym - syms->start);
  258. fsa->sym = sym;
  259. fsa->license = syms->license;
  260. return true;
  261. }
  262. /*
  263. * Find an exported symbol and return it, along with, (optional) crc and
  264. * (optional) module which owns it. Needs preempt disabled or module_mutex.
  265. */
  266. bool find_symbol(struct find_symbol_arg *fsa)
  267. {
  268. static const struct symsearch arr[] = {
  269. { __start___ksymtab, __stop___ksymtab, __start___kcrctab,
  270. NOT_GPL_ONLY },
  271. { __start___ksymtab_gpl, __stop___ksymtab_gpl,
  272. __start___kcrctab_gpl,
  273. GPL_ONLY },
  274. };
  275. struct module *mod;
  276. unsigned int i;
  277. module_assert_mutex_or_preempt();
  278. for (i = 0; i < ARRAY_SIZE(arr); i++)
  279. if (find_exported_symbol_in_section(&arr[i], NULL, fsa))
  280. return true;
  281. list_for_each_entry_rcu(mod, &modules, list,
  282. lockdep_is_held(&module_mutex)) {
  283. struct symsearch arr[] = {
  284. { mod->syms, mod->syms + mod->num_syms, mod->crcs,
  285. NOT_GPL_ONLY },
  286. { mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
  287. mod->gpl_crcs,
  288. GPL_ONLY },
  289. };
  290. if (mod->state == MODULE_STATE_UNFORMED)
  291. continue;
  292. for (i = 0; i < ARRAY_SIZE(arr); i++)
  293. if (find_exported_symbol_in_section(&arr[i], mod, fsa))
  294. return true;
  295. }
  296. pr_debug("Failed to find symbol %s\n", fsa->name);
  297. return false;
  298. }
  299. /*
  300. * Search for module by name: must hold module_mutex (or preempt disabled
  301. * for read-only access).
  302. */
  303. struct module *find_module_all(const char *name, size_t len,
  304. bool even_unformed)
  305. {
  306. struct module *mod;
  307. module_assert_mutex_or_preempt();
  308. list_for_each_entry_rcu(mod, &modules, list,
  309. lockdep_is_held(&module_mutex)) {
  310. if (!even_unformed && mod->state == MODULE_STATE_UNFORMED)
  311. continue;
  312. if (strlen(mod->name) == len && !memcmp(mod->name, name, len))
  313. return mod;
  314. }
  315. return NULL;
  316. }
  317. struct module *find_module(const char *name)
  318. {
  319. return find_module_all(name, strlen(name), false);
  320. }
  321. #ifdef CONFIG_SMP
  322. static inline void __percpu *mod_percpu(struct module *mod)
  323. {
  324. return mod->percpu;
  325. }
  326. static int percpu_modalloc(struct module *mod, struct load_info *info)
  327. {
  328. Elf_Shdr *pcpusec = &info->sechdrs[info->index.pcpu];
  329. unsigned long align = pcpusec->sh_addralign;
  330. if (!pcpusec->sh_size)
  331. return 0;
  332. if (align > PAGE_SIZE) {
  333. pr_warn("%s: per-cpu alignment %li > %li\n",
  334. mod->name, align, PAGE_SIZE);
  335. align = PAGE_SIZE;
  336. }
  337. mod->percpu = __alloc_reserved_percpu(pcpusec->sh_size, align);
  338. if (!mod->percpu) {
  339. pr_warn("%s: Could not allocate %lu bytes percpu data\n",
  340. mod->name, (unsigned long)pcpusec->sh_size);
  341. return -ENOMEM;
  342. }
  343. mod->percpu_size = pcpusec->sh_size;
  344. return 0;
  345. }
  346. static void percpu_modfree(struct module *mod)
  347. {
  348. free_percpu(mod->percpu);
  349. }
  350. static unsigned int find_pcpusec(struct load_info *info)
  351. {
  352. return find_sec(info, ".data..percpu");
  353. }
  354. static void percpu_modcopy(struct module *mod,
  355. const void *from, unsigned long size)
  356. {
  357. int cpu;
  358. for_each_possible_cpu(cpu)
  359. memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
  360. }
  361. bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
  362. {
  363. struct module *mod;
  364. unsigned int cpu;
  365. preempt_disable();
  366. list_for_each_entry_rcu(mod, &modules, list) {
  367. if (mod->state == MODULE_STATE_UNFORMED)
  368. continue;
  369. if (!mod->percpu_size)
  370. continue;
  371. for_each_possible_cpu(cpu) {
  372. void *start = per_cpu_ptr(mod->percpu, cpu);
  373. void *va = (void *)addr;
  374. if (va >= start && va < start + mod->percpu_size) {
  375. if (can_addr) {
  376. *can_addr = (unsigned long) (va - start);
  377. *can_addr += (unsigned long)
  378. per_cpu_ptr(mod->percpu,
  379. get_boot_cpu_id());
  380. }
  381. preempt_enable();
  382. return true;
  383. }
  384. }
  385. }
  386. preempt_enable();
  387. return false;
  388. }
  389. /**
  390. * is_module_percpu_address() - test whether address is from module static percpu
  391. * @addr: address to test
  392. *
  393. * Test whether @addr belongs to module static percpu area.
  394. *
  395. * Return: %true if @addr is from module static percpu area
  396. */
  397. bool is_module_percpu_address(unsigned long addr)
  398. {
  399. return __is_module_percpu_address(addr, NULL);
  400. }
  401. #else /* ... !CONFIG_SMP */
  402. static inline void __percpu *mod_percpu(struct module *mod)
  403. {
  404. return NULL;
  405. }
  406. static int percpu_modalloc(struct module *mod, struct load_info *info)
  407. {
  408. /* UP modules shouldn't have this section: ENOMEM isn't quite right */
  409. if (info->sechdrs[info->index.pcpu].sh_size != 0)
  410. return -ENOMEM;
  411. return 0;
  412. }
  413. static inline void percpu_modfree(struct module *mod)
  414. {
  415. }
  416. static unsigned int find_pcpusec(struct load_info *info)
  417. {
  418. return 0;
  419. }
  420. static inline void percpu_modcopy(struct module *mod,
  421. const void *from, unsigned long size)
  422. {
  423. /* pcpusec should be 0, and size of that section should be 0. */
  424. BUG_ON(size != 0);
  425. }
  426. bool is_module_percpu_address(unsigned long addr)
  427. {
  428. return false;
  429. }
  430. bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
  431. {
  432. return false;
  433. }
  434. #endif /* CONFIG_SMP */
  435. #define MODINFO_ATTR(field) \
  436. static void setup_modinfo_##field(struct module *mod, const char *s) \
  437. { \
  438. mod->field = kstrdup(s, GFP_KERNEL); \
  439. } \
  440. static ssize_t show_modinfo_##field(struct module_attribute *mattr, \
  441. struct module_kobject *mk, char *buffer) \
  442. { \
  443. return scnprintf(buffer, PAGE_SIZE, "%s\n", mk->mod->field); \
  444. } \
  445. static int modinfo_##field##_exists(struct module *mod) \
  446. { \
  447. return mod->field != NULL; \
  448. } \
  449. static void free_modinfo_##field(struct module *mod) \
  450. { \
  451. kfree(mod->field); \
  452. mod->field = NULL; \
  453. } \
  454. static struct module_attribute modinfo_##field = { \
  455. .attr = { .name = __stringify(field), .mode = 0444 }, \
  456. .show = show_modinfo_##field, \
  457. .setup = setup_modinfo_##field, \
  458. .test = modinfo_##field##_exists, \
  459. .free = free_modinfo_##field, \
  460. };
  461. MODINFO_ATTR(version);
  462. MODINFO_ATTR(srcversion);
  463. static struct {
  464. char name[MODULE_NAME_LEN + 1];
  465. char taints[MODULE_FLAGS_BUF_SIZE];
  466. } last_unloaded_module;
  467. #ifdef CONFIG_MODULE_UNLOAD
  468. EXPORT_TRACEPOINT_SYMBOL(module_get);
  469. /* MODULE_REF_BASE is the base reference count by kmodule loader. */
  470. #define MODULE_REF_BASE 1
  471. /* Init the unload section of the module. */
  472. static int module_unload_init(struct module *mod)
  473. {
  474. /*
  475. * Initialize reference counter to MODULE_REF_BASE.
  476. * refcnt == 0 means module is going.
  477. */
  478. atomic_set(&mod->refcnt, MODULE_REF_BASE);
  479. INIT_LIST_HEAD(&mod->source_list);
  480. INIT_LIST_HEAD(&mod->target_list);
  481. /* Hold reference count during initialization. */
  482. atomic_inc(&mod->refcnt);
  483. return 0;
  484. }
  485. /* Does a already use b? */
  486. static int already_uses(struct module *a, struct module *b)
  487. {
  488. struct module_use *use;
  489. list_for_each_entry(use, &b->source_list, source_list) {
  490. if (use->source == a)
  491. return 1;
  492. }
  493. pr_debug("%s does not use %s!\n", a->name, b->name);
  494. return 0;
  495. }
  496. /*
  497. * Module a uses b
  498. * - we add 'a' as a "source", 'b' as a "target" of module use
  499. * - the module_use is added to the list of 'b' sources (so
  500. * 'b' can walk the list to see who sourced them), and of 'a'
  501. * targets (so 'a' can see what modules it targets).
  502. */
  503. static int add_module_usage(struct module *a, struct module *b)
  504. {
  505. struct module_use *use;
  506. pr_debug("Allocating new usage for %s.\n", a->name);
  507. use = kmalloc(sizeof(*use), GFP_ATOMIC);
  508. if (!use)
  509. return -ENOMEM;
  510. use->source = a;
  511. use->target = b;
  512. list_add(&use->source_list, &b->source_list);
  513. list_add(&use->target_list, &a->target_list);
  514. return 0;
  515. }
  516. /* Module a uses b: caller needs module_mutex() */
  517. static int ref_module(struct module *a, struct module *b)
  518. {
  519. int err;
  520. if (b == NULL || already_uses(a, b))
  521. return 0;
  522. /* If module isn't available, we fail. */
  523. err = strong_try_module_get(b);
  524. if (err)
  525. return err;
  526. err = add_module_usage(a, b);
  527. if (err) {
  528. module_put(b);
  529. return err;
  530. }
  531. return 0;
  532. }
  533. /* Clear the unload stuff of the module. */
  534. static void module_unload_free(struct module *mod)
  535. {
  536. struct module_use *use, *tmp;
  537. mutex_lock(&module_mutex);
  538. list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
  539. struct module *i = use->target;
  540. pr_debug("%s unusing %s\n", mod->name, i->name);
  541. module_put(i);
  542. list_del(&use->source_list);
  543. list_del(&use->target_list);
  544. kfree(use);
  545. }
  546. mutex_unlock(&module_mutex);
  547. }
  548. #ifdef CONFIG_MODULE_FORCE_UNLOAD
  549. static inline int try_force_unload(unsigned int flags)
  550. {
  551. int ret = (flags & O_TRUNC);
  552. if (ret)
  553. add_taint(TAINT_FORCED_RMMOD, LOCKDEP_NOW_UNRELIABLE);
  554. return ret;
  555. }
  556. #else
  557. static inline int try_force_unload(unsigned int flags)
  558. {
  559. return 0;
  560. }
  561. #endif /* CONFIG_MODULE_FORCE_UNLOAD */
  562. /* Try to release refcount of module, 0 means success. */
  563. static int try_release_module_ref(struct module *mod)
  564. {
  565. int ret;
  566. /* Try to decrement refcnt which we set at loading */
  567. ret = atomic_sub_return(MODULE_REF_BASE, &mod->refcnt);
  568. BUG_ON(ret < 0);
  569. if (ret)
  570. /* Someone can put this right now, recover with checking */
  571. ret = atomic_add_unless(&mod->refcnt, MODULE_REF_BASE, 0);
  572. return ret;
  573. }
  574. static int try_stop_module(struct module *mod, int flags, int *forced)
  575. {
  576. /* If it's not unused, quit unless we're forcing. */
  577. if (try_release_module_ref(mod) != 0) {
  578. *forced = try_force_unload(flags);
  579. if (!(*forced))
  580. return -EWOULDBLOCK;
  581. }
  582. /* Mark it as dying. */
  583. mod->state = MODULE_STATE_GOING;
  584. return 0;
  585. }
  586. /**
  587. * module_refcount() - return the refcount or -1 if unloading
  588. * @mod: the module we're checking
  589. *
  590. * Return:
  591. * -1 if the module is in the process of unloading
  592. * otherwise the number of references in the kernel to the module
  593. */
  594. int module_refcount(struct module *mod)
  595. {
  596. return atomic_read(&mod->refcnt) - MODULE_REF_BASE;
  597. }
  598. EXPORT_SYMBOL(module_refcount);
  599. /* This exists whether we can unload or not */
  600. static void free_module(struct module *mod);
  601. SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
  602. unsigned int, flags)
  603. {
  604. struct module *mod;
  605. char name[MODULE_NAME_LEN];
  606. char buf[MODULE_FLAGS_BUF_SIZE];
  607. int ret, forced = 0;
  608. if (!capable(CAP_SYS_MODULE) || modules_disabled)
  609. return -EPERM;
  610. if (strncpy_from_user(name, name_user, MODULE_NAME_LEN-1) < 0)
  611. return -EFAULT;
  612. name[MODULE_NAME_LEN-1] = '\0';
  613. audit_log_kern_module(name);
  614. if (mutex_lock_interruptible(&module_mutex) != 0)
  615. return -EINTR;
  616. mod = find_module(name);
  617. if (!mod) {
  618. ret = -ENOENT;
  619. goto out;
  620. }
  621. if (!list_empty(&mod->source_list)) {
  622. /* Other modules depend on us: get rid of them first. */
  623. ret = -EWOULDBLOCK;
  624. goto out;
  625. }
  626. /* Doing init or already dying? */
  627. if (mod->state != MODULE_STATE_LIVE) {
  628. /* FIXME: if (force), slam module count damn the torpedoes */
  629. pr_debug("%s already dying\n", mod->name);
  630. ret = -EBUSY;
  631. goto out;
  632. }
  633. /* If it has an init func, it must have an exit func to unload */
  634. if (mod->init && !mod->exit) {
  635. forced = try_force_unload(flags);
  636. if (!forced) {
  637. /* This module can't be removed */
  638. ret = -EBUSY;
  639. goto out;
  640. }
  641. }
  642. ret = try_stop_module(mod, flags, &forced);
  643. if (ret != 0)
  644. goto out;
  645. mutex_unlock(&module_mutex);
  646. /* Final destruction now no one is using it. */
  647. if (mod->exit != NULL)
  648. mod->exit();
  649. blocking_notifier_call_chain(&module_notify_list,
  650. MODULE_STATE_GOING, mod);
  651. klp_module_going(mod);
  652. ftrace_release_mod(mod);
  653. async_synchronize_full();
  654. /* Store the name and taints of the last unloaded module for diagnostic purposes */
  655. strscpy(last_unloaded_module.name, mod->name, sizeof(last_unloaded_module.name));
  656. strscpy(last_unloaded_module.taints, module_flags(mod, buf, false), sizeof(last_unloaded_module.taints));
  657. free_module(mod);
  658. /* someone could wait for the module in add_unformed_module() */
  659. wake_up_all(&module_wq);
  660. return 0;
  661. out:
  662. mutex_unlock(&module_mutex);
  663. return ret;
  664. }
  665. void __symbol_put(const char *symbol)
  666. {
  667. struct find_symbol_arg fsa = {
  668. .name = symbol,
  669. .gplok = true,
  670. };
  671. preempt_disable();
  672. BUG_ON(!find_symbol(&fsa));
  673. module_put(fsa.owner);
  674. preempt_enable();
  675. }
  676. EXPORT_SYMBOL(__symbol_put);
  677. /* Note this assumes addr is a function, which it currently always is. */
  678. void symbol_put_addr(void *addr)
  679. {
  680. struct module *modaddr;
  681. unsigned long a = (unsigned long)dereference_function_descriptor(addr);
  682. if (core_kernel_text(a))
  683. return;
  684. /*
  685. * Even though we hold a reference on the module; we still need to
  686. * disable preemption in order to safely traverse the data structure.
  687. */
  688. preempt_disable();
  689. modaddr = __module_text_address(a);
  690. BUG_ON(!modaddr);
  691. module_put(modaddr);
  692. preempt_enable();
  693. }
  694. EXPORT_SYMBOL_GPL(symbol_put_addr);
  695. static ssize_t show_refcnt(struct module_attribute *mattr,
  696. struct module_kobject *mk, char *buffer)
  697. {
  698. return sprintf(buffer, "%i\n", module_refcount(mk->mod));
  699. }
  700. static struct module_attribute modinfo_refcnt =
  701. __ATTR(refcnt, 0444, show_refcnt, NULL);
  702. void __module_get(struct module *module)
  703. {
  704. if (module) {
  705. atomic_inc(&module->refcnt);
  706. trace_module_get(module, _RET_IP_);
  707. }
  708. }
  709. EXPORT_SYMBOL(__module_get);
  710. bool try_module_get(struct module *module)
  711. {
  712. bool ret = true;
  713. if (module) {
  714. /* Note: here, we can fail to get a reference */
  715. if (likely(module_is_live(module) &&
  716. atomic_inc_not_zero(&module->refcnt) != 0))
  717. trace_module_get(module, _RET_IP_);
  718. else
  719. ret = false;
  720. }
  721. return ret;
  722. }
  723. EXPORT_SYMBOL(try_module_get);
  724. void module_put(struct module *module)
  725. {
  726. int ret;
  727. if (module) {
  728. ret = atomic_dec_if_positive(&module->refcnt);
  729. WARN_ON(ret < 0); /* Failed to put refcount */
  730. trace_module_put(module, _RET_IP_);
  731. }
  732. }
  733. EXPORT_SYMBOL(module_put);
  734. #else /* !CONFIG_MODULE_UNLOAD */
  735. static inline void module_unload_free(struct module *mod)
  736. {
  737. }
  738. static int ref_module(struct module *a, struct module *b)
  739. {
  740. return strong_try_module_get(b);
  741. }
  742. static inline int module_unload_init(struct module *mod)
  743. {
  744. return 0;
  745. }
  746. #endif /* CONFIG_MODULE_UNLOAD */
  747. size_t module_flags_taint(unsigned long taints, char *buf)
  748. {
  749. size_t l = 0;
  750. int i;
  751. for (i = 0; i < TAINT_FLAGS_COUNT; i++) {
  752. if (taint_flags[i].module && test_bit(i, &taints))
  753. buf[l++] = taint_flags[i].c_true;
  754. }
  755. return l;
  756. }
  757. static ssize_t show_initstate(struct module_attribute *mattr,
  758. struct module_kobject *mk, char *buffer)
  759. {
  760. const char *state = "unknown";
  761. switch (mk->mod->state) {
  762. case MODULE_STATE_LIVE:
  763. state = "live";
  764. break;
  765. case MODULE_STATE_COMING:
  766. state = "coming";
  767. break;
  768. case MODULE_STATE_GOING:
  769. state = "going";
  770. break;
  771. default:
  772. BUG();
  773. }
  774. return sprintf(buffer, "%s\n", state);
  775. }
  776. static struct module_attribute modinfo_initstate =
  777. __ATTR(initstate, 0444, show_initstate, NULL);
  778. static ssize_t store_uevent(struct module_attribute *mattr,
  779. struct module_kobject *mk,
  780. const char *buffer, size_t count)
  781. {
  782. int rc;
  783. rc = kobject_synth_uevent(&mk->kobj, buffer, count);
  784. return rc ? rc : count;
  785. }
  786. struct module_attribute module_uevent =
  787. __ATTR(uevent, 0200, NULL, store_uevent);
  788. static ssize_t show_coresize(struct module_attribute *mattr,
  789. struct module_kobject *mk, char *buffer)
  790. {
  791. unsigned int size = mk->mod->mem[MOD_TEXT].size;
  792. if (!IS_ENABLED(CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC)) {
  793. for_class_mod_mem_type(type, core_data)
  794. size += mk->mod->mem[type].size;
  795. }
  796. return sprintf(buffer, "%u\n", size);
  797. }
  798. static struct module_attribute modinfo_coresize =
  799. __ATTR(coresize, 0444, show_coresize, NULL);
  800. #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
  801. static ssize_t show_datasize(struct module_attribute *mattr,
  802. struct module_kobject *mk, char *buffer)
  803. {
  804. unsigned int size = 0;
  805. for_class_mod_mem_type(type, core_data)
  806. size += mk->mod->mem[type].size;
  807. return sprintf(buffer, "%u\n", size);
  808. }
  809. static struct module_attribute modinfo_datasize =
  810. __ATTR(datasize, 0444, show_datasize, NULL);
  811. #endif
  812. static ssize_t show_initsize(struct module_attribute *mattr,
  813. struct module_kobject *mk, char *buffer)
  814. {
  815. unsigned int size = 0;
  816. for_class_mod_mem_type(type, init)
  817. size += mk->mod->mem[type].size;
  818. return sprintf(buffer, "%u\n", size);
  819. }
  820. static struct module_attribute modinfo_initsize =
  821. __ATTR(initsize, 0444, show_initsize, NULL);
  822. static ssize_t show_taint(struct module_attribute *mattr,
  823. struct module_kobject *mk, char *buffer)
  824. {
  825. size_t l;
  826. l = module_flags_taint(mk->mod->taints, buffer);
  827. buffer[l++] = '\n';
  828. return l;
  829. }
  830. static struct module_attribute modinfo_taint =
  831. __ATTR(taint, 0444, show_taint, NULL);
  832. struct module_attribute *modinfo_attrs[] = {
  833. &module_uevent,
  834. &modinfo_version,
  835. &modinfo_srcversion,
  836. &modinfo_initstate,
  837. &modinfo_coresize,
  838. #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
  839. &modinfo_datasize,
  840. #endif
  841. &modinfo_initsize,
  842. &modinfo_taint,
  843. #ifdef CONFIG_MODULE_UNLOAD
  844. &modinfo_refcnt,
  845. #endif
  846. NULL,
  847. };
  848. size_t modinfo_attrs_count = ARRAY_SIZE(modinfo_attrs);
  849. static const char vermagic[] = VERMAGIC_STRING;
  850. int try_to_force_load(struct module *mod, const char *reason)
  851. {
  852. #ifdef CONFIG_MODULE_FORCE_LOAD
  853. if (!test_taint(TAINT_FORCED_MODULE))
  854. pr_warn("%s: %s: kernel tainted.\n", mod->name, reason);
  855. add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_NOW_UNRELIABLE);
  856. return 0;
  857. #else
  858. return -ENOEXEC;
  859. #endif
  860. }
  861. /* Parse tag=value strings from .modinfo section */
  862. char *module_next_tag_pair(char *string, unsigned long *secsize)
  863. {
  864. /* Skip non-zero chars */
  865. while (string[0]) {
  866. string++;
  867. if ((*secsize)-- <= 1)
  868. return NULL;
  869. }
  870. /* Skip any zero padding. */
  871. while (!string[0]) {
  872. string++;
  873. if ((*secsize)-- <= 1)
  874. return NULL;
  875. }
  876. return string;
  877. }
  878. static char *get_next_modinfo(const struct load_info *info, const char *tag,
  879. char *prev)
  880. {
  881. char *p;
  882. unsigned int taglen = strlen(tag);
  883. Elf_Shdr *infosec = &info->sechdrs[info->index.info];
  884. unsigned long size = infosec->sh_size;
  885. /*
  886. * get_modinfo() calls made before rewrite_section_headers()
  887. * must use sh_offset, as sh_addr isn't set!
  888. */
  889. char *modinfo = (char *)info->hdr + infosec->sh_offset;
  890. if (prev) {
  891. size -= prev - modinfo;
  892. modinfo = module_next_tag_pair(prev, &size);
  893. }
  894. for (p = modinfo; p; p = module_next_tag_pair(p, &size)) {
  895. if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
  896. return p + taglen + 1;
  897. }
  898. return NULL;
  899. }
  900. static char *get_modinfo(const struct load_info *info, const char *tag)
  901. {
  902. return get_next_modinfo(info, tag, NULL);
  903. }
  904. static int verify_namespace_is_imported(const struct load_info *info,
  905. const struct kernel_symbol *sym,
  906. struct module *mod)
  907. {
  908. const char *namespace;
  909. char *imported_namespace;
  910. namespace = kernel_symbol_namespace(sym);
  911. if (namespace && namespace[0]) {
  912. for_each_modinfo_entry(imported_namespace, info, "import_ns") {
  913. if (strcmp(namespace, imported_namespace) == 0)
  914. return 0;
  915. }
  916. #ifdef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
  917. pr_warn(
  918. #else
  919. pr_err(
  920. #endif
  921. "%s: module uses symbol (%s) from namespace %s, but does not import it.\n",
  922. mod->name, kernel_symbol_name(sym), namespace);
  923. #ifndef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
  924. return -EINVAL;
  925. #endif
  926. }
  927. return 0;
  928. }
  929. static bool inherit_taint(struct module *mod, struct module *owner, const char *name)
  930. {
  931. if (!owner || !test_bit(TAINT_PROPRIETARY_MODULE, &owner->taints))
  932. return true;
  933. if (mod->using_gplonly_symbols) {
  934. pr_err("%s: module using GPL-only symbols uses symbols %s from proprietary module %s.\n",
  935. mod->name, name, owner->name);
  936. return false;
  937. }
  938. if (!test_bit(TAINT_PROPRIETARY_MODULE, &mod->taints)) {
  939. pr_warn("%s: module uses symbols %s from proprietary module %s, inheriting taint.\n",
  940. mod->name, name, owner->name);
  941. set_bit(TAINT_PROPRIETARY_MODULE, &mod->taints);
  942. }
  943. return true;
  944. }
  945. /* Resolve a symbol for this module. I.e. if we find one, record usage. */
  946. static const struct kernel_symbol *resolve_symbol(struct module *mod,
  947. const struct load_info *info,
  948. const char *name,
  949. char ownername[])
  950. {
  951. struct find_symbol_arg fsa = {
  952. .name = name,
  953. .gplok = !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)),
  954. .warn = true,
  955. };
  956. int err;
  957. /*
  958. * The module_mutex should not be a heavily contended lock;
  959. * if we get the occasional sleep here, we'll go an extra iteration
  960. * in the wait_event_interruptible(), which is harmless.
  961. */
  962. sched_annotate_sleep();
  963. mutex_lock(&module_mutex);
  964. if (!find_symbol(&fsa))
  965. goto unlock;
  966. if (fsa.license == GPL_ONLY)
  967. mod->using_gplonly_symbols = true;
  968. if (!inherit_taint(mod, fsa.owner, name)) {
  969. fsa.sym = NULL;
  970. goto getname;
  971. }
  972. if (!check_version(info, name, mod, fsa.crc)) {
  973. fsa.sym = ERR_PTR(-EINVAL);
  974. goto getname;
  975. }
  976. err = verify_namespace_is_imported(info, fsa.sym, mod);
  977. if (err) {
  978. fsa.sym = ERR_PTR(err);
  979. goto getname;
  980. }
  981. err = ref_module(mod, fsa.owner);
  982. if (err) {
  983. fsa.sym = ERR_PTR(err);
  984. goto getname;
  985. }
  986. getname:
  987. /* We must make copy under the lock if we failed to get ref. */
  988. strncpy(ownername, module_name(fsa.owner), MODULE_NAME_LEN);
  989. unlock:
  990. mutex_unlock(&module_mutex);
  991. return fsa.sym;
  992. }
  993. static const struct kernel_symbol *
  994. resolve_symbol_wait(struct module *mod,
  995. const struct load_info *info,
  996. const char *name)
  997. {
  998. const struct kernel_symbol *ksym;
  999. char owner[MODULE_NAME_LEN];
  1000. if (wait_event_interruptible_timeout(module_wq,
  1001. !IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
  1002. || PTR_ERR(ksym) != -EBUSY,
  1003. 30 * HZ) <= 0) {
  1004. pr_warn("%s: gave up waiting for init of module %s.\n",
  1005. mod->name, owner);
  1006. }
  1007. return ksym;
  1008. }
  1009. void __weak module_arch_cleanup(struct module *mod)
  1010. {
  1011. }
  1012. void __weak module_arch_freeing_init(struct module *mod)
  1013. {
  1014. }
  1015. static int module_memory_alloc(struct module *mod, enum mod_mem_type type)
  1016. {
  1017. unsigned int size = PAGE_ALIGN(mod->mem[type].size);
  1018. enum execmem_type execmem_type;
  1019. void *ptr;
  1020. mod->mem[type].size = size;
  1021. if (mod_mem_type_is_data(type))
  1022. execmem_type = EXECMEM_MODULE_DATA;
  1023. else
  1024. execmem_type = EXECMEM_MODULE_TEXT;
  1025. ptr = execmem_alloc(execmem_type, size);
  1026. if (!ptr)
  1027. return -ENOMEM;
  1028. /*
  1029. * The pointer to these blocks of memory are stored on the module
  1030. * structure and we keep that around so long as the module is
  1031. * around. We only free that memory when we unload the module.
  1032. * Just mark them as not being a leak then. The .init* ELF
  1033. * sections *do* get freed after boot so we *could* treat them
  1034. * slightly differently with kmemleak_ignore() and only grey
  1035. * them out as they work as typical memory allocations which
  1036. * *do* eventually get freed, but let's just keep things simple
  1037. * and avoid *any* false positives.
  1038. */
  1039. kmemleak_not_leak(ptr);
  1040. memset(ptr, 0, size);
  1041. mod->mem[type].base = ptr;
  1042. return 0;
  1043. }
  1044. static void module_memory_free(struct module *mod, enum mod_mem_type type,
  1045. bool unload_codetags)
  1046. {
  1047. void *ptr = mod->mem[type].base;
  1048. if (!unload_codetags && mod_mem_type_is_core_data(type))
  1049. return;
  1050. execmem_free(ptr);
  1051. }
  1052. static void free_mod_mem(struct module *mod, bool unload_codetags)
  1053. {
  1054. for_each_mod_mem_type(type) {
  1055. struct module_memory *mod_mem = &mod->mem[type];
  1056. if (type == MOD_DATA)
  1057. continue;
  1058. /* Free lock-classes; relies on the preceding sync_rcu(). */
  1059. lockdep_free_key_range(mod_mem->base, mod_mem->size);
  1060. if (mod_mem->size)
  1061. module_memory_free(mod, type, unload_codetags);
  1062. }
  1063. /* MOD_DATA hosts mod, so free it at last */
  1064. lockdep_free_key_range(mod->mem[MOD_DATA].base, mod->mem[MOD_DATA].size);
  1065. module_memory_free(mod, MOD_DATA, unload_codetags);
  1066. }
  1067. /* Free a module, remove from lists, etc. */
  1068. static void free_module(struct module *mod)
  1069. {
  1070. bool unload_codetags;
  1071. trace_module_free(mod);
  1072. unload_codetags = codetag_unload_module(mod);
  1073. if (!unload_codetags)
  1074. pr_warn("%s: memory allocation(s) from the module still alive, cannot unload cleanly\n",
  1075. mod->name);
  1076. mod_sysfs_teardown(mod);
  1077. /*
  1078. * We leave it in list to prevent duplicate loads, but make sure
  1079. * that noone uses it while it's being deconstructed.
  1080. */
  1081. mutex_lock(&module_mutex);
  1082. mod->state = MODULE_STATE_UNFORMED;
  1083. mutex_unlock(&module_mutex);
  1084. /* Arch-specific cleanup. */
  1085. module_arch_cleanup(mod);
  1086. /* Module unload stuff */
  1087. module_unload_free(mod);
  1088. /* Free any allocated parameters. */
  1089. destroy_params(mod->kp, mod->num_kp);
  1090. if (is_livepatch_module(mod))
  1091. free_module_elf(mod);
  1092. /* Now we can delete it from the lists */
  1093. mutex_lock(&module_mutex);
  1094. /* Unlink carefully: kallsyms could be walking list. */
  1095. list_del_rcu(&mod->list);
  1096. mod_tree_remove(mod);
  1097. /* Remove this module from bug list, this uses list_del_rcu */
  1098. module_bug_cleanup(mod);
  1099. /* Wait for RCU-sched synchronizing before releasing mod->list and buglist. */
  1100. synchronize_rcu();
  1101. if (try_add_tainted_module(mod))
  1102. pr_err("%s: adding tainted module to the unloaded tainted modules list failed.\n",
  1103. mod->name);
  1104. mutex_unlock(&module_mutex);
  1105. /* This may be empty, but that's OK */
  1106. module_arch_freeing_init(mod);
  1107. kfree(mod->args);
  1108. percpu_modfree(mod);
  1109. free_mod_mem(mod, unload_codetags);
  1110. }
  1111. void *__symbol_get(const char *symbol)
  1112. {
  1113. struct find_symbol_arg fsa = {
  1114. .name = symbol,
  1115. .gplok = true,
  1116. .warn = true,
  1117. };
  1118. preempt_disable();
  1119. if (!find_symbol(&fsa))
  1120. goto fail;
  1121. if (fsa.license != GPL_ONLY) {
  1122. pr_warn("failing symbol_get of non-GPLONLY symbol %s.\n",
  1123. symbol);
  1124. goto fail;
  1125. }
  1126. if (strong_try_module_get(fsa.owner))
  1127. goto fail;
  1128. preempt_enable();
  1129. return (void *)kernel_symbol_value(fsa.sym);
  1130. fail:
  1131. preempt_enable();
  1132. return NULL;
  1133. }
  1134. EXPORT_SYMBOL_GPL(__symbol_get);
  1135. /*
  1136. * Ensure that an exported symbol [global namespace] does not already exist
  1137. * in the kernel or in some other module's exported symbol table.
  1138. *
  1139. * You must hold the module_mutex.
  1140. */
  1141. static int verify_exported_symbols(struct module *mod)
  1142. {
  1143. unsigned int i;
  1144. const struct kernel_symbol *s;
  1145. struct {
  1146. const struct kernel_symbol *sym;
  1147. unsigned int num;
  1148. } arr[] = {
  1149. { mod->syms, mod->num_syms },
  1150. { mod->gpl_syms, mod->num_gpl_syms },
  1151. };
  1152. for (i = 0; i < ARRAY_SIZE(arr); i++) {
  1153. for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
  1154. struct find_symbol_arg fsa = {
  1155. .name = kernel_symbol_name(s),
  1156. .gplok = true,
  1157. };
  1158. if (find_symbol(&fsa)) {
  1159. pr_err("%s: exports duplicate symbol %s"
  1160. " (owned by %s)\n",
  1161. mod->name, kernel_symbol_name(s),
  1162. module_name(fsa.owner));
  1163. return -ENOEXEC;
  1164. }
  1165. }
  1166. }
  1167. return 0;
  1168. }
  1169. static bool ignore_undef_symbol(Elf_Half emachine, const char *name)
  1170. {
  1171. /*
  1172. * On x86, PIC code and Clang non-PIC code may have call foo@PLT. GNU as
  1173. * before 2.37 produces an unreferenced _GLOBAL_OFFSET_TABLE_ on x86-64.
  1174. * i386 has a similar problem but may not deserve a fix.
  1175. *
  1176. * If we ever have to ignore many symbols, consider refactoring the code to
  1177. * only warn if referenced by a relocation.
  1178. */
  1179. if (emachine == EM_386 || emachine == EM_X86_64)
  1180. return !strcmp(name, "_GLOBAL_OFFSET_TABLE_");
  1181. return false;
  1182. }
  1183. /* Change all symbols so that st_value encodes the pointer directly. */
  1184. static int simplify_symbols(struct module *mod, const struct load_info *info)
  1185. {
  1186. Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
  1187. Elf_Sym *sym = (void *)symsec->sh_addr;
  1188. unsigned long secbase;
  1189. unsigned int i;
  1190. int ret = 0;
  1191. const struct kernel_symbol *ksym;
  1192. for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
  1193. const char *name = info->strtab + sym[i].st_name;
  1194. switch (sym[i].st_shndx) {
  1195. case SHN_COMMON:
  1196. /* Ignore common symbols */
  1197. if (!strncmp(name, "__gnu_lto", 9))
  1198. break;
  1199. /*
  1200. * We compiled with -fno-common. These are not
  1201. * supposed to happen.
  1202. */
  1203. pr_debug("Common symbol: %s\n", name);
  1204. pr_warn("%s: please compile with -fno-common\n",
  1205. mod->name);
  1206. ret = -ENOEXEC;
  1207. break;
  1208. case SHN_ABS:
  1209. /* Don't need to do anything */
  1210. pr_debug("Absolute symbol: 0x%08lx %s\n",
  1211. (long)sym[i].st_value, name);
  1212. break;
  1213. case SHN_LIVEPATCH:
  1214. /* Livepatch symbols are resolved by livepatch */
  1215. break;
  1216. case SHN_UNDEF:
  1217. ksym = resolve_symbol_wait(mod, info, name);
  1218. /* Ok if resolved. */
  1219. if (ksym && !IS_ERR(ksym)) {
  1220. sym[i].st_value = kernel_symbol_value(ksym);
  1221. break;
  1222. }
  1223. /* Ok if weak or ignored. */
  1224. if (!ksym &&
  1225. (ELF_ST_BIND(sym[i].st_info) == STB_WEAK ||
  1226. ignore_undef_symbol(info->hdr->e_machine, name)))
  1227. break;
  1228. ret = PTR_ERR(ksym) ?: -ENOENT;
  1229. pr_warn("%s: Unknown symbol %s (err %d)\n",
  1230. mod->name, name, ret);
  1231. break;
  1232. default:
  1233. /* Divert to percpu allocation if a percpu var. */
  1234. if (sym[i].st_shndx == info->index.pcpu)
  1235. secbase = (unsigned long)mod_percpu(mod);
  1236. else
  1237. secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
  1238. sym[i].st_value += secbase;
  1239. break;
  1240. }
  1241. }
  1242. return ret;
  1243. }
  1244. static int apply_relocations(struct module *mod, const struct load_info *info)
  1245. {
  1246. unsigned int i;
  1247. int err = 0;
  1248. /* Now do relocations. */
  1249. for (i = 1; i < info->hdr->e_shnum; i++) {
  1250. unsigned int infosec = info->sechdrs[i].sh_info;
  1251. /* Not a valid relocation section? */
  1252. if (infosec >= info->hdr->e_shnum)
  1253. continue;
  1254. /* Don't bother with non-allocated sections */
  1255. if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
  1256. continue;
  1257. if (info->sechdrs[i].sh_flags & SHF_RELA_LIVEPATCH)
  1258. err = klp_apply_section_relocs(mod, info->sechdrs,
  1259. info->secstrings,
  1260. info->strtab,
  1261. info->index.sym, i,
  1262. NULL);
  1263. else if (info->sechdrs[i].sh_type == SHT_REL)
  1264. err = apply_relocate(info->sechdrs, info->strtab,
  1265. info->index.sym, i, mod);
  1266. else if (info->sechdrs[i].sh_type == SHT_RELA)
  1267. err = apply_relocate_add(info->sechdrs, info->strtab,
  1268. info->index.sym, i, mod);
  1269. if (err < 0)
  1270. break;
  1271. }
  1272. return err;
  1273. }
  1274. /* Additional bytes needed by arch in front of individual sections */
  1275. unsigned int __weak arch_mod_section_prepend(struct module *mod,
  1276. unsigned int section)
  1277. {
  1278. /* default implementation just returns zero */
  1279. return 0;
  1280. }
  1281. long module_get_offset_and_type(struct module *mod, enum mod_mem_type type,
  1282. Elf_Shdr *sechdr, unsigned int section)
  1283. {
  1284. long offset;
  1285. long mask = ((unsigned long)(type) & SH_ENTSIZE_TYPE_MASK) << SH_ENTSIZE_TYPE_SHIFT;
  1286. mod->mem[type].size += arch_mod_section_prepend(mod, section);
  1287. offset = ALIGN(mod->mem[type].size, sechdr->sh_addralign ?: 1);
  1288. mod->mem[type].size = offset + sechdr->sh_size;
  1289. WARN_ON_ONCE(offset & mask);
  1290. return offset | mask;
  1291. }
  1292. bool module_init_layout_section(const char *sname)
  1293. {
  1294. #ifndef CONFIG_MODULE_UNLOAD
  1295. if (module_exit_section(sname))
  1296. return true;
  1297. #endif
  1298. return module_init_section(sname);
  1299. }
  1300. static void __layout_sections(struct module *mod, struct load_info *info, bool is_init)
  1301. {
  1302. unsigned int m, i;
  1303. static const unsigned long masks[][2] = {
  1304. /*
  1305. * NOTE: all executable code must be the first section
  1306. * in this array; otherwise modify the text_size
  1307. * finder in the two loops below
  1308. */
  1309. { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
  1310. { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
  1311. { SHF_RO_AFTER_INIT | SHF_ALLOC, ARCH_SHF_SMALL },
  1312. { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
  1313. { ARCH_SHF_SMALL | SHF_ALLOC, 0 }
  1314. };
  1315. static const int core_m_to_mem_type[] = {
  1316. MOD_TEXT,
  1317. MOD_RODATA,
  1318. MOD_RO_AFTER_INIT,
  1319. MOD_DATA,
  1320. MOD_DATA,
  1321. };
  1322. static const int init_m_to_mem_type[] = {
  1323. MOD_INIT_TEXT,
  1324. MOD_INIT_RODATA,
  1325. MOD_INVALID,
  1326. MOD_INIT_DATA,
  1327. MOD_INIT_DATA,
  1328. };
  1329. for (m = 0; m < ARRAY_SIZE(masks); ++m) {
  1330. enum mod_mem_type type = is_init ? init_m_to_mem_type[m] : core_m_to_mem_type[m];
  1331. for (i = 0; i < info->hdr->e_shnum; ++i) {
  1332. Elf_Shdr *s = &info->sechdrs[i];
  1333. const char *sname = info->secstrings + s->sh_name;
  1334. if ((s->sh_flags & masks[m][0]) != masks[m][0]
  1335. || (s->sh_flags & masks[m][1])
  1336. || s->sh_entsize != ~0UL
  1337. || is_init != module_init_layout_section(sname))
  1338. continue;
  1339. if (WARN_ON_ONCE(type == MOD_INVALID))
  1340. continue;
  1341. s->sh_entsize = module_get_offset_and_type(mod, type, s, i);
  1342. pr_debug("\t%s\n", sname);
  1343. }
  1344. }
  1345. }
  1346. /*
  1347. * Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
  1348. * might -- code, read-only data, read-write data, small data. Tally
  1349. * sizes, and place the offsets into sh_entsize fields: high bit means it
  1350. * belongs in init.
  1351. */
  1352. static void layout_sections(struct module *mod, struct load_info *info)
  1353. {
  1354. unsigned int i;
  1355. for (i = 0; i < info->hdr->e_shnum; i++)
  1356. info->sechdrs[i].sh_entsize = ~0UL;
  1357. pr_debug("Core section allocation order for %s:\n", mod->name);
  1358. __layout_sections(mod, info, false);
  1359. pr_debug("Init section allocation order for %s:\n", mod->name);
  1360. __layout_sections(mod, info, true);
  1361. }
  1362. static void module_license_taint_check(struct module *mod, const char *license)
  1363. {
  1364. if (!license)
  1365. license = "unspecified";
  1366. if (!license_is_gpl_compatible(license)) {
  1367. if (!test_taint(TAINT_PROPRIETARY_MODULE))
  1368. pr_warn("%s: module license '%s' taints kernel.\n",
  1369. mod->name, license);
  1370. add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
  1371. LOCKDEP_NOW_UNRELIABLE);
  1372. }
  1373. }
  1374. static void setup_modinfo(struct module *mod, struct load_info *info)
  1375. {
  1376. struct module_attribute *attr;
  1377. int i;
  1378. for (i = 0; (attr = modinfo_attrs[i]); i++) {
  1379. if (attr->setup)
  1380. attr->setup(mod, get_modinfo(info, attr->attr.name));
  1381. }
  1382. }
  1383. static void free_modinfo(struct module *mod)
  1384. {
  1385. struct module_attribute *attr;
  1386. int i;
  1387. for (i = 0; (attr = modinfo_attrs[i]); i++) {
  1388. if (attr->free)
  1389. attr->free(mod);
  1390. }
  1391. }
  1392. bool __weak module_init_section(const char *name)
  1393. {
  1394. return strstarts(name, ".init");
  1395. }
  1396. bool __weak module_exit_section(const char *name)
  1397. {
  1398. return strstarts(name, ".exit");
  1399. }
  1400. static int validate_section_offset(struct load_info *info, Elf_Shdr *shdr)
  1401. {
  1402. #if defined(CONFIG_64BIT)
  1403. unsigned long long secend;
  1404. #else
  1405. unsigned long secend;
  1406. #endif
  1407. /*
  1408. * Check for both overflow and offset/size being
  1409. * too large.
  1410. */
  1411. secend = shdr->sh_offset + shdr->sh_size;
  1412. if (secend < shdr->sh_offset || secend > info->len)
  1413. return -ENOEXEC;
  1414. return 0;
  1415. }
  1416. /*
  1417. * Check userspace passed ELF module against our expectations, and cache
  1418. * useful variables for further processing as we go.
  1419. *
  1420. * This does basic validity checks against section offsets and sizes, the
  1421. * section name string table, and the indices used for it (sh_name).
  1422. *
  1423. * As a last step, since we're already checking the ELF sections we cache
  1424. * useful variables which will be used later for our convenience:
  1425. *
  1426. * o pointers to section headers
  1427. * o cache the modinfo symbol section
  1428. * o cache the string symbol section
  1429. * o cache the module section
  1430. *
  1431. * As a last step we set info->mod to the temporary copy of the module in
  1432. * info->hdr. The final one will be allocated in move_module(). Any
  1433. * modifications we make to our copy of the module will be carried over
  1434. * to the final minted module.
  1435. */
  1436. static int elf_validity_cache_copy(struct load_info *info, int flags)
  1437. {
  1438. unsigned int i;
  1439. Elf_Shdr *shdr, *strhdr;
  1440. int err;
  1441. unsigned int num_mod_secs = 0, mod_idx;
  1442. unsigned int num_info_secs = 0, info_idx;
  1443. unsigned int num_sym_secs = 0, sym_idx;
  1444. if (info->len < sizeof(*(info->hdr))) {
  1445. pr_err("Invalid ELF header len %lu\n", info->len);
  1446. goto no_exec;
  1447. }
  1448. if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0) {
  1449. pr_err("Invalid ELF header magic: != %s\n", ELFMAG);
  1450. goto no_exec;
  1451. }
  1452. if (info->hdr->e_type != ET_REL) {
  1453. pr_err("Invalid ELF header type: %u != %u\n",
  1454. info->hdr->e_type, ET_REL);
  1455. goto no_exec;
  1456. }
  1457. if (!elf_check_arch(info->hdr)) {
  1458. pr_err("Invalid architecture in ELF header: %u\n",
  1459. info->hdr->e_machine);
  1460. goto no_exec;
  1461. }
  1462. if (!module_elf_check_arch(info->hdr)) {
  1463. pr_err("Invalid module architecture in ELF header: %u\n",
  1464. info->hdr->e_machine);
  1465. goto no_exec;
  1466. }
  1467. if (info->hdr->e_shentsize != sizeof(Elf_Shdr)) {
  1468. pr_err("Invalid ELF section header size\n");
  1469. goto no_exec;
  1470. }
  1471. /*
  1472. * e_shnum is 16 bits, and sizeof(Elf_Shdr) is
  1473. * known and small. So e_shnum * sizeof(Elf_Shdr)
  1474. * will not overflow unsigned long on any platform.
  1475. */
  1476. if (info->hdr->e_shoff >= info->len
  1477. || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
  1478. info->len - info->hdr->e_shoff)) {
  1479. pr_err("Invalid ELF section header overflow\n");
  1480. goto no_exec;
  1481. }
  1482. info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
  1483. /*
  1484. * Verify if the section name table index is valid.
  1485. */
  1486. if (info->hdr->e_shstrndx == SHN_UNDEF
  1487. || info->hdr->e_shstrndx >= info->hdr->e_shnum) {
  1488. pr_err("Invalid ELF section name index: %d || e_shstrndx (%d) >= e_shnum (%d)\n",
  1489. info->hdr->e_shstrndx, info->hdr->e_shstrndx,
  1490. info->hdr->e_shnum);
  1491. goto no_exec;
  1492. }
  1493. strhdr = &info->sechdrs[info->hdr->e_shstrndx];
  1494. err = validate_section_offset(info, strhdr);
  1495. if (err < 0) {
  1496. pr_err("Invalid ELF section hdr(type %u)\n", strhdr->sh_type);
  1497. return err;
  1498. }
  1499. /*
  1500. * The section name table must be NUL-terminated, as required
  1501. * by the spec. This makes strcmp and pr_* calls that access
  1502. * strings in the section safe.
  1503. */
  1504. info->secstrings = (void *)info->hdr + strhdr->sh_offset;
  1505. if (strhdr->sh_size == 0) {
  1506. pr_err("empty section name table\n");
  1507. goto no_exec;
  1508. }
  1509. if (info->secstrings[strhdr->sh_size - 1] != '\0') {
  1510. pr_err("ELF Spec violation: section name table isn't null terminated\n");
  1511. goto no_exec;
  1512. }
  1513. /*
  1514. * The code assumes that section 0 has a length of zero and
  1515. * an addr of zero, so check for it.
  1516. */
  1517. if (info->sechdrs[0].sh_type != SHT_NULL
  1518. || info->sechdrs[0].sh_size != 0
  1519. || info->sechdrs[0].sh_addr != 0) {
  1520. pr_err("ELF Spec violation: section 0 type(%d)!=SH_NULL or non-zero len or addr\n",
  1521. info->sechdrs[0].sh_type);
  1522. goto no_exec;
  1523. }
  1524. for (i = 1; i < info->hdr->e_shnum; i++) {
  1525. shdr = &info->sechdrs[i];
  1526. switch (shdr->sh_type) {
  1527. case SHT_NULL:
  1528. case SHT_NOBITS:
  1529. continue;
  1530. case SHT_SYMTAB:
  1531. if (shdr->sh_link == SHN_UNDEF
  1532. || shdr->sh_link >= info->hdr->e_shnum) {
  1533. pr_err("Invalid ELF sh_link!=SHN_UNDEF(%d) or (sh_link(%d) >= hdr->e_shnum(%d)\n",
  1534. shdr->sh_link, shdr->sh_link,
  1535. info->hdr->e_shnum);
  1536. goto no_exec;
  1537. }
  1538. num_sym_secs++;
  1539. sym_idx = i;
  1540. fallthrough;
  1541. default:
  1542. err = validate_section_offset(info, shdr);
  1543. if (err < 0) {
  1544. pr_err("Invalid ELF section in module (section %u type %u)\n",
  1545. i, shdr->sh_type);
  1546. return err;
  1547. }
  1548. if (strcmp(info->secstrings + shdr->sh_name,
  1549. ".gnu.linkonce.this_module") == 0) {
  1550. num_mod_secs++;
  1551. mod_idx = i;
  1552. } else if (strcmp(info->secstrings + shdr->sh_name,
  1553. ".modinfo") == 0) {
  1554. num_info_secs++;
  1555. info_idx = i;
  1556. }
  1557. if (shdr->sh_flags & SHF_ALLOC) {
  1558. if (shdr->sh_name >= strhdr->sh_size) {
  1559. pr_err("Invalid ELF section name in module (section %u type %u)\n",
  1560. i, shdr->sh_type);
  1561. return -ENOEXEC;
  1562. }
  1563. }
  1564. break;
  1565. }
  1566. }
  1567. if (num_info_secs > 1) {
  1568. pr_err("Only one .modinfo section must exist.\n");
  1569. goto no_exec;
  1570. } else if (num_info_secs == 1) {
  1571. /* Try to find a name early so we can log errors with a module name */
  1572. info->index.info = info_idx;
  1573. info->name = get_modinfo(info, "name");
  1574. }
  1575. if (num_sym_secs != 1) {
  1576. pr_warn("%s: module has no symbols (stripped?)\n",
  1577. info->name ?: "(missing .modinfo section or name field)");
  1578. goto no_exec;
  1579. }
  1580. /* Sets internal symbols and strings. */
  1581. info->index.sym = sym_idx;
  1582. shdr = &info->sechdrs[sym_idx];
  1583. info->index.str = shdr->sh_link;
  1584. info->strtab = (char *)info->hdr + info->sechdrs[info->index.str].sh_offset;
  1585. /*
  1586. * The ".gnu.linkonce.this_module" ELF section is special. It is
  1587. * what modpost uses to refer to __this_module and let's use rely
  1588. * on THIS_MODULE to point to &__this_module properly. The kernel's
  1589. * modpost declares it on each modules's *.mod.c file. If the struct
  1590. * module of the kernel changes a full kernel rebuild is required.
  1591. *
  1592. * We have a few expectaions for this special section, the following
  1593. * code validates all this for us:
  1594. *
  1595. * o Only one section must exist
  1596. * o We expect the kernel to always have to allocate it: SHF_ALLOC
  1597. * o The section size must match the kernel's run time's struct module
  1598. * size
  1599. */
  1600. if (num_mod_secs != 1) {
  1601. pr_err("module %s: Only one .gnu.linkonce.this_module section must exist.\n",
  1602. info->name ?: "(missing .modinfo section or name field)");
  1603. goto no_exec;
  1604. }
  1605. shdr = &info->sechdrs[mod_idx];
  1606. /*
  1607. * This is already implied on the switch above, however let's be
  1608. * pedantic about it.
  1609. */
  1610. if (shdr->sh_type == SHT_NOBITS) {
  1611. pr_err("module %s: .gnu.linkonce.this_module section must have a size set\n",
  1612. info->name ?: "(missing .modinfo section or name field)");
  1613. goto no_exec;
  1614. }
  1615. if (!(shdr->sh_flags & SHF_ALLOC)) {
  1616. pr_err("module %s: .gnu.linkonce.this_module must occupy memory during process execution\n",
  1617. info->name ?: "(missing .modinfo section or name field)");
  1618. goto no_exec;
  1619. }
  1620. if (shdr->sh_size != sizeof(struct module)) {
  1621. pr_err("module %s: .gnu.linkonce.this_module section size must match the kernel's built struct module size at run time\n",
  1622. info->name ?: "(missing .modinfo section or name field)");
  1623. goto no_exec;
  1624. }
  1625. info->index.mod = mod_idx;
  1626. /* This is temporary: point mod into copy of data. */
  1627. info->mod = (void *)info->hdr + shdr->sh_offset;
  1628. /*
  1629. * If we didn't load the .modinfo 'name' field earlier, fall back to
  1630. * on-disk struct mod 'name' field.
  1631. */
  1632. if (!info->name)
  1633. info->name = info->mod->name;
  1634. if (flags & MODULE_INIT_IGNORE_MODVERSIONS)
  1635. info->index.vers = 0; /* Pretend no __versions section! */
  1636. else
  1637. info->index.vers = find_sec(info, "__versions");
  1638. info->index.pcpu = find_pcpusec(info);
  1639. return 0;
  1640. no_exec:
  1641. return -ENOEXEC;
  1642. }
  1643. #define COPY_CHUNK_SIZE (16*PAGE_SIZE)
  1644. static int copy_chunked_from_user(void *dst, const void __user *usrc, unsigned long len)
  1645. {
  1646. do {
  1647. unsigned long n = min(len, COPY_CHUNK_SIZE);
  1648. if (copy_from_user(dst, usrc, n) != 0)
  1649. return -EFAULT;
  1650. cond_resched();
  1651. dst += n;
  1652. usrc += n;
  1653. len -= n;
  1654. } while (len);
  1655. return 0;
  1656. }
  1657. static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
  1658. {
  1659. if (!get_modinfo(info, "livepatch"))
  1660. /* Nothing more to do */
  1661. return 0;
  1662. if (set_livepatch_module(mod))
  1663. return 0;
  1664. pr_err("%s: module is marked as livepatch module, but livepatch support is disabled",
  1665. mod->name);
  1666. return -ENOEXEC;
  1667. }
  1668. static void check_modinfo_retpoline(struct module *mod, struct load_info *info)
  1669. {
  1670. if (retpoline_module_ok(get_modinfo(info, "retpoline")))
  1671. return;
  1672. pr_warn("%s: loading module not compiled with retpoline compiler.\n",
  1673. mod->name);
  1674. }
  1675. /* Sets info->hdr and info->len. */
  1676. static int copy_module_from_user(const void __user *umod, unsigned long len,
  1677. struct load_info *info)
  1678. {
  1679. int err;
  1680. info->len = len;
  1681. if (info->len < sizeof(*(info->hdr)))
  1682. return -ENOEXEC;
  1683. err = security_kernel_load_data(LOADING_MODULE, true);
  1684. if (err)
  1685. return err;
  1686. /* Suck in entire file: we'll want most of it. */
  1687. info->hdr = __vmalloc(info->len, GFP_KERNEL | __GFP_NOWARN);
  1688. if (!info->hdr)
  1689. return -ENOMEM;
  1690. if (copy_chunked_from_user(info->hdr, umod, info->len) != 0) {
  1691. err = -EFAULT;
  1692. goto out;
  1693. }
  1694. err = security_kernel_post_load_data((char *)info->hdr, info->len,
  1695. LOADING_MODULE, "init_module");
  1696. out:
  1697. if (err)
  1698. vfree(info->hdr);
  1699. return err;
  1700. }
  1701. static void free_copy(struct load_info *info, int flags)
  1702. {
  1703. if (flags & MODULE_INIT_COMPRESSED_FILE)
  1704. module_decompress_cleanup(info);
  1705. else
  1706. vfree(info->hdr);
  1707. }
  1708. static int rewrite_section_headers(struct load_info *info, int flags)
  1709. {
  1710. unsigned int i;
  1711. /* This should always be true, but let's be sure. */
  1712. info->sechdrs[0].sh_addr = 0;
  1713. for (i = 1; i < info->hdr->e_shnum; i++) {
  1714. Elf_Shdr *shdr = &info->sechdrs[i];
  1715. /*
  1716. * Mark all sections sh_addr with their address in the
  1717. * temporary image.
  1718. */
  1719. shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
  1720. }
  1721. /* Track but don't keep modinfo and version sections. */
  1722. info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
  1723. info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
  1724. return 0;
  1725. }
  1726. /*
  1727. * These calls taint the kernel depending certain module circumstances */
  1728. static void module_augment_kernel_taints(struct module *mod, struct load_info *info)
  1729. {
  1730. int prev_taint = test_taint(TAINT_PROPRIETARY_MODULE);
  1731. if (!get_modinfo(info, "intree")) {
  1732. if (!test_taint(TAINT_OOT_MODULE))
  1733. pr_warn("%s: loading out-of-tree module taints kernel.\n",
  1734. mod->name);
  1735. add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
  1736. }
  1737. check_modinfo_retpoline(mod, info);
  1738. if (get_modinfo(info, "staging")) {
  1739. add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
  1740. pr_warn("%s: module is from the staging directory, the quality "
  1741. "is unknown, you have been warned.\n", mod->name);
  1742. }
  1743. if (is_livepatch_module(mod)) {
  1744. add_taint_module(mod, TAINT_LIVEPATCH, LOCKDEP_STILL_OK);
  1745. pr_notice_once("%s: tainting kernel with TAINT_LIVEPATCH\n",
  1746. mod->name);
  1747. }
  1748. module_license_taint_check(mod, get_modinfo(info, "license"));
  1749. if (get_modinfo(info, "test")) {
  1750. if (!test_taint(TAINT_TEST))
  1751. pr_warn("%s: loading test module taints kernel.\n",
  1752. mod->name);
  1753. add_taint_module(mod, TAINT_TEST, LOCKDEP_STILL_OK);
  1754. }
  1755. #ifdef CONFIG_MODULE_SIG
  1756. mod->sig_ok = info->sig_ok;
  1757. if (!mod->sig_ok) {
  1758. pr_notice_once("%s: module verification failed: signature "
  1759. "and/or required key missing - tainting "
  1760. "kernel\n", mod->name);
  1761. add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK);
  1762. }
  1763. #endif
  1764. /*
  1765. * ndiswrapper is under GPL by itself, but loads proprietary modules.
  1766. * Don't use add_taint_module(), as it would prevent ndiswrapper from
  1767. * using GPL-only symbols it needs.
  1768. */
  1769. if (strcmp(mod->name, "ndiswrapper") == 0)
  1770. add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
  1771. /* driverloader was caught wrongly pretending to be under GPL */
  1772. if (strcmp(mod->name, "driverloader") == 0)
  1773. add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
  1774. LOCKDEP_NOW_UNRELIABLE);
  1775. /* lve claims to be GPL but upstream won't provide source */
  1776. if (strcmp(mod->name, "lve") == 0)
  1777. add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
  1778. LOCKDEP_NOW_UNRELIABLE);
  1779. if (!prev_taint && test_taint(TAINT_PROPRIETARY_MODULE))
  1780. pr_warn("%s: module license taints kernel.\n", mod->name);
  1781. }
  1782. static int check_modinfo(struct module *mod, struct load_info *info, int flags)
  1783. {
  1784. const char *modmagic = get_modinfo(info, "vermagic");
  1785. int err;
  1786. if (flags & MODULE_INIT_IGNORE_VERMAGIC)
  1787. modmagic = NULL;
  1788. /* This is allowed: modprobe --force will invalidate it. */
  1789. if (!modmagic) {
  1790. err = try_to_force_load(mod, "bad vermagic");
  1791. if (err)
  1792. return err;
  1793. } else if (!same_magic(modmagic, vermagic, info->index.vers)) {
  1794. pr_err("%s: version magic '%s' should be '%s'\n",
  1795. info->name, modmagic, vermagic);
  1796. return -ENOEXEC;
  1797. }
  1798. err = check_modinfo_livepatch(mod, info);
  1799. if (err)
  1800. return err;
  1801. return 0;
  1802. }
  1803. static int find_module_sections(struct module *mod, struct load_info *info)
  1804. {
  1805. mod->kp = section_objs(info, "__param",
  1806. sizeof(*mod->kp), &mod->num_kp);
  1807. mod->syms = section_objs(info, "__ksymtab",
  1808. sizeof(*mod->syms), &mod->num_syms);
  1809. mod->crcs = section_addr(info, "__kcrctab");
  1810. mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
  1811. sizeof(*mod->gpl_syms),
  1812. &mod->num_gpl_syms);
  1813. mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
  1814. #ifdef CONFIG_CONSTRUCTORS
  1815. mod->ctors = section_objs(info, ".ctors",
  1816. sizeof(*mod->ctors), &mod->num_ctors);
  1817. if (!mod->ctors)
  1818. mod->ctors = section_objs(info, ".init_array",
  1819. sizeof(*mod->ctors), &mod->num_ctors);
  1820. else if (find_sec(info, ".init_array")) {
  1821. /*
  1822. * This shouldn't happen with same compiler and binutils
  1823. * building all parts of the module.
  1824. */
  1825. pr_warn("%s: has both .ctors and .init_array.\n",
  1826. mod->name);
  1827. return -EINVAL;
  1828. }
  1829. #endif
  1830. mod->noinstr_text_start = section_objs(info, ".noinstr.text", 1,
  1831. &mod->noinstr_text_size);
  1832. #ifdef CONFIG_TRACEPOINTS
  1833. mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
  1834. sizeof(*mod->tracepoints_ptrs),
  1835. &mod->num_tracepoints);
  1836. #endif
  1837. #ifdef CONFIG_TREE_SRCU
  1838. mod->srcu_struct_ptrs = section_objs(info, "___srcu_struct_ptrs",
  1839. sizeof(*mod->srcu_struct_ptrs),
  1840. &mod->num_srcu_structs);
  1841. #endif
  1842. #ifdef CONFIG_BPF_EVENTS
  1843. mod->bpf_raw_events = section_objs(info, "__bpf_raw_tp_map",
  1844. sizeof(*mod->bpf_raw_events),
  1845. &mod->num_bpf_raw_events);
  1846. #endif
  1847. #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
  1848. mod->btf_data = any_section_objs(info, ".BTF", 1, &mod->btf_data_size);
  1849. mod->btf_base_data = any_section_objs(info, ".BTF.base", 1,
  1850. &mod->btf_base_data_size);
  1851. #endif
  1852. #ifdef CONFIG_JUMP_LABEL
  1853. mod->jump_entries = section_objs(info, "__jump_table",
  1854. sizeof(*mod->jump_entries),
  1855. &mod->num_jump_entries);
  1856. #endif
  1857. #ifdef CONFIG_EVENT_TRACING
  1858. mod->trace_events = section_objs(info, "_ftrace_events",
  1859. sizeof(*mod->trace_events),
  1860. &mod->num_trace_events);
  1861. mod->trace_evals = section_objs(info, "_ftrace_eval_map",
  1862. sizeof(*mod->trace_evals),
  1863. &mod->num_trace_evals);
  1864. #endif
  1865. #ifdef CONFIG_TRACING
  1866. mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
  1867. sizeof(*mod->trace_bprintk_fmt_start),
  1868. &mod->num_trace_bprintk_fmt);
  1869. #endif
  1870. #ifdef CONFIG_FTRACE_MCOUNT_RECORD
  1871. /* sechdrs[0].sh_size is always zero */
  1872. mod->ftrace_callsites = section_objs(info, FTRACE_CALLSITE_SECTION,
  1873. sizeof(*mod->ftrace_callsites),
  1874. &mod->num_ftrace_callsites);
  1875. #endif
  1876. #ifdef CONFIG_FUNCTION_ERROR_INJECTION
  1877. mod->ei_funcs = section_objs(info, "_error_injection_whitelist",
  1878. sizeof(*mod->ei_funcs),
  1879. &mod->num_ei_funcs);
  1880. #endif
  1881. #ifdef CONFIG_KPROBES
  1882. mod->kprobes_text_start = section_objs(info, ".kprobes.text", 1,
  1883. &mod->kprobes_text_size);
  1884. mod->kprobe_blacklist = section_objs(info, "_kprobe_blacklist",
  1885. sizeof(unsigned long),
  1886. &mod->num_kprobe_blacklist);
  1887. #endif
  1888. #ifdef CONFIG_PRINTK_INDEX
  1889. mod->printk_index_start = section_objs(info, ".printk_index",
  1890. sizeof(*mod->printk_index_start),
  1891. &mod->printk_index_size);
  1892. #endif
  1893. #ifdef CONFIG_HAVE_STATIC_CALL_INLINE
  1894. mod->static_call_sites = section_objs(info, ".static_call_sites",
  1895. sizeof(*mod->static_call_sites),
  1896. &mod->num_static_call_sites);
  1897. #endif
  1898. #if IS_ENABLED(CONFIG_KUNIT)
  1899. mod->kunit_suites = section_objs(info, ".kunit_test_suites",
  1900. sizeof(*mod->kunit_suites),
  1901. &mod->num_kunit_suites);
  1902. mod->kunit_init_suites = section_objs(info, ".kunit_init_test_suites",
  1903. sizeof(*mod->kunit_init_suites),
  1904. &mod->num_kunit_init_suites);
  1905. #endif
  1906. mod->extable = section_objs(info, "__ex_table",
  1907. sizeof(*mod->extable), &mod->num_exentries);
  1908. if (section_addr(info, "__obsparm"))
  1909. pr_warn("%s: Ignoring obsolete parameters\n", mod->name);
  1910. #ifdef CONFIG_DYNAMIC_DEBUG_CORE
  1911. mod->dyndbg_info.descs = section_objs(info, "__dyndbg",
  1912. sizeof(*mod->dyndbg_info.descs),
  1913. &mod->dyndbg_info.num_descs);
  1914. mod->dyndbg_info.classes = section_objs(info, "__dyndbg_classes",
  1915. sizeof(*mod->dyndbg_info.classes),
  1916. &mod->dyndbg_info.num_classes);
  1917. #endif
  1918. return 0;
  1919. }
  1920. static int move_module(struct module *mod, struct load_info *info)
  1921. {
  1922. int i;
  1923. enum mod_mem_type t = 0;
  1924. int ret = -ENOMEM;
  1925. for_each_mod_mem_type(type) {
  1926. if (!mod->mem[type].size) {
  1927. mod->mem[type].base = NULL;
  1928. continue;
  1929. }
  1930. ret = module_memory_alloc(mod, type);
  1931. if (ret) {
  1932. t = type;
  1933. goto out_enomem;
  1934. }
  1935. }
  1936. /* Transfer each section which specifies SHF_ALLOC */
  1937. pr_debug("Final section addresses for %s:\n", mod->name);
  1938. for (i = 0; i < info->hdr->e_shnum; i++) {
  1939. void *dest;
  1940. Elf_Shdr *shdr = &info->sechdrs[i];
  1941. enum mod_mem_type type = shdr->sh_entsize >> SH_ENTSIZE_TYPE_SHIFT;
  1942. if (!(shdr->sh_flags & SHF_ALLOC))
  1943. continue;
  1944. dest = mod->mem[type].base + (shdr->sh_entsize & SH_ENTSIZE_OFFSET_MASK);
  1945. if (shdr->sh_type != SHT_NOBITS) {
  1946. /*
  1947. * Our ELF checker already validated this, but let's
  1948. * be pedantic and make the goal clearer. We actually
  1949. * end up copying over all modifications made to the
  1950. * userspace copy of the entire struct module.
  1951. */
  1952. if (i == info->index.mod &&
  1953. (WARN_ON_ONCE(shdr->sh_size != sizeof(struct module)))) {
  1954. ret = -ENOEXEC;
  1955. goto out_enomem;
  1956. }
  1957. memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
  1958. }
  1959. /*
  1960. * Update the userspace copy's ELF section address to point to
  1961. * our newly allocated memory as a pure convenience so that
  1962. * users of info can keep taking advantage and using the newly
  1963. * minted official memory area.
  1964. */
  1965. shdr->sh_addr = (unsigned long)dest;
  1966. pr_debug("\t0x%lx 0x%.8lx %s\n", (long)shdr->sh_addr,
  1967. (long)shdr->sh_size, info->secstrings + shdr->sh_name);
  1968. }
  1969. return 0;
  1970. out_enomem:
  1971. for (t--; t >= 0; t--)
  1972. module_memory_free(mod, t, true);
  1973. return ret;
  1974. }
  1975. static int check_export_symbol_versions(struct module *mod)
  1976. {
  1977. #ifdef CONFIG_MODVERSIONS
  1978. if ((mod->num_syms && !mod->crcs) ||
  1979. (mod->num_gpl_syms && !mod->gpl_crcs)) {
  1980. return try_to_force_load(mod,
  1981. "no versions for exported symbols");
  1982. }
  1983. #endif
  1984. return 0;
  1985. }
  1986. static void flush_module_icache(const struct module *mod)
  1987. {
  1988. /*
  1989. * Flush the instruction cache, since we've played with text.
  1990. * Do it before processing of module parameters, so the module
  1991. * can provide parameter accessor functions of its own.
  1992. */
  1993. for_each_mod_mem_type(type) {
  1994. const struct module_memory *mod_mem = &mod->mem[type];
  1995. if (mod_mem->size) {
  1996. flush_icache_range((unsigned long)mod_mem->base,
  1997. (unsigned long)mod_mem->base + mod_mem->size);
  1998. }
  1999. }
  2000. }
  2001. bool __weak module_elf_check_arch(Elf_Ehdr *hdr)
  2002. {
  2003. return true;
  2004. }
  2005. int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
  2006. Elf_Shdr *sechdrs,
  2007. char *secstrings,
  2008. struct module *mod)
  2009. {
  2010. return 0;
  2011. }
  2012. /* module_blacklist is a comma-separated list of module names */
  2013. static char *module_blacklist;
  2014. static bool blacklisted(const char *module_name)
  2015. {
  2016. const char *p;
  2017. size_t len;
  2018. if (!module_blacklist)
  2019. return false;
  2020. for (p = module_blacklist; *p; p += len) {
  2021. len = strcspn(p, ",");
  2022. if (strlen(module_name) == len && !memcmp(module_name, p, len))
  2023. return true;
  2024. if (p[len] == ',')
  2025. len++;
  2026. }
  2027. return false;
  2028. }
  2029. core_param(module_blacklist, module_blacklist, charp, 0400);
  2030. static struct module *layout_and_allocate(struct load_info *info, int flags)
  2031. {
  2032. struct module *mod;
  2033. unsigned int ndx;
  2034. int err;
  2035. /* Allow arches to frob section contents and sizes. */
  2036. err = module_frob_arch_sections(info->hdr, info->sechdrs,
  2037. info->secstrings, info->mod);
  2038. if (err < 0)
  2039. return ERR_PTR(err);
  2040. err = module_enforce_rwx_sections(info->hdr, info->sechdrs,
  2041. info->secstrings, info->mod);
  2042. if (err < 0)
  2043. return ERR_PTR(err);
  2044. /* We will do a special allocation for per-cpu sections later. */
  2045. info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
  2046. /*
  2047. * Mark ro_after_init section with SHF_RO_AFTER_INIT so that
  2048. * layout_sections() can put it in the right place.
  2049. * Note: ro_after_init sections also have SHF_{WRITE,ALLOC} set.
  2050. */
  2051. ndx = find_sec(info, ".data..ro_after_init");
  2052. if (ndx)
  2053. info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
  2054. /*
  2055. * Mark the __jump_table section as ro_after_init as well: these data
  2056. * structures are never modified, with the exception of entries that
  2057. * refer to code in the __init section, which are annotated as such
  2058. * at module load time.
  2059. */
  2060. ndx = find_sec(info, "__jump_table");
  2061. if (ndx)
  2062. info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
  2063. /*
  2064. * Determine total sizes, and put offsets in sh_entsize. For now
  2065. * this is done generically; there doesn't appear to be any
  2066. * special cases for the architectures.
  2067. */
  2068. layout_sections(info->mod, info);
  2069. layout_symtab(info->mod, info);
  2070. /* Allocate and move to the final place */
  2071. err = move_module(info->mod, info);
  2072. if (err)
  2073. return ERR_PTR(err);
  2074. /* Module has been copied to its final place now: return it. */
  2075. mod = (void *)info->sechdrs[info->index.mod].sh_addr;
  2076. kmemleak_load_module(mod, info);
  2077. return mod;
  2078. }
  2079. /* mod is no longer valid after this! */
  2080. static void module_deallocate(struct module *mod, struct load_info *info)
  2081. {
  2082. percpu_modfree(mod);
  2083. module_arch_freeing_init(mod);
  2084. free_mod_mem(mod, true);
  2085. }
  2086. int __weak module_finalize(const Elf_Ehdr *hdr,
  2087. const Elf_Shdr *sechdrs,
  2088. struct module *me)
  2089. {
  2090. return 0;
  2091. }
  2092. static int post_relocation(struct module *mod, const struct load_info *info)
  2093. {
  2094. /* Sort exception table now relocations are done. */
  2095. sort_extable(mod->extable, mod->extable + mod->num_exentries);
  2096. /* Copy relocated percpu area over. */
  2097. percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
  2098. info->sechdrs[info->index.pcpu].sh_size);
  2099. /* Setup kallsyms-specific fields. */
  2100. add_kallsyms(mod, info);
  2101. /* Arch-specific module finalizing. */
  2102. return module_finalize(info->hdr, info->sechdrs, mod);
  2103. }
  2104. /* Call module constructors. */
  2105. static void do_mod_ctors(struct module *mod)
  2106. {
  2107. #ifdef CONFIG_CONSTRUCTORS
  2108. unsigned long i;
  2109. for (i = 0; i < mod->num_ctors; i++)
  2110. mod->ctors[i]();
  2111. #endif
  2112. }
  2113. /* For freeing module_init on success, in case kallsyms traversing */
  2114. struct mod_initfree {
  2115. struct llist_node node;
  2116. void *init_text;
  2117. void *init_data;
  2118. void *init_rodata;
  2119. };
  2120. static void do_free_init(struct work_struct *w)
  2121. {
  2122. struct llist_node *pos, *n, *list;
  2123. struct mod_initfree *initfree;
  2124. list = llist_del_all(&init_free_list);
  2125. synchronize_rcu();
  2126. llist_for_each_safe(pos, n, list) {
  2127. initfree = container_of(pos, struct mod_initfree, node);
  2128. execmem_free(initfree->init_text);
  2129. execmem_free(initfree->init_data);
  2130. execmem_free(initfree->init_rodata);
  2131. kfree(initfree);
  2132. }
  2133. }
  2134. void flush_module_init_free_work(void)
  2135. {
  2136. flush_work(&init_free_wq);
  2137. }
  2138. #undef MODULE_PARAM_PREFIX
  2139. #define MODULE_PARAM_PREFIX "module."
  2140. /* Default value for module->async_probe_requested */
  2141. static bool async_probe;
  2142. module_param(async_probe, bool, 0644);
  2143. /*
  2144. * This is where the real work happens.
  2145. *
  2146. * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb
  2147. * helper command 'lx-symbols'.
  2148. */
  2149. static noinline int do_init_module(struct module *mod)
  2150. {
  2151. int ret = 0;
  2152. struct mod_initfree *freeinit;
  2153. #if defined(CONFIG_MODULE_STATS)
  2154. unsigned int text_size = 0, total_size = 0;
  2155. for_each_mod_mem_type(type) {
  2156. const struct module_memory *mod_mem = &mod->mem[type];
  2157. if (mod_mem->size) {
  2158. total_size += mod_mem->size;
  2159. if (type == MOD_TEXT || type == MOD_INIT_TEXT)
  2160. text_size += mod_mem->size;
  2161. }
  2162. }
  2163. #endif
  2164. freeinit = kmalloc(sizeof(*freeinit), GFP_KERNEL);
  2165. if (!freeinit) {
  2166. ret = -ENOMEM;
  2167. goto fail;
  2168. }
  2169. freeinit->init_text = mod->mem[MOD_INIT_TEXT].base;
  2170. freeinit->init_data = mod->mem[MOD_INIT_DATA].base;
  2171. freeinit->init_rodata = mod->mem[MOD_INIT_RODATA].base;
  2172. do_mod_ctors(mod);
  2173. /* Start the module */
  2174. if (mod->init != NULL)
  2175. ret = do_one_initcall(mod->init);
  2176. if (ret < 0) {
  2177. goto fail_free_freeinit;
  2178. }
  2179. if (ret > 0) {
  2180. pr_warn("%s: '%s'->init suspiciously returned %d, it should "
  2181. "follow 0/-E convention\n"
  2182. "%s: loading module anyway...\n",
  2183. __func__, mod->name, ret, __func__);
  2184. dump_stack();
  2185. }
  2186. /* Now it's a first class citizen! */
  2187. mod->state = MODULE_STATE_LIVE;
  2188. blocking_notifier_call_chain(&module_notify_list,
  2189. MODULE_STATE_LIVE, mod);
  2190. /* Delay uevent until module has finished its init routine */
  2191. kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
  2192. /*
  2193. * We need to finish all async code before the module init sequence
  2194. * is done. This has potential to deadlock if synchronous module
  2195. * loading is requested from async (which is not allowed!).
  2196. *
  2197. * See commit 0fdff3ec6d87 ("async, kmod: warn on synchronous
  2198. * request_module() from async workers") for more details.
  2199. */
  2200. if (!mod->async_probe_requested)
  2201. async_synchronize_full();
  2202. ftrace_free_mem(mod, mod->mem[MOD_INIT_TEXT].base,
  2203. mod->mem[MOD_INIT_TEXT].base + mod->mem[MOD_INIT_TEXT].size);
  2204. mutex_lock(&module_mutex);
  2205. /* Drop initial reference. */
  2206. module_put(mod);
  2207. trim_init_extable(mod);
  2208. #ifdef CONFIG_KALLSYMS
  2209. /* Switch to core kallsyms now init is done: kallsyms may be walking! */
  2210. rcu_assign_pointer(mod->kallsyms, &mod->core_kallsyms);
  2211. #endif
  2212. ret = module_enable_rodata_ro(mod, true);
  2213. if (ret)
  2214. pr_warn("%s: module_enable_rodata_ro_after_init() returned %d, "
  2215. "ro_after_init data might still be writable\n",
  2216. mod->name, ret);
  2217. mod_tree_remove_init(mod);
  2218. module_arch_freeing_init(mod);
  2219. for_class_mod_mem_type(type, init) {
  2220. mod->mem[type].base = NULL;
  2221. mod->mem[type].size = 0;
  2222. }
  2223. #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
  2224. /* .BTF is not SHF_ALLOC and will get removed, so sanitize pointers */
  2225. mod->btf_data = NULL;
  2226. mod->btf_base_data = NULL;
  2227. #endif
  2228. /*
  2229. * We want to free module_init, but be aware that kallsyms may be
  2230. * walking this with preempt disabled. In all the failure paths, we
  2231. * call synchronize_rcu(), but we don't want to slow down the success
  2232. * path. execmem_free() cannot be called in an interrupt, so do the
  2233. * work and call synchronize_rcu() in a work queue.
  2234. *
  2235. * Note that execmem_alloc() on most architectures creates W+X page
  2236. * mappings which won't be cleaned up until do_free_init() runs. Any
  2237. * code such as mark_rodata_ro() which depends on those mappings to
  2238. * be cleaned up needs to sync with the queued work by invoking
  2239. * flush_module_init_free_work().
  2240. */
  2241. if (llist_add(&freeinit->node, &init_free_list))
  2242. schedule_work(&init_free_wq);
  2243. mutex_unlock(&module_mutex);
  2244. wake_up_all(&module_wq);
  2245. mod_stat_add_long(text_size, &total_text_size);
  2246. mod_stat_add_long(total_size, &total_mod_size);
  2247. mod_stat_inc(&modcount);
  2248. return 0;
  2249. fail_free_freeinit:
  2250. kfree(freeinit);
  2251. fail:
  2252. /* Try to protect us from buggy refcounters. */
  2253. mod->state = MODULE_STATE_GOING;
  2254. synchronize_rcu();
  2255. module_put(mod);
  2256. blocking_notifier_call_chain(&module_notify_list,
  2257. MODULE_STATE_GOING, mod);
  2258. klp_module_going(mod);
  2259. ftrace_release_mod(mod);
  2260. free_module(mod);
  2261. wake_up_all(&module_wq);
  2262. return ret;
  2263. }
  2264. static int may_init_module(void)
  2265. {
  2266. if (!capable(CAP_SYS_MODULE) || modules_disabled)
  2267. return -EPERM;
  2268. return 0;
  2269. }
  2270. /* Is this module of this name done loading? No locks held. */
  2271. static bool finished_loading(const char *name)
  2272. {
  2273. struct module *mod;
  2274. bool ret;
  2275. /*
  2276. * The module_mutex should not be a heavily contended lock;
  2277. * if we get the occasional sleep here, we'll go an extra iteration
  2278. * in the wait_event_interruptible(), which is harmless.
  2279. */
  2280. sched_annotate_sleep();
  2281. mutex_lock(&module_mutex);
  2282. mod = find_module_all(name, strlen(name), true);
  2283. ret = !mod || mod->state == MODULE_STATE_LIVE
  2284. || mod->state == MODULE_STATE_GOING;
  2285. mutex_unlock(&module_mutex);
  2286. return ret;
  2287. }
  2288. /* Must be called with module_mutex held */
  2289. static int module_patient_check_exists(const char *name,
  2290. enum fail_dup_mod_reason reason)
  2291. {
  2292. struct module *old;
  2293. int err = 0;
  2294. old = find_module_all(name, strlen(name), true);
  2295. if (old == NULL)
  2296. return 0;
  2297. if (old->state == MODULE_STATE_COMING ||
  2298. old->state == MODULE_STATE_UNFORMED) {
  2299. /* Wait in case it fails to load. */
  2300. mutex_unlock(&module_mutex);
  2301. err = wait_event_interruptible(module_wq,
  2302. finished_loading(name));
  2303. mutex_lock(&module_mutex);
  2304. if (err)
  2305. return err;
  2306. /* The module might have gone in the meantime. */
  2307. old = find_module_all(name, strlen(name), true);
  2308. }
  2309. if (try_add_failed_module(name, reason))
  2310. pr_warn("Could not add fail-tracking for module: %s\n", name);
  2311. /*
  2312. * We are here only when the same module was being loaded. Do
  2313. * not try to load it again right now. It prevents long delays
  2314. * caused by serialized module load failures. It might happen
  2315. * when more devices of the same type trigger load of
  2316. * a particular module.
  2317. */
  2318. if (old && old->state == MODULE_STATE_LIVE)
  2319. return -EEXIST;
  2320. return -EBUSY;
  2321. }
  2322. /*
  2323. * We try to place it in the list now to make sure it's unique before
  2324. * we dedicate too many resources. In particular, temporary percpu
  2325. * memory exhaustion.
  2326. */
  2327. static int add_unformed_module(struct module *mod)
  2328. {
  2329. int err;
  2330. mod->state = MODULE_STATE_UNFORMED;
  2331. mutex_lock(&module_mutex);
  2332. err = module_patient_check_exists(mod->name, FAIL_DUP_MOD_LOAD);
  2333. if (err)
  2334. goto out;
  2335. mod_update_bounds(mod);
  2336. list_add_rcu(&mod->list, &modules);
  2337. mod_tree_insert(mod);
  2338. err = 0;
  2339. out:
  2340. mutex_unlock(&module_mutex);
  2341. return err;
  2342. }
  2343. static int complete_formation(struct module *mod, struct load_info *info)
  2344. {
  2345. int err;
  2346. mutex_lock(&module_mutex);
  2347. /* Find duplicate symbols (must be called under lock). */
  2348. err = verify_exported_symbols(mod);
  2349. if (err < 0)
  2350. goto out;
  2351. /* These rely on module_mutex for list integrity. */
  2352. module_bug_finalize(info->hdr, info->sechdrs, mod);
  2353. module_cfi_finalize(info->hdr, info->sechdrs, mod);
  2354. err = module_enable_rodata_ro(mod, false);
  2355. if (err)
  2356. goto out_strict_rwx;
  2357. err = module_enable_data_nx(mod);
  2358. if (err)
  2359. goto out_strict_rwx;
  2360. err = module_enable_text_rox(mod);
  2361. if (err)
  2362. goto out_strict_rwx;
  2363. /*
  2364. * Mark state as coming so strong_try_module_get() ignores us,
  2365. * but kallsyms etc. can see us.
  2366. */
  2367. mod->state = MODULE_STATE_COMING;
  2368. mutex_unlock(&module_mutex);
  2369. return 0;
  2370. out_strict_rwx:
  2371. module_bug_cleanup(mod);
  2372. out:
  2373. mutex_unlock(&module_mutex);
  2374. return err;
  2375. }
  2376. static int prepare_coming_module(struct module *mod)
  2377. {
  2378. int err;
  2379. ftrace_module_enable(mod);
  2380. err = klp_module_coming(mod);
  2381. if (err)
  2382. return err;
  2383. err = blocking_notifier_call_chain_robust(&module_notify_list,
  2384. MODULE_STATE_COMING, MODULE_STATE_GOING, mod);
  2385. err = notifier_to_errno(err);
  2386. if (err)
  2387. klp_module_going(mod);
  2388. return err;
  2389. }
  2390. static int unknown_module_param_cb(char *param, char *val, const char *modname,
  2391. void *arg)
  2392. {
  2393. struct module *mod = arg;
  2394. int ret;
  2395. if (strcmp(param, "async_probe") == 0) {
  2396. if (kstrtobool(val, &mod->async_probe_requested))
  2397. mod->async_probe_requested = true;
  2398. return 0;
  2399. }
  2400. /* Check for magic 'dyndbg' arg */
  2401. ret = ddebug_dyndbg_module_param_cb(param, val, modname);
  2402. if (ret != 0)
  2403. pr_warn("%s: unknown parameter '%s' ignored\n", modname, param);
  2404. return 0;
  2405. }
  2406. /* Module within temporary copy, this doesn't do any allocation */
  2407. static int early_mod_check(struct load_info *info, int flags)
  2408. {
  2409. int err;
  2410. /*
  2411. * Now that we know we have the correct module name, check
  2412. * if it's blacklisted.
  2413. */
  2414. if (blacklisted(info->name)) {
  2415. pr_err("Module %s is blacklisted\n", info->name);
  2416. return -EPERM;
  2417. }
  2418. err = rewrite_section_headers(info, flags);
  2419. if (err)
  2420. return err;
  2421. /* Check module struct version now, before we try to use module. */
  2422. if (!check_modstruct_version(info, info->mod))
  2423. return -ENOEXEC;
  2424. err = check_modinfo(info->mod, info, flags);
  2425. if (err)
  2426. return err;
  2427. mutex_lock(&module_mutex);
  2428. err = module_patient_check_exists(info->mod->name, FAIL_DUP_MOD_BECOMING);
  2429. mutex_unlock(&module_mutex);
  2430. return err;
  2431. }
  2432. /*
  2433. * Allocate and load the module: note that size of section 0 is always
  2434. * zero, and we rely on this for optional sections.
  2435. */
  2436. static int load_module(struct load_info *info, const char __user *uargs,
  2437. int flags)
  2438. {
  2439. struct module *mod;
  2440. bool module_allocated = false;
  2441. long err = 0;
  2442. char *after_dashes;
  2443. /*
  2444. * Do the signature check (if any) first. All that
  2445. * the signature check needs is info->len, it does
  2446. * not need any of the section info. That can be
  2447. * set up later. This will minimize the chances
  2448. * of a corrupt module causing problems before
  2449. * we even get to the signature check.
  2450. *
  2451. * The check will also adjust info->len by stripping
  2452. * off the sig length at the end of the module, making
  2453. * checks against info->len more correct.
  2454. */
  2455. err = module_sig_check(info, flags);
  2456. if (err)
  2457. goto free_copy;
  2458. /*
  2459. * Do basic sanity checks against the ELF header and
  2460. * sections. Cache useful sections and set the
  2461. * info->mod to the userspace passed struct module.
  2462. */
  2463. err = elf_validity_cache_copy(info, flags);
  2464. if (err)
  2465. goto free_copy;
  2466. err = early_mod_check(info, flags);
  2467. if (err)
  2468. goto free_copy;
  2469. /* Figure out module layout, and allocate all the memory. */
  2470. mod = layout_and_allocate(info, flags);
  2471. if (IS_ERR(mod)) {
  2472. err = PTR_ERR(mod);
  2473. goto free_copy;
  2474. }
  2475. module_allocated = true;
  2476. audit_log_kern_module(mod->name);
  2477. /* Reserve our place in the list. */
  2478. err = add_unformed_module(mod);
  2479. if (err)
  2480. goto free_module;
  2481. /*
  2482. * We are tainting your kernel if your module gets into
  2483. * the modules linked list somehow.
  2484. */
  2485. module_augment_kernel_taints(mod, info);
  2486. /* To avoid stressing percpu allocator, do this once we're unique. */
  2487. err = percpu_modalloc(mod, info);
  2488. if (err)
  2489. goto unlink_mod;
  2490. /* Now module is in final location, initialize linked lists, etc. */
  2491. err = module_unload_init(mod);
  2492. if (err)
  2493. goto unlink_mod;
  2494. init_param_lock(mod);
  2495. /*
  2496. * Now we've got everything in the final locations, we can
  2497. * find optional sections.
  2498. */
  2499. err = find_module_sections(mod, info);
  2500. if (err)
  2501. goto free_unload;
  2502. err = check_export_symbol_versions(mod);
  2503. if (err)
  2504. goto free_unload;
  2505. /* Set up MODINFO_ATTR fields */
  2506. setup_modinfo(mod, info);
  2507. /* Fix up syms, so that st_value is a pointer to location. */
  2508. err = simplify_symbols(mod, info);
  2509. if (err < 0)
  2510. goto free_modinfo;
  2511. err = apply_relocations(mod, info);
  2512. if (err < 0)
  2513. goto free_modinfo;
  2514. err = post_relocation(mod, info);
  2515. if (err < 0)
  2516. goto free_modinfo;
  2517. flush_module_icache(mod);
  2518. /* Now copy in args */
  2519. mod->args = strndup_user(uargs, ~0UL >> 1);
  2520. if (IS_ERR(mod->args)) {
  2521. err = PTR_ERR(mod->args);
  2522. goto free_arch_cleanup;
  2523. }
  2524. init_build_id(mod, info);
  2525. /* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
  2526. ftrace_module_init(mod);
  2527. /* Finally it's fully formed, ready to start executing. */
  2528. err = complete_formation(mod, info);
  2529. if (err)
  2530. goto ddebug_cleanup;
  2531. err = prepare_coming_module(mod);
  2532. if (err)
  2533. goto bug_cleanup;
  2534. mod->async_probe_requested = async_probe;
  2535. /* Module is ready to execute: parsing args may do that. */
  2536. after_dashes = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
  2537. -32768, 32767, mod,
  2538. unknown_module_param_cb);
  2539. if (IS_ERR(after_dashes)) {
  2540. err = PTR_ERR(after_dashes);
  2541. goto coming_cleanup;
  2542. } else if (after_dashes) {
  2543. pr_warn("%s: parameters '%s' after `--' ignored\n",
  2544. mod->name, after_dashes);
  2545. }
  2546. /* Link in to sysfs. */
  2547. err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
  2548. if (err < 0)
  2549. goto coming_cleanup;
  2550. if (is_livepatch_module(mod)) {
  2551. err = copy_module_elf(mod, info);
  2552. if (err < 0)
  2553. goto sysfs_cleanup;
  2554. }
  2555. /* Get rid of temporary copy. */
  2556. free_copy(info, flags);
  2557. codetag_load_module(mod);
  2558. /* Done! */
  2559. trace_module_load(mod);
  2560. return do_init_module(mod);
  2561. sysfs_cleanup:
  2562. mod_sysfs_teardown(mod);
  2563. coming_cleanup:
  2564. mod->state = MODULE_STATE_GOING;
  2565. destroy_params(mod->kp, mod->num_kp);
  2566. blocking_notifier_call_chain(&module_notify_list,
  2567. MODULE_STATE_GOING, mod);
  2568. klp_module_going(mod);
  2569. bug_cleanup:
  2570. mod->state = MODULE_STATE_GOING;
  2571. /* module_bug_cleanup needs module_mutex protection */
  2572. mutex_lock(&module_mutex);
  2573. module_bug_cleanup(mod);
  2574. mutex_unlock(&module_mutex);
  2575. ddebug_cleanup:
  2576. ftrace_release_mod(mod);
  2577. synchronize_rcu();
  2578. kfree(mod->args);
  2579. free_arch_cleanup:
  2580. module_arch_cleanup(mod);
  2581. free_modinfo:
  2582. free_modinfo(mod);
  2583. free_unload:
  2584. module_unload_free(mod);
  2585. unlink_mod:
  2586. mutex_lock(&module_mutex);
  2587. /* Unlink carefully: kallsyms could be walking list. */
  2588. list_del_rcu(&mod->list);
  2589. mod_tree_remove(mod);
  2590. wake_up_all(&module_wq);
  2591. /* Wait for RCU-sched synchronizing before releasing mod->list. */
  2592. synchronize_rcu();
  2593. mutex_unlock(&module_mutex);
  2594. free_module:
  2595. mod_stat_bump_invalid(info, flags);
  2596. /* Free lock-classes; relies on the preceding sync_rcu() */
  2597. for_class_mod_mem_type(type, core_data) {
  2598. lockdep_free_key_range(mod->mem[type].base,
  2599. mod->mem[type].size);
  2600. }
  2601. module_deallocate(mod, info);
  2602. free_copy:
  2603. /*
  2604. * The info->len is always set. We distinguish between
  2605. * failures once the proper module was allocated and
  2606. * before that.
  2607. */
  2608. if (!module_allocated)
  2609. mod_stat_bump_becoming(info, flags);
  2610. free_copy(info, flags);
  2611. return err;
  2612. }
  2613. SYSCALL_DEFINE3(init_module, void __user *, umod,
  2614. unsigned long, len, const char __user *, uargs)
  2615. {
  2616. int err;
  2617. struct load_info info = { };
  2618. err = may_init_module();
  2619. if (err)
  2620. return err;
  2621. pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
  2622. umod, len, uargs);
  2623. err = copy_module_from_user(umod, len, &info);
  2624. if (err) {
  2625. mod_stat_inc(&failed_kreads);
  2626. mod_stat_add_long(len, &invalid_kread_bytes);
  2627. return err;
  2628. }
  2629. return load_module(&info, uargs, 0);
  2630. }
  2631. struct idempotent {
  2632. const void *cookie;
  2633. struct hlist_node entry;
  2634. struct completion complete;
  2635. int ret;
  2636. };
  2637. #define IDEM_HASH_BITS 8
  2638. static struct hlist_head idem_hash[1 << IDEM_HASH_BITS];
  2639. static DEFINE_SPINLOCK(idem_lock);
  2640. static bool idempotent(struct idempotent *u, const void *cookie)
  2641. {
  2642. int hash = hash_ptr(cookie, IDEM_HASH_BITS);
  2643. struct hlist_head *head = idem_hash + hash;
  2644. struct idempotent *existing;
  2645. bool first;
  2646. u->ret = -EINTR;
  2647. u->cookie = cookie;
  2648. init_completion(&u->complete);
  2649. spin_lock(&idem_lock);
  2650. first = true;
  2651. hlist_for_each_entry(existing, head, entry) {
  2652. if (existing->cookie != cookie)
  2653. continue;
  2654. first = false;
  2655. break;
  2656. }
  2657. hlist_add_head(&u->entry, idem_hash + hash);
  2658. spin_unlock(&idem_lock);
  2659. return !first;
  2660. }
  2661. /*
  2662. * We were the first one with 'cookie' on the list, and we ended
  2663. * up completing the operation. We now need to walk the list,
  2664. * remove everybody - which includes ourselves - fill in the return
  2665. * value, and then complete the operation.
  2666. */
  2667. static int idempotent_complete(struct idempotent *u, int ret)
  2668. {
  2669. const void *cookie = u->cookie;
  2670. int hash = hash_ptr(cookie, IDEM_HASH_BITS);
  2671. struct hlist_head *head = idem_hash + hash;
  2672. struct hlist_node *next;
  2673. struct idempotent *pos;
  2674. spin_lock(&idem_lock);
  2675. hlist_for_each_entry_safe(pos, next, head, entry) {
  2676. if (pos->cookie != cookie)
  2677. continue;
  2678. hlist_del_init(&pos->entry);
  2679. pos->ret = ret;
  2680. complete(&pos->complete);
  2681. }
  2682. spin_unlock(&idem_lock);
  2683. return ret;
  2684. }
  2685. /*
  2686. * Wait for the idempotent worker.
  2687. *
  2688. * If we get interrupted, we need to remove ourselves from the
  2689. * the idempotent list, and the completion may still come in.
  2690. *
  2691. * The 'idem_lock' protects against the race, and 'idem.ret' was
  2692. * initialized to -EINTR and is thus always the right return
  2693. * value even if the idempotent work then completes between
  2694. * the wait_for_completion and the cleanup.
  2695. */
  2696. static int idempotent_wait_for_completion(struct idempotent *u)
  2697. {
  2698. if (wait_for_completion_interruptible(&u->complete)) {
  2699. spin_lock(&idem_lock);
  2700. if (!hlist_unhashed(&u->entry))
  2701. hlist_del(&u->entry);
  2702. spin_unlock(&idem_lock);
  2703. }
  2704. return u->ret;
  2705. }
  2706. static int init_module_from_file(struct file *f, const char __user * uargs, int flags)
  2707. {
  2708. struct load_info info = { };
  2709. void *buf = NULL;
  2710. int len;
  2711. len = kernel_read_file(f, 0, &buf, INT_MAX, NULL, READING_MODULE);
  2712. if (len < 0) {
  2713. mod_stat_inc(&failed_kreads);
  2714. return len;
  2715. }
  2716. if (flags & MODULE_INIT_COMPRESSED_FILE) {
  2717. int err = module_decompress(&info, buf, len);
  2718. vfree(buf); /* compressed data is no longer needed */
  2719. if (err) {
  2720. mod_stat_inc(&failed_decompress);
  2721. mod_stat_add_long(len, &invalid_decompress_bytes);
  2722. return err;
  2723. }
  2724. } else {
  2725. info.hdr = buf;
  2726. info.len = len;
  2727. }
  2728. return load_module(&info, uargs, flags);
  2729. }
  2730. static int idempotent_init_module(struct file *f, const char __user * uargs, int flags)
  2731. {
  2732. struct idempotent idem;
  2733. if (!f || !(f->f_mode & FMODE_READ))
  2734. return -EBADF;
  2735. /* Are we the winners of the race and get to do this? */
  2736. if (!idempotent(&idem, file_inode(f))) {
  2737. int ret = init_module_from_file(f, uargs, flags);
  2738. return idempotent_complete(&idem, ret);
  2739. }
  2740. /*
  2741. * Somebody else won the race and is loading the module.
  2742. */
  2743. return idempotent_wait_for_completion(&idem);
  2744. }
  2745. SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
  2746. {
  2747. int err;
  2748. struct fd f;
  2749. err = may_init_module();
  2750. if (err)
  2751. return err;
  2752. pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
  2753. if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
  2754. |MODULE_INIT_IGNORE_VERMAGIC
  2755. |MODULE_INIT_COMPRESSED_FILE))
  2756. return -EINVAL;
  2757. f = fdget(fd);
  2758. err = idempotent_init_module(fd_file(f), uargs, flags);
  2759. fdput(f);
  2760. return err;
  2761. }
  2762. /* Keep in sync with MODULE_FLAGS_BUF_SIZE !!! */
  2763. char *module_flags(struct module *mod, char *buf, bool show_state)
  2764. {
  2765. int bx = 0;
  2766. BUG_ON(mod->state == MODULE_STATE_UNFORMED);
  2767. if (!mod->taints && !show_state)
  2768. goto out;
  2769. if (mod->taints ||
  2770. mod->state == MODULE_STATE_GOING ||
  2771. mod->state == MODULE_STATE_COMING) {
  2772. buf[bx++] = '(';
  2773. bx += module_flags_taint(mod->taints, buf + bx);
  2774. /* Show a - for module-is-being-unloaded */
  2775. if (mod->state == MODULE_STATE_GOING && show_state)
  2776. buf[bx++] = '-';
  2777. /* Show a + for module-is-being-loaded */
  2778. if (mod->state == MODULE_STATE_COMING && show_state)
  2779. buf[bx++] = '+';
  2780. buf[bx++] = ')';
  2781. }
  2782. out:
  2783. buf[bx] = '\0';
  2784. return buf;
  2785. }
  2786. /* Given an address, look for it in the module exception tables. */
  2787. const struct exception_table_entry *search_module_extables(unsigned long addr)
  2788. {
  2789. const struct exception_table_entry *e = NULL;
  2790. struct module *mod;
  2791. preempt_disable();
  2792. mod = __module_address(addr);
  2793. if (!mod)
  2794. goto out;
  2795. if (!mod->num_exentries)
  2796. goto out;
  2797. e = search_extable(mod->extable,
  2798. mod->num_exentries,
  2799. addr);
  2800. out:
  2801. preempt_enable();
  2802. /*
  2803. * Now, if we found one, we are running inside it now, hence
  2804. * we cannot unload the module, hence no refcnt needed.
  2805. */
  2806. return e;
  2807. }
  2808. /**
  2809. * is_module_address() - is this address inside a module?
  2810. * @addr: the address to check.
  2811. *
  2812. * See is_module_text_address() if you simply want to see if the address
  2813. * is code (not data).
  2814. */
  2815. bool is_module_address(unsigned long addr)
  2816. {
  2817. bool ret;
  2818. preempt_disable();
  2819. ret = __module_address(addr) != NULL;
  2820. preempt_enable();
  2821. return ret;
  2822. }
  2823. /**
  2824. * __module_address() - get the module which contains an address.
  2825. * @addr: the address.
  2826. *
  2827. * Must be called with preempt disabled or module mutex held so that
  2828. * module doesn't get freed during this.
  2829. */
  2830. struct module *__module_address(unsigned long addr)
  2831. {
  2832. struct module *mod;
  2833. if (addr >= mod_tree.addr_min && addr <= mod_tree.addr_max)
  2834. goto lookup;
  2835. #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
  2836. if (addr >= mod_tree.data_addr_min && addr <= mod_tree.data_addr_max)
  2837. goto lookup;
  2838. #endif
  2839. return NULL;
  2840. lookup:
  2841. module_assert_mutex_or_preempt();
  2842. mod = mod_find(addr, &mod_tree);
  2843. if (mod) {
  2844. BUG_ON(!within_module(addr, mod));
  2845. if (mod->state == MODULE_STATE_UNFORMED)
  2846. mod = NULL;
  2847. }
  2848. return mod;
  2849. }
  2850. /**
  2851. * is_module_text_address() - is this address inside module code?
  2852. * @addr: the address to check.
  2853. *
  2854. * See is_module_address() if you simply want to see if the address is
  2855. * anywhere in a module. See kernel_text_address() for testing if an
  2856. * address corresponds to kernel or module code.
  2857. */
  2858. bool is_module_text_address(unsigned long addr)
  2859. {
  2860. bool ret;
  2861. preempt_disable();
  2862. ret = __module_text_address(addr) != NULL;
  2863. preempt_enable();
  2864. return ret;
  2865. }
  2866. /**
  2867. * __module_text_address() - get the module whose code contains an address.
  2868. * @addr: the address.
  2869. *
  2870. * Must be called with preempt disabled or module mutex held so that
  2871. * module doesn't get freed during this.
  2872. */
  2873. struct module *__module_text_address(unsigned long addr)
  2874. {
  2875. struct module *mod = __module_address(addr);
  2876. if (mod) {
  2877. /* Make sure it's within the text section. */
  2878. if (!within_module_mem_type(addr, mod, MOD_TEXT) &&
  2879. !within_module_mem_type(addr, mod, MOD_INIT_TEXT))
  2880. mod = NULL;
  2881. }
  2882. return mod;
  2883. }
  2884. /* Don't grab lock, we're oopsing. */
  2885. void print_modules(void)
  2886. {
  2887. struct module *mod;
  2888. char buf[MODULE_FLAGS_BUF_SIZE];
  2889. printk(KERN_DEFAULT "Modules linked in:");
  2890. /* Most callers should already have preempt disabled, but make sure */
  2891. preempt_disable();
  2892. list_for_each_entry_rcu(mod, &modules, list) {
  2893. if (mod->state == MODULE_STATE_UNFORMED)
  2894. continue;
  2895. pr_cont(" %s%s", mod->name, module_flags(mod, buf, true));
  2896. }
  2897. print_unloaded_tainted_modules();
  2898. preempt_enable();
  2899. if (last_unloaded_module.name[0])
  2900. pr_cont(" [last unloaded: %s%s]", last_unloaded_module.name,
  2901. last_unloaded_module.taints);
  2902. pr_cont("\n");
  2903. }
  2904. #ifdef CONFIG_MODULE_DEBUGFS
  2905. struct dentry *mod_debugfs_root;
  2906. static int module_debugfs_init(void)
  2907. {
  2908. mod_debugfs_root = debugfs_create_dir("modules", NULL);
  2909. return 0;
  2910. }
  2911. module_init(module_debugfs_init);
  2912. #endif