main.c 87 KB

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