1 /*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <dlfcn.h>
18 #include <cctype>
19 #include <cmath>
20 #include <cstring>
21
22 #include "chre/platform/shared/nanoapp_loader.h"
23
24 #include "chre.h"
25 #include "chre/platform/assert.h"
26 #include "chre/platform/fatal_error.h"
27 #include "chre/platform/shared/debug_dump.h"
28 #include "chre/platform/shared/memory.h"
29 #include "chre/platform/shared/nanoapp/tokenized_log.h"
30 #include "chre/target_platform/platform_cache_management.h"
31 #include "chre/util/dynamic_vector.h"
32 #include "chre/util/macros.h"
33
34 #ifdef CHREX_SYMBOL_EXTENSIONS
35 #include "chre/extensions/platform/symbol_list.h"
36 #endif
37
38 #ifndef CHRE_LOADER_ARCH
39 #define CHRE_LOADER_ARCH EM_ARM
40 #endif // CHRE_LOADER_ARCH
41
42 namespace chre {
43 namespace {
44
45 using ElfHeader = ElfW(Ehdr);
46 using ProgramHeader = ElfW(Phdr);
47
48 struct ExportedData {
49 void *data;
50 const char *dataName;
51 };
52
53 //! If non-null, a nanoapp is currently being loaded. This allows certain C
54 //! functions to access the nanoapp if called during static init.
55 NanoappLoader *gCurrentlyLoadingNanoapp = nullptr;
56 //! Indicates whether a failure occurred during static initialization.
57 bool gStaticInitFailure = false;
58
deleteOpOverride(void *,unsigned int size)59 void deleteOpOverride(void* /* ptr */, unsigned int size) {
60 FATAL_ERROR("Nanoapp: delete(void *, unsigned int) override : sz = %u", size);
61 }
62
63 #ifdef __clang__
deleteOp2Override(void *)64 void deleteOp2Override(void*) {
65 FATAL_ERROR("Nanoapp: delete(void *)");
66 }
67 #endif
68
atexitInternal(struct AtExitCallback & cb)69 int atexitInternal(struct AtExitCallback &cb) {
70 if (gCurrentlyLoadingNanoapp == nullptr) {
71 CHRE_ASSERT_LOG(false,
72 "atexit is only supported during static initialization.");
73 return -1;
74 }
75
76 gCurrentlyLoadingNanoapp->registerAtexitFunction(cb);
77 return 0;
78 }
79
80 // atexit is used to register functions that must be called when a binary is
81 // removed from the system. The call back function has an arg (void *)
cxaAtexitOverride(void (* func)(void *),void * arg,void * dso)82 int cxaAtexitOverride(void (*func)(void *), void *arg, void *dso) {
83 LOGV("__cxa_atexit invoked with %p, %p, %p", func, arg, dso);
84 struct AtExitCallback cb(func, arg);
85 atexitInternal(cb);
86 return 0;
87 }
88
89 // The call back function has no arg.
atexitOverride(void (* func)(void))90 int atexitOverride(void (*func)(void)) {
91 LOGV("atexit invoked with %p", func);
92 struct AtExitCallback cb(func);
93 atexitInternal(cb);
94 return 0;
95 }
96
97 // The following functions from the cmath header need to be overridden, since
98 // they're overloaded functions, and we need to specify explicit types of the
99 // template for the compiler.
frexpOverride(double value,int * exp)100 double frexpOverride(double value, int *exp) {
101 return frexp(value, exp);
102 }
103
fmaxOverride(double x,double y)104 double fmaxOverride(double x, double y) {
105 return fmax(x, y);
106 }
107
fminOverride(double x,double y)108 double fminOverride(double x, double y) {
109 return fmin(x, y);
110 }
111
floorOverride(double value)112 double floorOverride(double value) {
113 return floor(value);
114 }
115
ceilOverride(double value)116 double ceilOverride(double value) {
117 return ceil(value);
118 }
119
sinOverride(double rad)120 double sinOverride(double rad) {
121 return sin(rad);
122 }
123
asinOverride(double val)124 double asinOverride(double val) {
125 return asin(val);
126 }
127
atan2Override(double y,double x)128 double atan2Override(double y, double x) {
129 return atan2(y, x);
130 }
131
cosOverride(double rad)132 double cosOverride(double rad) {
133 return cos(rad);
134 }
135
sqrtOverride(float val)136 float sqrtOverride(float val) {
137 return sqrt(val);
138 }
139
roundOverride(double val)140 double roundOverride(double val) {
141 return round(val);
142 }
143
144 // This function is required to be exposed to nanoapps to handle errors from
145 // invoking virtual functions.
__cxa_pure_virtual(void)146 void __cxa_pure_virtual(void) {
147 chreAbort(CHRE_ERROR /* abortCode */);
148 }
149
150 // TODO(karthikmb/stange): While this array was hand-coded for simple
151 // "hello-world" prototyping, the list of exported symbols must be
152 // generated to minimize runtime errors and build breaks.
153 // clang-format off
154 // Disable deprecation warning so that deprecated symbols in the array
155 // can be exported for older nanoapps and tests.
156 CHRE_DEPRECATED_PREAMBLE
157 const ExportedData kExportedData[] = {
158 /* libmath overrides and symbols */
159 ADD_EXPORTED_SYMBOL(asinOverride, "asin"),
160 ADD_EXPORTED_SYMBOL(atan2Override, "atan2"),
161 ADD_EXPORTED_SYMBOL(cosOverride, "cos"),
162 ADD_EXPORTED_SYMBOL(floorOverride, "floor"),
163 ADD_EXPORTED_SYMBOL(ceilOverride, "ceil"),
164 ADD_EXPORTED_SYMBOL(fmaxOverride, "fmax"),
165 ADD_EXPORTED_SYMBOL(fminOverride, "fmin"),
166 ADD_EXPORTED_SYMBOL(frexpOverride, "frexp"),
167 ADD_EXPORTED_SYMBOL(roundOverride, "round"),
168 ADD_EXPORTED_SYMBOL(sinOverride, "sin"),
169 ADD_EXPORTED_SYMBOL(sqrtOverride, "sqrt"),
170 ADD_EXPORTED_C_SYMBOL(acosf),
171 ADD_EXPORTED_C_SYMBOL(asinf),
172 ADD_EXPORTED_C_SYMBOL(atan2f),
173 ADD_EXPORTED_C_SYMBOL(ceilf),
174 ADD_EXPORTED_C_SYMBOL(cosf),
175 ADD_EXPORTED_C_SYMBOL(expf),
176 ADD_EXPORTED_C_SYMBOL(fabsf),
177 ADD_EXPORTED_C_SYMBOL(floorf),
178 ADD_EXPORTED_C_SYMBOL(fmaxf),
179 ADD_EXPORTED_C_SYMBOL(fminf),
180 ADD_EXPORTED_C_SYMBOL(fmodf),
181 ADD_EXPORTED_C_SYMBOL(log10f),
182 ADD_EXPORTED_C_SYMBOL(log1pf),
183 ADD_EXPORTED_C_SYMBOL(log2f),
184 ADD_EXPORTED_C_SYMBOL(logf),
185 ADD_EXPORTED_C_SYMBOL(lrintf),
186 ADD_EXPORTED_C_SYMBOL(lroundf),
187 ADD_EXPORTED_C_SYMBOL(powf),
188 ADD_EXPORTED_C_SYMBOL(remainderf),
189 ADD_EXPORTED_C_SYMBOL(roundf),
190 ADD_EXPORTED_C_SYMBOL(sinf),
191 ADD_EXPORTED_C_SYMBOL(sqrtf),
192 ADD_EXPORTED_C_SYMBOL(tanf),
193 ADD_EXPORTED_C_SYMBOL(tanhf),
194 /* libc overrides and symbols */
195 ADD_EXPORTED_C_SYMBOL(__cxa_pure_virtual),
196 ADD_EXPORTED_SYMBOL(cxaAtexitOverride, "__cxa_atexit"),
197 ADD_EXPORTED_SYMBOL(atexitOverride, "atexit"),
198 ADD_EXPORTED_SYMBOL(deleteOpOverride, "_ZdlPvj"),
199 #ifdef __clang__
200 ADD_EXPORTED_SYMBOL(deleteOp2Override, "_ZdlPv"),
201 #endif
202 ADD_EXPORTED_C_SYMBOL(dlsym),
203 ADD_EXPORTED_C_SYMBOL(isgraph),
204 ADD_EXPORTED_C_SYMBOL(memcmp),
205 ADD_EXPORTED_C_SYMBOL(memcpy),
206 ADD_EXPORTED_C_SYMBOL(memmove),
207 ADD_EXPORTED_C_SYMBOL(memset),
208 ADD_EXPORTED_C_SYMBOL(snprintf),
209 ADD_EXPORTED_C_SYMBOL(strcmp),
210 ADD_EXPORTED_C_SYMBOL(strlen),
211 ADD_EXPORTED_C_SYMBOL(strncmp),
212 ADD_EXPORTED_C_SYMBOL(tolower),
213 /* CHRE symbols */
214 ADD_EXPORTED_C_SYMBOL(chreAbort),
215 ADD_EXPORTED_C_SYMBOL(chreAudioConfigureSource),
216 ADD_EXPORTED_C_SYMBOL(chreAudioGetSource),
217 ADD_EXPORTED_C_SYMBOL(chreBleGetCapabilities),
218 ADD_EXPORTED_C_SYMBOL(chreBleGetFilterCapabilities),
219 ADD_EXPORTED_C_SYMBOL(chreBleFlushAsync),
220 ADD_EXPORTED_C_SYMBOL(chreBleStartScanAsync),
221 ADD_EXPORTED_C_SYMBOL(chreBleStartScanAsyncV1_9),
222 ADD_EXPORTED_C_SYMBOL(chreBleStopScanAsync),
223 ADD_EXPORTED_C_SYMBOL(chreBleStopScanAsyncV1_9),
224 ADD_EXPORTED_C_SYMBOL(chreBleReadRssiAsync),
225 ADD_EXPORTED_C_SYMBOL(chreBleGetScanStatus),
226 ADD_EXPORTED_C_SYMBOL(chreConfigureDebugDumpEvent),
227 ADD_EXPORTED_C_SYMBOL(chreConfigureHostSleepStateEvents),
228 ADD_EXPORTED_C_SYMBOL(chreConfigureNanoappInfoEvents),
229 ADD_EXPORTED_C_SYMBOL(chreDebugDumpLog),
230 ADD_EXPORTED_C_SYMBOL(chreGetApiVersion),
231 ADD_EXPORTED_C_SYMBOL(chreGetCapabilities),
232 ADD_EXPORTED_C_SYMBOL(chreGetMessageToHostMaxSize),
233 ADD_EXPORTED_C_SYMBOL(chreGetAppId),
234 ADD_EXPORTED_C_SYMBOL(chreGetInstanceId),
235 ADD_EXPORTED_C_SYMBOL(chreGetEstimatedHostTimeOffset),
236 ADD_EXPORTED_C_SYMBOL(chreGetNanoappInfoByAppId),
237 ADD_EXPORTED_C_SYMBOL(chreGetNanoappInfoByInstanceId),
238 ADD_EXPORTED_C_SYMBOL(chreGetPlatformId),
239 ADD_EXPORTED_C_SYMBOL(chreGetSensorInfo),
240 ADD_EXPORTED_C_SYMBOL(chreGetSensorSamplingStatus),
241 ADD_EXPORTED_C_SYMBOL(chreGetTime),
242 ADD_EXPORTED_C_SYMBOL(chreGetVersion),
243 ADD_EXPORTED_C_SYMBOL(chreGnssConfigurePassiveLocationListener),
244 ADD_EXPORTED_C_SYMBOL(chreGnssGetCapabilities),
245 ADD_EXPORTED_C_SYMBOL(chreGnssLocationSessionStartAsync),
246 ADD_EXPORTED_C_SYMBOL(chreGnssLocationSessionStopAsync),
247 ADD_EXPORTED_C_SYMBOL(chreGnssMeasurementSessionStartAsync),
248 ADD_EXPORTED_C_SYMBOL(chreGnssMeasurementSessionStopAsync),
249 ADD_EXPORTED_C_SYMBOL(chreHeapAlloc),
250 ADD_EXPORTED_C_SYMBOL(chreHeapFree),
251 ADD_EXPORTED_C_SYMBOL(chreIsHostAwake),
252 ADD_EXPORTED_C_SYMBOL(chreLog),
253 ADD_EXPORTED_C_SYMBOL(chreSendEvent),
254 ADD_EXPORTED_C_SYMBOL(chreSendMessageToHost),
255 ADD_EXPORTED_C_SYMBOL(chreSendMessageToHostEndpoint),
256 ADD_EXPORTED_C_SYMBOL(chreSendMessageWithPermissions),
257 ADD_EXPORTED_C_SYMBOL(chreSendReliableMessageAsync),
258 ADD_EXPORTED_C_SYMBOL(chreSensorConfigure),
259 ADD_EXPORTED_C_SYMBOL(chreSensorConfigureBiasEvents),
260 ADD_EXPORTED_C_SYMBOL(chreSensorFind),
261 ADD_EXPORTED_C_SYMBOL(chreSensorFindDefault),
262 ADD_EXPORTED_C_SYMBOL(chreSensorFlushAsync),
263 ADD_EXPORTED_C_SYMBOL(chreSensorGetThreeAxisBias),
264 ADD_EXPORTED_C_SYMBOL(chreTimerCancel),
265 ADD_EXPORTED_C_SYMBOL(chreTimerSet),
266 ADD_EXPORTED_C_SYMBOL(chreUserSettingConfigureEvents),
267 ADD_EXPORTED_C_SYMBOL(chreUserSettingGetState),
268 ADD_EXPORTED_C_SYMBOL(chreWifiConfigureScanMonitorAsync),
269 ADD_EXPORTED_C_SYMBOL(chreWifiGetCapabilities),
270 ADD_EXPORTED_C_SYMBOL(chreWifiRequestScanAsync),
271 ADD_EXPORTED_C_SYMBOL(chreWifiRequestRangingAsync),
272 ADD_EXPORTED_C_SYMBOL(chreWifiNanRequestRangingAsync),
273 ADD_EXPORTED_C_SYMBOL(chreWifiNanSubscribe),
274 ADD_EXPORTED_C_SYMBOL(chreWifiNanSubscribeCancel),
275 ADD_EXPORTED_C_SYMBOL(chreWwanGetCapabilities),
276 ADD_EXPORTED_C_SYMBOL(chreWwanGetCellInfoAsync),
277 ADD_EXPORTED_C_SYMBOL(platform_chreDebugDumpVaLog),
278 #ifdef CHRE_NANOAPP_TOKENIZED_LOGGING_SUPPORT_ENABLED
279 ADD_EXPORTED_C_SYMBOL(platform_chrePwTokenizedLog),
280 #endif // CHRE_NANOAPP_TOKENIZED_LOGGING_SUPPORT_ENABLED
281 ADD_EXPORTED_C_SYMBOL(chreConfigureHostEndpointNotifications),
282 ADD_EXPORTED_C_SYMBOL(chrePublishRpcServices),
283 ADD_EXPORTED_C_SYMBOL(chreGetHostEndpointInfo),
284 };
285 CHRE_DEPRECATED_EPILOGUE
286 // clang-format on
287
288 } // namespace
289
create(void * elfInput,bool mapIntoTcm)290 NanoappLoader *NanoappLoader::create(void *elfInput, bool mapIntoTcm) {
291 if (elfInput == nullptr) {
292 LOGE("Elf header must not be null");
293 return nullptr;
294 }
295
296 auto *loader =
297 static_cast<NanoappLoader *>(memoryAllocDram(sizeof(NanoappLoader)));
298 if (loader == nullptr) {
299 LOG_OOM();
300 return nullptr;
301 }
302 new (loader) NanoappLoader(elfInput, mapIntoTcm);
303
304 if (loader->open()) {
305 return loader;
306 }
307
308 // Call the destructor explicitly as memoryFreeDram() never calls it.
309 loader->~NanoappLoader();
310 memoryFreeDram(loader);
311 return nullptr;
312 }
313
destroy(NanoappLoader * loader)314 void NanoappLoader::destroy(NanoappLoader *loader) {
315 loader->close();
316 // TODO(b/151847750): Modify utilities to support free'ing from regions other
317 // than SRAM.
318 loader->~NanoappLoader();
319 memoryFreeDram(loader);
320 }
321
findExportedSymbol(const char * name)322 void *NanoappLoader::findExportedSymbol(const char *name) {
323 size_t nameLen = strlen(name);
324 for (size_t i = 0; i < ARRAY_SIZE(kExportedData); i++) {
325 if (nameLen == strlen(kExportedData[i].dataName) &&
326 strncmp(name, kExportedData[i].dataName, nameLen) == 0) {
327 return kExportedData[i].data;
328 }
329 }
330
331 #ifdef CHREX_SYMBOL_EXTENSIONS
332 for (size_t i = 0; i < ARRAY_SIZE(kVendorExportedData); i++) {
333 if (nameLen == strlen(kVendorExportedData[i].dataName) &&
334 strncmp(name, kVendorExportedData[i].dataName, nameLen) == 0) {
335 return kVendorExportedData[i].data;
336 }
337 }
338 #endif
339
340 return nullptr;
341 }
342
open()343 bool NanoappLoader::open() {
344 if (!copyAndVerifyHeaders()) {
345 LOGE("Failed to copy and verify elf headers");
346 } else if (!createMappings()) {
347 LOGE("Failed to create mappings");
348 } else if (!fixRelocations()) {
349 LOGE("Failed to fix relocations");
350 } else if (!resolveGot()) {
351 LOGE("Failed to resolve GOT");
352 } else {
353 // Wipe caches before calling init array to ensure initializers are not in
354 // the data cache.
355 wipeSystemCaches(reinterpret_cast<uintptr_t>(mMapping), mMemorySpan);
356 if (!callInitArray()) {
357 LOGE("Failed to perform static init");
358 } else {
359 return true;
360 }
361 }
362 freeAllocatedData();
363 return false;
364 }
365
close()366 void NanoappLoader::close() {
367 callAtexitFunctions();
368 callTerminatorArray();
369 freeAllocatedData();
370 }
371
findSymbolByName(const char * name)372 void *NanoappLoader::findSymbolByName(const char *name) {
373 for (size_t offset = 0; offset < mDynamicSymbolTableSize;
374 offset += sizeof(ElfSym)) {
375 ElfSym *currSym =
376 reinterpret_cast<ElfSym *>(mDynamicSymbolTablePtr + offset);
377 const char *symbolName = getDataName(currSym);
378
379 if (strncmp(symbolName, name, strlen(name)) == 0) {
380 return getSymbolTarget(currSym);
381 }
382 }
383 return nullptr;
384 }
385
registerAtexitFunction(struct AtExitCallback & cb)386 void NanoappLoader::registerAtexitFunction(struct AtExitCallback &cb) {
387 if (!mAtexitFunctions.push_back(cb)) {
388 LOG_OOM();
389 gStaticInitFailure = true;
390 }
391 }
392
mapBss(const ProgramHeader * hdr)393 void NanoappLoader::mapBss(const ProgramHeader *hdr) {
394 // if the memory size of this segment exceeds the file size zero fill the
395 // difference.
396 LOGV("Program Hdr mem sz: %u file size: %u", hdr->p_memsz, hdr->p_filesz);
397 if (hdr->p_memsz > hdr->p_filesz) {
398 ElfAddr endOfFile = hdr->p_vaddr + hdr->p_filesz + mLoadBias;
399 ElfAddr endOfMem = hdr->p_vaddr + hdr->p_memsz + mLoadBias;
400 if (endOfMem > endOfFile) {
401 auto deltaMem = endOfMem - endOfFile;
402 LOGV("Zeroing out %u from page %x", deltaMem, endOfFile);
403 memset(reinterpret_cast<void *>(endOfFile), 0, deltaMem);
404 }
405 }
406 }
407
callInitArray()408 bool NanoappLoader::callInitArray() {
409 bool success = true;
410 // Sets global variable used by atexit in case it's invoked as part of
411 // initializing static data.
412 gCurrentlyLoadingNanoapp = this;
413
414 // TODO(b/151847750): ELF can have other sections like .init, .preinit, .fini
415 // etc. Be sure to look for those if they end up being something that should
416 // be supported for nanoapps.
417 for (size_t i = 0; i < mNumSectionHeaders; ++i) {
418 const char *name = getSectionHeaderName(mSectionHeadersPtr[i].sh_name);
419 if (strncmp(name, kInitArrayName, strlen(kInitArrayName)) == 0) {
420 LOGV("Invoking init function");
421 uintptr_t initArray =
422 static_cast<uintptr_t>(mLoadBias + mSectionHeadersPtr[i].sh_addr);
423 uintptr_t offset = 0;
424 while (offset < mSectionHeadersPtr[i].sh_size) {
425 ElfAddr *funcPtr = reinterpret_cast<ElfAddr *>(initArray + offset);
426 uintptr_t initFunction = static_cast<uintptr_t>(*funcPtr);
427 ((void (*)())initFunction)();
428 offset += sizeof(initFunction);
429 if (gStaticInitFailure) {
430 success = false;
431 break;
432 }
433 }
434 break;
435 }
436 }
437
438 //! Reset global state so it doesn't leak into the next load.
439 gCurrentlyLoadingNanoapp = nullptr;
440 gStaticInitFailure = false;
441 return success;
442 }
443
roundDownToAlign(uintptr_t virtualAddr,size_t alignment)444 uintptr_t NanoappLoader::roundDownToAlign(uintptr_t virtualAddr,
445 size_t alignment) {
446 return alignment == 0 ? virtualAddr : virtualAddr & -alignment;
447 }
448
freeAllocatedData()449 void NanoappLoader::freeAllocatedData() {
450 if (mIsTcmBinary) {
451 nanoappBinaryFree(mMapping);
452 } else {
453 nanoappBinaryDramFree(mMapping);
454 }
455 memoryFreeDram(mSectionHeadersPtr);
456 memoryFreeDram(mSectionNamesPtr);
457 mDynamicSymbolTablePtr = nullptr;
458 mDynamicSymbolTableSize = 0;
459 }
460
verifyElfHeader()461 bool NanoappLoader::verifyElfHeader() {
462 ElfHeader *elfHeader = getElfHeader();
463 if (elfHeader != nullptr && (elfHeader->e_ident[EI_MAG0] == ELFMAG0) &&
464 (elfHeader->e_ident[EI_MAG1] == ELFMAG1) &&
465 (elfHeader->e_ident[EI_MAG2] == ELFMAG2) &&
466 (elfHeader->e_ident[EI_MAG3] == ELFMAG3) &&
467 (elfHeader->e_ehsize == sizeof(ElfHeader)) &&
468 (elfHeader->e_phentsize == sizeof(ProgramHeader)) &&
469 (elfHeader->e_shentsize == sizeof(SectionHeader)) &&
470 (elfHeader->e_shstrndx < elfHeader->e_shnum) &&
471 (elfHeader->e_version == EV_CURRENT) &&
472 (elfHeader->e_machine == CHRE_LOADER_ARCH) &&
473 (elfHeader->e_type == ET_DYN)) {
474 return true;
475 }
476 return false;
477 }
478
verifyProgramHeaders()479 bool NanoappLoader::verifyProgramHeaders() {
480 // This is a minimal check for now -
481 // there should be at least one load segment.
482 for (size_t i = 0; i < getProgramHeaderArraySize(); ++i) {
483 if (getProgramHeaderArray()[i].p_type == PT_LOAD) {
484 return true;
485 }
486 }
487 LOGE("No load segment found");
488 return false;
489 }
490
getSectionHeaderName(size_t headerOffset)491 const char *NanoappLoader::getSectionHeaderName(size_t headerOffset) {
492 if (headerOffset == 0) {
493 return "";
494 }
495
496 return &mSectionNamesPtr[headerOffset];
497 }
498
getSectionHeader(const char * headerName)499 NanoappLoader::SectionHeader *NanoappLoader::getSectionHeader(
500 const char *headerName) {
501 SectionHeader *rv = nullptr;
502 for (size_t i = 0; i < mNumSectionHeaders; ++i) {
503 const char *name = getSectionHeaderName(mSectionHeadersPtr[i].sh_name);
504 if (strncmp(name, headerName, strlen(headerName)) == 0) {
505 rv = &mSectionHeadersPtr[i];
506 break;
507 }
508 }
509 return rv;
510 }
511
getProgramHeaderArray()512 ProgramHeader *NanoappLoader::getProgramHeaderArray() {
513 return reinterpret_cast<ProgramHeader *>(mBinary + getElfHeader()->e_phoff);
514 }
515
getProgramHeaderArraySize()516 size_t NanoappLoader::getProgramHeaderArraySize() {
517 return getElfHeader()->e_phnum;
518 }
519
verifyDynamicTables()520 bool NanoappLoader::verifyDynamicTables() {
521 SectionHeader *dynamicStringTablePtr = getSectionHeader(kDynstrTableName);
522 if (dynamicStringTablePtr == nullptr) {
523 LOGE("Failed to find table %s", kDynstrTableName);
524 return false;
525 }
526 mDynamicStringTablePtr =
527 reinterpret_cast<char *>(mBinary + dynamicStringTablePtr->sh_offset);
528
529 SectionHeader *dynamicSymbolTablePtr = getSectionHeader(kDynsymTableName);
530 if (dynamicSymbolTablePtr == nullptr) {
531 LOGE("Failed to find table %s", kDynsymTableName);
532 return false;
533 }
534 mDynamicSymbolTablePtr = (mBinary + dynamicSymbolTablePtr->sh_offset);
535 mDynamicSymbolTableSize = dynamicSymbolTablePtr->sh_size;
536
537 return true;
538 }
539
copyAndVerifyHeaders()540 bool NanoappLoader::copyAndVerifyHeaders() {
541 // Verify the ELF Header
542 if (!verifyElfHeader()) {
543 LOGE("ELF header is invalid");
544 return false;
545 }
546
547 // Verify Program Headers
548 if (!verifyProgramHeaders()) {
549 LOGE("Program headers are invalid");
550 return false;
551 }
552
553 // Load Section Headers
554 ElfHeader *elfHeader = getElfHeader();
555 size_t sectionHeaderSizeBytes = sizeof(SectionHeader) * elfHeader->e_shnum;
556 mSectionHeadersPtr =
557 static_cast<SectionHeader *>(memoryAllocDram(sectionHeaderSizeBytes));
558 if (mSectionHeadersPtr == nullptr) {
559 LOG_OOM();
560 return false;
561 }
562 memcpy(mSectionHeadersPtr, (mBinary + elfHeader->e_shoff),
563 sectionHeaderSizeBytes);
564 mNumSectionHeaders = elfHeader->e_shnum;
565
566 // Load section header names
567 SectionHeader &stringSection = mSectionHeadersPtr[elfHeader->e_shstrndx];
568 size_t sectionSize = stringSection.sh_size;
569 mSectionNamesPtr = static_cast<char *>(memoryAllocDram(sectionSize));
570 if (mSectionNamesPtr == nullptr) {
571 LOG_OOM();
572 return false;
573 }
574 memcpy(mSectionNamesPtr, mBinary + stringSection.sh_offset, sectionSize);
575
576 // Verify dynamic symbol table
577 if (!verifyDynamicTables()) {
578 LOGE("Failed to verify dynamic tables");
579 return false;
580 }
581
582 return true;
583 }
584
createMappings()585 bool NanoappLoader::createMappings() {
586 // ELF needs pt_load segments to be in contiguous ascending order of
587 // virtual addresses. So the first and last segs can be used to
588 // calculate the entire address span of the image.
589 ProgramHeader *programHeaderArray = getProgramHeaderArray();
590 size_t numProgramHeaders = getProgramHeaderArraySize();
591 const ProgramHeader *first = &programHeaderArray[0];
592 const ProgramHeader *last = &programHeaderArray[numProgramHeaders - 1];
593
594 // Find first load segment
595 while (first->p_type != PT_LOAD && first <= last) {
596 ++first;
597 }
598
599 bool success = false;
600 if (first->p_type != PT_LOAD) {
601 LOGE("Unable to find any load segments in the binary");
602 } else {
603 // Verify that the first load segment has a program header
604 // first byte of a valid load segment can't be greater than the
605 // program header offset
606 bool valid =
607 (first->p_offset < getElfHeader()->e_phoff) &&
608 (first->p_filesz >= (getElfHeader()->e_phoff +
609 (numProgramHeaders * sizeof(ProgramHeader))));
610 if (!valid) {
611 LOGE("Load segment program header validation failed");
612 } else {
613 // Get the last load segment
614 while (last > first && last->p_type != PT_LOAD) --last;
615
616 size_t alignment = first->p_align;
617 size_t memorySpan = last->p_vaddr + last->p_memsz - first->p_vaddr;
618 LOGV("Nanoapp image Memory Span: %zu", memorySpan);
619
620 if (mIsTcmBinary) {
621 mMapping =
622 static_cast<uint8_t *>(nanoappBinaryAlloc(memorySpan, alignment));
623 } else {
624 mMapping = static_cast<uint8_t *>(
625 nanoappBinaryDramAlloc(memorySpan, alignment));
626 }
627
628 if (mMapping == nullptr) {
629 LOG_OOM();
630 } else {
631 LOGV("Starting location of mappings %p", mMapping);
632 mMemorySpan = memorySpan;
633
634 // Calculate the load bias using the first load segment.
635 uintptr_t adjustedFirstLoadSegAddr =
636 roundDownToAlign(first->p_vaddr, alignment);
637 mLoadBias =
638 reinterpret_cast<uintptr_t>(mMapping) - adjustedFirstLoadSegAddr;
639 LOGV("Load bias is %lu", static_cast<long unsigned int>(mLoadBias));
640
641 success = true;
642 }
643 }
644 }
645
646 if (success) {
647 // Map the remaining segments
648 for (const ProgramHeader *ph = first; ph <= last; ++ph) {
649 if (ph->p_type == PT_LOAD) {
650 ElfAddr segStart = ph->p_vaddr + mLoadBias;
651 void *startPage = reinterpret_cast<void *>(segStart);
652 void *binaryStartPage = mBinary + ph->p_offset;
653 size_t segmentLen = ph->p_filesz;
654
655 LOGV("Mapping start page %p from %p with length %zu", startPage,
656 binaryStartPage, segmentLen);
657 memcpy(startPage, binaryStartPage, segmentLen);
658 mapBss(ph);
659 } else {
660 LOGE("Non-load segment found between load segments");
661 success = false;
662 break;
663 }
664 }
665 }
666
667 return success;
668 }
669
getDynamicSymbol(size_t posInSymbolTable)670 NanoappLoader::ElfSym *NanoappLoader::getDynamicSymbol(
671 size_t posInSymbolTable) {
672 size_t numElements = mDynamicSymbolTableSize / sizeof(ElfSym);
673 CHRE_ASSERT(posInSymbolTable < numElements);
674 if (posInSymbolTable < numElements) {
675 return reinterpret_cast<ElfSym *>(
676 &mDynamicSymbolTablePtr[posInSymbolTable * sizeof(ElfSym)]);
677 }
678 LOGE("Symbol index %zu is out of bound %zu", posInSymbolTable, numElements);
679 return nullptr;
680 }
681
getDataName(const ElfSym * symbol)682 const char *NanoappLoader::getDataName(const ElfSym *symbol) {
683 return symbol == nullptr ? nullptr : &mDynamicStringTablePtr[symbol->st_name];
684 }
685
getSymbolTarget(const ElfSym * symbol)686 void *NanoappLoader::getSymbolTarget(const ElfSym *symbol) {
687 if (symbol == nullptr || symbol->st_shndx == SHN_UNDEF) {
688 return nullptr;
689 }
690 return mMapping + symbol->st_value;
691 }
692
resolveData(size_t posInSymbolTable)693 void *NanoappLoader::resolveData(size_t posInSymbolTable) {
694 const ElfSym *symbol = getDynamicSymbol(posInSymbolTable);
695 const char *dataName = getDataName(symbol);
696 void *target = nullptr;
697
698 if (dataName != nullptr) {
699 LOGV("Resolving %s", dataName);
700 target = findExportedSymbol(dataName);
701 if (target == nullptr) {
702 target = getSymbolTarget(symbol);
703 }
704 if (target == nullptr) {
705 LOGE("Unable to find %s", dataName);
706 }
707 }
708
709 return target;
710 }
711
getDynamicHeader()712 NanoappLoader::DynamicHeader *NanoappLoader::getDynamicHeader() {
713 DynamicHeader *dyn = nullptr;
714 ProgramHeader *programHeaders = getProgramHeaderArray();
715 for (size_t i = 0; i < getProgramHeaderArraySize(); ++i) {
716 if (programHeaders[i].p_type == PT_DYNAMIC) {
717 dyn = reinterpret_cast<DynamicHeader *>(programHeaders[i].p_offset +
718 mBinary);
719 break;
720 }
721 }
722 return dyn;
723 }
724
getFirstRoSegHeader()725 NanoappLoader::ProgramHeader *NanoappLoader::getFirstRoSegHeader() {
726 // return the first read only segment found
727 ProgramHeader *ro = nullptr;
728 ProgramHeader *programHeaders = getProgramHeaderArray();
729 for (size_t i = 0; i < getProgramHeaderArraySize(); ++i) {
730 if (!(programHeaders[i].p_flags & PF_W)) {
731 ro = &programHeaders[i];
732 break;
733 }
734 }
735 return ro;
736 }
737
getDynEntry(DynamicHeader * dyn,int field)738 NanoappLoader::ElfWord NanoappLoader::getDynEntry(DynamicHeader *dyn,
739 int field) {
740 ElfWord rv = 0;
741
742 while (dyn->d_tag != DT_NULL) {
743 if (dyn->d_tag == field) {
744 rv = dyn->d_un.d_val;
745 break;
746 }
747 ++dyn;
748 }
749
750 return rv;
751 }
752
fixRelocations()753 bool NanoappLoader::fixRelocations() {
754 DynamicHeader *dyn = getDynamicHeader();
755 if (dyn == nullptr) {
756 LOGE("Dynamic headers are missing from shared object");
757 }
758 if (relocateTable(dyn, DT_RELA) && relocateTable(dyn, DT_REL)) {
759 return true;
760 }
761 LOGE("Unable to resolve all symbols in the binary");
762 return false;
763 }
764
callAtexitFunctions()765 void NanoappLoader::callAtexitFunctions() {
766 while (!mAtexitFunctions.empty()) {
767 struct AtExitCallback cb = mAtexitFunctions.back();
768 if (cb.arg.has_value()) {
769 LOGV("Calling __cxa_atexit at %p, arg %p", cb.func1, cb.arg.value());
770 cb.func1(cb.arg.value());
771 } else {
772 LOGV("Calling atexit at %p", cb.func0);
773 cb.func0();
774 }
775 mAtexitFunctions.pop_back();
776 }
777 }
778
callTerminatorArray()779 void NanoappLoader::callTerminatorArray() {
780 for (size_t i = 0; i < mNumSectionHeaders; ++i) {
781 const char *name = getSectionHeaderName(mSectionHeadersPtr[i].sh_name);
782 if (strncmp(name, kFiniArrayName, strlen(kFiniArrayName)) == 0) {
783 uintptr_t finiArray =
784 static_cast<uintptr_t>(mLoadBias + mSectionHeadersPtr[i].sh_addr);
785 uintptr_t offset = 0;
786 while (offset < mSectionHeadersPtr[i].sh_size) {
787 ElfAddr *funcPtr = reinterpret_cast<ElfAddr *>(finiArray + offset);
788 uintptr_t finiFunction = static_cast<uintptr_t>(*funcPtr);
789 ((void (*)())finiFunction)();
790 offset += sizeof(finiFunction);
791 }
792 break;
793 }
794 }
795 }
796
getTokenDatabaseSectionInfo(uint32_t * offset,size_t * size)797 void NanoappLoader::getTokenDatabaseSectionInfo(uint32_t *offset,
798 size_t *size) {
799 // Find token database.
800 SectionHeader *pwTokenTableHeader = getSectionHeader(kTokenTableName);
801 if (pwTokenTableHeader != nullptr) {
802 if (pwTokenTableHeader->sh_size != 0) {
803 *size = pwTokenTableHeader->sh_size;
804 *offset = pwTokenTableHeader->sh_offset;
805 } else {
806 LOGE("Found empty token database");
807 *size = 0;
808 *offset = 0;
809 }
810 } else {
811 *size = 0;
812 *offset = 0;
813 }
814 }
815
816 } // namespace chre
817