VirtualBox

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

Last change on this file since 85501 was 85501, checked in by vboxsync, 5 years ago

IPRT/ldrELF: Early support for loading ET_DYN images. Current code is a bit cumbersome as it approaches it from the ET_REL/sections perspective rather than using program headers and the dynamic section. bugref:9801

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

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