dyld API on iPhone - strange output - ios

I have three question for you, all related to dyld :)
I have been using this dyld man page as a basis. I have compiled the following code and successfully executed the binary on my jailbroken device.
#include <stdio.h>
#include <mach-o/dyld.h>
int main(int argc, const char* argv[]) {
uint32_t image_count, i;
image_count = _dyld_image_count();
for (i = 0; i < image_count; i++) {
printf("%s\n", _dyld_get_image_name(i));
}
return 0;
}
I thought that these functions let me find all the shared libraries that are loaded in my program's address-space. On my mac, the output is pretty straightforward: It shows the paths to all the libraries that are currently loaded in memory. On my iPhone the output is nearly the same - i also get filepaths - but there are no files at the specified location. (On my mac on the other hand, i can locate the files!)
This is a sample line from the output:
/usr/lib/system/libdyld.dylib
According to ls, iFile and all the other tools i've used, this directory (/usr/lib/system/) is empty. Why? Where are those files?
Another thing i'd like to know is: Is it possible to locate a library in memory? From what offset to what offset the library is mapped into memory? I think i know how to find the beginning but i have no idea how to find the end of the library. To find the beginning, i'd use the address returned by _dyld_get_image_header - Is that correct?
Last question: I wanted to load a dynamic lib system-wide so i assumed i could use DYLD_INSERT_LIBRARIES to do just that. However, every binary i try to execute after inserting my lib crashes and produces a bus error! Did i forget something or is it the dynamic library that causes the crash?

the libraries are located at :
/System/Library/Caches/com.apple.dyld/dyld_shared_cache_armv6 (_armv7)
This is a big file were all the single libraries have been joined into one large one.
See http://iphonedevwiki.net/index.php/MobileSubstrate for hooking on jailbroken device
Yes one can determine the position of a dylib in memory, even on non jailbroken devices.
parse the LC_SEGMENT(_TEXT)-Section Header(_text) of the library then you can get the base address of the library and the size of the TEXT __text segment. Then query for the vmslide. Add this to the base address of the TEXT __text.
A detailed description of the mach-o file format can be found here:
https://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html. Pay special attention to "segment_command"-structure.

Related

Program compiles but doesn't do anything

