VirtualBox

source: vbox/trunk/src/VBox/Runtime/common/ldr/ldrELFRelocatable.cpp.h@ 92113

Last change on this file since 92113 was 92113, checked in by vboxsync, 3 years ago

IPRT/ldrElf: Fixed incorrect validation of unknown dynamic table entries. A couple of PT_LOAD vs section validation hacks to make isolinux-debug.elf palatable.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 133.6 KB
Line 
1/* $Id: ldrELFRelocatable.cpp.h 92113 2021-10-27 20:00:05Z vboxsync $ */
2/** @file
3 * IPRT - Binary Image Loader, Template for ELF Relocatable Images.
4 */
5
6/*
7 * Copyright (C) 2006-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*******************************************************************************
29* Defined Constants And Macros *
30*******************************************************************************/
31#if ELF_MODE == 32
32# define RTLDRELF_NAME(name) rtldrELF32##name
33# define RTLDRELF_SUFF(name) name##32
34# define RTLDRELF_MID(pre,suff) pre##32##suff
35# define FMT_ELF_ADDR "%08RX32"
36# define FMT_ELF_ADDR7 "%07RX32"
37# define FMT_ELF_HALF "%04RX16"
38# define FMT_ELF_OFF "%08RX32"
39# define FMT_ELF_SIZE "%08RX32"
40# define FMT_ELF_SWORD "%RI32"
41# define FMT_ELF_WORD "%08RX32"
42# define FMT_ELF_XWORD "%08RX32"
43# define FMT_ELF_SXWORD "%RI32"
44# define Elf_Xword Elf32_Word
45# define Elf_Sxword Elf32_Sword
46
47#elif ELF_MODE == 64
48# define RTLDRELF_NAME(name) rtldrELF64##name
49# define RTLDRELF_SUFF(name) name##64
50# define RTLDRELF_MID(pre,suff) pre##64##suff
51# define FMT_ELF_ADDR "%016RX64"
52# define FMT_ELF_ADDR7 "%08RX64"
53# define FMT_ELF_HALF "%04RX16"
54# define FMT_ELF_SHALF "%RI16"
55# define FMT_ELF_OFF "%016RX64"
56# define FMT_ELF_SIZE "%016RX64"
57# define FMT_ELF_SWORD "%RI32"
58# define FMT_ELF_WORD "%08RX32"
59# define FMT_ELF_XWORD "%016RX64"
60# define FMT_ELF_SXWORD "%RI64"
61# define Elf_Xword Elf64_Xword
62# define Elf_Sxword Elf64_Sxword
63#endif
64
65#define Elf_Ehdr RTLDRELF_MID(Elf,_Ehdr)
66#define Elf_Phdr RTLDRELF_MID(Elf,_Phdr)
67#define Elf_Shdr RTLDRELF_MID(Elf,_Shdr)
68#define Elf_Sym RTLDRELF_MID(Elf,_Sym)
69#define Elf_Rel RTLDRELF_MID(Elf,_Rel)
70#define Elf_Rela RTLDRELF_MID(Elf,_Rela)
71#define Elf_Nhdr RTLDRELF_MID(Elf,_Nhdr)
72#define Elf_Dyn RTLDRELF_MID(Elf,_Dyn)
73#define Elf_Addr RTLDRELF_MID(Elf,_Addr)
74#define Elf_Half RTLDRELF_MID(Elf,_Half)
75#define Elf_Off RTLDRELF_MID(Elf,_Off)
76#define Elf_Size RTLDRELF_MID(Elf,_Size)
77#define Elf_Sword RTLDRELF_MID(Elf,_Sword)
78#define Elf_Word RTLDRELF_MID(Elf,_Word)
79
80#define RTLDRMODELF RTLDRELF_MID(RTLDRMODELF,RT_NOTHING)
81#define PRTLDRMODELF RTLDRELF_MID(PRTLDRMODELF,RT_NOTHING)
82
83#define RTLDRMODELFSHX RTLDRELF_MID(RTLDRMODELFSHX,RT_NOTHING)
84#define PRTLDRMODELFSHX RTLDRELF_MID(PRTLDRMODELFSHX,RT_NOTHING)
85
86#define ELF_R_SYM(info) RTLDRELF_MID(ELF,_R_SYM)(info)
87#define ELF_R_TYPE(info) RTLDRELF_MID(ELF,_R_TYPE)(info)
88#define ELF_R_INFO(sym, type) RTLDRELF_MID(ELF,_R_INFO)(sym, type)
89
90#define ELF_ST_BIND(info) RTLDRELF_MID(ELF,_ST_BIND)(info)
91
92
93
94/*******************************************************************************
95* Structures and Typedefs *
96*******************************************************************************/
97/**
98 * Extra section info.
99 */
100typedef struct RTLDRMODELFSHX
101{
102 /** The corresponding program header. */
103 uint16_t idxPhdr;
104 /** The corresponding dynamic section entry (address). */
105 uint16_t idxDt;
106 /** The DT tag. */
107 uint32_t uDtTag;
108} RTLDRMODELFSHX;
109typedef RTLDRMODELFSHX *PRTLDRMODELFSHX;
110
111/**
112 * The ELF loader structure.
113 */
114typedef struct RTLDRMODELF
115{
116 /** Core module structure. */
117 RTLDRMODINTERNAL Core;
118 /** Pointer to readonly mapping of the image bits.
119 * This mapping is provided by the pReader. */
120 const void *pvBits;
121
122 /** The ELF header. */
123 Elf_Ehdr Ehdr;
124 /** Pointer to our copy of the section headers with sh_addr as RVAs.
125 * The virtual addresses in this array is the 0 based assignments we've given the image.
126 * Not valid if the image is DONE. */
127 Elf_Shdr *paShdrs;
128 /** Unmodified section headers (allocated after paShdrs, so no need to free).
129 * Not valid if the image is DONE. */
130 Elf_Shdr const *paOrgShdrs;
131 /** Runs parallel to paShdrs and is part of the same allocation. */
132 PRTLDRMODELFSHX paShdrExtras;
133 /** Base section number, either 1 or zero depending on whether we've
134 * re-used the NULL entry for .elf.headers in ET_EXEC/ET_DYN. */
135 unsigned iFirstSect;
136 /** Set if the SHF_ALLOC section headers are in order of sh_addr. */
137 bool fShdrInOrder;
138 /** The size of the loaded image. */
139 size_t cbImage;
140
141 /** The image base address if it's an EXEC or DYN image. */
142 Elf_Addr LinkAddress;
143
144 struct
145 {
146 /** The symbol section index. */
147 unsigned iSymSh;
148 /** Number of symbols in the table. */
149 unsigned cSyms;
150 /** Pointer to symbol table within RTLDRMODELF::pvBits. */
151 const Elf_Sym *paSyms;
152
153 /** The string section index. */
154 unsigned iStrSh;
155 /** Size of the string table. */
156 unsigned cbStr;
157 /** Pointer to string table within RTLDRMODELF::pvBits. */
158 const char *pStr;
159 } Rel /**< Regular symbols and strings. */
160 , Dyn /**< Dynamic symbols and strings. */;
161
162 /** Pointer to section header string table within RTLDRMODELF::pvBits. */
163 const char *pShStr;
164 /** Size of the section header string table. */
165 unsigned cbShStr;
166
167 /** The '.eh_frame' section index. Zero if not searched for, ~0U if not found. */
168 unsigned iShEhFrame;
169 /** The '.eh_frame_hdr' section index. Zero if not searched for, ~0U if not found. */
170 unsigned iShEhFrameHdr;
171
172 /** The '.dynamic' / SHT_DYNAMIC section index. ~0U if not present. */
173 unsigned iShDynamic;
174 /** Number of entries in paDynamic. */
175 unsigned cDynamic;
176 /** The dynamic section (NULL for ET_REL). */
177 Elf_Dyn *paDynamic;
178 /** Program headers (NULL for ET_REL). */
179 Elf_Phdr *paPhdrs;
180
181 /** Info extracted from PT_DYNAMIC and the program headers. */
182 struct
183 {
184 /** DT_RELA/DT_REL. */
185 Elf_Addr uPtrRelocs;
186 /** DT_RELASZ/DT_RELSZ. */
187 Elf_Xword cbRelocs;
188 /** Non-zero if we've seen DT_RELAENT/DT_RELENT. */
189 unsigned cbRelocEntry;
190 /** DT_RELA or DT_REL. */
191 unsigned uRelocType;
192 /** The index of the section header matching DT_RELA/DT_REL. */
193 unsigned idxShRelocs;
194
195 /** DT_JMPREL. */
196 Elf_Addr uPtrJmpRelocs;
197 /** DT_PLTRELSZ. */
198 Elf_Xword cbJmpRelocs;
199 /** DT_RELA or DT_REL (if we've seen DT_PLTREL). */
200 unsigned uJmpRelocType;
201 /** The index of the section header matching DT_JMPREL. */
202 unsigned idxShJmpRelocs;
203 } DynInfo;
204} RTLDRMODELF;
205/** Pointer to an ELF module instance. */
206typedef RTLDRMODELF *PRTLDRMODELF;
207
208
209/**
210 * Maps the image bits into memory and resolve pointers into it.
211 *
212 * @returns iprt status code.
213 * @param pModElf The ELF loader module instance data.
214 * @param fNeedsBits Set if we actually need the pvBits member.
215 * If we don't, we can simply read the string and symbol sections, thus saving memory.
216 */
217static int RTLDRELF_NAME(MapBits)(PRTLDRMODELF pModElf, bool fNeedsBits)
218{
219 NOREF(fNeedsBits);
220 if (pModElf->pvBits)
221 return VINF_SUCCESS;
222 int rc = pModElf->Core.pReader->pfnMap(pModElf->Core.pReader, &pModElf->pvBits);
223 if (RT_SUCCESS(rc))
224 {
225 const uint8_t *pu8 = (const uint8_t *)pModElf->pvBits;
226 if (pModElf->Rel.iSymSh != ~0U)
227 pModElf->Rel.paSyms = (const Elf_Sym *)(pu8 + pModElf->paShdrs[pModElf->Rel.iSymSh].sh_offset);
228 if (pModElf->Rel.iStrSh != ~0U)
229 pModElf->Rel.pStr = (const char *)(pu8 + pModElf->paShdrs[pModElf->Rel.iStrSh].sh_offset);
230 if (pModElf->Dyn.iSymSh != ~0U)
231 pModElf->Dyn.paSyms = (const Elf_Sym *)(pu8 + pModElf->paShdrs[pModElf->Dyn.iSymSh].sh_offset);
232 if (pModElf->Dyn.iStrSh != ~0U)
233 pModElf->Dyn.pStr = (const char *)(pu8 + pModElf->paShdrs[pModElf->Dyn.iStrSh].sh_offset);
234 pModElf->pShStr = (const char *)(pu8 + pModElf->paShdrs[pModElf->Ehdr.e_shstrndx].sh_offset);
235
236 /*
237 * Verify that the ends of the string tables have a zero terminator
238 * (this avoids duplicating the appropriate checks later in the code accessing the string tables).
239 *
240 * sh_offset and sh_size were verfied in RTLDRELF_NAME(ValidateSectionHeader)() already so they
241 * are safe to use.
242 */
243 AssertMsgStmt( pModElf->Rel.iStrSh == ~0U
244 || pModElf->Rel.pStr[pModElf->paShdrs[pModElf->Rel.iStrSh].sh_size - 1] == '\0',
245 ("The string table is not zero terminated!\n"),
246 rc = VERR_LDRELF_UNTERMINATED_STRING_TAB);
247 AssertMsgStmt( pModElf->Dyn.iStrSh == ~0U
248 || pModElf->Dyn.pStr[pModElf->paShdrs[pModElf->Dyn.iStrSh].sh_size - 1] == '\0',
249 ("The string table is not zero terminated!\n"),
250 rc = VERR_LDRELF_UNTERMINATED_STRING_TAB);
251 AssertMsgStmt(pModElf->pShStr[pModElf->paShdrs[pModElf->Ehdr.e_shstrndx].sh_size - 1] == '\0',
252 ("The section header string table is not zero terminated!\n"),
253 rc = VERR_LDRELF_UNTERMINATED_STRING_TAB);
254
255 if (RT_FAILURE(rc))
256 {
257 /* Unmap. */
258 int rc2 = pModElf->Core.pReader->pfnUnmap(pModElf->Core.pReader, pModElf->pvBits);
259 AssertRC(rc2);
260 pModElf->pvBits = NULL;
261 pModElf->Rel.paSyms = NULL;
262 pModElf->Rel.pStr = NULL;
263 pModElf->Dyn.paSyms = NULL;
264 pModElf->Dyn.pStr = NULL;
265 pModElf->pShStr = NULL;
266 }
267 }
268 return rc;
269}
270
271
272/*
273 *
274 * EXEC & DYN.
275 * EXEC & DYN.
276 * EXEC & DYN.
277 * EXEC & DYN.
278 * EXEC & DYN.
279 *
280 */
281
282/**
283 * Get the symbol and symbol value.
284 *
285 * @returns iprt status code.
286 * @param pModElf The ELF loader module instance data.
287 * @param BaseAddr The base address which the module is being fixedup to.
288 * @param pfnGetImport The callback function to use to resolve imports (aka unresolved externals).
289 * @param pvUser User argument to pass to the callback.
290 * @param iSym The symbol to get.
291 * @param ppSym Where to store the symbol pointer on success. (read only)
292 * @param pSymValue Where to store the symbol value on success.
293 */
294static int RTLDRELF_NAME(SymbolExecDyn)(PRTLDRMODELF pModElf, Elf_Addr BaseAddr, PFNRTLDRIMPORT pfnGetImport, void *pvUser,
295 Elf_Size iSym, const Elf_Sym **ppSym, Elf_Addr *pSymValue)
296{
297 /*
298 * Validate and find the symbol.
299 */
300 AssertMsgReturn(iSym < pModElf->Dyn.cSyms, ("iSym=%d is an invalid symbol index!\n", iSym), VERR_LDRELF_INVALID_SYMBOL_INDEX);
301 const Elf_Sym *pSym = &pModElf->Dyn.paSyms[iSym];
302 *ppSym = pSym;
303
304 AssertMsgReturn(pSym->st_name < pModElf->Dyn.cbStr,
305 ("iSym=%d st_name=%d str sh_size=%d\n", iSym, pSym->st_name, pModElf->Dyn.cbStr),
306 VERR_LDRELF_INVALID_SYMBOL_NAME_OFFSET);
307 const char * const pszName = pModElf->Dyn.pStr + pSym->st_name;
308
309 /*
310 * Determine the symbol value.
311 *
312 * Symbols needs different treatment depending on which section their are in.
313 * Undefined and absolute symbols goes into special non-existing sections.
314 */
315 switch (pSym->st_shndx)
316 {
317 /*
318 * Undefined symbol, needs resolving.
319 *
320 * Since ELF has no generic concept of importing from specific module (the OS/2 ELF format
321 * has but that's an OS extension and only applies to programs and dlls), we'll have to ask
322 * the resolver callback to do a global search.
323 */
324 case SHN_UNDEF:
325 {
326 /* Try to resolve the symbol. */
327 RTUINTPTR Value;
328 int rc = pfnGetImport(&pModElf->Core, "", pszName, ~0U, &Value, pvUser);
329 AssertMsgRCReturn(rc, ("Failed to resolve '%s' (iSym=" FMT_ELF_SIZE " rc=%Rrc\n", pszName, iSym, rc), rc);
330
331 *pSymValue = (Elf_Addr)Value;
332 AssertMsgReturn((RTUINTPTR)*pSymValue == Value,
333 ("Symbol value overflowed! '%s' (iSym=" FMT_ELF_SIZE "\n", pszName, iSym), VERR_SYMBOL_VALUE_TOO_BIG);
334
335 Log2(("rtldrELF: #%-3d - UNDEF " FMT_ELF_ADDR " '%s'\n", iSym, *pSymValue, pszName));
336 break;
337 }
338
339 /*
340 * Absolute symbols needs no fixing since they are, well, absolute.
341 */
342 case SHN_ABS:
343 *pSymValue = pSym->st_value;
344 Log2(("rtldrELF: #%-3d - ABS " FMT_ELF_ADDR " '%s'\n", iSym, *pSymValue, pszName));
345 break;
346
347 /*
348 * All other symbols are addressed relative the image base in DYN and EXEC binaries.
349 */
350 default:
351 AssertMsgReturn(pSym->st_shndx < pModElf->Ehdr.e_shnum,
352 ("iSym=%d st_shndx=%d e_shnum=%d pszName=%s\n", iSym, pSym->st_shndx, pModElf->Ehdr.e_shnum, pszName),
353 VERR_BAD_EXE_FORMAT);
354 *pSymValue = pSym->st_value + BaseAddr;
355 Log2(("rtldrELF: #%-3d - %5d " FMT_ELF_ADDR " '%s'\n", iSym, pSym->st_shndx, *pSymValue, pszName));
356 break;
357 }
358
359 return VINF_SUCCESS;
360}
361
362
363#if ELF_MODE == 32
364/** Helper for RelocateSectionExecDyn. */
365DECLINLINE(const Elf_Shdr *) RTLDRELF_NAME(RvaToSectionHeader)(PRTLDRMODELF pModElf, Elf_Addr uRva)
366{
367 const Elf_Shdr * const pShdrFirst = pModElf->paShdrs;
368 const Elf_Shdr *pShdr = pShdrFirst + pModElf->Ehdr.e_shnum;
369 while (--pShdr != pShdrFirst)
370 if (uRva - pShdr->sh_addr /*rva*/ < pShdr->sh_size)
371 return pShdr;
372 AssertFailed();
373 return pShdr;
374}
375#endif
376
377
378/**
379 * Applies the fixups for a section in an executable image.
380 *
381 * @returns iprt status code.
382 * @param pModElf The ELF loader module instance data.
383 * @param BaseAddr The base address which the module is being fixedup to.
384 * @param pfnGetImport The callback function to use to resolve imports (aka unresolved externals).
385 * @param pvUser User argument to pass to the callback.
386 * @param SecAddr The section address. This is the address the relocations are relative to.
387 * @param cbSec The section size. The relocations must be inside this.
388 * @param pu8SecBaseR Where we read section bits from.
389 * @param pu8SecBaseW Where we write section bits to.
390 * @param pvRelocs Pointer to where we read the relocations from.
391 * @param cbRelocs Size of the relocations.
392 */
393static int RTLDRELF_NAME(RelocateSectionExecDyn)(PRTLDRMODELF pModElf, Elf_Addr BaseAddr,
394 PFNRTLDRIMPORT pfnGetImport, void *pvUser,
395 const Elf_Addr SecAddr, Elf_Size cbSec,
396 const uint8_t *pu8SecBaseR, uint8_t *pu8SecBaseW,
397 const void *pvRelocs, Elf_Size cbRelocs)
398{
399#if ELF_MODE != 32
400 NOREF(pu8SecBaseR);
401#endif
402
403 /*
404 * Iterate the relocations.
405 * The relocations are stored in an array of Elf32_Rel records and covers the entire relocation section.
406 */
407#if ELF_MODE == 32
408 const Elf_Shdr *pShdr = pModElf->paShdrs;
409 const Elf_Addr offDelta = BaseAddr - pModElf->LinkAddress;
410#endif
411 const Elf_Reloc *paRels = (const Elf_Reloc *)pvRelocs;
412 const unsigned iRelMax = (unsigned)(cbRelocs / sizeof(paRels[0]));
413 AssertMsgReturn(iRelMax == cbRelocs / sizeof(paRels[0]), (FMT_ELF_SIZE "\n", cbRelocs / sizeof(paRels[0])),
414 VERR_IMAGE_TOO_BIG);
415 for (unsigned iRel = 0; iRel < iRelMax; iRel++)
416 {
417 /*
418 * Apply fixups not taking a symbol (will 'continue' rather than 'break').
419 */
420 AssertMsgReturn(paRels[iRel].r_offset < cbSec, (FMT_ELF_ADDR " " FMT_ELF_SIZE "\n", paRels[iRel].r_offset, cbSec),
421 VERR_LDRELF_INVALID_RELOCATION_OFFSET);
422#if ELF_MODE == 32
423 if (paRels[iRel].r_offset - pShdr->sh_addr /*rva*/ >= pShdr->sh_size)
424 pShdr = RTLDRELF_NAME(RvaToSectionHeader)(pModElf, paRels[iRel].r_offset);
425 static const Elf_Addr s_uZero = 0;
426 const Elf_Addr *pAddrR = RT_LIKELY(pShdr->sh_type != SHT_NOBITS) /* Where to read the addend. */
427 ? (const Elf_Addr *)(pu8SecBaseR + paRels[iRel].r_offset - pShdr->sh_addr /*rva*/
428 + pShdr->sh_offset)
429 : &s_uZero;
430#endif
431 Elf_Addr *pAddrW = (Elf_Addr *)(pu8SecBaseW + paRels[iRel].r_offset); /* Where to write the fixup. */
432 switch (ELF_R_TYPE(paRels[iRel].r_info))
433 {
434 /*
435 * Image relative (addend + base).
436 */
437#if ELF_MODE == 32
438 case R_386_RELATIVE:
439 {
440 const Elf_Addr Value = *pAddrR + BaseAddr;
441 *(uint32_t *)pAddrW = Value;
442 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_386_RELATIVE Value=" FMT_ELF_ADDR "\n",
443 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, Value));
444 AssertCompile(sizeof(Value) == sizeof(uint32_t));
445 continue;
446 }
447#elif ELF_MODE == 64
448 case R_X86_64_RELATIVE:
449 {
450 const Elf_Addr Value = paRels[iRel].r_addend + BaseAddr;
451 *(uint64_t *)pAddrW = (uint64_t)Value;
452 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_X86_64_RELATIVE Value=" FMT_ELF_ADDR "\n",
453 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, Value));
454 AssertCompile(sizeof(Value) == sizeof(uint64_t));
455 continue;
456 }
457#endif
458
459 /*
460 * R_XXX_NONE.
461 */
462#if ELF_MODE == 32
463 case R_386_NONE:
464#elif ELF_MODE == 64
465 case R_X86_64_NONE:
466#endif
467 continue;
468 }
469
470 /*
471 * Validate and find the symbol, resolve undefined ones.
472 */
473 const Elf_Sym *pSym = NULL; /* shut up gcc */
474 Elf_Addr SymValue = 0; /* shut up gcc-4 */
475 int rc = RTLDRELF_NAME(SymbolExecDyn)(pModElf, BaseAddr, pfnGetImport, pvUser, ELF_R_SYM(paRels[iRel].r_info), &pSym, &SymValue);
476 if (RT_FAILURE(rc))
477 return rc;
478
479 /*
480 * Apply the fixup.
481 */
482 switch (ELF_R_TYPE(paRels[iRel].r_info))
483 {
484#if ELF_MODE == 32
485 /*
486 * GOT/PLT.
487 */
488 case R_386_GLOB_DAT:
489 {
490 *(uint32_t *)pAddrW = (uint32_t)SymValue;
491 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_386_GLOB_DAT Value=" FMT_ELF_ADDR "\n",
492 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, SymValue));
493 AssertCompile(sizeof(SymValue) == sizeof(uint32_t));
494 break;
495 }
496
497 case R_386_JMP_SLOT:
498 {
499 *(uint32_t *)pAddrW = (uint32_t)SymValue;
500 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_386_JMP_SLOT Value=" FMT_ELF_ADDR "\n",
501 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, SymValue));
502 AssertCompile(sizeof(SymValue) == sizeof(uint32_t));
503 break;
504 }
505
506 /*
507 * Absolute addressing.
508 */
509 case R_386_32:
510 {
511 Elf_Addr Value;
512 if (pSym->st_shndx < pModElf->Ehdr.e_shnum)
513 Value = *pAddrR + offDelta; /* Simplified. */
514 else if (pSym->st_shndx == SHN_ABS)
515 continue; /* Internal fixup, no need to apply it. */
516 else if (pSym->st_shndx == SHN_UNDEF)
517 Value = SymValue + *pAddrR;
518 else
519 AssertFailedReturn(VERR_LDR_GENERAL_FAILURE); /** @todo SHN_COMMON */
520 *(uint32_t *)pAddrW = Value;
521 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_386_32 Value=" FMT_ELF_ADDR "\n",
522 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, Value));
523 break;
524 }
525
526 /*
527 * PC relative addressing.
528 */
529 case R_386_PC32:
530 {
531 Elf_Addr Value;
532 if (pSym->st_shndx < pModElf->Ehdr.e_shnum)
533 continue; /* Internal fixup, no need to apply it. */
534 else if (pSym->st_shndx == SHN_ABS)
535 Value = *pAddrR + offDelta; /* Simplified. */
536 else if (pSym->st_shndx == SHN_UNDEF)
537 {
538 const Elf_Addr SourceAddr = SecAddr + paRels[iRel].r_offset + BaseAddr; /* Where the source really is. */
539 Value = SymValue + *(uint32_t *)pAddrR - SourceAddr;
540 *(uint32_t *)pAddrW = Value;
541 }
542 else
543 AssertFailedReturn(VERR_LDR_GENERAL_FAILURE); /** @todo SHN_COMMON */
544 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_386_PC32 Value=" FMT_ELF_ADDR "\n",
545 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, Value));
546 break;
547 }
548
549#elif ELF_MODE == 64
550 /*
551 * GOT/PLT.
552 */
553 case R_X86_64_GLOB_DAT:
554 {
555 *(uint64_t *)pAddrW = (uint64_t)SymValue;
556 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_X86_64_GLOB_DAT Value=" FMT_ELF_ADDR "\n",
557 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, SymValue));
558 AssertCompile(sizeof(SymValue) == sizeof(uint64_t));
559 break;
560 }
561
562 case R_X86_64_JMP_SLOT:
563 {
564 *(uint64_t *)pAddrW = (uint64_t)SymValue;
565 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_X86_64_JMP_SLOT Value=" FMT_ELF_ADDR "\n",
566 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, SymValue));
567 AssertCompile(sizeof(SymValue) == sizeof(uint64_t));
568 break;
569 }
570
571 /*
572 * Absolute addressing.
573 */
574 case R_X86_64_64:
575 {
576 const Elf_Addr Value = SymValue + paRels[iRel].r_addend;
577 *(uint64_t *)pAddrW = Value;
578 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_X86_64_64 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
579 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, Value, SymValue));
580 break;
581 }
582
583 /*
584 * Truncated 32-bit value (zero-extendedable to the 64-bit value).
585 */
586 case R_X86_64_32:
587 {
588 const Elf_Addr Value = SymValue + paRels[iRel].r_addend;
589 *(uint32_t *)pAddrW = (uint32_t)Value;
590 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_X86_64_32 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
591 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, Value, SymValue));
592 AssertMsgReturn((Elf_Addr)*(uint32_t *)pAddrW == SymValue, ("Value=" FMT_ELF_ADDR "\n", SymValue),
593 VERR_SYMBOL_VALUE_TOO_BIG);
594 break;
595 }
596
597 /*
598 * Truncated 32-bit value (sign-extendedable to the 64-bit value).
599 */
600 case R_X86_64_32S:
601 {
602 const Elf_Addr Value = SymValue + paRels[iRel].r_addend;
603 *(int32_t *)pAddrW = (int32_t)Value;
604 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_X86_64_32S Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
605 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, Value, SymValue));
606 AssertMsgReturn((Elf_Addr)*(int32_t *)pAddrW == Value, ("Value=" FMT_ELF_ADDR "\n", Value), VERR_SYMBOL_VALUE_TOO_BIG); /** @todo check the sign-extending here. */
607 break;
608 }
609
610 /*
611 * PC relative addressing.
612 */
613 case R_X86_64_PC32:
614 {
615 const Elf_Addr SourceAddr = SecAddr + paRels[iRel].r_offset + BaseAddr; /* Where the source really is. */
616 const Elf_Addr Value = SymValue + paRels[iRel].r_addend - SourceAddr;
617 *(int32_t *)pAddrW = (int32_t)Value;
618 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_X86_64_PC32 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
619 SourceAddr, paRels[iRel].r_offset, Value, SymValue));
620 AssertMsgReturn((Elf_Addr)*(int32_t *)pAddrW == Value, ("Value=" FMT_ELF_ADDR "\n", Value), VERR_SYMBOL_VALUE_TOO_BIG); /** @todo check the sign-extending here. */
621 break;
622 }
623
624#endif
625 default:
626 AssertMsgFailed(("Unknown relocation type: %d (iRel=%d iRelMax=%d)\n",
627 ELF_R_TYPE(paRels[iRel].r_info), iRel, iRelMax));
628 return VERR_LDRELF_RELOCATION_NOT_SUPPORTED;
629 }
630 }
631
632 return VINF_SUCCESS;
633}
634
635
636
637/*
638 *
639 * REL
640 * REL
641 * REL
642 * REL
643 * REL
644 *
645 */
646
647/**
648 * Get the symbol and symbol value.
649 *
650 * @returns iprt status code.
651 * @param pModElf The ELF loader module instance data.
652 * @param BaseAddr The base address which the module is being fixedup to.
653 * @param pfnGetImport The callback function to use to resolve imports (aka unresolved externals).
654 * @param pvUser User argument to pass to the callback.
655 * @param iSym The symbol to get.
656 * @param ppSym Where to store the symbol pointer on success. (read only)
657 * @param pSymValue Where to store the symbol value on success.
658 */
659static int RTLDRELF_NAME(Symbol)(PRTLDRMODELF pModElf, Elf_Addr BaseAddr, PFNRTLDRIMPORT pfnGetImport, void *pvUser,
660 Elf_Size iSym, const Elf_Sym **ppSym, Elf_Addr *pSymValue)
661{
662 /*
663 * Validate and find the symbol.
664 */
665 AssertMsgReturn(iSym < pModElf->Rel.cSyms, ("iSym=%d is an invalid symbol index!\n", iSym), VERR_LDRELF_INVALID_SYMBOL_INDEX);
666 const Elf_Sym *pSym = &pModElf->Rel.paSyms[iSym];
667 *ppSym = pSym;
668
669 AssertMsgReturn(pSym->st_name < pModElf->Rel.cbStr,
670 ("iSym=%d st_name=%d str sh_size=%d\n", iSym, pSym->st_name, pModElf->Rel.cbStr),
671 VERR_LDRELF_INVALID_SYMBOL_NAME_OFFSET);
672 const char *pszName = ELF_STR(pModElf, pSym->st_name);
673
674 /*
675 * Determine the symbol value.
676 *
677 * Symbols needs different treatment depending on which section their are in.
678 * Undefined and absolute symbols goes into special non-existing sections.
679 */
680 switch (pSym->st_shndx)
681 {
682 /*
683 * Undefined symbol, needs resolving.
684 *
685 * Since ELF has no generic concept of importing from specific module (the OS/2 ELF format
686 * has but that's an OS extension and only applies to programs and dlls), we'll have to ask
687 * the resolver callback to do a global search.
688 */
689 case SHN_UNDEF:
690 {
691 /* Try to resolve the symbol. */
692 RTUINTPTR Value;
693 int rc = pfnGetImport(&pModElf->Core, "", pszName, ~0U, &Value, pvUser);
694 AssertMsgRCReturn(rc, ("Failed to resolve '%s' (iSym=" FMT_ELF_SIZE " rc=%Rrc\n", pszName, iSym, rc), rc);
695 *pSymValue = (Elf_Addr)Value;
696
697 AssertMsgReturn((RTUINTPTR)*pSymValue == Value,
698 ("Symbol value overflowed! '%s' (iSym=" FMT_ELF_SIZE ")\n", pszName, iSym),
699 VERR_SYMBOL_VALUE_TOO_BIG);
700
701 Log2(("rtldrELF: #%-3d - UNDEF " FMT_ELF_ADDR " '%s'\n", iSym, *pSymValue, pszName));
702 break;
703 }
704
705 /*
706 * Absolute symbols needs no fixing since they are, well, absolute.
707 */
708 case SHN_ABS:
709 *pSymValue = pSym->st_value;
710 Log2(("rtldrELF: #%-3d - ABS " FMT_ELF_ADDR " '%s'\n", iSym, *pSymValue, pszName));
711 break;
712
713 /*
714 * All other symbols are addressed relative to their section and need to be fixed up.
715 */
716 default:
717 if (pSym->st_shndx >= pModElf->Ehdr.e_shnum)
718 {
719 /* what about common symbols? */
720 AssertMsg(pSym->st_shndx < pModElf->Ehdr.e_shnum,
721 ("iSym=%d st_shndx=%d e_shnum=%d pszName=%s\n", iSym, pSym->st_shndx, pModElf->Ehdr.e_shnum, pszName));
722 return VERR_BAD_EXE_FORMAT;
723 }
724 *pSymValue = pSym->st_value + pModElf->paShdrs[pSym->st_shndx].sh_addr + BaseAddr;
725 Log2(("rtldrELF: #%-3d - %5d " FMT_ELF_ADDR " '%s'\n", iSym, pSym->st_shndx, *pSymValue, pszName));
726 break;
727 }
728
729 return VINF_SUCCESS;
730}
731
732
733/**
734 * Applies the fixups for a sections.
735 *
736 * @returns iprt status code.
737 * @param pModElf The ELF loader module instance data.
738 * @param BaseAddr The base address which the module is being fixedup to.
739 * @param pfnGetImport The callback function to use to resolve imports (aka unresolved externals).
740 * @param pvUser User argument to pass to the callback.
741 * @param SecAddr The section address. This is the address the relocations are relative to.
742 * @param cbSec The section size. The relocations must be inside this.
743 * @param pu8SecBaseR Where we read section bits from.
744 * @param pu8SecBaseW Where we write section bits to.
745 * @param pvRelocs Pointer to where we read the relocations from.
746 * @param cbRelocs Size of the relocations.
747 */
748static int RTLDRELF_NAME(RelocateSectionRel)(PRTLDRMODELF pModElf, Elf_Addr BaseAddr, PFNRTLDRIMPORT pfnGetImport, void *pvUser,
749 const Elf_Addr SecAddr, Elf_Size cbSec, const uint8_t *pu8SecBaseR,
750 uint8_t *pu8SecBaseW, const void *pvRelocs, Elf_Size cbRelocs)
751{
752#if ELF_MODE != 32
753 NOREF(pu8SecBaseR);
754#endif
755
756 /*
757 * Iterate the relocations.
758 * The relocations are stored in an array of Elf32_Rel records and covers the entire relocation section.
759 */
760 const Elf_Reloc *paRels = (const Elf_Reloc *)pvRelocs;
761 const unsigned iRelMax = (unsigned)(cbRelocs / sizeof(paRels[0]));
762 AssertMsgReturn(iRelMax == cbRelocs / sizeof(paRels[0]), (FMT_ELF_SIZE "\n", cbRelocs / sizeof(paRels[0])), VERR_IMAGE_TOO_BIG);
763 for (unsigned iRel = 0; iRel < iRelMax; iRel++)
764 {
765 /*
766 * Skip R_XXX_NONE entries early to avoid confusion in the symbol
767 * getter code.
768 */
769#if ELF_MODE == 32
770 if (ELF_R_TYPE(paRels[iRel].r_info) == R_386_NONE)
771 continue;
772#elif ELF_MODE == 64
773 if (ELF_R_TYPE(paRels[iRel].r_info) == R_X86_64_NONE)
774 continue;
775#endif
776
777
778 /*
779 * Get the symbol.
780 */
781 const Elf_Sym *pSym = NULL; /* shut up gcc */
782 Elf_Addr SymValue = 0; /* shut up gcc-4 */
783 int rc = RTLDRELF_NAME(Symbol)(pModElf, BaseAddr, pfnGetImport, pvUser, ELF_R_SYM(paRels[iRel].r_info), &pSym, &SymValue);
784 if (RT_FAILURE(rc))
785 return rc;
786
787 Log3(("rtldrELF: " FMT_ELF_ADDR " %02x %06x - " FMT_ELF_ADDR " %3d %02x %s\n",
788 paRels[iRel].r_offset, ELF_R_TYPE(paRels[iRel].r_info), (unsigned)ELF_R_SYM(paRels[iRel].r_info),
789 SymValue, (unsigned)pSym->st_shndx, pSym->st_info, ELF_STR(pModElf, pSym->st_name)));
790
791 /*
792 * Apply the fixup.
793 */
794 AssertMsgReturn(paRels[iRel].r_offset < cbSec, (FMT_ELF_ADDR " " FMT_ELF_SIZE "\n", paRels[iRel].r_offset, cbSec), VERR_LDRELF_INVALID_RELOCATION_OFFSET);
795#if ELF_MODE == 32
796 const Elf_Addr *pAddrR = (const Elf_Addr *)(pu8SecBaseR + paRels[iRel].r_offset); /* Where to read the addend. */
797#endif
798 Elf_Addr *pAddrW = (Elf_Addr *)(pu8SecBaseW + paRels[iRel].r_offset); /* Where to write the fixup. */
799 switch (ELF_R_TYPE(paRels[iRel].r_info))
800 {
801#if ELF_MODE == 32
802 /*
803 * Absolute addressing.
804 */
805 case R_386_32:
806 {
807 const Elf_Addr Value = SymValue + *pAddrR;
808 *(uint32_t *)pAddrW = Value;
809 Log4((FMT_ELF_ADDR": R_386_32 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
810 SecAddr + paRels[iRel].r_offset + BaseAddr, Value, SymValue));
811 break;
812 }
813
814 /*
815 * PC relative addressing.
816 */
817 case R_386_PC32:
818 {
819 const Elf_Addr SourceAddr = SecAddr + paRels[iRel].r_offset + BaseAddr; /* Where the source really is. */
820 const Elf_Addr Value = SymValue + *(uint32_t *)pAddrR - SourceAddr;
821 *(uint32_t *)pAddrW = Value;
822 Log4((FMT_ELF_ADDR": R_386_PC32 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
823 SourceAddr, Value, SymValue));
824 break;
825 }
826
827 /* ignore */
828 case R_386_NONE:
829 break;
830
831#elif ELF_MODE == 64
832
833 /*
834 * Absolute addressing
835 */
836 case R_X86_64_64:
837 {
838 const Elf_Addr Value = SymValue + paRels[iRel].r_addend;
839 *(uint64_t *)pAddrW = Value;
840 Log4((FMT_ELF_ADDR": R_X86_64_64 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
841 SecAddr + paRels[iRel].r_offset + BaseAddr, Value, SymValue));
842 break;
843 }
844
845 /*
846 * Truncated 32-bit value (zero-extendedable to the 64-bit value).
847 */
848 case R_X86_64_32:
849 {
850 const Elf_Addr Value = SymValue + paRels[iRel].r_addend;
851 *(uint32_t *)pAddrW = (uint32_t)Value;
852 Log4((FMT_ELF_ADDR": R_X86_64_32 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
853 SecAddr + paRels[iRel].r_offset + BaseAddr, Value, SymValue));
854 AssertMsgReturn((Elf_Addr)*(uint32_t *)pAddrW == Value, ("Value=" FMT_ELF_ADDR "\n", Value), VERR_SYMBOL_VALUE_TOO_BIG);
855 break;
856 }
857
858 /*
859 * Truncated 32-bit value (sign-extendedable to the 64-bit value).
860 */
861 case R_X86_64_32S:
862 {
863 const Elf_Addr Value = SymValue + paRels[iRel].r_addend;
864 *(int32_t *)pAddrW = (int32_t)Value;
865 Log4((FMT_ELF_ADDR": R_X86_64_32S Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
866 SecAddr + paRels[iRel].r_offset + BaseAddr, Value, SymValue));
867 AssertMsgReturn((Elf_Addr)*(int32_t *)pAddrW == Value, ("Value=" FMT_ELF_ADDR "\n", Value), VERR_SYMBOL_VALUE_TOO_BIG); /** @todo check the sign-extending here. */
868 break;
869 }
870
871 /*
872 * PC relative addressing.
873 */
874 case R_X86_64_PC32:
875 case R_X86_64_PLT32: /* binutils commit 451875b4f976a527395e9303224c7881b65e12ed feature/regression. */
876 {
877 const Elf_Addr SourceAddr = SecAddr + paRels[iRel].r_offset + BaseAddr; /* Where the source really is. */
878 const Elf_Addr Value = SymValue + paRels[iRel].r_addend - SourceAddr;
879 *(int32_t *)pAddrW = (int32_t)Value;
880 Log4((FMT_ELF_ADDR": R_X86_64_PC32 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
881 SourceAddr, Value, SymValue));
882 AssertMsgReturn((Elf_Addr)*(int32_t *)pAddrW == Value, ("Value=" FMT_ELF_ADDR "\n", Value), VERR_SYMBOL_VALUE_TOO_BIG); /** @todo check the sign-extending here. */
883 break;
884 }
885
886 /* ignore */
887 case R_X86_64_NONE:
888 break;
889#endif
890
891 default:
892 AssertMsgFailed(("Unknown relocation type: %d (iRel=%d iRelMax=%d)\n",
893 ELF_R_TYPE(paRels[iRel].r_info), iRel, iRelMax));
894 return VERR_LDRELF_RELOCATION_NOT_SUPPORTED;
895 }
896 }
897
898 return VINF_SUCCESS;
899}
900
901
902
903/** @copydoc RTLDROPS::pfnClose */
904static DECLCALLBACK(int) RTLDRELF_NAME(Close)(PRTLDRMODINTERNAL pMod)
905{
906 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
907
908 if (pModElf->paShdrs)
909 {
910 RTMemFree(pModElf->paShdrs);
911 pModElf->paShdrs = NULL;
912 }
913
914 if (pModElf->paPhdrs)
915 {
916 RTMemFree(pModElf->paPhdrs);
917 pModElf->paPhdrs = NULL;
918 }
919
920 if (pModElf->paDynamic)
921 {
922 RTMemFree(pModElf->paDynamic);
923 pModElf->paDynamic = NULL;
924 }
925
926 if (pModElf->pvBits)
927 {
928 pModElf->Core.pReader->pfnUnmap(pModElf->Core.pReader, pModElf->pvBits);
929 pModElf->pvBits = NULL;
930 }
931
932 return VINF_SUCCESS;
933}
934
935
936/** @copydoc RTLDROPS::Done */
937static DECLCALLBACK(int) RTLDRELF_NAME(Done)(PRTLDRMODINTERNAL pMod)
938{
939 NOREF(pMod); /*PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;*/
940 /** @todo Have to think more about this .... */
941 return -1;
942}
943
944
945/** @copydoc RTLDROPS::pfnEnumSymbols */
946static DECLCALLBACK(int) RTLDRELF_NAME(EnumSymbols)(PRTLDRMODINTERNAL pMod, unsigned fFlags, const void *pvBits,
947 RTUINTPTR BaseAddress, PFNRTLDRENUMSYMS pfnCallback, void *pvUser)
948{
949 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
950 NOREF(pvBits);
951
952 /*
953 * Validate the input.
954 */
955 Elf_Addr BaseAddr = (Elf_Addr)BaseAddress;
956 AssertMsgReturn((RTUINTPTR)BaseAddr == BaseAddress, ("%RTptr", BaseAddress), VERR_IMAGE_BASE_TOO_HIGH);
957
958 /*
959 * Make sure we've got the string and symbol tables. (We don't need the pvBits.)
960 */
961 int rc = RTLDRELF_NAME(MapBits)(pModElf, false);
962 if (RT_FAILURE(rc))
963 return rc;
964
965 /*
966 * Enumerate the symbol table.
967 */
968 const Elf_Sym *paSyms = pModElf->Rel.paSyms;
969 unsigned cSyms = pModElf->Rel.cSyms;
970 const char *pszzStr = pModElf->Rel.pStr;
971 unsigned cbStr = pModElf->Rel.cbStr;
972 if ( ( !(fFlags & RTLDR_ENUM_SYMBOL_FLAGS_ALL)
973 && pModElf->Dyn.cSyms > 0)
974 || cSyms == 0)
975 {
976 paSyms = pModElf->Dyn.paSyms;
977 cSyms = pModElf->Dyn.cSyms;
978 pszzStr = pModElf->Dyn.pStr;
979 cbStr = pModElf->Dyn.cbStr;
980 }
981
982 for (unsigned iSym = 1; iSym < cSyms; iSym++)
983 {
984 /*
985 * Skip imports (undefined).
986 */
987 if (paSyms[iSym].st_shndx != SHN_UNDEF)
988 {
989 /*
990 * Calc value and get name.
991 */
992 Elf_Addr Value;
993 if (paSyms[iSym].st_shndx == SHN_ABS)
994 /* absolute symbols are not subject to any relocation. */
995 Value = paSyms[iSym].st_value;
996 else if (paSyms[iSym].st_shndx < pModElf->Ehdr.e_shnum)
997 {
998 if (pModElf->Ehdr.e_type == ET_REL)
999 /* relative to the section. */
1000 Value = BaseAddr + paSyms[iSym].st_value + pModElf->paShdrs[paSyms[iSym].st_shndx].sh_addr;
1001 else /* Fixed up for link address. */
1002 Value = BaseAddr + paSyms[iSym].st_value - pModElf->LinkAddress;
1003 }
1004 else
1005 {
1006 AssertMsgFailed(("Arg! paSyms[%u].st_shndx=" FMT_ELF_HALF "\n", iSym, paSyms[iSym].st_shndx));
1007 return VERR_BAD_EXE_FORMAT;
1008 }
1009
1010 AssertMsgReturn(paSyms[iSym].st_name < cbStr,
1011 ("String outside string table! iSym=%d paSyms[iSym].st_name=%#x\n", iSym, paSyms[iSym].st_name),
1012 VERR_LDRELF_INVALID_SYMBOL_NAME_OFFSET);
1013 const char * const pszName = pszzStr + paSyms[iSym].st_name;
1014
1015 /* String termination was already checked when the string table was mapped. */
1016 if ( *pszName != '\0'
1017 && ( (fFlags & RTLDR_ENUM_SYMBOL_FLAGS_ALL)
1018 || ELF_ST_BIND(paSyms[iSym].st_info) == STB_GLOBAL) )
1019 {
1020 /*
1021 * Call back.
1022 */
1023 AssertMsgReturn(Value == (RTUINTPTR)Value, (FMT_ELF_ADDR "\n", Value), VERR_SYMBOL_VALUE_TOO_BIG);
1024 rc = pfnCallback(pMod, pszName, iSym, (RTUINTPTR)Value, pvUser);
1025 if (rc)
1026 return rc;
1027 }
1028 }
1029 }
1030
1031 return VINF_SUCCESS;
1032}
1033
1034
1035/** @copydoc RTLDROPS::GetImageSize */
1036static DECLCALLBACK(size_t) RTLDRELF_NAME(GetImageSize)(PRTLDRMODINTERNAL pMod)
1037{
1038 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1039
1040 return pModElf->cbImage;
1041}
1042
1043
1044/** @copydoc RTLDROPS::GetBits */
1045static DECLCALLBACK(int) RTLDRELF_NAME(GetBits)(PRTLDRMODINTERNAL pMod, void *pvBits, RTUINTPTR BaseAddress, PFNRTLDRIMPORT pfnGetImport, void *pvUser)
1046{
1047 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1048
1049 /*
1050 * This operation is currently only available on relocatable images.
1051 */
1052 switch (pModElf->Ehdr.e_type)
1053 {
1054 case ET_REL:
1055 case ET_DYN:
1056 break;
1057 case ET_EXEC:
1058 Log(("RTLdrELF: %s: Executable images are not supported yet!\n", pModElf->Core.pReader->pfnLogName(pModElf->Core.pReader)));
1059 return VERR_LDRELF_EXEC;
1060 default: AssertFailedReturn(VERR_BAD_EXE_FORMAT);
1061 }
1062
1063 /*
1064 * Load the bits into pvBits.
1065 */
1066 const Elf_Shdr *paShdrs = pModElf->paShdrs;
1067 for (unsigned iShdr = 0; iShdr < pModElf->Ehdr.e_shnum; iShdr++)
1068 {
1069 if (paShdrs[iShdr].sh_flags & SHF_ALLOC)
1070 {
1071 AssertMsgReturn((size_t)paShdrs[iShdr].sh_size == (size_t)paShdrs[iShdr].sh_size, (FMT_ELF_SIZE "\n", paShdrs[iShdr].sh_size), VERR_IMAGE_TOO_BIG);
1072 switch (paShdrs[iShdr].sh_type)
1073 {
1074 case SHT_NOBITS:
1075 memset((uint8_t *)pvBits + paShdrs[iShdr].sh_addr, 0, (size_t)paShdrs[iShdr].sh_size);
1076 break;
1077
1078 case SHT_PROGBITS:
1079 default:
1080 {
1081 int rc = pModElf->Core.pReader->pfnRead(pModElf->Core.pReader, (uint8_t *)pvBits + paShdrs[iShdr].sh_addr,
1082 (size_t)paShdrs[iShdr].sh_size, paShdrs[iShdr].sh_offset);
1083 if (RT_FAILURE(rc))
1084 {
1085 Log(("RTLdrELF: %s: Read error when reading " FMT_ELF_SIZE " bytes at " FMT_ELF_OFF ", iShdr=%d\n",
1086 pModElf->Core.pReader->pfnLogName(pModElf->Core.pReader),
1087 paShdrs[iShdr].sh_size, paShdrs[iShdr].sh_offset, iShdr));
1088 return rc;
1089 }
1090 }
1091 }
1092 }
1093 }
1094
1095 /*
1096 * Relocate the image.
1097 */
1098 return pModElf->Core.pOps->pfnRelocate(pMod, pvBits, BaseAddress, ~(RTUINTPTR)0, pfnGetImport, pvUser);
1099}
1100
1101
1102/** @copydoc RTLDROPS::Relocate */
1103static DECLCALLBACK(int) RTLDRELF_NAME(Relocate)(PRTLDRMODINTERNAL pMod, void *pvBits, RTUINTPTR NewBaseAddress,
1104 RTUINTPTR OldBaseAddress, PFNRTLDRIMPORT pfnGetImport, void *pvUser)
1105{
1106 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1107#ifdef LOG_ENABLED
1108 const char *pszLogName = pModElf->Core.pReader->pfnLogName(pModElf->Core.pReader);
1109#endif
1110 NOREF(OldBaseAddress);
1111
1112 /*
1113 * This operation is currently only available on relocatable images.
1114 */
1115 switch (pModElf->Ehdr.e_type)
1116 {
1117 case ET_REL:
1118 case ET_DYN:
1119 break;
1120 case ET_EXEC:
1121 Log(("RTLdrELF: %s: Executable images are not supported yet!\n", pszLogName));
1122 return VERR_LDRELF_EXEC;
1123 default: AssertFailedReturn(VERR_BAD_EXE_FORMAT);
1124 }
1125
1126 /*
1127 * Validate the input.
1128 */
1129 Elf_Addr BaseAddr = (Elf_Addr)NewBaseAddress;
1130 AssertMsgReturn((RTUINTPTR)BaseAddr == NewBaseAddress, ("%RTptr", NewBaseAddress), VERR_IMAGE_BASE_TOO_HIGH);
1131
1132 /*
1133 * Map the image bits if not already done and setup pointer into it.
1134 */
1135 int rc = RTLDRELF_NAME(MapBits)(pModElf, true);
1136 if (RT_FAILURE(rc))
1137 return rc;
1138
1139 /*
1140 * Iterate the sections looking for interesting SHT_REL[A] sections.
1141 *
1142 * In ET_REL files the SHT_REL[A] sections have the section index of
1143 * the section they contain fixups for in the sh_info member.
1144 */
1145 const Elf_Shdr *paShdrs = pModElf->paShdrs;
1146 Log2(("rtLdrElf: %s: Fixing up image\n", pszLogName));
1147 for (unsigned iShdr = 0; iShdr < pModElf->Ehdr.e_shnum; iShdr++)
1148 {
1149 const Elf_Shdr *pShdrRel = &paShdrs[iShdr];
1150
1151 /*
1152 * Skip sections without interest to us.
1153 */
1154#if ELF_MODE == 32
1155 if (pShdrRel->sh_type != SHT_REL)
1156#else
1157 if (pShdrRel->sh_type != SHT_RELA)
1158#endif
1159 continue;
1160 if (pModElf->Ehdr.e_type == ET_REL)
1161 {
1162 if (pShdrRel->sh_info >= pModElf->Ehdr.e_shnum)
1163 continue;
1164 const Elf_Shdr *pShdr = &paShdrs[pShdrRel->sh_info]; /* the section to fixup. */
1165 if (!(pShdr->sh_flags & SHF_ALLOC))
1166 continue;
1167
1168 /*
1169 * Relocate the section.
1170 */
1171 Log2(("rtldrELF: %s: Relocation records for #%d [%s] (sh_info=%d sh_link=%d) found in #%d [%s] (sh_info=%d sh_link=%d)\n",
1172 pszLogName, (int)pShdrRel->sh_info, ELF_SH_STR(pModElf, pShdr->sh_name), (int)pShdr->sh_info, (int)pShdr->sh_link,
1173 iShdr, ELF_SH_STR(pModElf, pShdrRel->sh_name), (int)pShdrRel->sh_info, (int)pShdrRel->sh_link));
1174
1175 rc = RTLDRELF_NAME(RelocateSectionRel)(pModElf, BaseAddr, pfnGetImport, pvUser,
1176 pShdr->sh_addr,
1177 pShdr->sh_size,
1178 (const uint8_t *)pModElf->pvBits + pShdr->sh_offset,
1179 (uint8_t *)pvBits + pShdr->sh_addr,
1180 (const uint8_t *)pModElf->pvBits + pShdrRel->sh_offset,
1181 pShdrRel->sh_size);
1182 }
1183 else
1184 rc = RTLDRELF_NAME(RelocateSectionExecDyn)(pModElf, BaseAddr, pfnGetImport, pvUser,
1185 0, (Elf_Size)pModElf->cbImage,
1186 (const uint8_t *)pModElf->pvBits /** @todo file offset ?? */,
1187 (uint8_t *)pvBits,
1188 (const uint8_t *)pModElf->pvBits + pShdrRel->sh_offset,
1189 pShdrRel->sh_size);
1190
1191 if (RT_FAILURE(rc))
1192 return rc;
1193 }
1194 return VINF_SUCCESS;
1195}
1196
1197
1198/**
1199 * Worker for pfnGetSymbolEx.
1200 */
1201static int RTLDRELF_NAME(ReturnSymbol)(PRTLDRMODELF pThis, const Elf_Sym *pSym, Elf_Addr uBaseAddr, PRTUINTPTR pValue)
1202{
1203 Elf_Addr Value;
1204 if (pSym->st_shndx == SHN_ABS)
1205 /* absolute symbols are not subject to any relocation. */
1206 Value = pSym->st_value;
1207 else if (pSym->st_shndx < pThis->Ehdr.e_shnum)
1208 {
1209 if (pThis->Ehdr.e_type == ET_REL)
1210 /* relative to the section. */
1211 Value = uBaseAddr + pSym->st_value + pThis->paShdrs[pSym->st_shndx].sh_addr;
1212 else /* Fixed up for link address. */
1213 Value = uBaseAddr + pSym->st_value - pThis->LinkAddress;
1214 }
1215 else
1216 {
1217 AssertMsgFailed(("Arg! pSym->st_shndx=%d\n", pSym->st_shndx));
1218 return VERR_BAD_EXE_FORMAT;
1219 }
1220 AssertMsgReturn(Value == (RTUINTPTR)Value, (FMT_ELF_ADDR "\n", Value), VERR_SYMBOL_VALUE_TOO_BIG);
1221 *pValue = (RTUINTPTR)Value;
1222 return VINF_SUCCESS;
1223}
1224
1225
1226/** @copydoc RTLDROPS::pfnGetSymbolEx */
1227static DECLCALLBACK(int) RTLDRELF_NAME(GetSymbolEx)(PRTLDRMODINTERNAL pMod, const void *pvBits, RTUINTPTR BaseAddress,
1228 uint32_t iOrdinal, const char *pszSymbol, RTUINTPTR *pValue)
1229{
1230 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1231 NOREF(pvBits);
1232
1233 /*
1234 * Validate the input.
1235 */
1236 Elf_Addr uBaseAddr = (Elf_Addr)BaseAddress;
1237 AssertMsgReturn((RTUINTPTR)uBaseAddr == BaseAddress, ("%RTptr", BaseAddress), VERR_IMAGE_BASE_TOO_HIGH);
1238
1239 /*
1240 * Map the image bits if not already done and setup pointer into it.
1241 */
1242 int rc = RTLDRELF_NAME(MapBits)(pModElf, true);
1243 if (RT_FAILURE(rc))
1244 return rc;
1245
1246 /*
1247 * Calc all kinds of pointers before we start iterating the symbol table.
1248 */
1249 const Elf_Sym *paSyms = pModElf->Rel.paSyms;
1250 unsigned cSyms = pModElf->Rel.cSyms;
1251 const char *pszzStr = pModElf->Rel.pStr;
1252 unsigned cbStr = pModElf->Rel.cbStr;
1253 if (pModElf->Dyn.cSyms > 0)
1254 {
1255 paSyms = pModElf->Dyn.paSyms;
1256 cSyms = pModElf->Dyn.cSyms;
1257 pszzStr = pModElf->Dyn.pStr;
1258 cbStr = pModElf->Dyn.cbStr;
1259 }
1260
1261 if (iOrdinal == UINT32_MAX)
1262 {
1263 for (unsigned iSym = 1; iSym < cSyms; iSym++)
1264 {
1265 /* Undefined symbols are not exports, they are imports. */
1266 if ( paSyms[iSym].st_shndx != SHN_UNDEF
1267 && ( ELF_ST_BIND(paSyms[iSym].st_info) == STB_GLOBAL
1268 || ELF_ST_BIND(paSyms[iSym].st_info) == STB_WEAK))
1269 {
1270 /* Validate the name string and try match with it. */
1271 AssertMsgReturn(paSyms[iSym].st_name < cbStr,
1272 ("String outside string table! iSym=%d paSyms[iSym].st_name=%#x\n", iSym, paSyms[iSym].st_name),
1273 VERR_LDRELF_INVALID_SYMBOL_NAME_OFFSET);
1274 if (!strcmp(pszSymbol, pszzStr + paSyms[iSym].st_name))
1275 {
1276 /* matched! */
1277 return RTLDRELF_NAME(ReturnSymbol)(pModElf, &paSyms[iSym], uBaseAddr, pValue);
1278 }
1279 }
1280 }
1281 }
1282 else if (iOrdinal < cSyms)
1283 {
1284 if ( paSyms[iOrdinal].st_shndx != SHN_UNDEF
1285 && ( ELF_ST_BIND(paSyms[iOrdinal].st_info) == STB_GLOBAL
1286 || ELF_ST_BIND(paSyms[iOrdinal].st_info) == STB_WEAK))
1287 return RTLDRELF_NAME(ReturnSymbol)(pModElf, &paSyms[iOrdinal], uBaseAddr, pValue);
1288 }
1289
1290 return VERR_SYMBOL_NOT_FOUND;
1291}
1292
1293
1294/** @copydoc RTLDROPS::pfnEnumDbgInfo */
1295static DECLCALLBACK(int) RTLDRELF_NAME(EnumDbgInfo)(PRTLDRMODINTERNAL pMod, const void *pvBits,
1296 PFNRTLDRENUMDBG pfnCallback, void *pvUser)
1297{
1298 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1299 RT_NOREF_PV(pvBits);
1300
1301 /*
1302 * Map the image bits if not already done and setup pointer into it.
1303 */
1304 int rc = RTLDRELF_NAME(MapBits)(pModElf, true);
1305 if (RT_FAILURE(rc))
1306 return rc;
1307
1308 /*
1309 * Do the enumeration.
1310 */
1311 const Elf_Shdr *paShdrs = pModElf->paOrgShdrs;
1312 for (unsigned iShdr = 0; iShdr < pModElf->Ehdr.e_shnum; iShdr++)
1313 {
1314 /* Debug sections are expected to be PROGBITS and not allocated. */
1315 if (paShdrs[iShdr].sh_type != SHT_PROGBITS)
1316 continue;
1317 if (paShdrs[iShdr].sh_flags & SHF_ALLOC)
1318 continue;
1319
1320 RTLDRDBGINFO DbgInfo;
1321 const char *pszSectName = ELF_SH_STR(pModElf, paShdrs[iShdr].sh_name);
1322 if ( !strncmp(pszSectName, RT_STR_TUPLE(".debug_"))
1323 || !strcmp(pszSectName, ".WATCOM_references") )
1324 {
1325 RT_ZERO(DbgInfo.u);
1326 DbgInfo.enmType = RTLDRDBGINFOTYPE_DWARF;
1327 DbgInfo.pszExtFile = NULL;
1328 DbgInfo.offFile = paShdrs[iShdr].sh_offset;
1329 DbgInfo.cb = paShdrs[iShdr].sh_size;
1330 DbgInfo.u.Dwarf.pszSection = pszSectName;
1331 }
1332 else if (!strcmp(pszSectName, ".gnu_debuglink"))
1333 {
1334 if ((paShdrs[iShdr].sh_size & 3) || paShdrs[iShdr].sh_size < 8)
1335 return VERR_BAD_EXE_FORMAT;
1336
1337 RT_ZERO(DbgInfo.u);
1338 DbgInfo.enmType = RTLDRDBGINFOTYPE_DWARF_DWO;
1339 DbgInfo.pszExtFile = (const char *)((uintptr_t)pModElf->pvBits + (uintptr_t)paShdrs[iShdr].sh_offset);
1340 if (!RTStrEnd(DbgInfo.pszExtFile, paShdrs[iShdr].sh_size))
1341 return VERR_BAD_EXE_FORMAT;
1342 DbgInfo.u.Dwo.uCrc32 = *(uint32_t *)((uintptr_t)DbgInfo.pszExtFile + (uintptr_t)paShdrs[iShdr].sh_size
1343 - sizeof(uint32_t));
1344 DbgInfo.offFile = -1;
1345 DbgInfo.cb = 0;
1346 }
1347 else
1348 continue;
1349
1350 DbgInfo.LinkAddress = NIL_RTLDRADDR;
1351 DbgInfo.iDbgInfo = iShdr - 1;
1352
1353 rc = pfnCallback(pMod, &DbgInfo, pvUser);
1354 if (rc != VINF_SUCCESS)
1355 return rc;
1356
1357 }
1358
1359 return VINF_SUCCESS;
1360}
1361
1362
1363/**
1364 * Locate the next allocated section by RVA (sh_addr).
1365 *
1366 * This is a helper for EnumSegments and SegOffsetToRva.
1367 *
1368 * @returns Pointer to the section header if found, NULL if none.
1369 * @param pModElf The module instance.
1370 * @param iShdrCur The current section header.
1371 */
1372static const Elf_Shdr *RTLDRELF_NAME(GetNextAllocatedSection)(PRTLDRMODELF pModElf, unsigned iShdrCur)
1373{
1374 unsigned const cShdrs = pModElf->Ehdr.e_shnum;
1375 const Elf_Shdr * const paShdrs = pModElf->paShdrs;
1376 if (pModElf->fShdrInOrder)
1377 {
1378 for (unsigned iShdr = iShdrCur + 1; iShdr < cShdrs; iShdr++)
1379 if (paShdrs[iShdr].sh_flags & SHF_ALLOC)
1380 return &paShdrs[iShdr];
1381 }
1382 else
1383 {
1384 Elf_Addr const uEndCur = paShdrs[iShdrCur].sh_addr + paShdrs[iShdrCur].sh_size;
1385 Elf_Addr offBest = ~(Elf_Addr)0;
1386 unsigned iBest = cShdrs;
1387 for (unsigned iShdr = pModElf->iFirstSect; iShdr < cShdrs; iShdr++)
1388 if ((paShdrs[iShdr].sh_flags & SHF_ALLOC) && iShdr != iShdrCur)
1389 {
1390 Elf_Addr const offDelta = paShdrs[iShdr].sh_addr - uEndCur;
1391 if ( offDelta < offBest
1392 && paShdrs[iShdr].sh_addr >= uEndCur)
1393 {
1394 offBest = offDelta;
1395 iBest = iShdr;
1396 }
1397 }
1398 if (iBest < cShdrs)
1399 return &paShdrs[iBest];
1400 }
1401 return NULL;
1402}
1403
1404
1405/** @copydoc RTLDROPS::pfnEnumSegments. */
1406static DECLCALLBACK(int) RTLDRELF_NAME(EnumSegments)(PRTLDRMODINTERNAL pMod, PFNRTLDRENUMSEGS pfnCallback, void *pvUser)
1407{
1408 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1409
1410 /*
1411 * Map the image bits if not already done and setup pointer into it.
1412 */
1413 int rc = RTLDRELF_NAME(MapBits)(pModElf, true);
1414 if (RT_FAILURE(rc))
1415 return rc;
1416
1417 /*
1418 * Do the enumeration.
1419 */
1420 char szName[32];
1421 Elf_Addr uPrevMappedRva = 0;
1422 const Elf_Shdr *paShdrs = pModElf->paShdrs;
1423 const Elf_Shdr *paOrgShdrs = pModElf->paOrgShdrs;
1424 for (unsigned iShdr = pModElf->iFirstSect; iShdr < pModElf->Ehdr.e_shnum; iShdr++)
1425 {
1426 RTLDRSEG Seg;
1427 if (iShdr != 0)
1428 {
1429 Seg.pszName = ELF_SH_STR(pModElf, paShdrs[iShdr].sh_name);
1430 Seg.cchName = (uint32_t)strlen(Seg.pszName);
1431 if (Seg.cchName == 0)
1432 {
1433 Seg.pszName = szName;
1434 Seg.cchName = (uint32_t)RTStrPrintf(szName, sizeof(szName), "UnamedSect%02u", iShdr);
1435 }
1436 }
1437 else
1438 {
1439 Seg.pszName = ".elf.headers";
1440 Seg.cchName = 12;
1441 }
1442 Seg.SelFlat = 0;
1443 Seg.Sel16bit = 0;
1444 Seg.fFlags = 0;
1445 Seg.fProt = RTMEM_PROT_READ;
1446 if (paShdrs[iShdr].sh_flags & SHF_WRITE)
1447 Seg.fProt |= RTMEM_PROT_WRITE;
1448 if (paShdrs[iShdr].sh_flags & SHF_EXECINSTR)
1449 Seg.fProt |= RTMEM_PROT_EXEC;
1450 Seg.cb = paShdrs[iShdr].sh_size;
1451 Seg.Alignment = paShdrs[iShdr].sh_addralign;
1452 if (paShdrs[iShdr].sh_flags & SHF_ALLOC)
1453 {
1454 Seg.LinkAddress = paOrgShdrs[iShdr].sh_addr;
1455 Seg.RVA = paShdrs[iShdr].sh_addr;
1456 const Elf_Shdr *pShdr2 = RTLDRELF_NAME(GetNextAllocatedSection)(pModElf, iShdr);
1457 if (pShdr2)
1458 Seg.cbMapped = pShdr2->sh_addr - paShdrs[iShdr].sh_addr;
1459 else
1460 Seg.cbMapped = pModElf->cbImage - paShdrs[iShdr].sh_addr;
1461 uPrevMappedRva = Seg.RVA;
1462 }
1463 else
1464 {
1465 Seg.LinkAddress = NIL_RTLDRADDR;
1466 Seg.RVA = NIL_RTLDRADDR;
1467 Seg.cbMapped = NIL_RTLDRADDR;
1468 }
1469 if (paShdrs[iShdr].sh_type != SHT_NOBITS)
1470 {
1471 Seg.offFile = paShdrs[iShdr].sh_offset;
1472 Seg.cbFile = paShdrs[iShdr].sh_size;
1473 }
1474 else
1475 {
1476 Seg.offFile = -1;
1477 Seg.cbFile = 0;
1478 }
1479
1480 rc = pfnCallback(pMod, &Seg, pvUser);
1481 if (rc != VINF_SUCCESS)
1482 return rc;
1483 }
1484
1485 return VINF_SUCCESS;
1486}
1487
1488
1489/** @copydoc RTLDROPS::pfnLinkAddressToSegOffset. */
1490static DECLCALLBACK(int) RTLDRELF_NAME(LinkAddressToSegOffset)(PRTLDRMODINTERNAL pMod, RTLDRADDR LinkAddress,
1491 uint32_t *piSeg, PRTLDRADDR poffSeg)
1492{
1493 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1494
1495 const Elf_Shdr *pShdrEnd = NULL;
1496 unsigned cLeft = pModElf->Ehdr.e_shnum - pModElf->iFirstSect;
1497 const Elf_Shdr *pShdr = &pModElf->paOrgShdrs[pModElf->Ehdr.e_shnum];
1498 while (cLeft-- > 0)
1499 {
1500 pShdr--;
1501 if (pShdr->sh_flags & SHF_ALLOC)
1502 {
1503 RTLDRADDR offSeg = LinkAddress - pShdr->sh_addr;
1504 if (offSeg < pShdr->sh_size)
1505 {
1506 *poffSeg = offSeg;
1507 *piSeg = cLeft;
1508 return VINF_SUCCESS;
1509 }
1510 if (offSeg == pShdr->sh_size)
1511 pShdrEnd = pShdr;
1512 }
1513 }
1514
1515 if (pShdrEnd)
1516 {
1517 *poffSeg = pShdrEnd->sh_size;
1518 *piSeg = pShdrEnd - pModElf->paOrgShdrs - pModElf->iFirstSect;
1519 return VINF_SUCCESS;
1520 }
1521
1522 return VERR_LDR_INVALID_LINK_ADDRESS;
1523}
1524
1525
1526/** @copydoc RTLDROPS::pfnLinkAddressToRva. */
1527static DECLCALLBACK(int) RTLDRELF_NAME(LinkAddressToRva)(PRTLDRMODINTERNAL pMod, RTLDRADDR LinkAddress, PRTLDRADDR pRva)
1528{
1529 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1530 uint32_t iSeg;
1531 RTLDRADDR offSeg;
1532 int rc = RTLDRELF_NAME(LinkAddressToSegOffset)(pMod, LinkAddress, &iSeg, &offSeg);
1533 if (RT_SUCCESS(rc))
1534 *pRva = pModElf->paShdrs[iSeg + pModElf->iFirstSect].sh_addr + offSeg;
1535 return rc;
1536}
1537
1538
1539/** @copydoc RTLDROPS::pfnSegOffsetToRva. */
1540static DECLCALLBACK(int) RTLDRELF_NAME(SegOffsetToRva)(PRTLDRMODINTERNAL pMod, uint32_t iSeg, RTLDRADDR offSeg,
1541 PRTLDRADDR pRva)
1542{
1543 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1544 if (iSeg >= pModElf->Ehdr.e_shnum - pModElf->iFirstSect)
1545 return VERR_LDR_INVALID_SEG_OFFSET;
1546
1547 iSeg += pModElf->iFirstSect; /* skip section 0 if not used */
1548 if (offSeg > pModElf->paShdrs[iSeg].sh_size)
1549 {
1550 const Elf_Shdr *pShdr2 = RTLDRELF_NAME(GetNextAllocatedSection)(pModElf, iSeg);
1551 if ( !pShdr2
1552 || offSeg > (pShdr2->sh_addr - pModElf->paShdrs[iSeg].sh_addr))
1553 return VERR_LDR_INVALID_SEG_OFFSET;
1554 }
1555
1556 if (!(pModElf->paShdrs[iSeg].sh_flags & SHF_ALLOC))
1557 return VERR_LDR_INVALID_SEG_OFFSET;
1558
1559 *pRva = pModElf->paShdrs[iSeg].sh_addr;
1560 return VINF_SUCCESS;
1561}
1562
1563
1564/** @copydoc RTLDROPS::pfnRvaToSegOffset. */
1565static DECLCALLBACK(int) RTLDRELF_NAME(RvaToSegOffset)(PRTLDRMODINTERNAL pMod, RTLDRADDR Rva,
1566 uint32_t *piSeg, PRTLDRADDR poffSeg)
1567{
1568 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1569 Elf_Addr PrevAddr = 0;
1570 unsigned cLeft = pModElf->Ehdr.e_shnum - pModElf->iFirstSect;
1571 const Elf_Shdr *pShdr = &pModElf->paShdrs[pModElf->Ehdr.e_shnum];
1572 while (cLeft-- > 0)
1573 {
1574 pShdr--;
1575 if (pShdr->sh_flags & SHF_ALLOC)
1576 {
1577 Elf_Addr cbSeg = PrevAddr ? PrevAddr - pShdr->sh_addr : pShdr->sh_size;
1578 RTLDRADDR offSeg = Rva - pShdr->sh_addr;
1579 if (offSeg <= cbSeg)
1580 {
1581 *poffSeg = offSeg;
1582 *piSeg = cLeft;
1583 return VINF_SUCCESS;
1584 }
1585 PrevAddr = pShdr->sh_addr;
1586 }
1587 }
1588
1589 return VERR_LDR_INVALID_RVA;
1590}
1591
1592
1593/** @callback_method_impl{FNRTLDRIMPORT, Stub used by ReadDbgInfo.} */
1594static DECLCALLBACK(int) RTLDRELF_NAME(GetImportStubCallback)(RTLDRMOD hLdrMod, const char *pszModule, const char *pszSymbol,
1595 unsigned uSymbol, PRTLDRADDR pValue, void *pvUser)
1596{
1597 RT_NOREF_PV(hLdrMod); RT_NOREF_PV(pszModule); RT_NOREF_PV(pszSymbol);
1598 RT_NOREF_PV(uSymbol); RT_NOREF_PV(pValue); RT_NOREF_PV(pvUser);
1599 return VERR_SYMBOL_NOT_FOUND;
1600}
1601
1602
1603/** @copydoc RTLDROPS::pfnReadDbgInfo. */
1604static DECLCALLBACK(int) RTLDRELF_NAME(ReadDbgInfo)(PRTLDRMODINTERNAL pMod, uint32_t iDbgInfo, RTFOFF off,
1605 size_t cb, void *pvBuf)
1606{
1607 PRTLDRMODELF pThis = (PRTLDRMODELF)pMod;
1608 LogFlow(("%s: iDbgInfo=%#x off=%RTfoff cb=%#zu\n", __FUNCTION__, iDbgInfo, off, cb));
1609
1610 /*
1611 * Input validation.
1612 */
1613 AssertReturn(iDbgInfo < pThis->Ehdr.e_shnum && iDbgInfo + 1 < pThis->Ehdr.e_shnum, VERR_INVALID_PARAMETER);
1614 iDbgInfo++;
1615 AssertReturn(!(pThis->paShdrs[iDbgInfo].sh_flags & SHF_ALLOC), VERR_INVALID_PARAMETER);
1616 AssertReturn(pThis->paShdrs[iDbgInfo].sh_type == SHT_PROGBITS, VERR_INVALID_PARAMETER);
1617 AssertReturn(pThis->paShdrs[iDbgInfo].sh_offset == (uint64_t)off, VERR_INVALID_PARAMETER);
1618 AssertReturn(pThis->paShdrs[iDbgInfo].sh_size == cb, VERR_INVALID_PARAMETER);
1619 uint64_t cbRawImage = pThis->Core.pReader->pfnSize(pThis->Core.pReader);
1620 AssertReturn(off >= 0 && cb <= cbRawImage && (uint64_t)off + cb <= cbRawImage, VERR_INVALID_PARAMETER);
1621
1622 /*
1623 * Read it from the file and look for fixup sections.
1624 */
1625 int rc;
1626 if (pThis->pvBits)
1627 memcpy(pvBuf, (const uint8_t *)pThis->pvBits + (size_t)off, cb);
1628 else
1629 {
1630 rc = pThis->Core.pReader->pfnRead(pThis->Core.pReader, pvBuf, cb, off);
1631 if (RT_FAILURE(rc))
1632 return rc;
1633 }
1634
1635 uint32_t iRelocs = iDbgInfo + 1;
1636 if ( iRelocs >= pThis->Ehdr.e_shnum
1637 || pThis->paShdrs[iRelocs].sh_info != iDbgInfo
1638 || ( pThis->paShdrs[iRelocs].sh_type != SHT_REL
1639 && pThis->paShdrs[iRelocs].sh_type != SHT_RELA) )
1640 {
1641 iRelocs = 0;
1642 while ( iRelocs < pThis->Ehdr.e_shnum
1643 && ( pThis->paShdrs[iRelocs].sh_info != iDbgInfo
1644 || ( pThis->paShdrs[iRelocs].sh_type != SHT_REL
1645 && pThis->paShdrs[iRelocs].sh_type != SHT_RELA)) )
1646 iRelocs++;
1647 }
1648 if ( iRelocs < pThis->Ehdr.e_shnum
1649 && pThis->paShdrs[iRelocs].sh_size > 0)
1650 {
1651 /*
1652 * Load the relocations.
1653 */
1654 uint8_t *pbRelocsBuf = NULL;
1655 const uint8_t *pbRelocs;
1656 if (pThis->pvBits)
1657 pbRelocs = (const uint8_t *)pThis->pvBits + pThis->paShdrs[iRelocs].sh_offset;
1658 else
1659 {
1660 pbRelocs = pbRelocsBuf = (uint8_t *)RTMemTmpAlloc(pThis->paShdrs[iRelocs].sh_size);
1661 if (!pbRelocsBuf)
1662 return VERR_NO_TMP_MEMORY;
1663 rc = pThis->Core.pReader->pfnRead(pThis->Core.pReader, pbRelocsBuf,
1664 pThis->paShdrs[iRelocs].sh_size,
1665 pThis->paShdrs[iRelocs].sh_offset);
1666 if (RT_FAILURE(rc))
1667 {
1668 RTMemTmpFree(pbRelocsBuf);
1669 return rc;
1670 }
1671 }
1672
1673 /*
1674 * Apply the relocations.
1675 */
1676 if (pThis->Ehdr.e_type == ET_REL)
1677 rc = RTLDRELF_NAME(RelocateSectionRel)(pThis, pThis->LinkAddress,
1678 RTLDRELF_NAME(GetImportStubCallback), NULL /*pvUser*/,
1679 pThis->paShdrs[iDbgInfo].sh_addr,
1680 pThis->paShdrs[iDbgInfo].sh_size,
1681 (const uint8_t *)pvBuf,
1682 (uint8_t *)pvBuf,
1683 pbRelocs,
1684 pThis->paShdrs[iRelocs].sh_size);
1685 else
1686 rc = RTLDRELF_NAME(RelocateSectionExecDyn)(pThis, pThis->LinkAddress,
1687 RTLDRELF_NAME(GetImportStubCallback), NULL /*pvUser*/,
1688 pThis->paShdrs[iDbgInfo].sh_addr,
1689 pThis->paShdrs[iDbgInfo].sh_size,
1690 (const uint8_t *)pvBuf,
1691 (uint8_t *)pvBuf,
1692 pbRelocs,
1693 pThis->paShdrs[iRelocs].sh_size);
1694
1695 RTMemTmpFree(pbRelocsBuf);
1696 }
1697 else
1698 rc = VINF_SUCCESS;
1699 return rc;
1700}
1701
1702
1703/** @interface_method_impl{RTLDROPS,pfnQueryProp} */
1704static DECLCALLBACK(int) RTLDRELF_NAME(QueryProp)(PRTLDRMODINTERNAL pMod, RTLDRPROP enmProp, void const *pvBits,
1705 void *pvBuf, size_t cbBuf, size_t *pcbRet)
1706{
1707 PRTLDRMODELF pThis = (PRTLDRMODELF)pMod;
1708
1709 if (enmProp != RTLDRPROP_BUILDID)
1710 return VERR_NOT_FOUND;
1711
1712 /*
1713 * Map the image bits if not already done and setup pointer into it.
1714 */
1715 int rc = RTLDRELF_NAME(MapBits)(pThis, true);
1716 if (RT_FAILURE(rc))
1717 return rc;
1718
1719 /*
1720 * Search for the build ID.
1721 */
1722 const Elf_Shdr *paShdrs = pThis->paOrgShdrs;
1723 for (unsigned iShdr = 0; iShdr < pThis->Ehdr.e_shnum; iShdr++)
1724 {
1725 const char *pszSectName = ELF_SH_STR(pThis, paShdrs[iShdr].sh_name);
1726
1727 if (!strcmp(pszSectName, ".note.gnu.build-id"))
1728 {
1729 if ((paShdrs[iShdr].sh_size & 3) || paShdrs[iShdr].sh_size < sizeof(Elf_Nhdr))
1730 return VERR_BAD_EXE_FORMAT;
1731
1732 Elf_Nhdr *pNHdr = (Elf_Nhdr *)((uintptr_t)pThis->pvBits + (uintptr_t)paShdrs[iShdr].sh_offset);
1733 if ( pNHdr->n_namesz > paShdrs[iShdr].sh_size
1734 || pNHdr->n_descsz > paShdrs[iShdr].sh_size
1735 || (paShdrs[iShdr].sh_size - pNHdr->n_descsz) < pNHdr->n_namesz
1736 || pNHdr->n_type != NT_GNU_BUILD_ID)
1737 return VERR_BAD_EXE_FORMAT;
1738
1739 const char *pszOwner = (const char *)(pNHdr + 1);
1740 if ( !RTStrEnd(pszOwner, pNHdr->n_namesz)
1741 || strcmp(pszOwner, "GNU"))
1742 return VERR_BAD_EXE_FORMAT;
1743
1744 if (cbBuf < pNHdr->n_descsz)
1745 return VERR_BUFFER_OVERFLOW;
1746
1747 memcpy(pvBuf, pszOwner + pNHdr->n_namesz, pNHdr->n_descsz);
1748 *pcbRet = pNHdr->n_descsz;
1749 return VINF_SUCCESS;
1750 }
1751 }
1752
1753 NOREF(cbBuf);
1754 RT_NOREF_PV(pvBits);
1755 return VERR_NOT_FOUND;
1756}
1757
1758
1759/**
1760 * @interface_method_impl{RTLDROPS,pfnUnwindFrame}
1761 */
1762static DECLCALLBACK(int)
1763RTLDRELF_NAME(UnwindFrame)(PRTLDRMODINTERNAL pMod, void const *pvBits, uint32_t iSeg, RTUINTPTR off, PRTDBGUNWINDSTATE pState)
1764{
1765 PRTLDRMODELF pThis = (PRTLDRMODELF)pMod;
1766 LogFlow(("%s: iSeg=%#x off=%RTptr\n", __FUNCTION__, iSeg, off));
1767
1768 /*
1769 * Process the input address, making us both RVA and proper seg:offset out of it.
1770 */
1771 int rc;
1772 RTLDRADDR uRva = off;
1773 if (iSeg == UINT32_MAX)
1774 rc = RTLDRELF_NAME(RvaToSegOffset)(pMod, uRva, &iSeg, &off);
1775 else
1776 rc = RTLDRELF_NAME(SegOffsetToRva)(pMod, iSeg, off, &uRva);
1777 AssertRCReturn(rc, rc);
1778
1779 /*
1780 * Map the image bits if not already done and setup pointer into it.
1781 */
1782 RT_NOREF(pvBits); /** @todo Try use passed in pvBits? */
1783 rc = RTLDRELF_NAME(MapBits)(pThis, true);
1784 if (RT_FAILURE(rc))
1785 return rc;
1786
1787 /*
1788 * Do we need to search for .eh_frame and .eh_frame_hdr?
1789 */
1790 if (pThis->iShEhFrame == 0)
1791 {
1792 pThis->iShEhFrame = ~0U;
1793 pThis->iShEhFrameHdr = ~0U;
1794 unsigned cLeft = 2;
1795 for (unsigned iShdr = 1; iShdr < pThis->Ehdr.e_shnum; iShdr++)
1796 {
1797 const char *pszName = ELF_SH_STR(pThis, pThis->paShdrs[iShdr].sh_name);
1798 if ( pszName[0] == '.'
1799 && pszName[1] == 'e'
1800 && pszName[2] == 'h'
1801 && pszName[3] == '_'
1802 && pszName[4] == 'f'
1803 && pszName[5] == 'r'
1804 && pszName[6] == 'a'
1805 && pszName[7] == 'm'
1806 && pszName[8] == 'e')
1807 {
1808 if (pszName[9] == '\0')
1809 pThis->iShEhFrame = iShdr;
1810 else if ( pszName[9] == '_'
1811 && pszName[10] == 'h'
1812 && pszName[11] == 'd'
1813 && pszName[12] == 'r'
1814 && pszName[13] == '\0')
1815 pThis->iShEhFrameHdr = iShdr;
1816 else
1817 continue;
1818 if (--cLeft == 0)
1819 break;
1820 }
1821 }
1822 }
1823
1824 /*
1825 * Any info present?
1826 */
1827 unsigned iShdr = pThis->iShEhFrame;
1828 if ( iShdr != ~0U
1829 && pThis->paShdrs[iShdr].sh_size > 0)
1830 {
1831 if (pThis->paShdrs[iShdr].sh_flags & SHF_ALLOC)
1832 return rtDwarfUnwind_EhData((uint8_t const *)pThis->pvBits + pThis->paShdrs[iShdr].sh_addr,
1833 pThis->paShdrs[iShdr].sh_size, pThis->paShdrs[iShdr].sh_addr,
1834 iSeg, off, uRva, pState, pThis->Core.enmArch);
1835 }
1836 return VERR_DBG_NO_UNWIND_INFO;
1837}
1838
1839
1840/**
1841 * The ELF module operations.
1842 */
1843static RTLDROPS RTLDRELF_MID(s_rtldrElf,Ops) =
1844{
1845#if ELF_MODE == 32
1846 "elf32",
1847#elif ELF_MODE == 64
1848 "elf64",
1849#endif
1850 RTLDRELF_NAME(Close),
1851 NULL, /* Get Symbol */
1852 RTLDRELF_NAME(Done),
1853 RTLDRELF_NAME(EnumSymbols),
1854 /* ext: */
1855 RTLDRELF_NAME(GetImageSize),
1856 RTLDRELF_NAME(GetBits),
1857 RTLDRELF_NAME(Relocate),
1858 RTLDRELF_NAME(GetSymbolEx),
1859 NULL /*pfnQueryForwarderInfo*/,
1860 RTLDRELF_NAME(EnumDbgInfo),
1861 RTLDRELF_NAME(EnumSegments),
1862 RTLDRELF_NAME(LinkAddressToSegOffset),
1863 RTLDRELF_NAME(LinkAddressToRva),
1864 RTLDRELF_NAME(SegOffsetToRva),
1865 RTLDRELF_NAME(RvaToSegOffset),
1866 RTLDRELF_NAME(ReadDbgInfo),
1867 RTLDRELF_NAME(QueryProp),
1868 NULL /*pfnVerifySignature*/,
1869 NULL /*pfnHashImage*/,
1870 RTLDRELF_NAME(UnwindFrame),
1871 42
1872};
1873
1874
1875
1876/**
1877 * Validates the ELF header.
1878 *
1879 * @returns iprt status code.
1880 * @param pEhdr Pointer to the ELF header.
1881 * @param cbRawImage The size of the raw image.
1882 * @param pszLogName The log name.
1883 * @param penmArch Where to return the architecture.
1884 * @param pErrInfo Where to return extended error info. Optional.
1885 */
1886static int RTLDRELF_NAME(ValidateElfHeader)(const Elf_Ehdr *pEhdr, uint64_t cbRawImage, const char *pszLogName,
1887 PRTLDRARCH penmArch, PRTERRINFO pErrInfo)
1888{
1889 Log3(("RTLdrELF: e_ident: %.*Rhxs\n"
1890 "RTLdrELF: e_type: " FMT_ELF_HALF "\n"
1891 "RTLdrELF: e_version: " FMT_ELF_HALF "\n"
1892 "RTLdrELF: e_entry: " FMT_ELF_ADDR "\n"
1893 "RTLdrELF: e_phoff: " FMT_ELF_OFF "\n"
1894 "RTLdrELF: e_shoff: " FMT_ELF_OFF "\n"
1895 "RTLdrELF: e_flags: " FMT_ELF_WORD "\n"
1896 "RTLdrELF: e_ehsize: " FMT_ELF_HALF "\n"
1897 "RTLdrELF: e_phentsize: " FMT_ELF_HALF "\n"
1898 "RTLdrELF: e_phnum: " FMT_ELF_HALF "\n"
1899 "RTLdrELF: e_shentsize: " FMT_ELF_HALF "\n"
1900 "RTLdrELF: e_shnum: " FMT_ELF_HALF "\n"
1901 "RTLdrELF: e_shstrndx: " FMT_ELF_HALF "\n",
1902 RT_ELEMENTS(pEhdr->e_ident), &pEhdr->e_ident[0], pEhdr->e_type, pEhdr->e_version,
1903 pEhdr->e_entry, pEhdr->e_phoff, pEhdr->e_shoff,pEhdr->e_flags, pEhdr->e_ehsize, pEhdr->e_phentsize,
1904 pEhdr->e_phnum, pEhdr->e_shentsize, pEhdr->e_shnum, pEhdr->e_shstrndx));
1905
1906 if ( pEhdr->e_ident[EI_MAG0] != ELFMAG0
1907 || pEhdr->e_ident[EI_MAG1] != ELFMAG1
1908 || pEhdr->e_ident[EI_MAG2] != ELFMAG2
1909 || pEhdr->e_ident[EI_MAG3] != ELFMAG3)
1910 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1911 "%s: Invalid ELF magic (%.*Rhxs)", pszLogName, sizeof(pEhdr->e_ident), pEhdr->e_ident);
1912 if (pEhdr->e_ident[EI_CLASS] != RTLDRELF_SUFF(ELFCLASS))
1913 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1914 "%s: Invalid ELF class (%.*Rhxs)", pszLogName, sizeof(pEhdr->e_ident), pEhdr->e_ident);
1915 if (pEhdr->e_ident[EI_DATA] != ELFDATA2LSB)
1916 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDRELF_ODD_ENDIAN,
1917 "%s: ELF endian %x is unsupported", pszLogName, pEhdr->e_ident[EI_DATA]);
1918 if (pEhdr->e_version != EV_CURRENT)
1919 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDRELF_VERSION,
1920 "%s: ELF version %x is unsupported", pszLogName, pEhdr->e_version);
1921
1922 if (sizeof(Elf_Ehdr) != pEhdr->e_ehsize)
1923 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1924 "%s: Elf header e_ehsize is %d expected %d!", pszLogName, pEhdr->e_ehsize, sizeof(Elf_Ehdr));
1925 if ( sizeof(Elf_Phdr) != pEhdr->e_phentsize
1926 && ( pEhdr->e_phnum != 0
1927 || pEhdr->e_type == ET_DYN
1928 || pEhdr->e_type == ET_EXEC))
1929 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Elf header e_phentsize is %d expected %d!",
1930 pszLogName, pEhdr->e_phentsize, sizeof(Elf_Phdr));
1931 if (sizeof(Elf_Shdr) != pEhdr->e_shentsize)
1932 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Elf header e_shentsize is %d expected %d!",
1933 pszLogName, pEhdr->e_shentsize, sizeof(Elf_Shdr));
1934
1935 switch (pEhdr->e_type)
1936 {
1937 case ET_REL:
1938 case ET_EXEC:
1939 case ET_DYN:
1940 break;
1941 default:
1942 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: image type %#x is not supported!",
1943 pszLogName, pEhdr->e_type);
1944 }
1945
1946 switch (pEhdr->e_machine)
1947 {
1948#if ELF_MODE == 32
1949 case EM_386:
1950 case EM_486:
1951 *penmArch = RTLDRARCH_X86_32;
1952 break;
1953#elif ELF_MODE == 64
1954 case EM_X86_64:
1955 *penmArch = RTLDRARCH_AMD64;
1956 break;
1957#endif
1958 default:
1959 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDRELF_MACHINE,
1960 "%s: machine type %u is not supported!", pszLogName, pEhdr->e_machine);
1961 }
1962
1963 if ( pEhdr->e_phoff < pEhdr->e_ehsize
1964 && !(pEhdr->e_phoff && pEhdr->e_phnum)
1965 && pEhdr->e_phnum)
1966 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1967 "%s: The program headers overlap with the ELF header! e_phoff=" FMT_ELF_OFF,
1968 pszLogName, pEhdr->e_phoff);
1969 if ( pEhdr->e_phoff + pEhdr->e_phnum * pEhdr->e_phentsize > cbRawImage
1970 || pEhdr->e_phoff + pEhdr->e_phnum * pEhdr->e_phentsize < pEhdr->e_phoff)
1971 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1972 "%s: The program headers extends beyond the file! e_phoff=" FMT_ELF_OFF " e_phnum=" FMT_ELF_HALF,
1973 pszLogName, pEhdr->e_phoff, pEhdr->e_phnum);
1974
1975
1976 if ( pEhdr->e_shoff < pEhdr->e_ehsize
1977 && !(pEhdr->e_shoff && pEhdr->e_shnum))
1978 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1979 "%s: The section headers overlap with the ELF header! e_shoff=" FMT_ELF_OFF,
1980 pszLogName, pEhdr->e_shoff);
1981 if ( pEhdr->e_shoff + pEhdr->e_shnum * pEhdr->e_shentsize > cbRawImage
1982 || pEhdr->e_shoff + pEhdr->e_shnum * pEhdr->e_shentsize < pEhdr->e_shoff)
1983 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1984 "%s: The section headers extends beyond the file! e_shoff=" FMT_ELF_OFF " e_shnum=" FMT_ELF_HALF,
1985 pszLogName, pEhdr->e_shoff, pEhdr->e_shnum);
1986
1987 if (pEhdr->e_shstrndx == 0 || pEhdr->e_shstrndx > pEhdr->e_shnum)
1988 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1989 "%s: The section headers string table is out of bounds! e_shstrndx=" FMT_ELF_HALF " e_shnum=" FMT_ELF_HALF,
1990 pszLogName, pEhdr->e_shstrndx, pEhdr->e_shnum);
1991
1992 return VINF_SUCCESS;
1993}
1994
1995
1996/**
1997 * Gets the section header name.
1998 *
1999 * @returns pszName.
2000 * @param pEhdr The elf header.
2001 * @param offName The offset of the section header name.
2002 * @param pszName Where to store the name.
2003 * @param cbName The size of the buffer pointed to by pszName.
2004 */
2005const char *RTLDRELF_NAME(GetSHdrName)(PRTLDRMODELF pModElf, Elf_Word offName, char *pszName, size_t cbName)
2006{
2007 RTFOFF off = pModElf->paShdrs[pModElf->Ehdr.e_shstrndx].sh_offset + offName;
2008 int rc = pModElf->Core.pReader->pfnRead(pModElf->Core.pReader, pszName, cbName - 1, off);
2009 if (RT_FAILURE(rc))
2010 {
2011 /* read by for byte. */
2012 for (unsigned i = 0; i < cbName; i++, off++)
2013 {
2014 rc = pModElf->Core.pReader->pfnRead(pModElf->Core.pReader, pszName + i, 1, off);
2015 if (RT_FAILURE(rc))
2016 {
2017 pszName[i] = '\0';
2018 break;
2019 }
2020 }
2021 }
2022
2023 pszName[cbName - 1] = '\0';
2024 return pszName;
2025}
2026
2027
2028/**
2029 * Validates a section header.
2030 *
2031 * @returns iprt status code.
2032 * @param pModElf Pointer to the module structure.
2033 * @param iShdr The index of section header which should be validated.
2034 * The section headers are found in the pModElf->paShdrs array.
2035 * @param cbRawImage The size of the raw image.
2036 * @param pszLogName The log name.
2037 * @param pErrInfo Where to return extended error info. Optional.
2038 */
2039static int RTLDRELF_NAME(ValidateSectionHeader)(PRTLDRMODELF pModElf, unsigned iShdr, uint64_t cbRawImage,
2040 const char *pszLogName, PRTERRINFO pErrInfo)
2041{
2042 const Elf_Shdr *pShdr = &pModElf->paShdrs[iShdr];
2043 char szSectionName[80]; NOREF(szSectionName);
2044 Log3(("RTLdrELF: Section Header #%d:\n"
2045 "RTLdrELF: sh_name: " FMT_ELF_WORD " - %s\n"
2046 "RTLdrELF: sh_type: " FMT_ELF_WORD " (%s)\n"
2047 "RTLdrELF: sh_flags: " FMT_ELF_XWORD "\n"
2048 "RTLdrELF: sh_addr: " FMT_ELF_ADDR "\n"
2049 "RTLdrELF: sh_offset: " FMT_ELF_OFF "\n"
2050 "RTLdrELF: sh_size: " FMT_ELF_XWORD "\n"
2051 "RTLdrELF: sh_link: " FMT_ELF_WORD "\n"
2052 "RTLdrELF: sh_info: " FMT_ELF_WORD "\n"
2053 "RTLdrELF: sh_addralign: " FMT_ELF_XWORD "\n"
2054 "RTLdrELF: sh_entsize: " FMT_ELF_XWORD "\n",
2055 iShdr,
2056 pShdr->sh_name, RTLDRELF_NAME(GetSHdrName)(pModElf, pShdr->sh_name, szSectionName, sizeof(szSectionName)),
2057 pShdr->sh_type, rtldrElfGetShdrType(pShdr->sh_type), pShdr->sh_flags, pShdr->sh_addr,
2058 pShdr->sh_offset, pShdr->sh_size, pShdr->sh_link, pShdr->sh_info, pShdr->sh_addralign,
2059 pShdr->sh_entsize));
2060
2061 if (iShdr == 0)
2062 {
2063 if ( pShdr->sh_name != 0
2064 || pShdr->sh_type != SHT_NULL
2065 || pShdr->sh_flags != 0
2066 || pShdr->sh_addr != 0
2067 || pShdr->sh_size != 0
2068 || pShdr->sh_offset != 0
2069 || pShdr->sh_link != SHN_UNDEF
2070 || pShdr->sh_addralign != 0
2071 || pShdr->sh_entsize != 0 )
2072 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2073 "%s: Bad #0 section: %.*Rhxs", pszLogName, sizeof(*pShdr), pShdr);
2074 return VINF_SUCCESS;
2075 }
2076
2077 if (pShdr->sh_name >= pModElf->cbShStr)
2078 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2079 "%s: Shdr #%d: sh_name (%d) is beyond the end of the section header string table (%d)!",
2080 pszLogName, iShdr, pShdr->sh_name, pModElf->cbShStr);
2081
2082 if (pShdr->sh_link >= pModElf->Ehdr.e_shnum)
2083 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2084 "%s: Shdr #%d: sh_link (%d) is beyond the end of the section table (%d)!",
2085 pszLogName, iShdr, pShdr->sh_link, pModElf->Ehdr.e_shnum);
2086
2087 switch (pShdr->sh_type)
2088 {
2089 /** @todo find specs and check up which sh_info fields indicates section table entries */
2090 case 12301230:
2091 if (pShdr->sh_info >= pModElf->Ehdr.e_shnum)
2092 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2093 "%s: Shdr #%d: sh_info (%d) is beyond the end of the section table (%d)!",
2094 pszLogName, iShdr, pShdr->sh_link, pModElf->Ehdr.e_shnum);
2095 break;
2096
2097 case SHT_NULL:
2098 break;
2099 case SHT_PROGBITS:
2100 case SHT_SYMTAB:
2101 case SHT_STRTAB:
2102 case SHT_RELA:
2103 case SHT_HASH:
2104 case SHT_DYNAMIC:
2105 case SHT_NOTE:
2106 case SHT_NOBITS:
2107 case SHT_REL:
2108 case SHT_SHLIB:
2109 case SHT_DYNSYM:
2110 /*
2111 * For these types sh_info doesn't have any special meaning, or anything which
2112 * we need/can validate now.
2113 */
2114 break;
2115
2116
2117 default:
2118 Log(("RTLdrELF: %s: Warning, unknown type %d!\n", pszLogName, pShdr->sh_type));
2119 break;
2120 }
2121
2122 if ( pShdr->sh_type != SHT_NOBITS
2123 && pShdr->sh_size)
2124 {
2125 uint64_t offEnd = pShdr->sh_offset + pShdr->sh_size;
2126 if ( offEnd > cbRawImage
2127 || offEnd < (uint64_t)pShdr->sh_offset)
2128 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2129 "%s: Shdr #%d: sh_offset (" FMT_ELF_OFF ") + sh_size (" FMT_ELF_XWORD " = %RX64) is beyond the end of the file (%RX64)!",
2130 pszLogName, iShdr, pShdr->sh_offset, pShdr->sh_size, offEnd, cbRawImage);
2131 if (pShdr->sh_offset < sizeof(Elf_Ehdr))
2132 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2133 "%s: Shdr #%d: sh_offset (" FMT_ELF_OFF ") + sh_size (" FMT_ELF_XWORD ") is starting in the ELF header!",
2134 pszLogName, iShdr, pShdr->sh_offset, pShdr->sh_size);
2135 }
2136
2137 return VINF_SUCCESS;
2138}
2139
2140
2141/**
2142 * Process the section headers.
2143 *
2144 * @returns iprt status code.
2145 * @param pModElf Pointer to the module structure.
2146 * @param paShdrs The section headers.
2147 * @param cbRawImage The size of the raw image.
2148 * @param pszLogName The log name.
2149 * @param pErrInfo Where to return extended error info. Optional.
2150 */
2151static int RTLDRELF_NAME(ValidateAndProcessSectionHeaders)(PRTLDRMODELF pModElf, Elf_Shdr *paShdrs, uint64_t cbRawImage,
2152 const char *pszLogName, PRTERRINFO pErrInfo)
2153{
2154 Elf_Addr uNextAddr = 0;
2155 for (unsigned i = 0; i < pModElf->Ehdr.e_shnum; i++)
2156 {
2157 int rc = RTLDRELF_NAME(ValidateSectionHeader)(pModElf, i, cbRawImage, pszLogName, pErrInfo);
2158 if (RT_FAILURE(rc))
2159 return rc;
2160
2161 /*
2162 * We're looking for symbol tables.
2163 */
2164 if (paShdrs[i].sh_type == SHT_SYMTAB)
2165 {
2166 if (pModElf->Rel.iSymSh != ~0U)
2167 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDRELF_MULTIPLE_SYMTABS,
2168 "%s: Multiple symbol tabs! iSymSh=%d i=%d", pszLogName, pModElf->Rel.iSymSh, i);
2169 pModElf->Rel.iSymSh = i;
2170 pModElf->Rel.cSyms = (unsigned)(paShdrs[i].sh_size / sizeof(Elf_Sym));
2171 AssertBreakStmt(pModElf->Rel.cSyms == paShdrs[i].sh_size / sizeof(Elf_Sym), rc = VERR_IMAGE_TOO_BIG);
2172 pModElf->Rel.iStrSh = paShdrs[i].sh_link;
2173 pModElf->Rel.cbStr = (unsigned)paShdrs[pModElf->Rel.iStrSh].sh_size;
2174 AssertBreakStmt(pModElf->Rel.cbStr == paShdrs[pModElf->Rel.iStrSh].sh_size, rc = VERR_IMAGE_TOO_BIG);
2175 }
2176 else if (paShdrs[i].sh_type == SHT_DYNSYM)
2177 {
2178 if (pModElf->Dyn.iSymSh != ~0U)
2179 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDRELF_MULTIPLE_SYMTABS,
2180 "%s: Multiple dynamic symbol tabs! iSymSh=%d i=%d", pszLogName, pModElf->Dyn.iSymSh, i);
2181 if (pModElf->Ehdr.e_type != ET_DYN && pModElf->Ehdr.e_type != ET_EXEC)
2182 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2183 "%s: Unexpected SHT_DYNSYM (i=%d) for e_type=%d", pszLogName, i, pModElf->Ehdr.e_type);
2184 pModElf->Dyn.iSymSh = i;
2185 pModElf->Dyn.cSyms = (unsigned)(paShdrs[i].sh_size / sizeof(Elf_Sym));
2186 AssertBreakStmt(pModElf->Dyn.cSyms == paShdrs[i].sh_size / sizeof(Elf_Sym), rc = VERR_IMAGE_TOO_BIG);
2187 pModElf->Dyn.iStrSh = paShdrs[i].sh_link;
2188 pModElf->Dyn.cbStr = (unsigned)paShdrs[pModElf->Dyn.iStrSh].sh_size;
2189 AssertBreakStmt(pModElf->Dyn.cbStr == paShdrs[pModElf->Dyn.iStrSh].sh_size, rc = VERR_IMAGE_TOO_BIG);
2190 }
2191 /*
2192 * We're also look for the dynamic section.
2193 */
2194 else if (paShdrs[i].sh_type == SHT_DYNAMIC)
2195 {
2196 if (pModElf->iShDynamic != ~0U)
2197 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2198 "%s: Multiple dynamic sections! iShDynamic=%d i=%d",
2199 pszLogName, pModElf->iShDynamic, i);
2200 if (pModElf->Ehdr.e_type != ET_DYN && pModElf->Ehdr.e_type != ET_EXEC)
2201 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2202 "%s: Unexpected SHT_DYNAMIC (i=%d) for e_type=%d", pszLogName, i, pModElf->Ehdr.e_type);
2203 if (paShdrs[i].sh_entsize != sizeof(Elf_Dyn))
2204 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2205 "%s: SHT_DYNAMIC (i=%d) sh_entsize=" FMT_ELF_XWORD ", expected %#zx",
2206 pszLogName, i, paShdrs[i].sh_entsize, sizeof(Elf_Dyn));
2207 pModElf->iShDynamic = i;
2208 Elf_Xword const cDynamic = paShdrs[i].sh_size / sizeof(Elf_Dyn);
2209 if (cDynamic > _64K || cDynamic < 2)
2210 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2211 "%s: SHT_DYNAMIC (i=%d) sh_size=" FMT_ELF_XWORD " is out of range (2..64K)",
2212 pszLogName, i, paShdrs[i].sh_size);
2213 pModElf->cDynamic = (unsigned)cDynamic;
2214 }
2215
2216 /*
2217 * Special checks for the section string table.
2218 */
2219 if (i == pModElf->Ehdr.e_shstrndx)
2220 {
2221 if (paShdrs[i].sh_type != SHT_STRTAB)
2222 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2223 "%s: Section header string table is not a SHT_STRTAB: %#x",
2224 pszLogName, paShdrs[i].sh_type);
2225 if (paShdrs[i].sh_size == 0)
2226 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Section header string table is empty", pszLogName);
2227 }
2228
2229 /*
2230 * Kluge for the .data..percpu segment in 64-bit linux kernels.
2231 */
2232 if (paShdrs[i].sh_flags & SHF_ALLOC)
2233 {
2234 if ( paShdrs[i].sh_addr == 0
2235 && paShdrs[i].sh_addr < uNextAddr)
2236 {
2237 Elf_Addr uAddr = RT_ALIGN_T(uNextAddr, paShdrs[i].sh_addralign, Elf_Addr);
2238 Log(("RTLdrElf: Out of order section #%d; adjusting sh_addr from " FMT_ELF_ADDR " to " FMT_ELF_ADDR "\n",
2239 i, paShdrs[i].sh_addr, uAddr));
2240 paShdrs[i].sh_addr = uAddr;
2241 }
2242 uNextAddr = paShdrs[i].sh_addr + paShdrs[i].sh_size;
2243 }
2244 } /* for each section header */
2245
2246 return VINF_SUCCESS;
2247}
2248
2249
2250/**
2251 * Process the section headers.
2252 *
2253 * @returns iprt status code.
2254 * @param pModElf Pointer to the module structure.
2255 * @param paShdrs The section headers.
2256 * @param cbRawImage The size of the raw image.
2257 * @param pszLogName The log name.
2258 * @param pErrInfo Where to return extended error info. Optional.
2259 */
2260static int RTLDRELF_NAME(ValidateAndProcessDynamicInfo)(PRTLDRMODELF pModElf, uint64_t cbRawImage, uint32_t fFlags,
2261 const char *pszLogName, PRTERRINFO pErrInfo)
2262{
2263 /*
2264 * Check preconditions.
2265 */
2266 AssertReturn(pModElf->Ehdr.e_type == ET_DYN || pModElf->Ehdr.e_type == ET_EXEC, VERR_INTERNAL_ERROR_2);
2267 if (pModElf->Ehdr.e_phnum <= 1 || pModElf->Ehdr.e_phnum >= _32K)
2268 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2269 "%s: e_phnum=%u is out of bounds (2..32K)", pszLogName, pModElf->Ehdr.e_phnum);
2270 if (pModElf->iShDynamic == ~0U)
2271 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: no .dynamic section", pszLogName);
2272 AssertReturn(pModElf->cDynamic > 1 && pModElf->cDynamic <= _64K, VERR_INTERNAL_ERROR_3);
2273
2274 /* ASSUME that the sections are ordered by address. That simplifies
2275 validation code further down. */
2276 AssertReturn(pModElf->Ehdr.e_shnum >= 2, VERR_INTERNAL_ERROR_4);
2277 Elf_Shdr const *paShdrs = pModElf->paShdrs;
2278 Elf_Addr uPrevEnd = paShdrs[1].sh_addr + paShdrs[1].sh_size;
2279 for (unsigned i = 2; i < pModElf->Ehdr.e_shnum; i++)
2280 if (paShdrs[i].sh_flags & SHF_ALLOC)
2281 {
2282 if (uPrevEnd > paShdrs[i].sh_addr)
2283 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2284 "%s: section %u is out of order: uPrevEnd=" FMT_ELF_ADDR " sh_addr=" FMT_ELF_ADDR,
2285 pszLogName, i, uPrevEnd, paShdrs[i].sh_addr);
2286 uPrevEnd = paShdrs[i].sh_addr + paShdrs[i].sh_size;
2287 }
2288
2289 /* Must have string and symbol tables. */
2290 if (pModElf->Dyn.iStrSh == ~0U)
2291 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: No dynamic string table section", pszLogName);
2292 if (pModElf->Dyn.iSymSh == ~0U)
2293 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: No dynamic symbol table section", pszLogName);
2294
2295 /*
2296 * Load the program headers.
2297 */
2298 size_t const cbPhdrs = sizeof(pModElf->paPhdrs[0]) * pModElf->Ehdr.e_phnum;
2299 Elf_Phdr *paPhdrs = (Elf_Phdr *)RTMemAllocZ(cbPhdrs);
2300 pModElf->paPhdrs = paPhdrs;
2301 AssertReturn(paPhdrs, VERR_NO_MEMORY);
2302
2303 int rc = pModElf->Core.pReader->pfnRead(pModElf->Core.pReader, paPhdrs, cbPhdrs, pModElf->Ehdr.e_phoff);
2304 if (RT_FAILURE(rc))
2305 return RTERRINFO_LOG_SET_F(pErrInfo, rc, "%s: pfnRead(,,%#zx, " FMT_ELF_OFF ") -> %Rrc",
2306 pszLogName, cbPhdrs, pModElf->Ehdr.e_phoff, rc);
2307
2308 /*
2309 * Validate them.
2310 */
2311 unsigned cbPage = _4K; /** @todo generalize architecture specific stuff using its own code template header. */
2312 switch (pModElf->Core.enmArch)
2313 {
2314 case RTLDRARCH_AMD64:
2315 case RTLDRARCH_X86_32:
2316 break;
2317 default:
2318 AssertFailedBreak(/** @todo page size for got.plt hacks */);
2319 }
2320 unsigned iLoad = 0;
2321 unsigned iLoadShdr = 1; /* ASSUMES ordered (checked above). */
2322 unsigned cDynamic = 0;
2323 Elf_Addr cbImage = 0;
2324 Elf_Addr uLinkAddress = ~(Elf_Addr)0;
2325 for (unsigned i = 0; i < pModElf->Ehdr.e_phnum; i++)
2326 {
2327 const Elf_Phdr * const pPhdr = &paPhdrs[i];
2328 Log3(("RTLdrELF: Program Header #%d:\n"
2329 "RTLdrELF: p_type: " FMT_ELF_WORD " (%s)\n"
2330 "RTLdrELF: p_flags: " FMT_ELF_WORD "\n"
2331 "RTLdrELF: p_offset: " FMT_ELF_OFF "\n"
2332 "RTLdrELF: p_vaddr: " FMT_ELF_ADDR "\n"
2333 "RTLdrELF: p_paddr: " FMT_ELF_ADDR "\n"
2334 "RTLdrELF: p_filesz: " FMT_ELF_XWORD "\n"
2335 "RTLdrELF: p_memsz: " FMT_ELF_XWORD "\n"
2336 "RTLdrELF: p_align: " FMT_ELF_XWORD "\n",
2337 i,
2338 pPhdr->p_type, rtldrElfGetPhdrType(pPhdr->p_type), pPhdr->p_flags, pPhdr->p_offset,
2339 pPhdr->p_vaddr, pPhdr->p_paddr, pPhdr->p_filesz, pPhdr->p_memsz, pPhdr->p_align));
2340
2341 if (pPhdr->p_type == DT_NULL)
2342 continue;
2343
2344 if ( pPhdr->p_filesz != 0
2345 && ( pPhdr->p_offset >= cbRawImage
2346 || pPhdr->p_filesz > cbRawImage
2347 || pPhdr->p_offset + pPhdr->p_filesz > cbRawImage))
2348 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2349 "%s: Prog Hdr #%u: bogus p_offset=" FMT_ELF_OFF " & p_filesz=" FMT_ELF_XWORD " (file size %#RX64)",
2350 pszLogName, i, pPhdr->p_offset, pPhdr->p_filesz, cbRawImage);
2351
2352 if (pPhdr->p_flags & ~(Elf64_Word)(PF_X | PF_R | PF_W))
2353 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Prog Hdr #%u: bogus p_flags=" FMT_ELF_WORD,
2354 pszLogName, i, pPhdr->p_flags);
2355
2356 if (!RT_IS_POWER_OF_TWO(pPhdr->p_align))
2357 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Prog Hdr #%u: bogus p_align=" FMT_ELF_XWORD,
2358 pszLogName, i, pPhdr->p_align);
2359
2360 if ( pPhdr->p_align > 1
2361 && pPhdr->p_memsz > 0
2362 && pPhdr->p_filesz > 0
2363 && (pPhdr->p_offset & (pPhdr->p_align - 1)) != (pPhdr->p_vaddr & (pPhdr->p_align - 1)))
2364 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2365 "%s: Prog Hdr #%u: misaligned p_offset=" FMT_ELF_OFF " p_vaddr=" FMT_ELF_ADDR " p_align=" FMT_ELF_XWORD,
2366 pszLogName, i, pPhdr->p_offset, pPhdr->p_vaddr, pPhdr->p_align);
2367
2368 /* Do some type specfic checks: */
2369 switch (pPhdr->p_type)
2370 {
2371 case PT_LOAD:
2372 {
2373 if (pPhdr->p_memsz < pPhdr->p_filesz)
2374 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2375 "%s: Prog Hdr #%u/LOAD#%u: bogus p_memsz=" FMT_ELF_XWORD " or p_filesz=" FMT_ELF_XWORD,
2376 pszLogName, i, iLoad, pPhdr->p_memsz, pPhdr->p_filesz);
2377 cbImage = pPhdr->p_vaddr + pPhdr->p_memsz;
2378 if (iLoad == 0)
2379 uLinkAddress = pPhdr->p_vaddr;
2380
2381 /* Find the corresponding sections, checking their addresses and
2382 file offsets since the rest of the code is still section based
2383 rather than using program headers as it should... */
2384 Elf_Off off = pPhdr->p_offset;
2385 Elf_Addr uAddr = pPhdr->p_vaddr;
2386 Elf_Xword cbMem = pPhdr->p_memsz;
2387 Elf_Xword cbFile = pPhdr->p_filesz;
2388
2389 /* HACK to allow loading isolinux-debug.elf where program headers aren't
2390 sorted by virtual address. */
2391 if ( (fFlags & RTLDR_O_FOR_DEBUG)
2392 && uAddr != paShdrs[iLoadShdr].sh_addr)
2393 {
2394 for (unsigned iShdr = 1; iShdr < pModElf->Ehdr.e_shnum; iShdr++)
2395 if (uAddr == paShdrs[iShdr].sh_addr)
2396 {
2397 iLoadShdr = iShdr;
2398 break;
2399 }
2400 }
2401
2402 while (cbMem > 0)
2403 {
2404 if (iLoadShdr < pModElf->Ehdr.e_shnum)
2405 { /* likely */ }
2406 else if (iLoadShdr == pModElf->Ehdr.e_shnum)
2407 {
2408 /** @todo anything else to check here? */
2409 iLoadShdr++;
2410 break;
2411 }
2412 else
2413 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2414 "%s: Prog Hdr #%u/LOAD#%u: Out of sections at " FMT_ELF_ADDR " LB " FMT_ELF_XWORD,
2415 pszLogName, i, iLoad, uAddr, cbMem);
2416 if (!(paShdrs[iLoadShdr].sh_flags & SHF_ALLOC))
2417 {
2418 if ( paShdrs[iLoadShdr].sh_type != SHT_NOBITS
2419 && paShdrs[iLoadShdr].sh_size > 0
2420 && off < paShdrs[iLoadShdr].sh_offset + paShdrs[iLoadShdr].sh_size
2421 && paShdrs[iLoadShdr].sh_offset < off + cbMem)
2422 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2423 "%s: Prog Hdr #%u/LOAD#%u: Overlaps with !SHF_ALLOC section at " FMT_ELF_OFF " LB " FMT_ELF_XWORD,
2424 pszLogName, i, iLoad, paShdrs[iLoadShdr].sh_offset, paShdrs[iLoadShdr].sh_size);
2425 pModElf->paShdrExtras[iLoadShdr].idxPhdr = UINT16_MAX;
2426 iLoadShdr++;
2427 continue;
2428 }
2429
2430 if (uAddr != paShdrs[iLoadShdr].sh_addr)
2431 {
2432 /* Before the first section we expect headers to be loaded, so
2433 that the file is simply mapped from file offset zero. */
2434 if ( iLoadShdr == 1
2435 && iLoad == 0
2436 && paShdrs[1].sh_addr == paShdrs[1].sh_offset
2437 && cbFile >= paShdrs[1].sh_offset
2438 && cbMem >= paShdrs[1].sh_offset)
2439 {
2440 /* Modify paShdrs[0] to describe the gap. ".elf.headers" */
2441 pModElf->iFirstSect = 0;
2442 pModElf->paShdrs[0].sh_name = 0;
2443 pModElf->paShdrs[0].sh_type = SHT_PROGBITS;
2444 pModElf->paShdrs[0].sh_flags = SHF_ALLOC
2445 | (pPhdr->p_flags & PF_W ? SHF_WRITE : 0)
2446 | (pPhdr->p_flags & PF_X ? SHF_EXECINSTR : 0);
2447 pModElf->paShdrs[0].sh_addr = uAddr;
2448 pModElf->paShdrs[0].sh_offset = off;
2449 pModElf->paShdrs[0].sh_size = paShdrs[1].sh_offset;
2450 pModElf->paShdrs[0].sh_link = 0;
2451 pModElf->paShdrs[0].sh_info = 0;
2452 pModElf->paShdrs[0].sh_addralign = pPhdr->p_align;
2453 pModElf->paShdrs[0].sh_entsize = 0;
2454 *(Elf_Shdr *)pModElf->paOrgShdrs = pModElf->paShdrs[0]; /* (necessary for segment enumeration) */
2455
2456 uAddr += paShdrs[1].sh_offset;
2457 cbMem -= paShdrs[1].sh_offset;
2458 cbFile -= paShdrs[1].sh_offset;
2459 off = paShdrs[1].sh_offset;
2460 }
2461 /* Alignment padding? Allow up to a page size. */
2462 else if ( paShdrs[iLoadShdr].sh_addr > uAddr
2463 && paShdrs[iLoadShdr].sh_addr - uAddr
2464 < RT_MAX(paShdrs[iLoadShdr].sh_addralign, cbPage /*got.plt hack*/))
2465 {
2466 Elf_Xword cbAlignPadding = paShdrs[iLoadShdr].sh_addr - uAddr;
2467 if (cbAlignPadding >= cbMem)
2468 break;
2469 cbMem -= cbAlignPadding;
2470 uAddr += cbAlignPadding;
2471 if (cbFile > cbAlignPadding)
2472 {
2473 off += cbAlignPadding;
2474 cbFile -= cbAlignPadding;
2475 }
2476 else
2477 {
2478 off += cbFile;
2479 cbFile = 0;
2480 }
2481 }
2482 }
2483
2484 if ( uAddr == paShdrs[iLoadShdr].sh_addr
2485 && cbMem >= paShdrs[iLoadShdr].sh_size
2486 && ( paShdrs[iLoadShdr].sh_type != SHT_NOBITS
2487 ? off == paShdrs[iLoadShdr].sh_offset
2488 && cbFile >= paShdrs[iLoadShdr].sh_size /* this might be too strict... */
2489 : cbFile == 0
2490 || cbMem > paShdrs[iLoadShdr].sh_size /* isolinux.elf: linker merge no-bits and progbits sections */) )
2491 {
2492 if ( paShdrs[iLoadShdr].sh_type != SHT_NOBITS
2493 || cbFile != 0)
2494 {
2495 off += paShdrs[iLoadShdr].sh_size;
2496 cbFile -= paShdrs[iLoadShdr].sh_size;
2497 }
2498 uAddr += paShdrs[iLoadShdr].sh_size;
2499 cbMem -= paShdrs[iLoadShdr].sh_size;
2500 }
2501 else
2502 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2503 "%s: Prog Hdr #%u/LOAD#%u: Mismatch at " FMT_ELF_ADDR " LB " FMT_ELF_XWORD " (file " FMT_ELF_OFF " LB " FMT_ELF_XWORD ") with section #%u " FMT_ELF_ADDR " LB " FMT_ELF_XWORD " (file " FMT_ELF_OFF " sh_type=" FMT_ELF_WORD ")",
2504 pszLogName, i, iLoad, uAddr, cbMem, off, cbFile,
2505 iLoadShdr, paShdrs[iLoadShdr].sh_addr, paShdrs[iLoadShdr].sh_size,
2506 paShdrs[iLoadShdr].sh_offset, paShdrs[iLoadShdr].sh_type);
2507
2508 pModElf->paShdrExtras[iLoadShdr].idxPhdr = iLoad;
2509 iLoadShdr++;
2510 } /* section loop */
2511
2512 iLoad++;
2513 break;
2514 }
2515
2516 case PT_DYNAMIC:
2517 {
2518 const Elf_Shdr *pShdr = &pModElf->paShdrs[pModElf->iShDynamic];
2519 if (pPhdr->p_offset != pShdr->sh_offset)
2520 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2521 "%s: Prog Hdr #%u/DYNAMIC: p_offset=" FMT_ELF_OFF " expected " FMT_ELF_OFF,
2522 pszLogName, i, pPhdr->p_offset, pShdr->sh_offset);
2523 if (RT_MAX(pPhdr->p_memsz, pPhdr->p_filesz) != pShdr->sh_size)
2524 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2525 "%s: Prog Hdr #%u/DYNAMIC: expected " FMT_ELF_XWORD " for RT_MAX(p_memsz=" FMT_ELF_XWORD ", p_filesz=" FMT_ELF_XWORD ")",
2526 pszLogName, i, pShdr->sh_size, pPhdr->p_memsz, pPhdr->p_filesz);
2527 cDynamic++;
2528 break;
2529 }
2530 }
2531 }
2532
2533 if (iLoad == 0)
2534 return RTERRINFO_LOG_SET_F(pErrInfo, rc, "%s: No PT_LOAD program headers", pszLogName);
2535 if (cDynamic != 1)
2536 return RTERRINFO_LOG_SET_F(pErrInfo, rc, "%s: No program header for the DYNAMIC section", pszLogName);
2537
2538 cbImage -= uLinkAddress;
2539 pModElf->cbImage = (uint64_t)cbImage;
2540 pModElf->LinkAddress = uLinkAddress;
2541 AssertReturn(pModElf->cbImage == cbImage, VERR_INTERNAL_ERROR_5);
2542 Log3(("RTLdrELF: LinkAddress=" FMT_ELF_ADDR " cbImage=" FMT_ELF_ADDR " (from PT_LOAD)\n", uLinkAddress, cbImage));
2543
2544 for (; iLoadShdr < pModElf->Ehdr.e_shnum; iLoadShdr++)
2545 if ( !(paShdrs[iLoadShdr].sh_flags & SHF_ALLOC)
2546 || paShdrs[iLoadShdr].sh_size == 0)
2547 pModElf->paShdrExtras[iLoadShdr].idxPhdr = UINT16_MAX;
2548 else
2549 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2550 "%s: No PT_LOAD for section #%u " FMT_ELF_ADDR " LB " FMT_ELF_XWORD " (file " FMT_ELF_OFF " sh_type=" FMT_ELF_WORD ")",
2551 pszLogName, iLoadShdr, paShdrs[iLoadShdr].sh_addr, paShdrs[iLoadShdr].sh_size,
2552 paShdrs[iLoadShdr].sh_offset, paShdrs[iLoadShdr].sh_type);
2553
2554 /*
2555 * Load and validate the dynamic table. We have got / will get most of the
2556 * info we need from the section table, so we must make sure this matches up.
2557 */
2558 Log3(("RTLdrELF: Dynamic section - %u entries\n", pModElf->cDynamic));
2559 size_t const cbDynamic = pModElf->cDynamic * sizeof(pModElf->paDynamic[0]);
2560 Elf_Dyn * const paDynamic = (Elf_Dyn *)RTMemAlloc(cbDynamic);
2561 AssertReturn(paDynamic, VERR_NO_MEMORY);
2562 pModElf->paDynamic = paDynamic;
2563
2564 rc = pModElf->Core.pReader->pfnRead(pModElf->Core.pReader, paDynamic, cbDynamic, paShdrs[pModElf->iShDynamic].sh_offset);
2565 if (RT_FAILURE(rc))
2566 return RTERRINFO_LOG_SET_F(pErrInfo, rc, "%s: pfnRead(,,%#zx, " FMT_ELF_OFF ") -> %Rrc",
2567 pszLogName, cbDynamic, paShdrs[pModElf->iShDynamic].sh_offset, rc);
2568
2569 for (uint32_t i = 0; i < pModElf->cDynamic; i++)
2570 {
2571#define LOG_VALIDATE_PTR_RET(szName) do { \
2572 Log3(("RTLdrELF: DT[%u]: %16s " FMT_ELF_ADDR "\n", i, szName, paDynamic[i].d_un.d_ptr)); \
2573 if ((uint64_t)paDynamic[i].d_un.d_ptr - uLinkAddress < cbImage) { /* likely */ } \
2574 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" szName ": Invalid address " FMT_ELF_ADDR " (valid range: " FMT_ELF_ADDR " LB " FMT_ELF_ADDR ")", \
2575 pszLogName, i, paDynamic[i].d_un.d_ptr, uLinkAddress, cbImage); \
2576 } while (0)
2577#define LOG_VALIDATE_PTR_VAL_RET(szName, uExpected) do { \
2578 Log3(("RTLdrELF: DT[%u]: %16s " FMT_ELF_ADDR "\n", i, szName, (uint64_t)paDynamic[i].d_un.d_ptr)); \
2579 if (paDynamic[i].d_un.d_ptr == (Elf_Addr)(uExpected)) { /* likely */ } \
2580 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" szName ": " FMT_ELF_ADDR ", expected " FMT_ELF_ADDR, \
2581 pszLogName, i, paDynamic[i].d_un.d_ptr, (Elf_Addr)(uExpected)); \
2582 } while (0)
2583#define LOG_VALIDATE_STR_RET(szName) do { \
2584 Log3(("RTLdrELF: DT[%u]: %16s %#RX64\n", i, szName, (uint64_t)paDynamic[i].d_un.d_val)); \
2585 if ((uint64_t)paDynamic[i].d_un.d_val < pModElf->Dyn.cbStr) { /* likely */ } \
2586 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" szName ": Invalid string table offset %#RX64 (max %#x)", \
2587 pszLogName, i, (uint64_t)paDynamic[i].d_un.d_val, pModElf->Dyn.cbStr); \
2588 } while (0)
2589#define LOG_VALIDATE_VAL_RET(szName, uExpected) do { \
2590 Log3(("RTLdrELF: DT[%u]: %16s %#RX64\n", i, szName, (uint64_t)paDynamic[i].d_un.d_val)); \
2591 if ((uint64_t)paDynamic[i].d_un.d_val == (uint64_t)(uExpected)) { /* likely */ } \
2592 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" szName ": %#RX64, expected %#RX64", \
2593 pszLogName, i, (uint64_t)paDynamic[i].d_un.d_val, (uint64_t)(uExpected)); \
2594 } while (0)
2595#define SET_RELOC_TYPE_RET(a_szName, a_uType) do { \
2596 if (pModElf->DynInfo.uRelocType == 0 || pModElf->DynInfo.uRelocType == (a_uType)) \
2597 pModElf->DynInfo.uRelocType = (a_uType); \
2598 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" a_szName ": Mixing DT_RELA and DT_REL", pszLogName, i); \
2599 } while (0)
2600#define SET_INFO_FIELD_RET(a_szName, a_Field, a_Value, a_UnsetValue, a_szFmt) do { \
2601 if ((a_Field) == (a_UnsetValue) && (a_Value) != (a_UnsetValue)) \
2602 (a_Field) = (a_Value); /* likely */ \
2603 else if ((a_Field) != (a_UnsetValue)) \
2604 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" a_szName ": Multiple entries (first value " a_szFmt ", second " a_szFmt ")", pszLogName, i, (a_Field), (a_Value)); \
2605 else if ((a_Value) != (a_UnsetValue)) \
2606 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" a_szName ": Unexpected value " a_szFmt, pszLogName, i, (a_Value)); \
2607 } while (0)
2608#define FIND_MATCHING_SECTION_RET(a_szName, a_ExtraMatchExpr, a_idxShFieldToSet) do { \
2609 unsigned iSh; \
2610 for (iSh = 1; iSh < pModElf->Ehdr.e_shnum; iSh++) \
2611 if ( paShdrs[iSh].sh_addr == paDynamic[i].d_un.d_ptr \
2612 && (a_ExtraMatchExpr)) \
2613 { \
2614 (a_idxShFieldToSet) = iSh; \
2615 if (pModElf->paShdrExtras[iSh].idxDt != UINT16_MAX) \
2616 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, \
2617 "%s: DT[%u]/" a_szName ": section #%u (" FMT_ELF_ADDR ") already referenced by DT[%u]", \
2618 pszLogName, i, iSh, paShdrs[iSh].sh_addr, pModElf->paShdrExtras[iSh].idxDt); \
2619 pModElf->paShdrExtras[iSh].idxDt = i; \
2620 pModElf->paShdrExtras[iSh].uDtTag = (uint32_t)paDynamic[i].d_tag; \
2621 break; \
2622 } \
2623 if (iSh < pModElf->Ehdr.e_shnum) { /* likely */ } \
2624 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" a_szName ": No matching section for " FMT_ELF_ADDR, pszLogName, i, paDynamic[i].d_un.d_ptr); \
2625 } while (0)
2626#define ONLY_FOR_DEBUG_OR_VALIDATION_RET(a_szName) do { \
2627 if (fFlags & (RTLDR_O_FOR_DEBUG | RTLDR_O_FOR_VALIDATION)) { /* likely */ } \
2628 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" a_szName ": Not supported (" FMT_ELF_ADDR ")", pszLogName, i, paDynamic[i].d_un.d_ptr); \
2629 } while (0)
2630#define LOG_NON_VALUE_ENTRY(a_szName) Log3(("RTLdrELF: DT[%u]: %16s (%#RX64)\n", i, a_szName, (uint64_t)paDynamic[i].d_un.d_val))
2631
2632 switch (paDynamic[i].d_tag)
2633 {
2634 case DT_NULL:
2635 LOG_NON_VALUE_ENTRY("DT_NULL");
2636 for (unsigned iNull = i + 1; iNull < pModElf->cDynamic; iNull++)
2637 if (paDynamic[i].d_tag == DT_NULL) /* Not technically a bug, but let's try being extremely strict for now */
2638 LOG_NON_VALUE_ENTRY("DT_NULL");
2639 else if (!(fFlags & (RTLDR_O_FOR_DEBUG | RTLDR_O_FOR_VALIDATION)))
2640 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2641 "%s: DT[%u]/DT_NULL: Dynamic section isn't zero padded (extra #%u of #%u)",
2642 pszLogName, i, iNull - i, pModElf->cDynamic - i);
2643 i = pModElf->cDynamic;
2644 break;
2645 case DT_NEEDED:
2646 LOG_VALIDATE_STR_RET("DT_NEEDED");
2647 break;
2648 case DT_PLTRELSZ:
2649 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_PLTRELSZ", (uint64_t)paDynamic[i].d_un.d_val));
2650 SET_INFO_FIELD_RET("DT_PLTRELSZ", pModElf->DynInfo.cbJmpRelocs, (Elf_Xword)paDynamic[i].d_un.d_val, 0, FMT_ELF_XWORD);
2651 break;
2652 case DT_PLTGOT:
2653 LOG_VALIDATE_PTR_RET("DT_PLTGOT");
2654 break;
2655 case DT_HASH:
2656 LOG_VALIDATE_PTR_RET("DT_HASH");
2657 break;
2658 case DT_STRTAB:
2659 LOG_VALIDATE_PTR_VAL_RET("DT_STRTAB", paShdrs[pModElf->Dyn.iStrSh].sh_addr);
2660 pModElf->paShdrExtras[pModElf->Dyn.iStrSh].idxDt = i;
2661 pModElf->paShdrExtras[pModElf->Dyn.iSymSh].uDtTag = DT_STRTAB;
2662 break;
2663 case DT_SYMTAB:
2664 LOG_VALIDATE_PTR_VAL_RET("DT_SYMTAB", paShdrs[pModElf->Dyn.iSymSh].sh_addr);
2665 pModElf->paShdrExtras[pModElf->Dyn.iSymSh].idxDt = i;
2666 pModElf->paShdrExtras[pModElf->Dyn.iSymSh].uDtTag = DT_SYMTAB;
2667 break;
2668 case DT_RELA:
2669 LOG_VALIDATE_PTR_RET("DT_RELA");
2670 SET_RELOC_TYPE_RET("DT_RELA", DT_RELA);
2671 SET_INFO_FIELD_RET("DT_RELA", pModElf->DynInfo.uPtrRelocs, paDynamic[i].d_un.d_ptr, ~(Elf_Addr)0, FMT_ELF_ADDR);
2672 FIND_MATCHING_SECTION_RET("DT_RELA", paShdrs[iSh].sh_type == SHT_RELA, pModElf->DynInfo.idxShRelocs);
2673 break;
2674 case DT_RELASZ:
2675 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_RELASZ", (uint64_t)paDynamic[i].d_un.d_val));
2676 SET_RELOC_TYPE_RET("DT_RELASZ", DT_RELA);
2677 SET_INFO_FIELD_RET("DT_RELASZ", pModElf->DynInfo.cbRelocs, (Elf_Xword)paDynamic[i].d_un.d_val, 0, FMT_ELF_XWORD);
2678 break;
2679 case DT_RELAENT:
2680 LOG_VALIDATE_VAL_RET("DT_RELAENT", sizeof(Elf_Rela));
2681 SET_RELOC_TYPE_RET("DT_RELAENT", DT_RELA);
2682 SET_INFO_FIELD_RET("DT_RELAENT", pModElf->DynInfo.cbRelocEntry, (unsigned)sizeof(Elf_Rela), 0, "%u");
2683 break;
2684 case DT_STRSZ:
2685 LOG_VALIDATE_VAL_RET("DT_STRSZ", pModElf->Dyn.cbStr);
2686 break;
2687 case DT_SYMENT:
2688 LOG_VALIDATE_VAL_RET("DT_SYMENT", sizeof(Elf_Sym));
2689 break;
2690 case DT_INIT:
2691 LOG_VALIDATE_PTR_RET("DT_INIT");
2692 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_INIT");
2693 break;
2694 case DT_FINI:
2695 LOG_VALIDATE_PTR_RET("DT_FINI");
2696 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_FINI");
2697 break;
2698 case DT_SONAME:
2699 LOG_VALIDATE_STR_RET("DT_SONAME");
2700 break;
2701 case DT_RPATH:
2702 LOG_VALIDATE_STR_RET("DT_RPATH");
2703 break;
2704 case DT_SYMBOLIC:
2705 LOG_NON_VALUE_ENTRY("DT_SYMBOLIC");
2706 break;
2707 case DT_REL:
2708 LOG_VALIDATE_PTR_RET("DT_REL");
2709 SET_RELOC_TYPE_RET("DT_REL", DT_REL);
2710 SET_INFO_FIELD_RET("DT_REL", pModElf->DynInfo.uPtrRelocs, paDynamic[i].d_un.d_ptr, ~(Elf_Addr)0, FMT_ELF_ADDR);
2711 FIND_MATCHING_SECTION_RET("DT_REL", paShdrs[iSh].sh_type == SHT_REL, pModElf->DynInfo.idxShRelocs);
2712 break;
2713 case DT_RELSZ:
2714 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_RELSZ", (uint64_t)paDynamic[i].d_un.d_val));
2715 SET_RELOC_TYPE_RET("DT_RELSZ", DT_REL);
2716 SET_INFO_FIELD_RET("DT_RELSZ", pModElf->DynInfo.cbRelocs, (Elf_Xword)paDynamic[i].d_un.d_val, 0, FMT_ELF_XWORD);
2717 break;
2718 case DT_RELENT:
2719 LOG_VALIDATE_VAL_RET("DT_RELENT", sizeof(Elf_Rel));
2720 SET_RELOC_TYPE_RET("DT_RELENT", DT_REL);
2721 SET_INFO_FIELD_RET("DT_RELENT", pModElf->DynInfo.cbRelocEntry, (unsigned)sizeof(Elf_Rel), 0, "%u");
2722 break;
2723 case DT_PLTREL:
2724 if (paDynamic[i].d_un.d_val != DT_RELA && paDynamic[i].d_un.d_val != DT_REL)
2725 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/DT_PLTREL: Invalid value %#RX64",
2726 pszLogName, i, (uint64_t)paDynamic[i].d_un.d_val);
2727 Log3(("RTLdrELF: DT[%u]: %16s DT_REL%s\n", i, "DT_PLTREL", paDynamic[i].d_un.d_val == DT_RELA ? "A" : ""));
2728 SET_INFO_FIELD_RET("DT_PLTREL", pModElf->DynInfo.uJmpRelocType, (unsigned)paDynamic[i].d_un.d_val, 0, "%u");
2729 break;
2730 case DT_DEBUG:
2731 LOG_VALIDATE_PTR_RET("DT_DEBUG");
2732 break;
2733 case DT_TEXTREL:
2734 LOG_NON_VALUE_ENTRY("DT_TEXTREL");
2735 break;
2736 case DT_JMPREL:
2737 LOG_VALIDATE_PTR_RET("DT_JMPREL");
2738 SET_INFO_FIELD_RET("DT_JMPREL", pModElf->DynInfo.uPtrJmpRelocs, paDynamic[i].d_un.d_ptr, ~(Elf_Addr)0, FMT_ELF_ADDR);
2739 FIND_MATCHING_SECTION_RET("DT_JMPREL", 1, pModElf->DynInfo.idxShJmpRelocs);
2740 break;
2741 case DT_BIND_NOW:
2742 LOG_NON_VALUE_ENTRY("DT_BIND_NOW");
2743 break;
2744 case DT_INIT_ARRAY:
2745 LOG_VALIDATE_PTR_RET("DT_INIT_ARRAY");
2746 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_INIT_ARRAY");
2747 break;
2748 case DT_FINI_ARRAY:
2749 LOG_VALIDATE_PTR_RET("DT_FINI_ARRAY");
2750 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_FINI_ARRAY");
2751 break;
2752 case DT_INIT_ARRAYSZ:
2753 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_INIT_ARRAYSZ", (uint64_t)paDynamic[i].d_un.d_val));
2754 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_INIT_ARRAYSZ");
2755 break;
2756 case DT_FINI_ARRAYSZ:
2757 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_FINI_ARRAYSZ", (uint64_t)paDynamic[i].d_un.d_val));
2758 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_FINI_ARRAYSZ");
2759 break;
2760 case DT_RUNPATH:
2761 LOG_VALIDATE_STR_RET("DT_RUNPATH");
2762 break;
2763 case DT_FLAGS:
2764 Log3(("RTLdrELF: DT[%u]: %16s %#RX64\n", i, "DT_FLAGS", (uint64_t)paDynamic[i].d_un.d_val));
2765 break;
2766 case DT_PREINIT_ARRAY:
2767 LOG_VALIDATE_PTR_RET("DT_PREINIT_ARRAY");
2768 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_PREINIT_ARRAY");
2769 break;
2770 case DT_PREINIT_ARRAYSZ:
2771 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_PREINIT_ARRAYSZ", (uint64_t)paDynamic[i].d_un.d_val));
2772 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_PREINIT_ARRAYSZ");
2773 break;
2774 default:
2775 if ( paDynamic[i].d_tag < DT_ENCODING
2776 || paDynamic[i].d_tag >= DT_LOOS
2777 || (paDynamic[i].d_tag & 1))
2778 Log3(("RTLdrELF: DT[%u]: %#010RX64 %#RX64%s\n", i, (uint64_t)paDynamic[i].d_tag,
2779 (uint64_t)paDynamic[i].d_un.d_val, paDynamic[i].d_un.d_val >= DT_ENCODING ? " (val)" : ""));
2780 else
2781 {
2782 Log3(("RTLdrELF: DT[%u]: %#010RX64 " FMT_ELF_ADDR " (addr)\n",
2783 i, (uint64_t)paDynamic[i].d_tag, paDynamic[i].d_un.d_ptr));
2784 if ((uint64_t)paDynamic[i].d_un.d_ptr - uLinkAddress >= cbImage)
2785 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2786 "%s: DT[%u]/%#RX64: Invalid address " FMT_ELF_ADDR " (valid range: " FMT_ELF_ADDR " LB " FMT_ELF_ADDR ")",
2787 pszLogName, i, (uint64_t)paDynamic[i].d_tag,
2788 paDynamic[i].d_un.d_ptr, uLinkAddress, cbImage);
2789 }
2790 break;
2791 }
2792#undef LOG_VALIDATE_VAL_RET
2793#undef LOG_VALIDATE_STR_RET
2794#undef LOG_VALIDATE_PTR_VAL_RET
2795#undef LOG_VALIDATE_PTR_RET
2796#undef SET_RELOC_TYPE_RET
2797#undef SET_INFO_FIELD_RET
2798#undef FIND_MATCHING_SECTION_RET
2799#undef ONLY_FOR_DEBUG_OR_VALIDATION_RET
2800 }
2801
2802 /*
2803 * Validate the relocation information we've gathered.
2804 */
2805 Elf_Word uShTypeArch = SHT_RELA; /** @todo generalize architecture specific stuff using its own code template header. */
2806 switch (pModElf->Core.enmArch)
2807 {
2808 case RTLDRARCH_AMD64:
2809 break;
2810 case RTLDRARCH_X86_32:
2811 uShTypeArch = SHT_REL;
2812 break;
2813 default:
2814 AssertFailedBreak(/** @todo page size for got.plt hacks */);
2815
2816 }
2817
2818 if (pModElf->DynInfo.uRelocType != 0)
2819 {
2820 const char * const pszModifier = pModElf->DynInfo.uRelocType == DT_RELA ? "A" : "";
2821 if (pModElf->DynInfo.uPtrRelocs == ~(Elf_Addr)0)
2822 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_REL%s", pszLogName, pszModifier);
2823 if (pModElf->DynInfo.cbRelocs == 0)
2824 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_REL%sSZ", pszLogName, pszModifier);
2825 if (pModElf->DynInfo.cbRelocEntry == 0)
2826 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_REL%sENT", pszLogName, pszModifier);
2827 Elf_Shdr const *pShdrRelocs = &paShdrs[pModElf->DynInfo.idxShRelocs];
2828 Elf_Word const uShType = pModElf->DynInfo.uJmpRelocType == DT_RELA ? SHT_RELA : SHT_REL;
2829 if (pShdrRelocs->sh_type != uShType)
2830 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_REL%s* does not match section type: %u vs %u",
2831 pszLogName, pszModifier, pShdrRelocs->sh_type, uShType);
2832 if (pShdrRelocs->sh_size != pModElf->DynInfo.cbRelocs)
2833 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_REL%sSZ does not match section size: %u vs %u",
2834 pszLogName, pszModifier, pShdrRelocs->sh_size, pModElf->DynInfo.cbRelocs);
2835 if (uShType != uShTypeArch)
2836 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_REL%s* does not match architecture: %u, arch wants %u",
2837 pszLogName, pszModifier, uShType, uShTypeArch);
2838 }
2839
2840 if ( pModElf->DynInfo.uPtrJmpRelocs != ~(Elf_Addr)0
2841 || pModElf->DynInfo.cbJmpRelocs != 0
2842 || pModElf->DynInfo.uJmpRelocType != 0)
2843 {
2844 if (pModElf->DynInfo.uPtrJmpRelocs == ~(Elf_Addr)0)
2845 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_JMPREL", pszLogName);
2846 if (pModElf->DynInfo.cbJmpRelocs == 0)
2847 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_PLTRELSZ", pszLogName);
2848 if (pModElf->DynInfo.uJmpRelocType == 0)
2849 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_PLTREL", pszLogName);
2850 Elf_Shdr const *pShdrRelocs = &paShdrs[pModElf->DynInfo.idxShJmpRelocs];
2851 Elf_Word const uShType = pModElf->DynInfo.uJmpRelocType == DT_RELA ? SHT_RELA : SHT_REL;
2852 if (pShdrRelocs->sh_type != uShType)
2853 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_PLTREL does not match section type: %u vs %u",
2854 pszLogName, pShdrRelocs->sh_type, uShType);
2855 if (pShdrRelocs->sh_size != pModElf->DynInfo.cbJmpRelocs)
2856 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_PLTRELSZ does not match section size: %u vs %u",
2857 pszLogName, pShdrRelocs->sh_size, pModElf->DynInfo.cbJmpRelocs);
2858 if (uShType != uShTypeArch)
2859 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_PLTREL does not match architecture: %u, arch wants %u",
2860 pszLogName, uShType, uShTypeArch);
2861 }
2862
2863 /*
2864 * Check that there aren't any other relocations hiding in the section table.
2865 */
2866 for (uint32_t i = 1; i < pModElf->Ehdr.e_shnum; i++)
2867 if ( (paShdrs[i].sh_type == SHT_REL || paShdrs[i].sh_type == SHT_RELA)
2868 && pModElf->paShdrExtras[i].uDtTag != DT_REL
2869 && pModElf->paShdrExtras[i].uDtTag != DT_RELA
2870 && pModElf->paShdrExtras[i].uDtTag != DT_JMPREL)
2871 {
2872 char szSecHdrNm[80];
2873 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2874 "%s: section header #%u (%s type=" FMT_ELF_WORD " size=" FMT_ELF_XWORD ") contains relocations not referenced by the dynamic section",
2875 pszLogName, i,
2876 RTLDRELF_NAME(GetSHdrName)(pModElf, paShdrs[i].sh_name, szSecHdrNm, sizeof(szSecHdrNm)),
2877 paShdrs[i].sh_type, paShdrs[i].sh_size);
2878 }
2879
2880 return VINF_SUCCESS;
2881}
2882
2883
2884
2885/**
2886 * Opens an ELF image, fixed bitness.
2887 *
2888 * @returns iprt status code.
2889 * @param pReader The loader reader instance which will provide the raw image bits.
2890 * @param fFlags Reserved, MBZ.
2891 * @param enmArch Architecture specifier.
2892 * @param phLdrMod Where to store the handle.
2893 * @param pErrInfo Where to return extended error info. Optional.
2894 */
2895static int RTLDRELF_NAME(Open)(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phLdrMod, PRTERRINFO pErrInfo)
2896{
2897 const char *pszLogName = pReader->pfnLogName(pReader);
2898 uint64_t cbRawImage = pReader->pfnSize(pReader);
2899 RT_NOREF_PV(fFlags);
2900
2901 /*
2902 * Create the loader module instance.
2903 */
2904 PRTLDRMODELF pModElf = (PRTLDRMODELF)RTMemAllocZ(sizeof(*pModElf));
2905 if (!pModElf)
2906 return VERR_NO_MEMORY;
2907
2908 pModElf->Core.u32Magic = RTLDRMOD_MAGIC;
2909 pModElf->Core.eState = LDR_STATE_INVALID;
2910 pModElf->Core.pReader = pReader;
2911 pModElf->Core.enmFormat = RTLDRFMT_ELF;
2912 pModElf->Core.enmType = RTLDRTYPE_OBJECT;
2913 pModElf->Core.enmEndian = RTLDRENDIAN_LITTLE;
2914#if ELF_MODE == 32
2915 pModElf->Core.enmArch = RTLDRARCH_X86_32;
2916#else
2917 pModElf->Core.enmArch = RTLDRARCH_AMD64;
2918#endif
2919 //pModElf->pvBits = NULL;
2920 //pModElf->Ehdr = {0};
2921 //pModElf->paShdrs = NULL;
2922 //pModElf->Rel.paSyms = NULL;
2923 pModElf->Rel.iSymSh = ~0U;
2924 //pModElf->Rel.cSyms = 0;
2925 pModElf->Rel.iStrSh = ~0U;
2926 //pModElf->Rel.cbStr = 0;
2927 //pModElf->Rel.pStr = NULL;
2928 //pModElf->Dyn.paSyms = NULL;
2929 pModElf->Dyn.iSymSh = ~0U;
2930 //pModElf->Dyn.cSyms = 0;
2931 pModElf->Dyn.iStrSh = ~0U;
2932 //pModElf->Dyn.cbStr = 0;
2933 //pModElf->Dyn.pStr = NULL;
2934 pModElf->iFirstSect = 1;
2935 //pModElf->fShdrInOrder = false;
2936 //pModElf->cbImage = 0;
2937 pModElf->LinkAddress = ~(Elf_Addr)0;
2938 //pModElf->cbShStr = 0;
2939 //pModElf->pShStr = NULL;
2940 //pModElf->iShEhFrame = 0;
2941 //pModElf->iShEhFrameHdr= 0;
2942 pModElf->iShDynamic = ~0U;
2943 //pModElf->cDynamic = 0;
2944 //pModElf->paDynamic = NULL;
2945 //pModElf->paPhdrs = NULL;
2946 pModElf->DynInfo.uPtrRelocs = ~(Elf_Addr)0;
2947 //pModElf->DynInfo.cbRelocs = 0;
2948 //pModElf->DynInfo.cbRelocEntry = 0;
2949 //pModElf->DynInfo.uRelocType = 0;
2950 //pModElf->DynInfo.idxShRelocs = 0;
2951 pModElf->DynInfo.uPtrJmpRelocs = ~(Elf_Addr)0;
2952 //pModElf->DynInfo.cbJmpRelocs = 0;
2953 //pModElf->DynInfo.uJmpRelocType = 0;
2954 //pModElf->DynInfo.idxShJmpRelocs = 0;
2955
2956 /*
2957 * Read and validate the ELF header and match up the CPU architecture.
2958 */
2959 int rc = pReader->pfnRead(pReader, &pModElf->Ehdr, sizeof(pModElf->Ehdr), 0);
2960 if (RT_SUCCESS(rc))
2961 {
2962 RTLDRARCH enmArchImage = RTLDRARCH_INVALID; /* shut up gcc */
2963 rc = RTLDRELF_NAME(ValidateElfHeader)(&pModElf->Ehdr, cbRawImage, pszLogName, &enmArchImage, pErrInfo);
2964 if (RT_SUCCESS(rc))
2965 {
2966 if ( enmArch != RTLDRARCH_WHATEVER
2967 && enmArch != enmArchImage)
2968 rc = VERR_LDR_ARCH_MISMATCH;
2969 }
2970 }
2971 if (RT_SUCCESS(rc))
2972 {
2973 /*
2974 * Read the section headers, keeping a prestine copy for the module
2975 * introspection methods.
2976 */
2977 size_t const cbShdrs = pModElf->Ehdr.e_shnum * sizeof(Elf_Shdr);
2978 Elf_Shdr *paShdrs = (Elf_Shdr *)RTMemAlloc(cbShdrs * 2 + sizeof(RTLDRMODELFSHX) * pModElf->Ehdr.e_shnum);
2979 if (paShdrs)
2980 {
2981 pModElf->paShdrs = paShdrs;
2982 rc = pReader->pfnRead(pReader, paShdrs, cbShdrs, pModElf->Ehdr.e_shoff);
2983 if (RT_SUCCESS(rc))
2984 {
2985 memcpy(&paShdrs[pModElf->Ehdr.e_shnum], paShdrs, cbShdrs);
2986 pModElf->paOrgShdrs = &paShdrs[pModElf->Ehdr.e_shnum];
2987
2988 pModElf->paShdrExtras = (PRTLDRMODELFSHX)&pModElf->paOrgShdrs[pModElf->Ehdr.e_shnum];
2989 memset(pModElf->paShdrExtras, 0xff, sizeof(RTLDRMODELFSHX) * pModElf->Ehdr.e_shnum);
2990
2991 pModElf->cbShStr = paShdrs[pModElf->Ehdr.e_shstrndx].sh_size;
2992
2993 /*
2994 * Validate the section headers and find relevant sections.
2995 */
2996 rc = RTLDRELF_NAME(ValidateAndProcessSectionHeaders)(pModElf, paShdrs, cbRawImage, pszLogName, pErrInfo);
2997
2998 /*
2999 * Read validate and process program headers if ET_DYN or ET_EXEC.
3000 */
3001 if (RT_SUCCESS(rc) && (pModElf->Ehdr.e_type == ET_DYN || pModElf->Ehdr.e_type == ET_EXEC))
3002 rc = RTLDRELF_NAME(ValidateAndProcessDynamicInfo)(pModElf, cbRawImage, fFlags, pszLogName, pErrInfo);
3003
3004 /*
3005 * Massage the section headers.
3006 */
3007 if (RT_SUCCESS(rc))
3008 {
3009 if (pModElf->Ehdr.e_type == ET_REL)
3010 {
3011 /* Do allocations and figure the image size: */
3012 pModElf->LinkAddress = 0;
3013 for (unsigned i = 1; i < pModElf->Ehdr.e_shnum; i++)
3014 if (paShdrs[i].sh_flags & SHF_ALLOC)
3015 {
3016 paShdrs[i].sh_addr = paShdrs[i].sh_addralign
3017 ? RT_ALIGN_T(pModElf->cbImage, paShdrs[i].sh_addralign, Elf_Addr)
3018 : (Elf_Addr)pModElf->cbImage;
3019 Elf_Addr EndAddr = paShdrs[i].sh_addr + paShdrs[i].sh_size;
3020 if (pModElf->cbImage < EndAddr)
3021 {
3022 pModElf->cbImage = (size_t)EndAddr;
3023 AssertMsgBreakStmt(pModElf->cbImage == EndAddr, (FMT_ELF_ADDR "\n", EndAddr), rc = VERR_IMAGE_TOO_BIG);
3024 }
3025 Log2(("RTLdrElf: %s: Assigned " FMT_ELF_ADDR " to section #%d\n", pszLogName, paShdrs[i].sh_addr, i));
3026 }
3027 }
3028 else
3029 {
3030 /* Convert sh_addr to RVA: */
3031 Assert(pModElf->LinkAddress != ~(Elf_Addr)0);
3032 for (unsigned i = 0 /*!*/; i < pModElf->Ehdr.e_shnum; i++)
3033 if (paShdrs[i].sh_flags & SHF_ALLOC)
3034 paShdrs[i].sh_addr -= pModElf->LinkAddress;
3035 }
3036 }
3037
3038 /*
3039 * Check if the sections are in order by address, as that will simplify
3040 * enumeration and address translation.
3041 */
3042 pModElf->fShdrInOrder = true;
3043 Elf_Addr uEndAddr = 0;
3044 for (unsigned i = pModElf->iFirstSect; i < pModElf->Ehdr.e_shnum; i++)
3045 if (paShdrs[i].sh_flags & SHF_ALLOC)
3046 {
3047 if (uEndAddr <= paShdrs[i].sh_addr)
3048 uEndAddr = paShdrs[i].sh_addr + paShdrs[i].sh_size;
3049 else
3050 {
3051 pModElf->fShdrInOrder = false;
3052 break;
3053 }
3054 }
3055
3056 Log2(("RTLdrElf: iSymSh=%u cSyms=%u iStrSh=%u cbStr=%u rc=%Rrc cbImage=%#zx LinkAddress=" FMT_ELF_ADDR " fShdrInOrder=%RTbool\n",
3057 pModElf->Rel.iSymSh, pModElf->Rel.cSyms, pModElf->Rel.iStrSh, pModElf->Rel.cbStr, rc,
3058 pModElf->cbImage, pModElf->LinkAddress, pModElf->fShdrInOrder));
3059 if (RT_SUCCESS(rc))
3060 {
3061 pModElf->Core.pOps = &RTLDRELF_MID(s_rtldrElf,Ops);
3062 pModElf->Core.eState = LDR_STATE_OPENED;
3063 *phLdrMod = &pModElf->Core;
3064
3065 LogFlow(("%s: %s: returns VINF_SUCCESS *phLdrMod=%p\n", __FUNCTION__, pszLogName, *phLdrMod));
3066 return VINF_SUCCESS;
3067 }
3068 }
3069
3070 RTMemFree(paShdrs);
3071 }
3072 else
3073 rc = VERR_NO_MEMORY;
3074 }
3075
3076 RTMemFree(pModElf);
3077 LogFlow(("%s: returns %Rrc\n", __FUNCTION__, rc));
3078 return rc;
3079}
3080
3081
3082
3083
3084/*******************************************************************************
3085* Cleanup Constants And Macros *
3086*******************************************************************************/
3087#undef RTLDRELF_NAME
3088#undef RTLDRELF_SUFF
3089#undef RTLDRELF_MID
3090
3091#undef FMT_ELF_ADDR
3092#undef FMT_ELF_ADDR7
3093#undef FMT_ELF_HALF
3094#undef FMT_ELF_SHALF
3095#undef FMT_ELF_OFF
3096#undef FMT_ELF_SIZE
3097#undef FMT_ELF_SWORD
3098#undef FMT_ELF_WORD
3099#undef FMT_ELF_XWORD
3100#undef FMT_ELF_SXWORD
3101
3102#undef Elf_Ehdr
3103#undef Elf_Phdr
3104#undef Elf_Shdr
3105#undef Elf_Sym
3106#undef Elf_Rel
3107#undef Elf_Rela
3108#undef Elf_Reloc
3109#undef Elf_Nhdr
3110#undef Elf_Dyn
3111
3112#undef Elf_Addr
3113#undef Elf_Half
3114#undef Elf_Off
3115#undef Elf_Size
3116#undef Elf_Sword
3117#undef Elf_Word
3118#undef Elf_Xword
3119#undef Elf_Sxword
3120
3121#undef RTLDRMODELF
3122#undef PRTLDRMODELF
3123
3124#undef ELF_R_SYM
3125#undef ELF_R_TYPE
3126#undef ELF_R_INFO
3127
3128#undef ELF_ST_BIND
3129
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette