linker.c 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941
  1. // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
  2. /*
  3. * BPF static linker
  4. *
  5. * Copyright (c) 2021 Facebook
  6. */
  7. #include <stdbool.h>
  8. #include <stddef.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include <errno.h>
  14. #include <linux/err.h>
  15. #include <linux/btf.h>
  16. #include <elf.h>
  17. #include <libelf.h>
  18. #include <fcntl.h>
  19. #include "libbpf.h"
  20. #include "btf.h"
  21. #include "libbpf_internal.h"
  22. #include "strset.h"
  23. #define BTF_EXTERN_SEC ".extern"
  24. struct src_sec {
  25. const char *sec_name;
  26. /* positional (not necessarily ELF) index in an array of sections */
  27. int id;
  28. /* positional (not necessarily ELF) index of a matching section in a final object file */
  29. int dst_id;
  30. /* section data offset in a matching output section */
  31. int dst_off;
  32. /* whether section is omitted from the final ELF file */
  33. bool skipped;
  34. /* whether section is an ephemeral section, not mapped to an ELF section */
  35. bool ephemeral;
  36. /* ELF info */
  37. size_t sec_idx;
  38. Elf_Scn *scn;
  39. Elf64_Shdr *shdr;
  40. Elf_Data *data;
  41. /* corresponding BTF DATASEC type ID */
  42. int sec_type_id;
  43. };
  44. struct src_obj {
  45. const char *filename;
  46. int fd;
  47. Elf *elf;
  48. /* Section header strings section index */
  49. size_t shstrs_sec_idx;
  50. /* SYMTAB section index */
  51. size_t symtab_sec_idx;
  52. struct btf *btf;
  53. struct btf_ext *btf_ext;
  54. /* List of sections (including ephemeral). Slot zero is unused. */
  55. struct src_sec *secs;
  56. int sec_cnt;
  57. /* mapping of symbol indices from src to dst ELF */
  58. int *sym_map;
  59. /* mapping from the src BTF type IDs to dst ones */
  60. int *btf_type_map;
  61. };
  62. /* single .BTF.ext data section */
  63. struct btf_ext_sec_data {
  64. size_t rec_cnt;
  65. __u32 rec_sz;
  66. void *recs;
  67. };
  68. struct glob_sym {
  69. /* ELF symbol index */
  70. int sym_idx;
  71. /* associated section id for .ksyms, .kconfig, etc, but not .extern */
  72. int sec_id;
  73. /* extern name offset in STRTAB */
  74. int name_off;
  75. /* optional associated BTF type ID */
  76. int btf_id;
  77. /* BTF type ID to which VAR/FUNC type is pointing to; used for
  78. * rewriting types when extern VAR/FUNC is resolved to a concrete
  79. * definition
  80. */
  81. int underlying_btf_id;
  82. /* sec_var index in the corresponding dst_sec, if exists */
  83. int var_idx;
  84. /* extern or resolved/global symbol */
  85. bool is_extern;
  86. /* weak or strong symbol, never goes back from strong to weak */
  87. bool is_weak;
  88. };
  89. struct dst_sec {
  90. char *sec_name;
  91. /* positional (not necessarily ELF) index in an array of sections */
  92. int id;
  93. bool ephemeral;
  94. /* ELF info */
  95. size_t sec_idx;
  96. Elf_Scn *scn;
  97. Elf64_Shdr *shdr;
  98. Elf_Data *data;
  99. /* final output section size */
  100. int sec_sz;
  101. /* final output contents of the section */
  102. void *raw_data;
  103. /* corresponding STT_SECTION symbol index in SYMTAB */
  104. int sec_sym_idx;
  105. /* section's DATASEC variable info, emitted on BTF finalization */
  106. bool has_btf;
  107. int sec_var_cnt;
  108. struct btf_var_secinfo *sec_vars;
  109. /* section's .BTF.ext data */
  110. struct btf_ext_sec_data func_info;
  111. struct btf_ext_sec_data line_info;
  112. struct btf_ext_sec_data core_relo_info;
  113. };
  114. struct bpf_linker {
  115. char *filename;
  116. int fd;
  117. Elf *elf;
  118. Elf64_Ehdr *elf_hdr;
  119. /* Output sections metadata */
  120. struct dst_sec *secs;
  121. int sec_cnt;
  122. struct strset *strtab_strs; /* STRTAB unique strings */
  123. size_t strtab_sec_idx; /* STRTAB section index */
  124. size_t symtab_sec_idx; /* SYMTAB section index */
  125. struct btf *btf;
  126. struct btf_ext *btf_ext;
  127. /* global (including extern) ELF symbols */
  128. int glob_sym_cnt;
  129. struct glob_sym *glob_syms;
  130. };
  131. #define pr_warn_elf(fmt, ...) \
  132. libbpf_print(LIBBPF_WARN, "libbpf: " fmt ": %s\n", ##__VA_ARGS__, elf_errmsg(-1))
  133. static int init_output_elf(struct bpf_linker *linker, const char *file);
  134. static int linker_load_obj_file(struct bpf_linker *linker, const char *filename,
  135. const struct bpf_linker_file_opts *opts,
  136. struct src_obj *obj);
  137. static int linker_sanity_check_elf(struct src_obj *obj);
  138. static int linker_sanity_check_elf_symtab(struct src_obj *obj, struct src_sec *sec);
  139. static int linker_sanity_check_elf_relos(struct src_obj *obj, struct src_sec *sec);
  140. static int linker_sanity_check_btf(struct src_obj *obj);
  141. static int linker_sanity_check_btf_ext(struct src_obj *obj);
  142. static int linker_fixup_btf(struct src_obj *obj);
  143. static int linker_append_sec_data(struct bpf_linker *linker, struct src_obj *obj);
  144. static int linker_append_elf_syms(struct bpf_linker *linker, struct src_obj *obj);
  145. static int linker_append_elf_sym(struct bpf_linker *linker, struct src_obj *obj,
  146. Elf64_Sym *sym, const char *sym_name, int src_sym_idx);
  147. static int linker_append_elf_relos(struct bpf_linker *linker, struct src_obj *obj);
  148. static int linker_append_btf(struct bpf_linker *linker, struct src_obj *obj);
  149. static int linker_append_btf_ext(struct bpf_linker *linker, struct src_obj *obj);
  150. static int finalize_btf(struct bpf_linker *linker);
  151. static int finalize_btf_ext(struct bpf_linker *linker);
  152. void bpf_linker__free(struct bpf_linker *linker)
  153. {
  154. int i;
  155. if (!linker)
  156. return;
  157. free(linker->filename);
  158. if (linker->elf)
  159. elf_end(linker->elf);
  160. if (linker->fd >= 0)
  161. close(linker->fd);
  162. strset__free(linker->strtab_strs);
  163. btf__free(linker->btf);
  164. btf_ext__free(linker->btf_ext);
  165. for (i = 1; i < linker->sec_cnt; i++) {
  166. struct dst_sec *sec = &linker->secs[i];
  167. free(sec->sec_name);
  168. free(sec->raw_data);
  169. free(sec->sec_vars);
  170. free(sec->func_info.recs);
  171. free(sec->line_info.recs);
  172. free(sec->core_relo_info.recs);
  173. }
  174. free(linker->secs);
  175. free(linker->glob_syms);
  176. free(linker);
  177. }
  178. struct bpf_linker *bpf_linker__new(const char *filename, struct bpf_linker_opts *opts)
  179. {
  180. struct bpf_linker *linker;
  181. int err;
  182. if (!OPTS_VALID(opts, bpf_linker_opts))
  183. return errno = EINVAL, NULL;
  184. if (elf_version(EV_CURRENT) == EV_NONE) {
  185. pr_warn_elf("libelf initialization failed");
  186. return errno = EINVAL, NULL;
  187. }
  188. linker = calloc(1, sizeof(*linker));
  189. if (!linker)
  190. return errno = ENOMEM, NULL;
  191. linker->fd = -1;
  192. err = init_output_elf(linker, filename);
  193. if (err)
  194. goto err_out;
  195. return linker;
  196. err_out:
  197. bpf_linker__free(linker);
  198. return errno = -err, NULL;
  199. }
  200. static struct dst_sec *add_dst_sec(struct bpf_linker *linker, const char *sec_name)
  201. {
  202. struct dst_sec *secs = linker->secs, *sec;
  203. size_t new_cnt = linker->sec_cnt ? linker->sec_cnt + 1 : 2;
  204. secs = libbpf_reallocarray(secs, new_cnt, sizeof(*secs));
  205. if (!secs)
  206. return NULL;
  207. /* zero out newly allocated memory */
  208. memset(secs + linker->sec_cnt, 0, (new_cnt - linker->sec_cnt) * sizeof(*secs));
  209. linker->secs = secs;
  210. linker->sec_cnt = new_cnt;
  211. sec = &linker->secs[new_cnt - 1];
  212. sec->id = new_cnt - 1;
  213. sec->sec_name = strdup(sec_name);
  214. if (!sec->sec_name)
  215. return NULL;
  216. return sec;
  217. }
  218. static Elf64_Sym *add_new_sym(struct bpf_linker *linker, size_t *sym_idx)
  219. {
  220. struct dst_sec *symtab = &linker->secs[linker->symtab_sec_idx];
  221. Elf64_Sym *syms, *sym;
  222. size_t sym_cnt = symtab->sec_sz / sizeof(*sym);
  223. syms = libbpf_reallocarray(symtab->raw_data, sym_cnt + 1, sizeof(*sym));
  224. if (!syms)
  225. return NULL;
  226. sym = &syms[sym_cnt];
  227. memset(sym, 0, sizeof(*sym));
  228. symtab->raw_data = syms;
  229. symtab->sec_sz += sizeof(*sym);
  230. symtab->shdr->sh_size += sizeof(*sym);
  231. symtab->data->d_size += sizeof(*sym);
  232. if (sym_idx)
  233. *sym_idx = sym_cnt;
  234. return sym;
  235. }
  236. static int init_output_elf(struct bpf_linker *linker, const char *file)
  237. {
  238. int err, str_off;
  239. Elf64_Sym *init_sym;
  240. struct dst_sec *sec;
  241. linker->filename = strdup(file);
  242. if (!linker->filename)
  243. return -ENOMEM;
  244. linker->fd = open(file, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
  245. if (linker->fd < 0) {
  246. err = -errno;
  247. pr_warn("failed to create '%s': %d\n", file, err);
  248. return err;
  249. }
  250. linker->elf = elf_begin(linker->fd, ELF_C_WRITE, NULL);
  251. if (!linker->elf) {
  252. pr_warn_elf("failed to create ELF object");
  253. return -EINVAL;
  254. }
  255. /* ELF header */
  256. linker->elf_hdr = elf64_newehdr(linker->elf);
  257. if (!linker->elf_hdr) {
  258. pr_warn_elf("failed to create ELF header");
  259. return -EINVAL;
  260. }
  261. linker->elf_hdr->e_machine = EM_BPF;
  262. linker->elf_hdr->e_type = ET_REL;
  263. #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  264. linker->elf_hdr->e_ident[EI_DATA] = ELFDATA2LSB;
  265. #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
  266. linker->elf_hdr->e_ident[EI_DATA] = ELFDATA2MSB;
  267. #else
  268. #error "Unknown __BYTE_ORDER__"
  269. #endif
  270. /* STRTAB */
  271. /* initialize strset with an empty string to conform to ELF */
  272. linker->strtab_strs = strset__new(INT_MAX, "", sizeof(""));
  273. if (libbpf_get_error(linker->strtab_strs))
  274. return libbpf_get_error(linker->strtab_strs);
  275. sec = add_dst_sec(linker, ".strtab");
  276. if (!sec)
  277. return -ENOMEM;
  278. sec->scn = elf_newscn(linker->elf);
  279. if (!sec->scn) {
  280. pr_warn_elf("failed to create STRTAB section");
  281. return -EINVAL;
  282. }
  283. sec->shdr = elf64_getshdr(sec->scn);
  284. if (!sec->shdr)
  285. return -EINVAL;
  286. sec->data = elf_newdata(sec->scn);
  287. if (!sec->data) {
  288. pr_warn_elf("failed to create STRTAB data");
  289. return -EINVAL;
  290. }
  291. str_off = strset__add_str(linker->strtab_strs, sec->sec_name);
  292. if (str_off < 0)
  293. return str_off;
  294. sec->sec_idx = elf_ndxscn(sec->scn);
  295. linker->elf_hdr->e_shstrndx = sec->sec_idx;
  296. linker->strtab_sec_idx = sec->sec_idx;
  297. sec->shdr->sh_name = str_off;
  298. sec->shdr->sh_type = SHT_STRTAB;
  299. sec->shdr->sh_flags = SHF_STRINGS;
  300. sec->shdr->sh_offset = 0;
  301. sec->shdr->sh_link = 0;
  302. sec->shdr->sh_info = 0;
  303. sec->shdr->sh_addralign = 1;
  304. sec->shdr->sh_size = sec->sec_sz = 0;
  305. sec->shdr->sh_entsize = 0;
  306. /* SYMTAB */
  307. sec = add_dst_sec(linker, ".symtab");
  308. if (!sec)
  309. return -ENOMEM;
  310. sec->scn = elf_newscn(linker->elf);
  311. if (!sec->scn) {
  312. pr_warn_elf("failed to create SYMTAB section");
  313. return -EINVAL;
  314. }
  315. sec->shdr = elf64_getshdr(sec->scn);
  316. if (!sec->shdr)
  317. return -EINVAL;
  318. sec->data = elf_newdata(sec->scn);
  319. if (!sec->data) {
  320. pr_warn_elf("failed to create SYMTAB data");
  321. return -EINVAL;
  322. }
  323. /* Ensure libelf translates byte-order of symbol records */
  324. sec->data->d_type = ELF_T_SYM;
  325. str_off = strset__add_str(linker->strtab_strs, sec->sec_name);
  326. if (str_off < 0)
  327. return str_off;
  328. sec->sec_idx = elf_ndxscn(sec->scn);
  329. linker->symtab_sec_idx = sec->sec_idx;
  330. sec->shdr->sh_name = str_off;
  331. sec->shdr->sh_type = SHT_SYMTAB;
  332. sec->shdr->sh_flags = 0;
  333. sec->shdr->sh_offset = 0;
  334. sec->shdr->sh_link = linker->strtab_sec_idx;
  335. /* sh_info should be one greater than the index of the last local
  336. * symbol (i.e., binding is STB_LOCAL). But why and who cares?
  337. */
  338. sec->shdr->sh_info = 0;
  339. sec->shdr->sh_addralign = 8;
  340. sec->shdr->sh_entsize = sizeof(Elf64_Sym);
  341. /* .BTF */
  342. linker->btf = btf__new_empty();
  343. err = libbpf_get_error(linker->btf);
  344. if (err)
  345. return err;
  346. /* add the special all-zero symbol */
  347. init_sym = add_new_sym(linker, NULL);
  348. if (!init_sym)
  349. return -EINVAL;
  350. init_sym->st_name = 0;
  351. init_sym->st_info = 0;
  352. init_sym->st_other = 0;
  353. init_sym->st_shndx = SHN_UNDEF;
  354. init_sym->st_value = 0;
  355. init_sym->st_size = 0;
  356. return 0;
  357. }
  358. int bpf_linker__add_file(struct bpf_linker *linker, const char *filename,
  359. const struct bpf_linker_file_opts *opts)
  360. {
  361. struct src_obj obj = {};
  362. int err = 0;
  363. if (!OPTS_VALID(opts, bpf_linker_file_opts))
  364. return libbpf_err(-EINVAL);
  365. if (!linker->elf)
  366. return libbpf_err(-EINVAL);
  367. err = err ?: linker_load_obj_file(linker, filename, opts, &obj);
  368. err = err ?: linker_append_sec_data(linker, &obj);
  369. err = err ?: linker_append_elf_syms(linker, &obj);
  370. err = err ?: linker_append_elf_relos(linker, &obj);
  371. err = err ?: linker_append_btf(linker, &obj);
  372. err = err ?: linker_append_btf_ext(linker, &obj);
  373. /* free up src_obj resources */
  374. free(obj.btf_type_map);
  375. btf__free(obj.btf);
  376. btf_ext__free(obj.btf_ext);
  377. free(obj.secs);
  378. free(obj.sym_map);
  379. if (obj.elf)
  380. elf_end(obj.elf);
  381. if (obj.fd >= 0)
  382. close(obj.fd);
  383. return libbpf_err(err);
  384. }
  385. static bool is_dwarf_sec_name(const char *name)
  386. {
  387. /* approximation, but the actual list is too long */
  388. return strncmp(name, ".debug_", sizeof(".debug_") - 1) == 0;
  389. }
  390. static bool is_ignored_sec(struct src_sec *sec)
  391. {
  392. Elf64_Shdr *shdr = sec->shdr;
  393. const char *name = sec->sec_name;
  394. /* no special handling of .strtab */
  395. if (shdr->sh_type == SHT_STRTAB)
  396. return true;
  397. /* ignore .llvm_addrsig section as well */
  398. if (shdr->sh_type == SHT_LLVM_ADDRSIG)
  399. return true;
  400. /* no subprograms will lead to an empty .text section, ignore it */
  401. if (shdr->sh_type == SHT_PROGBITS && shdr->sh_size == 0 &&
  402. strcmp(sec->sec_name, ".text") == 0)
  403. return true;
  404. /* DWARF sections */
  405. if (is_dwarf_sec_name(sec->sec_name))
  406. return true;
  407. if (strncmp(name, ".rel", sizeof(".rel") - 1) == 0) {
  408. name += sizeof(".rel") - 1;
  409. /* DWARF section relocations */
  410. if (is_dwarf_sec_name(name))
  411. return true;
  412. /* .BTF and .BTF.ext don't need relocations */
  413. if (strcmp(name, BTF_ELF_SEC) == 0 ||
  414. strcmp(name, BTF_EXT_ELF_SEC) == 0)
  415. return true;
  416. }
  417. return false;
  418. }
  419. static struct src_sec *add_src_sec(struct src_obj *obj, const char *sec_name)
  420. {
  421. struct src_sec *secs = obj->secs, *sec;
  422. size_t new_cnt = obj->sec_cnt ? obj->sec_cnt + 1 : 2;
  423. secs = libbpf_reallocarray(secs, new_cnt, sizeof(*secs));
  424. if (!secs)
  425. return NULL;
  426. /* zero out newly allocated memory */
  427. memset(secs + obj->sec_cnt, 0, (new_cnt - obj->sec_cnt) * sizeof(*secs));
  428. obj->secs = secs;
  429. obj->sec_cnt = new_cnt;
  430. sec = &obj->secs[new_cnt - 1];
  431. sec->id = new_cnt - 1;
  432. sec->sec_name = sec_name;
  433. return sec;
  434. }
  435. static int linker_load_obj_file(struct bpf_linker *linker, const char *filename,
  436. const struct bpf_linker_file_opts *opts,
  437. struct src_obj *obj)
  438. {
  439. #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  440. const int host_endianness = ELFDATA2LSB;
  441. #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
  442. const int host_endianness = ELFDATA2MSB;
  443. #else
  444. #error "Unknown __BYTE_ORDER__"
  445. #endif
  446. int err = 0;
  447. Elf_Scn *scn;
  448. Elf_Data *data;
  449. Elf64_Ehdr *ehdr;
  450. Elf64_Shdr *shdr;
  451. struct src_sec *sec;
  452. pr_debug("linker: adding object file '%s'...\n", filename);
  453. obj->filename = filename;
  454. obj->fd = open(filename, O_RDONLY | O_CLOEXEC);
  455. if (obj->fd < 0) {
  456. err = -errno;
  457. pr_warn("failed to open file '%s': %d\n", filename, err);
  458. return err;
  459. }
  460. obj->elf = elf_begin(obj->fd, ELF_C_READ_MMAP, NULL);
  461. if (!obj->elf) {
  462. pr_warn_elf("failed to parse ELF file '%s'", filename);
  463. return -EINVAL;
  464. }
  465. /* Sanity check ELF file high-level properties */
  466. ehdr = elf64_getehdr(obj->elf);
  467. if (!ehdr) {
  468. pr_warn_elf("failed to get ELF header for %s", filename);
  469. return -EINVAL;
  470. }
  471. if (ehdr->e_ident[EI_DATA] != host_endianness) {
  472. err = -EOPNOTSUPP;
  473. pr_warn_elf("unsupported byte order of ELF file %s", filename);
  474. return err;
  475. }
  476. if (ehdr->e_type != ET_REL
  477. || ehdr->e_machine != EM_BPF
  478. || ehdr->e_ident[EI_CLASS] != ELFCLASS64) {
  479. err = -EOPNOTSUPP;
  480. pr_warn_elf("unsupported kind of ELF file %s", filename);
  481. return err;
  482. }
  483. if (elf_getshdrstrndx(obj->elf, &obj->shstrs_sec_idx)) {
  484. pr_warn_elf("failed to get SHSTRTAB section index for %s", filename);
  485. return -EINVAL;
  486. }
  487. scn = NULL;
  488. while ((scn = elf_nextscn(obj->elf, scn)) != NULL) {
  489. size_t sec_idx = elf_ndxscn(scn);
  490. const char *sec_name;
  491. shdr = elf64_getshdr(scn);
  492. if (!shdr) {
  493. pr_warn_elf("failed to get section #%zu header for %s",
  494. sec_idx, filename);
  495. return -EINVAL;
  496. }
  497. sec_name = elf_strptr(obj->elf, obj->shstrs_sec_idx, shdr->sh_name);
  498. if (!sec_name) {
  499. pr_warn_elf("failed to get section #%zu name for %s",
  500. sec_idx, filename);
  501. return -EINVAL;
  502. }
  503. data = elf_getdata(scn, 0);
  504. if (!data) {
  505. pr_warn_elf("failed to get section #%zu (%s) data from %s",
  506. sec_idx, sec_name, filename);
  507. return -EINVAL;
  508. }
  509. sec = add_src_sec(obj, sec_name);
  510. if (!sec)
  511. return -ENOMEM;
  512. sec->scn = scn;
  513. sec->shdr = shdr;
  514. sec->data = data;
  515. sec->sec_idx = elf_ndxscn(scn);
  516. if (is_ignored_sec(sec)) {
  517. sec->skipped = true;
  518. continue;
  519. }
  520. switch (shdr->sh_type) {
  521. case SHT_SYMTAB:
  522. if (obj->symtab_sec_idx) {
  523. err = -EOPNOTSUPP;
  524. pr_warn("multiple SYMTAB sections found, not supported\n");
  525. return err;
  526. }
  527. obj->symtab_sec_idx = sec_idx;
  528. break;
  529. case SHT_STRTAB:
  530. /* we'll construct our own string table */
  531. break;
  532. case SHT_PROGBITS:
  533. if (strcmp(sec_name, BTF_ELF_SEC) == 0) {
  534. obj->btf = btf__new(data->d_buf, shdr->sh_size);
  535. err = libbpf_get_error(obj->btf);
  536. if (err) {
  537. pr_warn("failed to parse .BTF from %s: %d\n", filename, err);
  538. return err;
  539. }
  540. sec->skipped = true;
  541. continue;
  542. }
  543. if (strcmp(sec_name, BTF_EXT_ELF_SEC) == 0) {
  544. obj->btf_ext = btf_ext__new(data->d_buf, shdr->sh_size);
  545. err = libbpf_get_error(obj->btf_ext);
  546. if (err) {
  547. pr_warn("failed to parse .BTF.ext from '%s': %d\n", filename, err);
  548. return err;
  549. }
  550. sec->skipped = true;
  551. continue;
  552. }
  553. /* data & code */
  554. break;
  555. case SHT_NOBITS:
  556. /* BSS */
  557. break;
  558. case SHT_REL:
  559. /* relocations */
  560. break;
  561. default:
  562. pr_warn("unrecognized section #%zu (%s) in %s\n",
  563. sec_idx, sec_name, filename);
  564. err = -EINVAL;
  565. return err;
  566. }
  567. }
  568. err = err ?: linker_sanity_check_elf(obj);
  569. err = err ?: linker_sanity_check_btf(obj);
  570. err = err ?: linker_sanity_check_btf_ext(obj);
  571. err = err ?: linker_fixup_btf(obj);
  572. return err;
  573. }
  574. static int linker_sanity_check_elf(struct src_obj *obj)
  575. {
  576. struct src_sec *sec;
  577. int i, err;
  578. if (!obj->symtab_sec_idx) {
  579. pr_warn("ELF is missing SYMTAB section in %s\n", obj->filename);
  580. return -EINVAL;
  581. }
  582. if (!obj->shstrs_sec_idx) {
  583. pr_warn("ELF is missing section headers STRTAB section in %s\n", obj->filename);
  584. return -EINVAL;
  585. }
  586. for (i = 1; i < obj->sec_cnt; i++) {
  587. sec = &obj->secs[i];
  588. if (sec->sec_name[0] == '\0') {
  589. pr_warn("ELF section #%zu has empty name in %s\n", sec->sec_idx, obj->filename);
  590. return -EINVAL;
  591. }
  592. if (is_dwarf_sec_name(sec->sec_name))
  593. continue;
  594. if (sec->shdr->sh_addralign && !is_pow_of_2(sec->shdr->sh_addralign)) {
  595. pr_warn("ELF section #%zu alignment %llu is non pow-of-2 alignment in %s\n",
  596. sec->sec_idx, (long long unsigned)sec->shdr->sh_addralign,
  597. obj->filename);
  598. return -EINVAL;
  599. }
  600. if (sec->shdr->sh_addralign != sec->data->d_align) {
  601. pr_warn("ELF section #%zu has inconsistent alignment addr=%llu != d=%llu in %s\n",
  602. sec->sec_idx, (long long unsigned)sec->shdr->sh_addralign,
  603. (long long unsigned)sec->data->d_align, obj->filename);
  604. return -EINVAL;
  605. }
  606. if (sec->shdr->sh_size != sec->data->d_size) {
  607. pr_warn("ELF section #%zu has inconsistent section size sh=%llu != d=%llu in %s\n",
  608. sec->sec_idx, (long long unsigned)sec->shdr->sh_size,
  609. (long long unsigned)sec->data->d_size, obj->filename);
  610. return -EINVAL;
  611. }
  612. switch (sec->shdr->sh_type) {
  613. case SHT_SYMTAB:
  614. err = linker_sanity_check_elf_symtab(obj, sec);
  615. if (err)
  616. return err;
  617. break;
  618. case SHT_STRTAB:
  619. break;
  620. case SHT_PROGBITS:
  621. if (sec->shdr->sh_flags & SHF_EXECINSTR) {
  622. if (sec->shdr->sh_size % sizeof(struct bpf_insn) != 0) {
  623. pr_warn("ELF section #%zu has unexpected size alignment %llu in %s\n",
  624. sec->sec_idx, (long long unsigned)sec->shdr->sh_size,
  625. obj->filename);
  626. return -EINVAL;
  627. }
  628. }
  629. break;
  630. case SHT_NOBITS:
  631. break;
  632. case SHT_REL:
  633. err = linker_sanity_check_elf_relos(obj, sec);
  634. if (err)
  635. return err;
  636. break;
  637. case SHT_LLVM_ADDRSIG:
  638. break;
  639. default:
  640. pr_warn("ELF section #%zu (%s) has unrecognized type %zu in %s\n",
  641. sec->sec_idx, sec->sec_name, (size_t)sec->shdr->sh_type, obj->filename);
  642. return -EINVAL;
  643. }
  644. }
  645. return 0;
  646. }
  647. static int linker_sanity_check_elf_symtab(struct src_obj *obj, struct src_sec *sec)
  648. {
  649. struct src_sec *link_sec;
  650. Elf64_Sym *sym;
  651. int i, n;
  652. if (sec->shdr->sh_entsize != sizeof(Elf64_Sym))
  653. return -EINVAL;
  654. if (sec->shdr->sh_size % sec->shdr->sh_entsize != 0)
  655. return -EINVAL;
  656. if (!sec->shdr->sh_link || sec->shdr->sh_link >= obj->sec_cnt) {
  657. pr_warn("ELF SYMTAB section #%zu points to missing STRTAB section #%zu in %s\n",
  658. sec->sec_idx, (size_t)sec->shdr->sh_link, obj->filename);
  659. return -EINVAL;
  660. }
  661. link_sec = &obj->secs[sec->shdr->sh_link];
  662. if (link_sec->shdr->sh_type != SHT_STRTAB) {
  663. pr_warn("ELF SYMTAB section #%zu points to invalid STRTAB section #%zu in %s\n",
  664. sec->sec_idx, (size_t)sec->shdr->sh_link, obj->filename);
  665. return -EINVAL;
  666. }
  667. n = sec->shdr->sh_size / sec->shdr->sh_entsize;
  668. sym = sec->data->d_buf;
  669. for (i = 0; i < n; i++, sym++) {
  670. int sym_type = ELF64_ST_TYPE(sym->st_info);
  671. int sym_bind = ELF64_ST_BIND(sym->st_info);
  672. int sym_vis = ELF64_ST_VISIBILITY(sym->st_other);
  673. if (i == 0) {
  674. if (sym->st_name != 0 || sym->st_info != 0
  675. || sym->st_other != 0 || sym->st_shndx != 0
  676. || sym->st_value != 0 || sym->st_size != 0) {
  677. pr_warn("ELF sym #0 is invalid in %s\n", obj->filename);
  678. return -EINVAL;
  679. }
  680. continue;
  681. }
  682. if (sym_bind != STB_LOCAL && sym_bind != STB_GLOBAL && sym_bind != STB_WEAK) {
  683. pr_warn("ELF sym #%d in section #%zu has unsupported symbol binding %d\n",
  684. i, sec->sec_idx, sym_bind);
  685. return -EINVAL;
  686. }
  687. if (sym_vis != STV_DEFAULT && sym_vis != STV_HIDDEN) {
  688. pr_warn("ELF sym #%d in section #%zu has unsupported symbol visibility %d\n",
  689. i, sec->sec_idx, sym_vis);
  690. return -EINVAL;
  691. }
  692. if (sym->st_shndx == 0) {
  693. if (sym_type != STT_NOTYPE || sym_bind == STB_LOCAL
  694. || sym->st_value != 0 || sym->st_size != 0) {
  695. pr_warn("ELF sym #%d is invalid extern symbol in %s\n",
  696. i, obj->filename);
  697. return -EINVAL;
  698. }
  699. continue;
  700. }
  701. if (sym->st_shndx < SHN_LORESERVE && sym->st_shndx >= obj->sec_cnt) {
  702. pr_warn("ELF sym #%d in section #%zu points to missing section #%zu in %s\n",
  703. i, sec->sec_idx, (size_t)sym->st_shndx, obj->filename);
  704. return -EINVAL;
  705. }
  706. if (sym_type == STT_SECTION) {
  707. if (sym->st_value != 0)
  708. return -EINVAL;
  709. continue;
  710. }
  711. }
  712. return 0;
  713. }
  714. static int linker_sanity_check_elf_relos(struct src_obj *obj, struct src_sec *sec)
  715. {
  716. struct src_sec *link_sec, *sym_sec;
  717. Elf64_Rel *relo;
  718. int i, n;
  719. if (sec->shdr->sh_entsize != sizeof(Elf64_Rel))
  720. return -EINVAL;
  721. if (sec->shdr->sh_size % sec->shdr->sh_entsize != 0)
  722. return -EINVAL;
  723. /* SHT_REL's sh_link should point to SYMTAB */
  724. if (sec->shdr->sh_link != obj->symtab_sec_idx) {
  725. pr_warn("ELF relo section #%zu points to invalid SYMTAB section #%zu in %s\n",
  726. sec->sec_idx, (size_t)sec->shdr->sh_link, obj->filename);
  727. return -EINVAL;
  728. }
  729. /* SHT_REL's sh_info points to relocated section */
  730. if (!sec->shdr->sh_info || sec->shdr->sh_info >= obj->sec_cnt) {
  731. pr_warn("ELF relo section #%zu points to missing section #%zu in %s\n",
  732. sec->sec_idx, (size_t)sec->shdr->sh_info, obj->filename);
  733. return -EINVAL;
  734. }
  735. link_sec = &obj->secs[sec->shdr->sh_info];
  736. /* .rel<secname> -> <secname> pattern is followed */
  737. if (strncmp(sec->sec_name, ".rel", sizeof(".rel") - 1) != 0
  738. || strcmp(sec->sec_name + sizeof(".rel") - 1, link_sec->sec_name) != 0) {
  739. pr_warn("ELF relo section #%zu name has invalid name in %s\n",
  740. sec->sec_idx, obj->filename);
  741. return -EINVAL;
  742. }
  743. /* don't further validate relocations for ignored sections */
  744. if (link_sec->skipped)
  745. return 0;
  746. /* relocatable section is data or instructions */
  747. if (link_sec->shdr->sh_type != SHT_PROGBITS && link_sec->shdr->sh_type != SHT_NOBITS) {
  748. pr_warn("ELF relo section #%zu points to invalid section #%zu in %s\n",
  749. sec->sec_idx, (size_t)sec->shdr->sh_info, obj->filename);
  750. return -EINVAL;
  751. }
  752. /* check sanity of each relocation */
  753. n = sec->shdr->sh_size / sec->shdr->sh_entsize;
  754. relo = sec->data->d_buf;
  755. sym_sec = &obj->secs[obj->symtab_sec_idx];
  756. for (i = 0; i < n; i++, relo++) {
  757. size_t sym_idx = ELF64_R_SYM(relo->r_info);
  758. size_t sym_type = ELF64_R_TYPE(relo->r_info);
  759. if (sym_type != R_BPF_64_64 && sym_type != R_BPF_64_32 &&
  760. sym_type != R_BPF_64_ABS64 && sym_type != R_BPF_64_ABS32) {
  761. pr_warn("ELF relo #%d in section #%zu has unexpected type %zu in %s\n",
  762. i, sec->sec_idx, sym_type, obj->filename);
  763. return -EINVAL;
  764. }
  765. if (!sym_idx || sym_idx * sizeof(Elf64_Sym) >= sym_sec->shdr->sh_size) {
  766. pr_warn("ELF relo #%d in section #%zu points to invalid symbol #%zu in %s\n",
  767. i, sec->sec_idx, sym_idx, obj->filename);
  768. return -EINVAL;
  769. }
  770. if (link_sec->shdr->sh_flags & SHF_EXECINSTR) {
  771. if (relo->r_offset % sizeof(struct bpf_insn) != 0) {
  772. pr_warn("ELF relo #%d in section #%zu points to missing symbol #%zu in %s\n",
  773. i, sec->sec_idx, sym_idx, obj->filename);
  774. return -EINVAL;
  775. }
  776. }
  777. }
  778. return 0;
  779. }
  780. static int check_btf_type_id(__u32 *type_id, void *ctx)
  781. {
  782. struct btf *btf = ctx;
  783. if (*type_id >= btf__type_cnt(btf))
  784. return -EINVAL;
  785. return 0;
  786. }
  787. static int check_btf_str_off(__u32 *str_off, void *ctx)
  788. {
  789. struct btf *btf = ctx;
  790. const char *s;
  791. s = btf__str_by_offset(btf, *str_off);
  792. if (!s)
  793. return -EINVAL;
  794. return 0;
  795. }
  796. static int linker_sanity_check_btf(struct src_obj *obj)
  797. {
  798. struct btf_type *t;
  799. int i, n, err;
  800. if (!obj->btf)
  801. return 0;
  802. n = btf__type_cnt(obj->btf);
  803. for (i = 1; i < n; i++) {
  804. struct btf_field_iter it;
  805. __u32 *type_id, *str_off;
  806. t = btf_type_by_id(obj->btf, i);
  807. err = btf_field_iter_init(&it, t, BTF_FIELD_ITER_IDS);
  808. if (err)
  809. return err;
  810. while ((type_id = btf_field_iter_next(&it))) {
  811. if (*type_id >= n)
  812. return -EINVAL;
  813. }
  814. err = btf_field_iter_init(&it, t, BTF_FIELD_ITER_STRS);
  815. if (err)
  816. return err;
  817. while ((str_off = btf_field_iter_next(&it))) {
  818. if (!btf__str_by_offset(obj->btf, *str_off))
  819. return -EINVAL;
  820. }
  821. }
  822. return 0;
  823. }
  824. static int linker_sanity_check_btf_ext(struct src_obj *obj)
  825. {
  826. int err = 0;
  827. if (!obj->btf_ext)
  828. return 0;
  829. /* can't use .BTF.ext without .BTF */
  830. if (!obj->btf)
  831. return -EINVAL;
  832. err = err ?: btf_ext_visit_type_ids(obj->btf_ext, check_btf_type_id, obj->btf);
  833. err = err ?: btf_ext_visit_str_offs(obj->btf_ext, check_btf_str_off, obj->btf);
  834. if (err)
  835. return err;
  836. return 0;
  837. }
  838. static int init_sec(struct bpf_linker *linker, struct dst_sec *dst_sec, struct src_sec *src_sec)
  839. {
  840. Elf_Scn *scn;
  841. Elf_Data *data;
  842. Elf64_Shdr *shdr;
  843. int name_off;
  844. dst_sec->sec_sz = 0;
  845. dst_sec->sec_idx = 0;
  846. dst_sec->ephemeral = src_sec->ephemeral;
  847. /* ephemeral sections are just thin section shells lacking most parts */
  848. if (src_sec->ephemeral)
  849. return 0;
  850. scn = elf_newscn(linker->elf);
  851. if (!scn)
  852. return -ENOMEM;
  853. data = elf_newdata(scn);
  854. if (!data)
  855. return -ENOMEM;
  856. shdr = elf64_getshdr(scn);
  857. if (!shdr)
  858. return -ENOMEM;
  859. dst_sec->scn = scn;
  860. dst_sec->shdr = shdr;
  861. dst_sec->data = data;
  862. dst_sec->sec_idx = elf_ndxscn(scn);
  863. name_off = strset__add_str(linker->strtab_strs, src_sec->sec_name);
  864. if (name_off < 0)
  865. return name_off;
  866. shdr->sh_name = name_off;
  867. shdr->sh_type = src_sec->shdr->sh_type;
  868. shdr->sh_flags = src_sec->shdr->sh_flags;
  869. shdr->sh_size = 0;
  870. /* sh_link and sh_info have different meaning for different types of
  871. * sections, so we leave it up to the caller code to fill them in, if
  872. * necessary
  873. */
  874. shdr->sh_link = 0;
  875. shdr->sh_info = 0;
  876. shdr->sh_addralign = src_sec->shdr->sh_addralign;
  877. shdr->sh_entsize = src_sec->shdr->sh_entsize;
  878. data->d_type = src_sec->data->d_type;
  879. data->d_size = 0;
  880. data->d_buf = NULL;
  881. data->d_align = src_sec->data->d_align;
  882. data->d_off = 0;
  883. return 0;
  884. }
  885. static struct dst_sec *find_dst_sec_by_name(struct bpf_linker *linker, const char *sec_name)
  886. {
  887. struct dst_sec *sec;
  888. int i;
  889. for (i = 1; i < linker->sec_cnt; i++) {
  890. sec = &linker->secs[i];
  891. if (strcmp(sec->sec_name, sec_name) == 0)
  892. return sec;
  893. }
  894. return NULL;
  895. }
  896. static bool secs_match(struct dst_sec *dst, struct src_sec *src)
  897. {
  898. if (dst->ephemeral || src->ephemeral)
  899. return true;
  900. if (dst->shdr->sh_type != src->shdr->sh_type) {
  901. pr_warn("sec %s types mismatch\n", dst->sec_name);
  902. return false;
  903. }
  904. if (dst->shdr->sh_flags != src->shdr->sh_flags) {
  905. pr_warn("sec %s flags mismatch\n", dst->sec_name);
  906. return false;
  907. }
  908. if (dst->shdr->sh_entsize != src->shdr->sh_entsize) {
  909. pr_warn("sec %s entsize mismatch\n", dst->sec_name);
  910. return false;
  911. }
  912. return true;
  913. }
  914. static bool sec_content_is_same(struct dst_sec *dst_sec, struct src_sec *src_sec)
  915. {
  916. if (dst_sec->sec_sz != src_sec->shdr->sh_size)
  917. return false;
  918. if (memcmp(dst_sec->raw_data, src_sec->data->d_buf, dst_sec->sec_sz) != 0)
  919. return false;
  920. return true;
  921. }
  922. static int extend_sec(struct bpf_linker *linker, struct dst_sec *dst, struct src_sec *src)
  923. {
  924. void *tmp;
  925. size_t dst_align, src_align;
  926. size_t dst_align_sz, dst_final_sz;
  927. int err;
  928. /* Ephemeral source section doesn't contribute anything to ELF
  929. * section data.
  930. */
  931. if (src->ephemeral)
  932. return 0;
  933. /* Some sections (like .maps) can contain both externs (and thus be
  934. * ephemeral) and non-externs (map definitions). So it's possible that
  935. * it has to be "upgraded" from ephemeral to non-ephemeral when the
  936. * first non-ephemeral entity appears. In such case, we add ELF
  937. * section, data, etc.
  938. */
  939. if (dst->ephemeral) {
  940. err = init_sec(linker, dst, src);
  941. if (err)
  942. return err;
  943. }
  944. dst_align = dst->shdr->sh_addralign;
  945. src_align = src->shdr->sh_addralign;
  946. if (dst_align == 0)
  947. dst_align = 1;
  948. if (dst_align < src_align)
  949. dst_align = src_align;
  950. dst_align_sz = (dst->sec_sz + dst_align - 1) / dst_align * dst_align;
  951. /* no need to re-align final size */
  952. dst_final_sz = dst_align_sz + src->shdr->sh_size;
  953. if (src->shdr->sh_type != SHT_NOBITS) {
  954. tmp = realloc(dst->raw_data, dst_final_sz);
  955. /* If dst_align_sz == 0, realloc() behaves in a special way:
  956. * 1. When dst->raw_data is NULL it returns:
  957. * "either NULL or a pointer suitable to be passed to free()" [1].
  958. * 2. When dst->raw_data is not-NULL it frees dst->raw_data and returns NULL,
  959. * thus invalidating any "pointer suitable to be passed to free()" obtained
  960. * at step (1).
  961. *
  962. * The dst_align_sz > 0 check avoids error exit after (2), otherwise
  963. * dst->raw_data would be freed again in bpf_linker__free().
  964. *
  965. * [1] man 3 realloc
  966. */
  967. if (!tmp && dst_align_sz > 0)
  968. return -ENOMEM;
  969. dst->raw_data = tmp;
  970. /* pad dst section, if it's alignment forced size increase */
  971. memset(dst->raw_data + dst->sec_sz, 0, dst_align_sz - dst->sec_sz);
  972. /* now copy src data at a properly aligned offset */
  973. memcpy(dst->raw_data + dst_align_sz, src->data->d_buf, src->shdr->sh_size);
  974. }
  975. dst->sec_sz = dst_final_sz;
  976. dst->shdr->sh_size = dst_final_sz;
  977. dst->data->d_size = dst_final_sz;
  978. dst->shdr->sh_addralign = dst_align;
  979. dst->data->d_align = dst_align;
  980. src->dst_off = dst_align_sz;
  981. return 0;
  982. }
  983. static bool is_data_sec(struct src_sec *sec)
  984. {
  985. if (!sec || sec->skipped)
  986. return false;
  987. /* ephemeral sections are data sections, e.g., .kconfig, .ksyms */
  988. if (sec->ephemeral)
  989. return true;
  990. return sec->shdr->sh_type == SHT_PROGBITS || sec->shdr->sh_type == SHT_NOBITS;
  991. }
  992. static bool is_relo_sec(struct src_sec *sec)
  993. {
  994. if (!sec || sec->skipped || sec->ephemeral)
  995. return false;
  996. return sec->shdr->sh_type == SHT_REL;
  997. }
  998. static int linker_append_sec_data(struct bpf_linker *linker, struct src_obj *obj)
  999. {
  1000. int i, err;
  1001. for (i = 1; i < obj->sec_cnt; i++) {
  1002. struct src_sec *src_sec;
  1003. struct dst_sec *dst_sec;
  1004. src_sec = &obj->secs[i];
  1005. if (!is_data_sec(src_sec))
  1006. continue;
  1007. dst_sec = find_dst_sec_by_name(linker, src_sec->sec_name);
  1008. if (!dst_sec) {
  1009. dst_sec = add_dst_sec(linker, src_sec->sec_name);
  1010. if (!dst_sec)
  1011. return -ENOMEM;
  1012. err = init_sec(linker, dst_sec, src_sec);
  1013. if (err) {
  1014. pr_warn("failed to init section '%s'\n", src_sec->sec_name);
  1015. return err;
  1016. }
  1017. } else {
  1018. if (!secs_match(dst_sec, src_sec)) {
  1019. pr_warn("ELF sections %s are incompatible\n", src_sec->sec_name);
  1020. return -EINVAL;
  1021. }
  1022. /* "license" and "version" sections are deduped */
  1023. if (strcmp(src_sec->sec_name, "license") == 0
  1024. || strcmp(src_sec->sec_name, "version") == 0) {
  1025. if (!sec_content_is_same(dst_sec, src_sec)) {
  1026. pr_warn("non-identical contents of section '%s' are not supported\n", src_sec->sec_name);
  1027. return -EINVAL;
  1028. }
  1029. src_sec->skipped = true;
  1030. src_sec->dst_id = dst_sec->id;
  1031. continue;
  1032. }
  1033. }
  1034. /* record mapped section index */
  1035. src_sec->dst_id = dst_sec->id;
  1036. err = extend_sec(linker, dst_sec, src_sec);
  1037. if (err)
  1038. return err;
  1039. }
  1040. return 0;
  1041. }
  1042. static int linker_append_elf_syms(struct bpf_linker *linker, struct src_obj *obj)
  1043. {
  1044. struct src_sec *symtab = &obj->secs[obj->symtab_sec_idx];
  1045. Elf64_Sym *sym = symtab->data->d_buf;
  1046. int i, n = symtab->shdr->sh_size / symtab->shdr->sh_entsize, err;
  1047. int str_sec_idx = symtab->shdr->sh_link;
  1048. const char *sym_name;
  1049. obj->sym_map = calloc(n + 1, sizeof(*obj->sym_map));
  1050. if (!obj->sym_map)
  1051. return -ENOMEM;
  1052. for (i = 0; i < n; i++, sym++) {
  1053. /* We already validated all-zero symbol #0 and we already
  1054. * appended it preventively to the final SYMTAB, so skip it.
  1055. */
  1056. if (i == 0)
  1057. continue;
  1058. sym_name = elf_strptr(obj->elf, str_sec_idx, sym->st_name);
  1059. if (!sym_name) {
  1060. pr_warn("can't fetch symbol name for symbol #%d in '%s'\n", i, obj->filename);
  1061. return -EINVAL;
  1062. }
  1063. err = linker_append_elf_sym(linker, obj, sym, sym_name, i);
  1064. if (err)
  1065. return err;
  1066. }
  1067. return 0;
  1068. }
  1069. static Elf64_Sym *get_sym_by_idx(struct bpf_linker *linker, size_t sym_idx)
  1070. {
  1071. struct dst_sec *symtab = &linker->secs[linker->symtab_sec_idx];
  1072. Elf64_Sym *syms = symtab->raw_data;
  1073. return &syms[sym_idx];
  1074. }
  1075. static struct glob_sym *find_glob_sym(struct bpf_linker *linker, const char *sym_name)
  1076. {
  1077. struct glob_sym *glob_sym;
  1078. const char *name;
  1079. int i;
  1080. for (i = 0; i < linker->glob_sym_cnt; i++) {
  1081. glob_sym = &linker->glob_syms[i];
  1082. name = strset__data(linker->strtab_strs) + glob_sym->name_off;
  1083. if (strcmp(name, sym_name) == 0)
  1084. return glob_sym;
  1085. }
  1086. return NULL;
  1087. }
  1088. static struct glob_sym *add_glob_sym(struct bpf_linker *linker)
  1089. {
  1090. struct glob_sym *syms, *sym;
  1091. syms = libbpf_reallocarray(linker->glob_syms, linker->glob_sym_cnt + 1,
  1092. sizeof(*linker->glob_syms));
  1093. if (!syms)
  1094. return NULL;
  1095. sym = &syms[linker->glob_sym_cnt];
  1096. memset(sym, 0, sizeof(*sym));
  1097. sym->var_idx = -1;
  1098. linker->glob_syms = syms;
  1099. linker->glob_sym_cnt++;
  1100. return sym;
  1101. }
  1102. static bool glob_sym_btf_matches(const char *sym_name, bool exact,
  1103. const struct btf *btf1, __u32 id1,
  1104. const struct btf *btf2, __u32 id2)
  1105. {
  1106. const struct btf_type *t1, *t2;
  1107. bool is_static1, is_static2;
  1108. const char *n1, *n2;
  1109. int i, n;
  1110. recur:
  1111. n1 = n2 = NULL;
  1112. t1 = skip_mods_and_typedefs(btf1, id1, &id1);
  1113. t2 = skip_mods_and_typedefs(btf2, id2, &id2);
  1114. /* check if only one side is FWD, otherwise handle with common logic */
  1115. if (!exact && btf_is_fwd(t1) != btf_is_fwd(t2)) {
  1116. n1 = btf__str_by_offset(btf1, t1->name_off);
  1117. n2 = btf__str_by_offset(btf2, t2->name_off);
  1118. if (strcmp(n1, n2) != 0) {
  1119. pr_warn("global '%s': incompatible forward declaration names '%s' and '%s'\n",
  1120. sym_name, n1, n2);
  1121. return false;
  1122. }
  1123. /* validate if FWD kind matches concrete kind */
  1124. if (btf_is_fwd(t1)) {
  1125. if (btf_kflag(t1) && btf_is_union(t2))
  1126. return true;
  1127. if (!btf_kflag(t1) && btf_is_struct(t2))
  1128. return true;
  1129. pr_warn("global '%s': incompatible %s forward declaration and concrete kind %s\n",
  1130. sym_name, btf_kflag(t1) ? "union" : "struct", btf_kind_str(t2));
  1131. } else {
  1132. if (btf_kflag(t2) && btf_is_union(t1))
  1133. return true;
  1134. if (!btf_kflag(t2) && btf_is_struct(t1))
  1135. return true;
  1136. pr_warn("global '%s': incompatible %s forward declaration and concrete kind %s\n",
  1137. sym_name, btf_kflag(t2) ? "union" : "struct", btf_kind_str(t1));
  1138. }
  1139. return false;
  1140. }
  1141. if (btf_kind(t1) != btf_kind(t2)) {
  1142. pr_warn("global '%s': incompatible BTF kinds %s and %s\n",
  1143. sym_name, btf_kind_str(t1), btf_kind_str(t2));
  1144. return false;
  1145. }
  1146. switch (btf_kind(t1)) {
  1147. case BTF_KIND_STRUCT:
  1148. case BTF_KIND_UNION:
  1149. case BTF_KIND_ENUM:
  1150. case BTF_KIND_ENUM64:
  1151. case BTF_KIND_FWD:
  1152. case BTF_KIND_FUNC:
  1153. case BTF_KIND_VAR:
  1154. n1 = btf__str_by_offset(btf1, t1->name_off);
  1155. n2 = btf__str_by_offset(btf2, t2->name_off);
  1156. if (strcmp(n1, n2) != 0) {
  1157. pr_warn("global '%s': incompatible %s names '%s' and '%s'\n",
  1158. sym_name, btf_kind_str(t1), n1, n2);
  1159. return false;
  1160. }
  1161. break;
  1162. default:
  1163. break;
  1164. }
  1165. switch (btf_kind(t1)) {
  1166. case BTF_KIND_UNKN: /* void */
  1167. case BTF_KIND_FWD:
  1168. return true;
  1169. case BTF_KIND_INT:
  1170. case BTF_KIND_FLOAT:
  1171. case BTF_KIND_ENUM:
  1172. case BTF_KIND_ENUM64:
  1173. /* ignore encoding for int and enum values for enum */
  1174. if (t1->size != t2->size) {
  1175. pr_warn("global '%s': incompatible %s '%s' size %u and %u\n",
  1176. sym_name, btf_kind_str(t1), n1, t1->size, t2->size);
  1177. return false;
  1178. }
  1179. return true;
  1180. case BTF_KIND_PTR:
  1181. /* just validate overall shape of the referenced type, so no
  1182. * contents comparison for struct/union, and allowed fwd vs
  1183. * struct/union
  1184. */
  1185. exact = false;
  1186. id1 = t1->type;
  1187. id2 = t2->type;
  1188. goto recur;
  1189. case BTF_KIND_ARRAY:
  1190. /* ignore index type and array size */
  1191. id1 = btf_array(t1)->type;
  1192. id2 = btf_array(t2)->type;
  1193. goto recur;
  1194. case BTF_KIND_FUNC:
  1195. /* extern and global linkages are compatible */
  1196. is_static1 = btf_func_linkage(t1) == BTF_FUNC_STATIC;
  1197. is_static2 = btf_func_linkage(t2) == BTF_FUNC_STATIC;
  1198. if (is_static1 != is_static2) {
  1199. pr_warn("global '%s': incompatible func '%s' linkage\n", sym_name, n1);
  1200. return false;
  1201. }
  1202. id1 = t1->type;
  1203. id2 = t2->type;
  1204. goto recur;
  1205. case BTF_KIND_VAR:
  1206. /* extern and global linkages are compatible */
  1207. is_static1 = btf_var(t1)->linkage == BTF_VAR_STATIC;
  1208. is_static2 = btf_var(t2)->linkage == BTF_VAR_STATIC;
  1209. if (is_static1 != is_static2) {
  1210. pr_warn("global '%s': incompatible var '%s' linkage\n", sym_name, n1);
  1211. return false;
  1212. }
  1213. id1 = t1->type;
  1214. id2 = t2->type;
  1215. goto recur;
  1216. case BTF_KIND_STRUCT:
  1217. case BTF_KIND_UNION: {
  1218. const struct btf_member *m1, *m2;
  1219. if (!exact)
  1220. return true;
  1221. if (btf_vlen(t1) != btf_vlen(t2)) {
  1222. pr_warn("global '%s': incompatible number of %s fields %u and %u\n",
  1223. sym_name, btf_kind_str(t1), btf_vlen(t1), btf_vlen(t2));
  1224. return false;
  1225. }
  1226. n = btf_vlen(t1);
  1227. m1 = btf_members(t1);
  1228. m2 = btf_members(t2);
  1229. for (i = 0; i < n; i++, m1++, m2++) {
  1230. n1 = btf__str_by_offset(btf1, m1->name_off);
  1231. n2 = btf__str_by_offset(btf2, m2->name_off);
  1232. if (strcmp(n1, n2) != 0) {
  1233. pr_warn("global '%s': incompatible field #%d names '%s' and '%s'\n",
  1234. sym_name, i, n1, n2);
  1235. return false;
  1236. }
  1237. if (m1->offset != m2->offset) {
  1238. pr_warn("global '%s': incompatible field #%d ('%s') offsets\n",
  1239. sym_name, i, n1);
  1240. return false;
  1241. }
  1242. if (!glob_sym_btf_matches(sym_name, exact, btf1, m1->type, btf2, m2->type))
  1243. return false;
  1244. }
  1245. return true;
  1246. }
  1247. case BTF_KIND_FUNC_PROTO: {
  1248. const struct btf_param *m1, *m2;
  1249. if (btf_vlen(t1) != btf_vlen(t2)) {
  1250. pr_warn("global '%s': incompatible number of %s params %u and %u\n",
  1251. sym_name, btf_kind_str(t1), btf_vlen(t1), btf_vlen(t2));
  1252. return false;
  1253. }
  1254. n = btf_vlen(t1);
  1255. m1 = btf_params(t1);
  1256. m2 = btf_params(t2);
  1257. for (i = 0; i < n; i++, m1++, m2++) {
  1258. /* ignore func arg names */
  1259. if (!glob_sym_btf_matches(sym_name, exact, btf1, m1->type, btf2, m2->type))
  1260. return false;
  1261. }
  1262. /* now check return type as well */
  1263. id1 = t1->type;
  1264. id2 = t2->type;
  1265. goto recur;
  1266. }
  1267. /* skip_mods_and_typedefs() make this impossible */
  1268. case BTF_KIND_TYPEDEF:
  1269. case BTF_KIND_VOLATILE:
  1270. case BTF_KIND_CONST:
  1271. case BTF_KIND_RESTRICT:
  1272. /* DATASECs are never compared with each other */
  1273. case BTF_KIND_DATASEC:
  1274. default:
  1275. pr_warn("global '%s': unsupported BTF kind %s\n",
  1276. sym_name, btf_kind_str(t1));
  1277. return false;
  1278. }
  1279. }
  1280. static bool map_defs_match(const char *sym_name,
  1281. const struct btf *main_btf,
  1282. const struct btf_map_def *main_def,
  1283. const struct btf_map_def *main_inner_def,
  1284. const struct btf *extra_btf,
  1285. const struct btf_map_def *extra_def,
  1286. const struct btf_map_def *extra_inner_def)
  1287. {
  1288. const char *reason;
  1289. if (main_def->map_type != extra_def->map_type) {
  1290. reason = "type";
  1291. goto mismatch;
  1292. }
  1293. /* check key type/size match */
  1294. if (main_def->key_size != extra_def->key_size) {
  1295. reason = "key_size";
  1296. goto mismatch;
  1297. }
  1298. if (!!main_def->key_type_id != !!extra_def->key_type_id) {
  1299. reason = "key type";
  1300. goto mismatch;
  1301. }
  1302. if ((main_def->parts & MAP_DEF_KEY_TYPE)
  1303. && !glob_sym_btf_matches(sym_name, true /*exact*/,
  1304. main_btf, main_def->key_type_id,
  1305. extra_btf, extra_def->key_type_id)) {
  1306. reason = "key type";
  1307. goto mismatch;
  1308. }
  1309. /* validate value type/size match */
  1310. if (main_def->value_size != extra_def->value_size) {
  1311. reason = "value_size";
  1312. goto mismatch;
  1313. }
  1314. if (!!main_def->value_type_id != !!extra_def->value_type_id) {
  1315. reason = "value type";
  1316. goto mismatch;
  1317. }
  1318. if ((main_def->parts & MAP_DEF_VALUE_TYPE)
  1319. && !glob_sym_btf_matches(sym_name, true /*exact*/,
  1320. main_btf, main_def->value_type_id,
  1321. extra_btf, extra_def->value_type_id)) {
  1322. reason = "key type";
  1323. goto mismatch;
  1324. }
  1325. if (main_def->max_entries != extra_def->max_entries) {
  1326. reason = "max_entries";
  1327. goto mismatch;
  1328. }
  1329. if (main_def->map_flags != extra_def->map_flags) {
  1330. reason = "map_flags";
  1331. goto mismatch;
  1332. }
  1333. if (main_def->numa_node != extra_def->numa_node) {
  1334. reason = "numa_node";
  1335. goto mismatch;
  1336. }
  1337. if (main_def->pinning != extra_def->pinning) {
  1338. reason = "pinning";
  1339. goto mismatch;
  1340. }
  1341. if ((main_def->parts & MAP_DEF_INNER_MAP) != (extra_def->parts & MAP_DEF_INNER_MAP)) {
  1342. reason = "inner map";
  1343. goto mismatch;
  1344. }
  1345. if (main_def->parts & MAP_DEF_INNER_MAP) {
  1346. char inner_map_name[128];
  1347. snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", sym_name);
  1348. return map_defs_match(inner_map_name,
  1349. main_btf, main_inner_def, NULL,
  1350. extra_btf, extra_inner_def, NULL);
  1351. }
  1352. return true;
  1353. mismatch:
  1354. pr_warn("global '%s': map %s mismatch\n", sym_name, reason);
  1355. return false;
  1356. }
  1357. static bool glob_map_defs_match(const char *sym_name,
  1358. struct bpf_linker *linker, struct glob_sym *glob_sym,
  1359. struct src_obj *obj, Elf64_Sym *sym, int btf_id)
  1360. {
  1361. struct btf_map_def dst_def = {}, dst_inner_def = {};
  1362. struct btf_map_def src_def = {}, src_inner_def = {};
  1363. const struct btf_type *t;
  1364. int err;
  1365. t = btf__type_by_id(obj->btf, btf_id);
  1366. if (!btf_is_var(t)) {
  1367. pr_warn("global '%s': invalid map definition type [%d]\n", sym_name, btf_id);
  1368. return false;
  1369. }
  1370. t = skip_mods_and_typedefs(obj->btf, t->type, NULL);
  1371. err = parse_btf_map_def(sym_name, obj->btf, t, true /*strict*/, &src_def, &src_inner_def);
  1372. if (err) {
  1373. pr_warn("global '%s': invalid map definition\n", sym_name);
  1374. return false;
  1375. }
  1376. /* re-parse existing map definition */
  1377. t = btf__type_by_id(linker->btf, glob_sym->btf_id);
  1378. t = skip_mods_and_typedefs(linker->btf, t->type, NULL);
  1379. err = parse_btf_map_def(sym_name, linker->btf, t, true /*strict*/, &dst_def, &dst_inner_def);
  1380. if (err) {
  1381. /* this should not happen, because we already validated it */
  1382. pr_warn("global '%s': invalid dst map definition\n", sym_name);
  1383. return false;
  1384. }
  1385. /* Currently extern map definition has to be complete and match
  1386. * concrete map definition exactly. This restriction might be lifted
  1387. * in the future.
  1388. */
  1389. return map_defs_match(sym_name, linker->btf, &dst_def, &dst_inner_def,
  1390. obj->btf, &src_def, &src_inner_def);
  1391. }
  1392. static bool glob_syms_match(const char *sym_name,
  1393. struct bpf_linker *linker, struct glob_sym *glob_sym,
  1394. struct src_obj *obj, Elf64_Sym *sym, size_t sym_idx, int btf_id)
  1395. {
  1396. const struct btf_type *src_t;
  1397. /* if we are dealing with externs, BTF types describing both global
  1398. * and extern VARs/FUNCs should be completely present in all files
  1399. */
  1400. if (!glob_sym->btf_id || !btf_id) {
  1401. pr_warn("BTF info is missing for global symbol '%s'\n", sym_name);
  1402. return false;
  1403. }
  1404. src_t = btf__type_by_id(obj->btf, btf_id);
  1405. if (!btf_is_var(src_t) && !btf_is_func(src_t)) {
  1406. pr_warn("only extern variables and functions are supported, but got '%s' for '%s'\n",
  1407. btf_kind_str(src_t), sym_name);
  1408. return false;
  1409. }
  1410. /* deal with .maps definitions specially */
  1411. if (glob_sym->sec_id && strcmp(linker->secs[glob_sym->sec_id].sec_name, MAPS_ELF_SEC) == 0)
  1412. return glob_map_defs_match(sym_name, linker, glob_sym, obj, sym, btf_id);
  1413. if (!glob_sym_btf_matches(sym_name, true /*exact*/,
  1414. linker->btf, glob_sym->btf_id, obj->btf, btf_id))
  1415. return false;
  1416. return true;
  1417. }
  1418. static bool btf_is_non_static(const struct btf_type *t)
  1419. {
  1420. return (btf_is_var(t) && btf_var(t)->linkage != BTF_VAR_STATIC)
  1421. || (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_STATIC);
  1422. }
  1423. static int find_glob_sym_btf(struct src_obj *obj, Elf64_Sym *sym, const char *sym_name,
  1424. int *out_btf_sec_id, int *out_btf_id)
  1425. {
  1426. int i, j, n, m, btf_id = 0;
  1427. const struct btf_type *t;
  1428. const struct btf_var_secinfo *vi;
  1429. const char *name;
  1430. if (!obj->btf) {
  1431. pr_warn("failed to find BTF info for object '%s'\n", obj->filename);
  1432. return -EINVAL;
  1433. }
  1434. n = btf__type_cnt(obj->btf);
  1435. for (i = 1; i < n; i++) {
  1436. t = btf__type_by_id(obj->btf, i);
  1437. /* some global and extern FUNCs and VARs might not be associated with any
  1438. * DATASEC, so try to detect them in the same pass
  1439. */
  1440. if (btf_is_non_static(t)) {
  1441. name = btf__str_by_offset(obj->btf, t->name_off);
  1442. if (strcmp(name, sym_name) != 0)
  1443. continue;
  1444. /* remember and still try to find DATASEC */
  1445. btf_id = i;
  1446. continue;
  1447. }
  1448. if (!btf_is_datasec(t))
  1449. continue;
  1450. vi = btf_var_secinfos(t);
  1451. for (j = 0, m = btf_vlen(t); j < m; j++, vi++) {
  1452. t = btf__type_by_id(obj->btf, vi->type);
  1453. name = btf__str_by_offset(obj->btf, t->name_off);
  1454. if (strcmp(name, sym_name) != 0)
  1455. continue;
  1456. if (btf_is_var(t) && btf_var(t)->linkage == BTF_VAR_STATIC)
  1457. continue;
  1458. if (btf_is_func(t) && btf_func_linkage(t) == BTF_FUNC_STATIC)
  1459. continue;
  1460. if (btf_id && btf_id != vi->type) {
  1461. pr_warn("global/extern '%s' BTF is ambiguous: both types #%d and #%u match\n",
  1462. sym_name, btf_id, vi->type);
  1463. return -EINVAL;
  1464. }
  1465. *out_btf_sec_id = i;
  1466. *out_btf_id = vi->type;
  1467. return 0;
  1468. }
  1469. }
  1470. /* free-floating extern or global FUNC */
  1471. if (btf_id) {
  1472. *out_btf_sec_id = 0;
  1473. *out_btf_id = btf_id;
  1474. return 0;
  1475. }
  1476. pr_warn("failed to find BTF info for global/extern symbol '%s'\n", sym_name);
  1477. return -ENOENT;
  1478. }
  1479. static struct src_sec *find_src_sec_by_name(struct src_obj *obj, const char *sec_name)
  1480. {
  1481. struct src_sec *sec;
  1482. int i;
  1483. for (i = 1; i < obj->sec_cnt; i++) {
  1484. sec = &obj->secs[i];
  1485. if (strcmp(sec->sec_name, sec_name) == 0)
  1486. return sec;
  1487. }
  1488. return NULL;
  1489. }
  1490. static int complete_extern_btf_info(struct btf *dst_btf, int dst_id,
  1491. struct btf *src_btf, int src_id)
  1492. {
  1493. struct btf_type *dst_t = btf_type_by_id(dst_btf, dst_id);
  1494. struct btf_type *src_t = btf_type_by_id(src_btf, src_id);
  1495. struct btf_param *src_p, *dst_p;
  1496. const char *s;
  1497. int i, n, off;
  1498. /* We already made sure that source and destination types (FUNC or
  1499. * VAR) match in terms of types and argument names.
  1500. */
  1501. if (btf_is_var(dst_t)) {
  1502. btf_var(dst_t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
  1503. return 0;
  1504. }
  1505. dst_t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_GLOBAL, 0);
  1506. /* now onto FUNC_PROTO types */
  1507. src_t = btf_type_by_id(src_btf, src_t->type);
  1508. dst_t = btf_type_by_id(dst_btf, dst_t->type);
  1509. /* Fill in all the argument names, which for extern FUNCs are missing.
  1510. * We'll end up with two copies of FUNCs/VARs for externs, but that
  1511. * will be taken care of by BTF dedup at the very end.
  1512. * It might be that BTF types for extern in one file has less/more BTF
  1513. * information (e.g., FWD instead of full STRUCT/UNION information),
  1514. * but that should be (in most cases, subject to BTF dedup rules)
  1515. * handled and resolved by BTF dedup algorithm as well, so we won't
  1516. * worry about it. Our only job is to make sure that argument names
  1517. * are populated on both sides, otherwise BTF dedup will pedantically
  1518. * consider them different.
  1519. */
  1520. src_p = btf_params(src_t);
  1521. dst_p = btf_params(dst_t);
  1522. for (i = 0, n = btf_vlen(dst_t); i < n; i++, src_p++, dst_p++) {
  1523. if (!src_p->name_off)
  1524. continue;
  1525. /* src_btf has more complete info, so add name to dst_btf */
  1526. s = btf__str_by_offset(src_btf, src_p->name_off);
  1527. off = btf__add_str(dst_btf, s);
  1528. if (off < 0)
  1529. return off;
  1530. dst_p->name_off = off;
  1531. }
  1532. return 0;
  1533. }
  1534. static void sym_update_bind(Elf64_Sym *sym, int sym_bind)
  1535. {
  1536. sym->st_info = ELF64_ST_INFO(sym_bind, ELF64_ST_TYPE(sym->st_info));
  1537. }
  1538. static void sym_update_type(Elf64_Sym *sym, int sym_type)
  1539. {
  1540. sym->st_info = ELF64_ST_INFO(ELF64_ST_BIND(sym->st_info), sym_type);
  1541. }
  1542. static void sym_update_visibility(Elf64_Sym *sym, int sym_vis)
  1543. {
  1544. /* libelf doesn't provide setters for ST_VISIBILITY,
  1545. * but it is stored in the lower 2 bits of st_other
  1546. */
  1547. sym->st_other &= ~0x03;
  1548. sym->st_other |= sym_vis;
  1549. }
  1550. static int linker_append_elf_sym(struct bpf_linker *linker, struct src_obj *obj,
  1551. Elf64_Sym *sym, const char *sym_name, int src_sym_idx)
  1552. {
  1553. struct src_sec *src_sec = NULL;
  1554. struct dst_sec *dst_sec = NULL;
  1555. struct glob_sym *glob_sym = NULL;
  1556. int name_off, sym_type, sym_bind, sym_vis, err;
  1557. int btf_sec_id = 0, btf_id = 0;
  1558. size_t dst_sym_idx;
  1559. Elf64_Sym *dst_sym;
  1560. bool sym_is_extern;
  1561. sym_type = ELF64_ST_TYPE(sym->st_info);
  1562. sym_bind = ELF64_ST_BIND(sym->st_info);
  1563. sym_vis = ELF64_ST_VISIBILITY(sym->st_other);
  1564. sym_is_extern = sym->st_shndx == SHN_UNDEF;
  1565. if (sym_is_extern) {
  1566. if (!obj->btf) {
  1567. pr_warn("externs without BTF info are not supported\n");
  1568. return -ENOTSUP;
  1569. }
  1570. } else if (sym->st_shndx < SHN_LORESERVE) {
  1571. src_sec = &obj->secs[sym->st_shndx];
  1572. if (src_sec->skipped)
  1573. return 0;
  1574. dst_sec = &linker->secs[src_sec->dst_id];
  1575. /* allow only one STT_SECTION symbol per section */
  1576. if (sym_type == STT_SECTION && dst_sec->sec_sym_idx) {
  1577. obj->sym_map[src_sym_idx] = dst_sec->sec_sym_idx;
  1578. return 0;
  1579. }
  1580. }
  1581. if (sym_bind == STB_LOCAL)
  1582. goto add_sym;
  1583. /* find matching BTF info */
  1584. err = find_glob_sym_btf(obj, sym, sym_name, &btf_sec_id, &btf_id);
  1585. if (err)
  1586. return err;
  1587. if (sym_is_extern && btf_sec_id) {
  1588. const char *sec_name = NULL;
  1589. const struct btf_type *t;
  1590. t = btf__type_by_id(obj->btf, btf_sec_id);
  1591. sec_name = btf__str_by_offset(obj->btf, t->name_off);
  1592. /* Clang puts unannotated extern vars into
  1593. * '.extern' BTF DATASEC. Treat them the same
  1594. * as unannotated extern funcs (which are
  1595. * currently not put into any DATASECs).
  1596. * Those don't have associated src_sec/dst_sec.
  1597. */
  1598. if (strcmp(sec_name, BTF_EXTERN_SEC) != 0) {
  1599. src_sec = find_src_sec_by_name(obj, sec_name);
  1600. if (!src_sec) {
  1601. pr_warn("failed to find matching ELF sec '%s'\n", sec_name);
  1602. return -ENOENT;
  1603. }
  1604. dst_sec = &linker->secs[src_sec->dst_id];
  1605. }
  1606. }
  1607. glob_sym = find_glob_sym(linker, sym_name);
  1608. if (glob_sym) {
  1609. /* Preventively resolve to existing symbol. This is
  1610. * needed for further relocation symbol remapping in
  1611. * the next step of linking.
  1612. */
  1613. obj->sym_map[src_sym_idx] = glob_sym->sym_idx;
  1614. /* If both symbols are non-externs, at least one of
  1615. * them has to be STB_WEAK, otherwise they are in
  1616. * a conflict with each other.
  1617. */
  1618. if (!sym_is_extern && !glob_sym->is_extern
  1619. && !glob_sym->is_weak && sym_bind != STB_WEAK) {
  1620. pr_warn("conflicting non-weak symbol #%d (%s) definition in '%s'\n",
  1621. src_sym_idx, sym_name, obj->filename);
  1622. return -EINVAL;
  1623. }
  1624. if (!glob_syms_match(sym_name, linker, glob_sym, obj, sym, src_sym_idx, btf_id))
  1625. return -EINVAL;
  1626. dst_sym = get_sym_by_idx(linker, glob_sym->sym_idx);
  1627. /* If new symbol is strong, then force dst_sym to be strong as
  1628. * well; this way a mix of weak and non-weak extern
  1629. * definitions will end up being strong.
  1630. */
  1631. if (sym_bind == STB_GLOBAL) {
  1632. /* We still need to preserve type (NOTYPE or
  1633. * OBJECT/FUNC, depending on whether the symbol is
  1634. * extern or not)
  1635. */
  1636. sym_update_bind(dst_sym, STB_GLOBAL);
  1637. glob_sym->is_weak = false;
  1638. }
  1639. /* Non-default visibility is "contaminating", with stricter
  1640. * visibility overwriting more permissive ones, even if more
  1641. * permissive visibility comes from just an extern definition.
  1642. * Currently only STV_DEFAULT and STV_HIDDEN are allowed and
  1643. * ensured by ELF symbol sanity checks above.
  1644. */
  1645. if (sym_vis > ELF64_ST_VISIBILITY(dst_sym->st_other))
  1646. sym_update_visibility(dst_sym, sym_vis);
  1647. /* If the new symbol is extern, then regardless if
  1648. * existing symbol is extern or resolved global, just
  1649. * keep the existing one untouched.
  1650. */
  1651. if (sym_is_extern)
  1652. return 0;
  1653. /* If existing symbol is a strong resolved symbol, bail out,
  1654. * because we lost resolution battle have nothing to
  1655. * contribute. We already checked above that there is no
  1656. * strong-strong conflict. We also already tightened binding
  1657. * and visibility, so nothing else to contribute at that point.
  1658. */
  1659. if (!glob_sym->is_extern && sym_bind == STB_WEAK)
  1660. return 0;
  1661. /* At this point, new symbol is strong non-extern,
  1662. * so overwrite glob_sym with new symbol information.
  1663. * Preserve binding and visibility.
  1664. */
  1665. sym_update_type(dst_sym, sym_type);
  1666. dst_sym->st_shndx = dst_sec->sec_idx;
  1667. dst_sym->st_value = src_sec->dst_off + sym->st_value;
  1668. dst_sym->st_size = sym->st_size;
  1669. /* see comment below about dst_sec->id vs dst_sec->sec_idx */
  1670. glob_sym->sec_id = dst_sec->id;
  1671. glob_sym->is_extern = false;
  1672. if (complete_extern_btf_info(linker->btf, glob_sym->btf_id,
  1673. obj->btf, btf_id))
  1674. return -EINVAL;
  1675. /* request updating VAR's/FUNC's underlying BTF type when appending BTF type */
  1676. glob_sym->underlying_btf_id = 0;
  1677. obj->sym_map[src_sym_idx] = glob_sym->sym_idx;
  1678. return 0;
  1679. }
  1680. add_sym:
  1681. name_off = strset__add_str(linker->strtab_strs, sym_name);
  1682. if (name_off < 0)
  1683. return name_off;
  1684. dst_sym = add_new_sym(linker, &dst_sym_idx);
  1685. if (!dst_sym)
  1686. return -ENOMEM;
  1687. dst_sym->st_name = name_off;
  1688. dst_sym->st_info = sym->st_info;
  1689. dst_sym->st_other = sym->st_other;
  1690. dst_sym->st_shndx = dst_sec ? dst_sec->sec_idx : sym->st_shndx;
  1691. dst_sym->st_value = (src_sec ? src_sec->dst_off : 0) + sym->st_value;
  1692. dst_sym->st_size = sym->st_size;
  1693. obj->sym_map[src_sym_idx] = dst_sym_idx;
  1694. if (sym_type == STT_SECTION && dst_sec) {
  1695. dst_sec->sec_sym_idx = dst_sym_idx;
  1696. dst_sym->st_value = 0;
  1697. }
  1698. if (sym_bind != STB_LOCAL) {
  1699. glob_sym = add_glob_sym(linker);
  1700. if (!glob_sym)
  1701. return -ENOMEM;
  1702. glob_sym->sym_idx = dst_sym_idx;
  1703. /* we use dst_sec->id (and not dst_sec->sec_idx), because
  1704. * ephemeral sections (.kconfig, .ksyms, etc) don't have
  1705. * sec_idx (as they don't have corresponding ELF section), but
  1706. * still have id. .extern doesn't have even ephemeral section
  1707. * associated with it, so dst_sec->id == dst_sec->sec_idx == 0.
  1708. */
  1709. glob_sym->sec_id = dst_sec ? dst_sec->id : 0;
  1710. glob_sym->name_off = name_off;
  1711. /* we will fill btf_id in during BTF merging step */
  1712. glob_sym->btf_id = 0;
  1713. glob_sym->is_extern = sym_is_extern;
  1714. glob_sym->is_weak = sym_bind == STB_WEAK;
  1715. }
  1716. return 0;
  1717. }
  1718. static int linker_append_elf_relos(struct bpf_linker *linker, struct src_obj *obj)
  1719. {
  1720. struct src_sec *src_symtab = &obj->secs[obj->symtab_sec_idx];
  1721. int i, err;
  1722. for (i = 1; i < obj->sec_cnt; i++) {
  1723. struct src_sec *src_sec, *src_linked_sec;
  1724. struct dst_sec *dst_sec, *dst_linked_sec;
  1725. Elf64_Rel *src_rel, *dst_rel;
  1726. int j, n;
  1727. src_sec = &obj->secs[i];
  1728. if (!is_relo_sec(src_sec))
  1729. continue;
  1730. /* shdr->sh_info points to relocatable section */
  1731. src_linked_sec = &obj->secs[src_sec->shdr->sh_info];
  1732. if (src_linked_sec->skipped)
  1733. continue;
  1734. dst_sec = find_dst_sec_by_name(linker, src_sec->sec_name);
  1735. if (!dst_sec) {
  1736. dst_sec = add_dst_sec(linker, src_sec->sec_name);
  1737. if (!dst_sec)
  1738. return -ENOMEM;
  1739. err = init_sec(linker, dst_sec, src_sec);
  1740. if (err) {
  1741. pr_warn("failed to init section '%s'\n", src_sec->sec_name);
  1742. return err;
  1743. }
  1744. } else if (!secs_match(dst_sec, src_sec)) {
  1745. pr_warn("sections %s are not compatible\n", src_sec->sec_name);
  1746. return -EINVAL;
  1747. }
  1748. /* shdr->sh_link points to SYMTAB */
  1749. dst_sec->shdr->sh_link = linker->symtab_sec_idx;
  1750. /* shdr->sh_info points to relocated section */
  1751. dst_linked_sec = &linker->secs[src_linked_sec->dst_id];
  1752. dst_sec->shdr->sh_info = dst_linked_sec->sec_idx;
  1753. src_sec->dst_id = dst_sec->id;
  1754. err = extend_sec(linker, dst_sec, src_sec);
  1755. if (err)
  1756. return err;
  1757. src_rel = src_sec->data->d_buf;
  1758. dst_rel = dst_sec->raw_data + src_sec->dst_off;
  1759. n = src_sec->shdr->sh_size / src_sec->shdr->sh_entsize;
  1760. for (j = 0; j < n; j++, src_rel++, dst_rel++) {
  1761. size_t src_sym_idx, dst_sym_idx, sym_type;
  1762. Elf64_Sym *src_sym;
  1763. src_sym_idx = ELF64_R_SYM(src_rel->r_info);
  1764. src_sym = src_symtab->data->d_buf + sizeof(*src_sym) * src_sym_idx;
  1765. dst_sym_idx = obj->sym_map[src_sym_idx];
  1766. dst_rel->r_offset += src_linked_sec->dst_off;
  1767. sym_type = ELF64_R_TYPE(src_rel->r_info);
  1768. dst_rel->r_info = ELF64_R_INFO(dst_sym_idx, sym_type);
  1769. if (ELF64_ST_TYPE(src_sym->st_info) == STT_SECTION) {
  1770. struct src_sec *sec = &obj->secs[src_sym->st_shndx];
  1771. struct bpf_insn *insn;
  1772. if (src_linked_sec->shdr->sh_flags & SHF_EXECINSTR) {
  1773. /* calls to the very first static function inside
  1774. * .text section at offset 0 will
  1775. * reference section symbol, not the
  1776. * function symbol. Fix that up,
  1777. * otherwise it won't be possible to
  1778. * relocate calls to two different
  1779. * static functions with the same name
  1780. * (rom two different object files)
  1781. */
  1782. insn = dst_linked_sec->raw_data + dst_rel->r_offset;
  1783. if (insn->code == (BPF_JMP | BPF_CALL))
  1784. insn->imm += sec->dst_off / sizeof(struct bpf_insn);
  1785. else
  1786. insn->imm += sec->dst_off;
  1787. } else {
  1788. pr_warn("relocation against STT_SECTION in non-exec section is not supported!\n");
  1789. return -EINVAL;
  1790. }
  1791. }
  1792. }
  1793. }
  1794. return 0;
  1795. }
  1796. static Elf64_Sym *find_sym_by_name(struct src_obj *obj, size_t sec_idx,
  1797. int sym_type, const char *sym_name)
  1798. {
  1799. struct src_sec *symtab = &obj->secs[obj->symtab_sec_idx];
  1800. Elf64_Sym *sym = symtab->data->d_buf;
  1801. int i, n = symtab->shdr->sh_size / symtab->shdr->sh_entsize;
  1802. int str_sec_idx = symtab->shdr->sh_link;
  1803. const char *name;
  1804. for (i = 0; i < n; i++, sym++) {
  1805. if (sym->st_shndx != sec_idx)
  1806. continue;
  1807. if (ELF64_ST_TYPE(sym->st_info) != sym_type)
  1808. continue;
  1809. name = elf_strptr(obj->elf, str_sec_idx, sym->st_name);
  1810. if (!name)
  1811. return NULL;
  1812. if (strcmp(sym_name, name) != 0)
  1813. continue;
  1814. return sym;
  1815. }
  1816. return NULL;
  1817. }
  1818. static int linker_fixup_btf(struct src_obj *obj)
  1819. {
  1820. const char *sec_name;
  1821. struct src_sec *sec;
  1822. int i, j, n, m;
  1823. if (!obj->btf)
  1824. return 0;
  1825. n = btf__type_cnt(obj->btf);
  1826. for (i = 1; i < n; i++) {
  1827. struct btf_var_secinfo *vi;
  1828. struct btf_type *t;
  1829. t = btf_type_by_id(obj->btf, i);
  1830. if (btf_kind(t) != BTF_KIND_DATASEC)
  1831. continue;
  1832. sec_name = btf__str_by_offset(obj->btf, t->name_off);
  1833. sec = find_src_sec_by_name(obj, sec_name);
  1834. if (sec) {
  1835. /* record actual section size, unless ephemeral */
  1836. if (sec->shdr)
  1837. t->size = sec->shdr->sh_size;
  1838. } else {
  1839. /* BTF can have some sections that are not represented
  1840. * in ELF, e.g., .kconfig, .ksyms, .extern, which are used
  1841. * for special extern variables.
  1842. *
  1843. * For all but one such special (ephemeral)
  1844. * sections, we pre-create "section shells" to be able
  1845. * to keep track of extra per-section metadata later
  1846. * (e.g., those BTF extern variables).
  1847. *
  1848. * .extern is even more special, though, because it
  1849. * contains extern variables that need to be resolved
  1850. * by static linker, not libbpf and kernel. When such
  1851. * externs are resolved, we are going to remove them
  1852. * from .extern BTF section and might end up not
  1853. * needing it at all. Each resolved extern should have
  1854. * matching non-extern VAR/FUNC in other sections.
  1855. *
  1856. * We do support leaving some of the externs
  1857. * unresolved, though, to support cases of building
  1858. * libraries, which will later be linked against final
  1859. * BPF applications. So if at finalization we still
  1860. * see unresolved externs, we'll create .extern
  1861. * section on our own.
  1862. */
  1863. if (strcmp(sec_name, BTF_EXTERN_SEC) == 0)
  1864. continue;
  1865. sec = add_src_sec(obj, sec_name);
  1866. if (!sec)
  1867. return -ENOMEM;
  1868. sec->ephemeral = true;
  1869. sec->sec_idx = 0; /* will match UNDEF shndx in ELF */
  1870. }
  1871. /* remember ELF section and its BTF type ID match */
  1872. sec->sec_type_id = i;
  1873. /* fix up variable offsets */
  1874. vi = btf_var_secinfos(t);
  1875. for (j = 0, m = btf_vlen(t); j < m; j++, vi++) {
  1876. const struct btf_type *vt = btf__type_by_id(obj->btf, vi->type);
  1877. const char *var_name;
  1878. int var_linkage;
  1879. Elf64_Sym *sym;
  1880. /* could be a variable or function */
  1881. if (!btf_is_var(vt))
  1882. continue;
  1883. var_name = btf__str_by_offset(obj->btf, vt->name_off);
  1884. var_linkage = btf_var(vt)->linkage;
  1885. /* no need to patch up static or extern vars */
  1886. if (var_linkage != BTF_VAR_GLOBAL_ALLOCATED)
  1887. continue;
  1888. sym = find_sym_by_name(obj, sec->sec_idx, STT_OBJECT, var_name);
  1889. if (!sym) {
  1890. pr_warn("failed to find symbol for variable '%s' in section '%s'\n", var_name, sec_name);
  1891. return -ENOENT;
  1892. }
  1893. vi->offset = sym->st_value;
  1894. }
  1895. }
  1896. return 0;
  1897. }
  1898. static int linker_append_btf(struct bpf_linker *linker, struct src_obj *obj)
  1899. {
  1900. const struct btf_type *t;
  1901. int i, j, n, start_id, id, err;
  1902. const char *name;
  1903. if (!obj->btf)
  1904. return 0;
  1905. start_id = btf__type_cnt(linker->btf);
  1906. n = btf__type_cnt(obj->btf);
  1907. obj->btf_type_map = calloc(n + 1, sizeof(int));
  1908. if (!obj->btf_type_map)
  1909. return -ENOMEM;
  1910. for (i = 1; i < n; i++) {
  1911. struct glob_sym *glob_sym = NULL;
  1912. t = btf__type_by_id(obj->btf, i);
  1913. /* DATASECs are handled specially below */
  1914. if (btf_kind(t) == BTF_KIND_DATASEC)
  1915. continue;
  1916. if (btf_is_non_static(t)) {
  1917. /* there should be glob_sym already */
  1918. name = btf__str_by_offset(obj->btf, t->name_off);
  1919. glob_sym = find_glob_sym(linker, name);
  1920. /* VARs without corresponding glob_sym are those that
  1921. * belong to skipped/deduplicated sections (i.e.,
  1922. * license and version), so just skip them
  1923. */
  1924. if (!glob_sym)
  1925. continue;
  1926. /* linker_append_elf_sym() might have requested
  1927. * updating underlying type ID, if extern was resolved
  1928. * to strong symbol or weak got upgraded to non-weak
  1929. */
  1930. if (glob_sym->underlying_btf_id == 0)
  1931. glob_sym->underlying_btf_id = -t->type;
  1932. /* globals from previous object files that match our
  1933. * VAR/FUNC already have a corresponding associated
  1934. * BTF type, so just make sure to use it
  1935. */
  1936. if (glob_sym->btf_id) {
  1937. /* reuse existing BTF type for global var/func */
  1938. obj->btf_type_map[i] = glob_sym->btf_id;
  1939. continue;
  1940. }
  1941. }
  1942. id = btf__add_type(linker->btf, obj->btf, t);
  1943. if (id < 0) {
  1944. pr_warn("failed to append BTF type #%d from file '%s'\n", i, obj->filename);
  1945. return id;
  1946. }
  1947. obj->btf_type_map[i] = id;
  1948. /* record just appended BTF type for var/func */
  1949. if (glob_sym) {
  1950. glob_sym->btf_id = id;
  1951. glob_sym->underlying_btf_id = -t->type;
  1952. }
  1953. }
  1954. /* remap all the types except DATASECs */
  1955. n = btf__type_cnt(linker->btf);
  1956. for (i = start_id; i < n; i++) {
  1957. struct btf_type *dst_t = btf_type_by_id(linker->btf, i);
  1958. struct btf_field_iter it;
  1959. __u32 *type_id;
  1960. err = btf_field_iter_init(&it, dst_t, BTF_FIELD_ITER_IDS);
  1961. if (err)
  1962. return err;
  1963. while ((type_id = btf_field_iter_next(&it))) {
  1964. int new_id = obj->btf_type_map[*type_id];
  1965. /* Error out if the type wasn't remapped. Ignore VOID which stays VOID. */
  1966. if (new_id == 0 && *type_id != 0) {
  1967. pr_warn("failed to find new ID mapping for original BTF type ID %u\n",
  1968. *type_id);
  1969. return -EINVAL;
  1970. }
  1971. *type_id = obj->btf_type_map[*type_id];
  1972. }
  1973. }
  1974. /* Rewrite VAR/FUNC underlying types (i.e., FUNC's FUNC_PROTO and VAR's
  1975. * actual type), if necessary
  1976. */
  1977. for (i = 0; i < linker->glob_sym_cnt; i++) {
  1978. struct glob_sym *glob_sym = &linker->glob_syms[i];
  1979. struct btf_type *glob_t;
  1980. if (glob_sym->underlying_btf_id >= 0)
  1981. continue;
  1982. glob_sym->underlying_btf_id = obj->btf_type_map[-glob_sym->underlying_btf_id];
  1983. glob_t = btf_type_by_id(linker->btf, glob_sym->btf_id);
  1984. glob_t->type = glob_sym->underlying_btf_id;
  1985. }
  1986. /* append DATASEC info */
  1987. for (i = 1; i < obj->sec_cnt; i++) {
  1988. struct src_sec *src_sec;
  1989. struct dst_sec *dst_sec;
  1990. const struct btf_var_secinfo *src_var;
  1991. struct btf_var_secinfo *dst_var;
  1992. src_sec = &obj->secs[i];
  1993. if (!src_sec->sec_type_id || src_sec->skipped)
  1994. continue;
  1995. dst_sec = &linker->secs[src_sec->dst_id];
  1996. /* Mark section as having BTF regardless of the presence of
  1997. * variables. In some cases compiler might generate empty BTF
  1998. * with no variables information. E.g., when promoting local
  1999. * array/structure variable initial values and BPF object
  2000. * file otherwise has no read-only static variables in
  2001. * .rodata. We need to preserve such empty BTF and just set
  2002. * correct section size.
  2003. */
  2004. dst_sec->has_btf = true;
  2005. t = btf__type_by_id(obj->btf, src_sec->sec_type_id);
  2006. src_var = btf_var_secinfos(t);
  2007. n = btf_vlen(t);
  2008. for (j = 0; j < n; j++, src_var++) {
  2009. void *sec_vars = dst_sec->sec_vars;
  2010. int new_id = obj->btf_type_map[src_var->type];
  2011. struct glob_sym *glob_sym = NULL;
  2012. t = btf_type_by_id(linker->btf, new_id);
  2013. if (btf_is_non_static(t)) {
  2014. name = btf__str_by_offset(linker->btf, t->name_off);
  2015. glob_sym = find_glob_sym(linker, name);
  2016. if (glob_sym->sec_id != dst_sec->id) {
  2017. pr_warn("global '%s': section mismatch %d vs %d\n",
  2018. name, glob_sym->sec_id, dst_sec->id);
  2019. return -EINVAL;
  2020. }
  2021. }
  2022. /* If there is already a member (VAR or FUNC) mapped
  2023. * to the same type, don't add a duplicate entry.
  2024. * This will happen when multiple object files define
  2025. * the same extern VARs/FUNCs.
  2026. */
  2027. if (glob_sym && glob_sym->var_idx >= 0) {
  2028. __s64 sz;
  2029. dst_var = &dst_sec->sec_vars[glob_sym->var_idx];
  2030. /* Because underlying BTF type might have
  2031. * changed, so might its size have changed, so
  2032. * re-calculate and update it in sec_var.
  2033. */
  2034. sz = btf__resolve_size(linker->btf, glob_sym->underlying_btf_id);
  2035. if (sz < 0) {
  2036. pr_warn("global '%s': failed to resolve size of underlying type: %d\n",
  2037. name, (int)sz);
  2038. return -EINVAL;
  2039. }
  2040. dst_var->size = sz;
  2041. continue;
  2042. }
  2043. sec_vars = libbpf_reallocarray(sec_vars,
  2044. dst_sec->sec_var_cnt + 1,
  2045. sizeof(*dst_sec->sec_vars));
  2046. if (!sec_vars)
  2047. return -ENOMEM;
  2048. dst_sec->sec_vars = sec_vars;
  2049. dst_sec->sec_var_cnt++;
  2050. dst_var = &dst_sec->sec_vars[dst_sec->sec_var_cnt - 1];
  2051. dst_var->type = obj->btf_type_map[src_var->type];
  2052. dst_var->size = src_var->size;
  2053. dst_var->offset = src_sec->dst_off + src_var->offset;
  2054. if (glob_sym)
  2055. glob_sym->var_idx = dst_sec->sec_var_cnt - 1;
  2056. }
  2057. }
  2058. return 0;
  2059. }
  2060. static void *add_btf_ext_rec(struct btf_ext_sec_data *ext_data, const void *src_rec)
  2061. {
  2062. void *tmp;
  2063. tmp = libbpf_reallocarray(ext_data->recs, ext_data->rec_cnt + 1, ext_data->rec_sz);
  2064. if (!tmp)
  2065. return NULL;
  2066. ext_data->recs = tmp;
  2067. tmp += ext_data->rec_cnt * ext_data->rec_sz;
  2068. memcpy(tmp, src_rec, ext_data->rec_sz);
  2069. ext_data->rec_cnt++;
  2070. return tmp;
  2071. }
  2072. static int linker_append_btf_ext(struct bpf_linker *linker, struct src_obj *obj)
  2073. {
  2074. const struct btf_ext_info_sec *ext_sec;
  2075. const char *sec_name, *s;
  2076. struct src_sec *src_sec;
  2077. struct dst_sec *dst_sec;
  2078. int rec_sz, str_off, i;
  2079. if (!obj->btf_ext)
  2080. return 0;
  2081. rec_sz = obj->btf_ext->func_info.rec_size;
  2082. for_each_btf_ext_sec(&obj->btf_ext->func_info, ext_sec) {
  2083. struct bpf_func_info_min *src_rec, *dst_rec;
  2084. sec_name = btf__name_by_offset(obj->btf, ext_sec->sec_name_off);
  2085. src_sec = find_src_sec_by_name(obj, sec_name);
  2086. if (!src_sec) {
  2087. pr_warn("can't find section '%s' referenced from .BTF.ext\n", sec_name);
  2088. return -EINVAL;
  2089. }
  2090. dst_sec = &linker->secs[src_sec->dst_id];
  2091. if (dst_sec->func_info.rec_sz == 0)
  2092. dst_sec->func_info.rec_sz = rec_sz;
  2093. if (dst_sec->func_info.rec_sz != rec_sz) {
  2094. pr_warn("incompatible .BTF.ext record sizes for section '%s'\n", sec_name);
  2095. return -EINVAL;
  2096. }
  2097. for_each_btf_ext_rec(&obj->btf_ext->func_info, ext_sec, i, src_rec) {
  2098. dst_rec = add_btf_ext_rec(&dst_sec->func_info, src_rec);
  2099. if (!dst_rec)
  2100. return -ENOMEM;
  2101. dst_rec->insn_off += src_sec->dst_off;
  2102. dst_rec->type_id = obj->btf_type_map[dst_rec->type_id];
  2103. }
  2104. }
  2105. rec_sz = obj->btf_ext->line_info.rec_size;
  2106. for_each_btf_ext_sec(&obj->btf_ext->line_info, ext_sec) {
  2107. struct bpf_line_info_min *src_rec, *dst_rec;
  2108. sec_name = btf__name_by_offset(obj->btf, ext_sec->sec_name_off);
  2109. src_sec = find_src_sec_by_name(obj, sec_name);
  2110. if (!src_sec) {
  2111. pr_warn("can't find section '%s' referenced from .BTF.ext\n", sec_name);
  2112. return -EINVAL;
  2113. }
  2114. dst_sec = &linker->secs[src_sec->dst_id];
  2115. if (dst_sec->line_info.rec_sz == 0)
  2116. dst_sec->line_info.rec_sz = rec_sz;
  2117. if (dst_sec->line_info.rec_sz != rec_sz) {
  2118. pr_warn("incompatible .BTF.ext record sizes for section '%s'\n", sec_name);
  2119. return -EINVAL;
  2120. }
  2121. for_each_btf_ext_rec(&obj->btf_ext->line_info, ext_sec, i, src_rec) {
  2122. dst_rec = add_btf_ext_rec(&dst_sec->line_info, src_rec);
  2123. if (!dst_rec)
  2124. return -ENOMEM;
  2125. dst_rec->insn_off += src_sec->dst_off;
  2126. s = btf__str_by_offset(obj->btf, src_rec->file_name_off);
  2127. str_off = btf__add_str(linker->btf, s);
  2128. if (str_off < 0)
  2129. return -ENOMEM;
  2130. dst_rec->file_name_off = str_off;
  2131. s = btf__str_by_offset(obj->btf, src_rec->line_off);
  2132. str_off = btf__add_str(linker->btf, s);
  2133. if (str_off < 0)
  2134. return -ENOMEM;
  2135. dst_rec->line_off = str_off;
  2136. /* dst_rec->line_col is fine */
  2137. }
  2138. }
  2139. rec_sz = obj->btf_ext->core_relo_info.rec_size;
  2140. for_each_btf_ext_sec(&obj->btf_ext->core_relo_info, ext_sec) {
  2141. struct bpf_core_relo *src_rec, *dst_rec;
  2142. sec_name = btf__name_by_offset(obj->btf, ext_sec->sec_name_off);
  2143. src_sec = find_src_sec_by_name(obj, sec_name);
  2144. if (!src_sec) {
  2145. pr_warn("can't find section '%s' referenced from .BTF.ext\n", sec_name);
  2146. return -EINVAL;
  2147. }
  2148. dst_sec = &linker->secs[src_sec->dst_id];
  2149. if (dst_sec->core_relo_info.rec_sz == 0)
  2150. dst_sec->core_relo_info.rec_sz = rec_sz;
  2151. if (dst_sec->core_relo_info.rec_sz != rec_sz) {
  2152. pr_warn("incompatible .BTF.ext record sizes for section '%s'\n", sec_name);
  2153. return -EINVAL;
  2154. }
  2155. for_each_btf_ext_rec(&obj->btf_ext->core_relo_info, ext_sec, i, src_rec) {
  2156. dst_rec = add_btf_ext_rec(&dst_sec->core_relo_info, src_rec);
  2157. if (!dst_rec)
  2158. return -ENOMEM;
  2159. dst_rec->insn_off += src_sec->dst_off;
  2160. dst_rec->type_id = obj->btf_type_map[dst_rec->type_id];
  2161. s = btf__str_by_offset(obj->btf, src_rec->access_str_off);
  2162. str_off = btf__add_str(linker->btf, s);
  2163. if (str_off < 0)
  2164. return -ENOMEM;
  2165. dst_rec->access_str_off = str_off;
  2166. /* dst_rec->kind is fine */
  2167. }
  2168. }
  2169. return 0;
  2170. }
  2171. int bpf_linker__finalize(struct bpf_linker *linker)
  2172. {
  2173. struct dst_sec *sec;
  2174. size_t strs_sz;
  2175. const void *strs;
  2176. int err, i;
  2177. if (!linker->elf)
  2178. return libbpf_err(-EINVAL);
  2179. err = finalize_btf(linker);
  2180. if (err)
  2181. return libbpf_err(err);
  2182. /* Finalize strings */
  2183. strs_sz = strset__data_size(linker->strtab_strs);
  2184. strs = strset__data(linker->strtab_strs);
  2185. sec = &linker->secs[linker->strtab_sec_idx];
  2186. sec->data->d_align = 1;
  2187. sec->data->d_off = 0LL;
  2188. sec->data->d_buf = (void *)strs;
  2189. sec->data->d_type = ELF_T_BYTE;
  2190. sec->data->d_size = strs_sz;
  2191. sec->shdr->sh_size = strs_sz;
  2192. for (i = 1; i < linker->sec_cnt; i++) {
  2193. sec = &linker->secs[i];
  2194. /* STRTAB is handled specially above */
  2195. if (sec->sec_idx == linker->strtab_sec_idx)
  2196. continue;
  2197. /* special ephemeral sections (.ksyms, .kconfig, etc) */
  2198. if (!sec->scn)
  2199. continue;
  2200. sec->data->d_buf = sec->raw_data;
  2201. }
  2202. /* Finalize ELF layout */
  2203. if (elf_update(linker->elf, ELF_C_NULL) < 0) {
  2204. err = -EINVAL;
  2205. pr_warn_elf("failed to finalize ELF layout");
  2206. return libbpf_err(err);
  2207. }
  2208. /* Write out final ELF contents */
  2209. if (elf_update(linker->elf, ELF_C_WRITE) < 0) {
  2210. err = -EINVAL;
  2211. pr_warn_elf("failed to write ELF contents");
  2212. return libbpf_err(err);
  2213. }
  2214. elf_end(linker->elf);
  2215. close(linker->fd);
  2216. linker->elf = NULL;
  2217. linker->fd = -1;
  2218. return 0;
  2219. }
  2220. static int emit_elf_data_sec(struct bpf_linker *linker, const char *sec_name,
  2221. size_t align, const void *raw_data, size_t raw_sz)
  2222. {
  2223. Elf_Scn *scn;
  2224. Elf_Data *data;
  2225. Elf64_Shdr *shdr;
  2226. int name_off;
  2227. name_off = strset__add_str(linker->strtab_strs, sec_name);
  2228. if (name_off < 0)
  2229. return name_off;
  2230. scn = elf_newscn(linker->elf);
  2231. if (!scn)
  2232. return -ENOMEM;
  2233. data = elf_newdata(scn);
  2234. if (!data)
  2235. return -ENOMEM;
  2236. shdr = elf64_getshdr(scn);
  2237. if (!shdr)
  2238. return -EINVAL;
  2239. shdr->sh_name = name_off;
  2240. shdr->sh_type = SHT_PROGBITS;
  2241. shdr->sh_flags = 0;
  2242. shdr->sh_size = raw_sz;
  2243. shdr->sh_link = 0;
  2244. shdr->sh_info = 0;
  2245. shdr->sh_addralign = align;
  2246. shdr->sh_entsize = 0;
  2247. data->d_type = ELF_T_BYTE;
  2248. data->d_size = raw_sz;
  2249. data->d_buf = (void *)raw_data;
  2250. data->d_align = align;
  2251. data->d_off = 0;
  2252. return 0;
  2253. }
  2254. static int finalize_btf(struct bpf_linker *linker)
  2255. {
  2256. LIBBPF_OPTS(btf_dedup_opts, opts);
  2257. struct btf *btf = linker->btf;
  2258. const void *raw_data;
  2259. int i, j, id, err;
  2260. __u32 raw_sz;
  2261. /* bail out if no BTF data was produced */
  2262. if (btf__type_cnt(linker->btf) == 1)
  2263. return 0;
  2264. for (i = 1; i < linker->sec_cnt; i++) {
  2265. struct dst_sec *sec = &linker->secs[i];
  2266. if (!sec->has_btf)
  2267. continue;
  2268. id = btf__add_datasec(btf, sec->sec_name, sec->sec_sz);
  2269. if (id < 0) {
  2270. pr_warn("failed to add consolidated BTF type for datasec '%s': %d\n",
  2271. sec->sec_name, id);
  2272. return id;
  2273. }
  2274. for (j = 0; j < sec->sec_var_cnt; j++) {
  2275. struct btf_var_secinfo *vi = &sec->sec_vars[j];
  2276. if (btf__add_datasec_var_info(btf, vi->type, vi->offset, vi->size))
  2277. return -EINVAL;
  2278. }
  2279. }
  2280. err = finalize_btf_ext(linker);
  2281. if (err) {
  2282. pr_warn(".BTF.ext generation failed: %d\n", err);
  2283. return err;
  2284. }
  2285. opts.btf_ext = linker->btf_ext;
  2286. err = btf__dedup(linker->btf, &opts);
  2287. if (err) {
  2288. pr_warn("BTF dedup failed: %d\n", err);
  2289. return err;
  2290. }
  2291. /* Emit .BTF section */
  2292. raw_data = btf__raw_data(linker->btf, &raw_sz);
  2293. if (!raw_data)
  2294. return -ENOMEM;
  2295. err = emit_elf_data_sec(linker, BTF_ELF_SEC, 8, raw_data, raw_sz);
  2296. if (err) {
  2297. pr_warn("failed to write out .BTF ELF section: %d\n", err);
  2298. return err;
  2299. }
  2300. /* Emit .BTF.ext section */
  2301. if (linker->btf_ext) {
  2302. raw_data = btf_ext__raw_data(linker->btf_ext, &raw_sz);
  2303. if (!raw_data)
  2304. return -ENOMEM;
  2305. err = emit_elf_data_sec(linker, BTF_EXT_ELF_SEC, 8, raw_data, raw_sz);
  2306. if (err) {
  2307. pr_warn("failed to write out .BTF.ext ELF section: %d\n", err);
  2308. return err;
  2309. }
  2310. }
  2311. return 0;
  2312. }
  2313. static int emit_btf_ext_data(struct bpf_linker *linker, void *output,
  2314. const char *sec_name, struct btf_ext_sec_data *sec_data)
  2315. {
  2316. struct btf_ext_info_sec *sec_info;
  2317. void *cur = output;
  2318. int str_off;
  2319. size_t sz;
  2320. if (!sec_data->rec_cnt)
  2321. return 0;
  2322. str_off = btf__add_str(linker->btf, sec_name);
  2323. if (str_off < 0)
  2324. return -ENOMEM;
  2325. sec_info = cur;
  2326. sec_info->sec_name_off = str_off;
  2327. sec_info->num_info = sec_data->rec_cnt;
  2328. cur += sizeof(struct btf_ext_info_sec);
  2329. sz = sec_data->rec_cnt * sec_data->rec_sz;
  2330. memcpy(cur, sec_data->recs, sz);
  2331. cur += sz;
  2332. return cur - output;
  2333. }
  2334. static int finalize_btf_ext(struct bpf_linker *linker)
  2335. {
  2336. size_t funcs_sz = 0, lines_sz = 0, core_relos_sz = 0, total_sz = 0;
  2337. size_t func_rec_sz = 0, line_rec_sz = 0, core_relo_rec_sz = 0;
  2338. struct btf_ext_header *hdr;
  2339. void *data, *cur;
  2340. int i, err, sz;
  2341. /* validate that all sections have the same .BTF.ext record sizes
  2342. * and calculate total data size for each type of data (func info,
  2343. * line info, core relos)
  2344. */
  2345. for (i = 1; i < linker->sec_cnt; i++) {
  2346. struct dst_sec *sec = &linker->secs[i];
  2347. if (sec->func_info.rec_cnt) {
  2348. if (func_rec_sz == 0)
  2349. func_rec_sz = sec->func_info.rec_sz;
  2350. if (func_rec_sz != sec->func_info.rec_sz) {
  2351. pr_warn("mismatch in func_info record size %zu != %u\n",
  2352. func_rec_sz, sec->func_info.rec_sz);
  2353. return -EINVAL;
  2354. }
  2355. funcs_sz += sizeof(struct btf_ext_info_sec) + func_rec_sz * sec->func_info.rec_cnt;
  2356. }
  2357. if (sec->line_info.rec_cnt) {
  2358. if (line_rec_sz == 0)
  2359. line_rec_sz = sec->line_info.rec_sz;
  2360. if (line_rec_sz != sec->line_info.rec_sz) {
  2361. pr_warn("mismatch in line_info record size %zu != %u\n",
  2362. line_rec_sz, sec->line_info.rec_sz);
  2363. return -EINVAL;
  2364. }
  2365. lines_sz += sizeof(struct btf_ext_info_sec) + line_rec_sz * sec->line_info.rec_cnt;
  2366. }
  2367. if (sec->core_relo_info.rec_cnt) {
  2368. if (core_relo_rec_sz == 0)
  2369. core_relo_rec_sz = sec->core_relo_info.rec_sz;
  2370. if (core_relo_rec_sz != sec->core_relo_info.rec_sz) {
  2371. pr_warn("mismatch in core_relo_info record size %zu != %u\n",
  2372. core_relo_rec_sz, sec->core_relo_info.rec_sz);
  2373. return -EINVAL;
  2374. }
  2375. core_relos_sz += sizeof(struct btf_ext_info_sec) + core_relo_rec_sz * sec->core_relo_info.rec_cnt;
  2376. }
  2377. }
  2378. if (!funcs_sz && !lines_sz && !core_relos_sz)
  2379. return 0;
  2380. total_sz += sizeof(struct btf_ext_header);
  2381. if (funcs_sz) {
  2382. funcs_sz += sizeof(__u32); /* record size prefix */
  2383. total_sz += funcs_sz;
  2384. }
  2385. if (lines_sz) {
  2386. lines_sz += sizeof(__u32); /* record size prefix */
  2387. total_sz += lines_sz;
  2388. }
  2389. if (core_relos_sz) {
  2390. core_relos_sz += sizeof(__u32); /* record size prefix */
  2391. total_sz += core_relos_sz;
  2392. }
  2393. cur = data = calloc(1, total_sz);
  2394. if (!data)
  2395. return -ENOMEM;
  2396. hdr = cur;
  2397. hdr->magic = BTF_MAGIC;
  2398. hdr->version = BTF_VERSION;
  2399. hdr->flags = 0;
  2400. hdr->hdr_len = sizeof(struct btf_ext_header);
  2401. cur += sizeof(struct btf_ext_header);
  2402. /* All offsets are in bytes relative to the end of this header */
  2403. hdr->func_info_off = 0;
  2404. hdr->func_info_len = funcs_sz;
  2405. hdr->line_info_off = funcs_sz;
  2406. hdr->line_info_len = lines_sz;
  2407. hdr->core_relo_off = funcs_sz + lines_sz;
  2408. hdr->core_relo_len = core_relos_sz;
  2409. if (funcs_sz) {
  2410. *(__u32 *)cur = func_rec_sz;
  2411. cur += sizeof(__u32);
  2412. for (i = 1; i < linker->sec_cnt; i++) {
  2413. struct dst_sec *sec = &linker->secs[i];
  2414. sz = emit_btf_ext_data(linker, cur, sec->sec_name, &sec->func_info);
  2415. if (sz < 0) {
  2416. err = sz;
  2417. goto out;
  2418. }
  2419. cur += sz;
  2420. }
  2421. }
  2422. if (lines_sz) {
  2423. *(__u32 *)cur = line_rec_sz;
  2424. cur += sizeof(__u32);
  2425. for (i = 1; i < linker->sec_cnt; i++) {
  2426. struct dst_sec *sec = &linker->secs[i];
  2427. sz = emit_btf_ext_data(linker, cur, sec->sec_name, &sec->line_info);
  2428. if (sz < 0) {
  2429. err = sz;
  2430. goto out;
  2431. }
  2432. cur += sz;
  2433. }
  2434. }
  2435. if (core_relos_sz) {
  2436. *(__u32 *)cur = core_relo_rec_sz;
  2437. cur += sizeof(__u32);
  2438. for (i = 1; i < linker->sec_cnt; i++) {
  2439. struct dst_sec *sec = &linker->secs[i];
  2440. sz = emit_btf_ext_data(linker, cur, sec->sec_name, &sec->core_relo_info);
  2441. if (sz < 0) {
  2442. err = sz;
  2443. goto out;
  2444. }
  2445. cur += sz;
  2446. }
  2447. }
  2448. linker->btf_ext = btf_ext__new(data, total_sz);
  2449. err = libbpf_get_error(linker->btf_ext);
  2450. if (err) {
  2451. linker->btf_ext = NULL;
  2452. pr_warn("failed to parse final .BTF.ext data: %d\n", err);
  2453. goto out;
  2454. }
  2455. out:
  2456. free(data);
  2457. return err;
  2458. }