I've recently started exploring and reading about Microchip's PIC32 MCUs, most specifically for motor control. I had some job done over the years but was a long while and haven't used the IDE with evaluation board since university years. Been using Arduino-compatible boards since or boards, compatible with the Arduino IDE.
So I'm running MPLAB X IDE v6.05 with the latest XC32 Compiler.
My Development board is DT100113 Curiosity Pro board, utilizing PIC32MK0512MCJ064 MCU and an on-board PicKit4 (PKoB4) for programming/debugging/serial connection purposes.
What I try to do is light up the two user LEDs on pins RA10 and RE13 respectively.
As I begin with creating new project, select my device, my program/debug tool and give my project a name, next step is to create a new main.c file.
I create the file and write the following:
#include <stdio.h>
#include <stdlib.h>
#include <xc.h>
int main(int argc, char** argv) {
//Define corresponding port bits as outputs (0 = output, 1 = input).
TRISAbits.TRISA10 = 0;
TRISEbits.TRISE13 = 0;
//Latch the outputs to HIGH (1) and hold.
while(1)
{
LATAbits.LATA10 = 1;
LATEbits.LATE13 = 1;
}
return (EXIT_SUCCESS);
}
When I build and run it - nothing happens. Build is successful, connected to programmer, erase/flash device OK, but nothing with the LEDs.
I think I'm missing the #pragma directives (read about that it must be defined first prior anything else), but am unaware on how to set configuration bits (used peripherals, internal clock speed, etc.).
Any pointers to how-to articles, posts, etc. will be highly appreciated. I was not able to find step-by-step tutorial for my development board so far :((
Thank you in advance!
Cheers,
Iliyan
I tried creating a new project, it compiled and ran, but the LEDs were not lit.
Obviously was missing some vital parts in the code.
Application software examples and driver libraries are included as part of the MPLAB Harmony V3 Framework. Add Harmony to 'Embedded' under the 'Tools' tab of the MPLAB IDE.

Getting the address of a section with Clang on OSX/iOS

For quite a while I've been using linker sections for registering elements that are used at runtime. I find that it's a simple way to make generic and extensible interface. A particularly useful use-case is something like unit tests or a multitool (e.g. busybox) so one can do something like:
$ ./tool <handler>
Where handler is a simple string that is "looked up" at runtime by walking the linker section. In this way, your parser doesn't have to "know" what commands are supported. It just finds their handlers in the linker section dedicated for them or it doesn't.
With GCC I've been doing something like (you can do this with Clang as well):
#define __tool __attribute__((__section__("tools")))
Then each handler I want to register gets a simple structure (with more or less information as needed)
struct tool {
const char *name;
const char *help;
int (*handler)(int argc, char **argv);
}
Then, for each tool you just do something like (often conveniently wrapped in a macro):
int example_tool0(int argc, char **argv)
{
return -1;
}
static const struct tool example_tool0 = {
.name = "exmaple_tool0",
.help = "usage: ...",
.handler = example_tool0
};
__tool static const struct tool *ptr = &example_tool0;
And used a such:
$ ./tool example_tool0
And because of __tool, each pointer registered in this way is packed into a linker section that can be walked.
Now, on GCC the linker creates two magic variables for each section: __start_SECTION and __stop_SECTION. So, to "walk" all of our registered handlers you just take the size of this section, divide by the size of a pointer, and then strncmp against the name (in this example) in the struct.
All of the above just to say, how can this be done using the OSX/iOS Clang-based toolchain? I would rather not use a custom linker script to achieve this seemingly simple operation.
Is there a way do this on OSX? I have worked around the issue by registering an empty entry at the beginning of the section and at the end. But doing so requires forcing the link order of the object files.
While OSX/iOS uses Clang as their platform compiler, they do not use the LLVM linker. Rather, they implement their own ld64 (which is open source) for whatever reason. So, it may just not be supported. I didn't readily see anything in man ld on OSX, but it's a bit info-dense.
For reference with ELF and GCC
And so this has been answered by others already. I did search, but I must have missed this answer. I've actually looked for an answer to this question many times before but must've never used the right words.
https://stackoverflow.com/a/22366882/2446071
In summary, apparently the linker supports syntax to define these desired symbols yourself:
extern char __start_SECTION __asm("section$start$SEGMENT$SECTION");
extern char __stop_SECTION __asm("section$end$SEGMENT$SECTION");

How to trace back #pragma pack?

I've been wrestling with an issue in iOS causing improper allocation, getting less memory back from malloc than I should have for a CPP object. I recently discovered it was due to two translation units including the same header, one of which along its include chain had a few occurrences of #pragma pack.
Now, I'm not sure how to properly trace back to whichever file is using it and ensure that it fixes it. I've added a bunch of #pragma pack(show) and have nailed down the offending file from the top (the offending file being the file that causes others files to have the same pack setting of 1). I've opened that file in Xcode and run preprocess on it.
In most cases, it looks like code is setting pack back to default (8 on arm64). Are there any tools that can help verify which is the offender along the chain?
The only tip that I have (a case of a pack 1, which is what the pack was being set to), is a header from the iOS SDK. But even it looks to be ok.
# 54 "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/usr/include/sys/kauth.h" 2 3 4
#pragma pack(1)
typedef struct {
u_int8_t sid_kind;
u_int8_t sid_authcount;
u_int8_t sid_authority[6];
u_int32_t sid_authorities[16];
} ntsid_t;
#pragma pack()
As I mentioned, when searching through the preprocessed source file, I wasn't able to find any instance of #pragma pack that wasn't undoing its setting shortly after. However, I wasn't aware that there was another way to set packing, via #pragma options align=(packed|reset). It turns out that it wasn't being undone, but I was looking for #pragma pack.

Complete list of paste operation constraints?

I've programmed for quite a long time - yet I never knew, until today - that folders can't be pasted into themselves.
I found this out in a rather unpleasant way - in my application (we're working on a file browsing app), when I pasted the folder into itself - it caused a segmentation fault (infinite recursion).
02-22 04:01:35.186: A/libc(786): Fatal signal 11 (SIGSEGV) at 0xdeadd00d (code=1), thread 786 (explorermanager)
My question is: are there any other paste constraints I should be aware of and are also appliable to most platforms?
On Win32 you can indeed copy a directory into itself. However if it is not put within a sub-directory it will simply overwrite existing files.
NOTE: For large directories this solution WILL take a little time.
// Make sure to link default lib "Shell32.lib"
#include <Windows.h>
#include <Shellapi.h>
int main() {
SHFILEOPSTRUCT hFileS = { 0 };
hFileS.hwnd = NULL;
hFileS.wFunc = FO_COPY;
hFileS.fFlags = FOF_SILENT;
hFileS.pTo = "C:\\DevkitPro\\TEST\0"; // Put into sub-dir TEST
hFileS.pFrom = "C:\\DevkitPro\\*\0";
SHFileOperation(&hFileS);
return 0;
}
Hopefully this helps (if you are using Windows)...
On MSDN:
http://msdn2.microsoft.com/en-us/library/ms647743.aspx

Code coverage with Xcode 4.2 - Missing files

I followed Claus's post to set up code coverage on Xcode 4.2 with LLVM 3.0. I'm able to see test coverage files, but they're only for my unit test classes, not my actual project classes. I've tried setting Generate Test Coverage Files and Instrument Program Flow to Yes on my main target, but that didn't help, as it failed with the following error:
fopen$UNIX2003 called from function llvm_gcda_start_file
To clarify, I don't think that's even the right approach - I just tried it to see if it would generate code coverage on my project classes.
At this point, I'd be happy to try anything that gets code coverage working on my app. Any suggestions?
You are expecting linker problem, profile_rt library uses fopen$UNIX2003 and fwrite$UNIX2003 functions instead of fopen and fwrite.
All you need is to add the following .c file to your project:
#include <stdio.h>
FILE *fopen$UNIX2003( const char *filename, const char *mode )
{
return fopen(filename, mode);
}
size_t fwrite$UNIX2003( const void *a, size_t b, size_t c, FILE *d )
{
return fwrite(a, b, c, d);
}
This code just remaps the missing functions to standard ones.
Note on $UNIX2003 suffix:
I've found an Apple document saying:
The UNIX™ conformance variants use the $UNIX2003 suffix.
Important: The work for UNIX™ conformance started in Mac OS 10.4, but was not completed until 10.5. Thus, in the 10.4 versions of libSystem.dylib, many of the conforming variant symbols (with the $UNIX2003 suffix) exist. The list is not complete, and the conforming behavior of the variant symbols may not be complete, so they should be avoided.
Because the 64-bit environment has no legacy to maintain, it was created to be UNIX™ conforming from the start, without the use of the $UNIX2003 suffix. So, for example, _fputs$UNIX2003 in 32-bit and _fputs in 64-bit will have the same conforming behavior.
So I expect libprofile_rt to be linked against 10.4 SDK.
I use CoverStory http://code.google.com/p/coverstory/ a GUI for .gcda and .gcno files.
The documentation explains the settings needed to generate these files http://code.google.com/p/coverstory/wiki/UsingCoverstory.

Resources