Exemple #1
0
static gboolean
find_image_address_and_slide (const gchar * image_name,
                              gpointer * address,
                              gpointer * slide)
{
  gboolean name_is_absolute;
  guint count, idx;

  name_is_absolute = index (image_name, '/') != NULL;

  count = _dyld_image_count ();

  for (idx = 0; idx != count; idx++)
  {
    const gchar * name, * s;

    name = _dyld_get_image_name (idx);
    if (!name_is_absolute && (s = strrchr (name, '/')) != NULL)
      name = s + 1;

    if (strcmp (name, image_name) == 0)
    {
      *address = (gpointer) _dyld_get_image_header (idx);
      *slide = (gpointer) _dyld_get_image_vmaddr_slide (idx);
      return TRUE;
    }
  }

  return FALSE;
}
static const void *__CFBundleDYLDFindImage(char *buff) {
    const void *header = NULL;
    uint32_t i, numImages = _dyld_image_count(), numMatches = 0;
    const char *curName, *p, *q;

    for (i = 0; !header && i < numImages; i++) {
        curName = _dyld_get_image_name(i);
        if (curName && 0 == strncmp(curName, buff, CFMaxPathSize)) {
            header = _dyld_get_image_header(i);
            numMatches = 1;
        }
    }
    if (!header) {
        for (i = 0; i < numImages; i++) {
            curName = _dyld_get_image_name(i);
            if (curName) {
                for (p = buff, q = curName; *p && *q && (q - curName < CFMaxPathSize); p++, q++) {
                    if (*p != *q && (q - curName > 11) && 0 == strncmp(q - 11, ".framework/Versions/", 20) && *(q + 9) && '/' == *(q + 10)) q += 11;
                    else if (*p != *q && (q - curName > 12) && 0 == strncmp(q - 12, ".framework/Versions/", 20) && *(q + 8) && '/' == *(q + 9)) q += 10;
                    if (*p != *q) break;
                }
                if (*p == *q) {
                    header = _dyld_get_image_header(i);
                    numMatches++;
                }
            }
        }
    }
    return (numMatches == 1) ? header : NULL;
}
CF_PRIVATE CFArrayRef _CFBundleDYLDCopyLoadedImagePathsIfChanged(void) {
    // This returns an array of the paths of all the dyld images in the process.  These paths may not be absolute, they may point at things that are not bundles, they may be staticly linked bundles or dynamically loaded bundles, they may be NULL.
    uint32_t i, numImages = _dyld_image_count();
    CFMutableArrayRef result = NULL;
    static uint32_t _cachedDYLDImageCount = -1;

    if (numImages != _cachedDYLDImageCount) {
        const char *curName;
        char *cleanedCurName = NULL;
        CFStringRef curStr;
        const char *processPath = _CFProcessPath();
        const void *mhp = (const void *)_NSGetMachExecuteHeader();

        result = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks);

        for (i = 0; i < numImages; i++) {
            curName = _dyld_get_image_name(i);
            if (curName && i == 0) cleanedCurName = _cleanedPathForPath(curName);
            if (curName && (!processPath || 0 != strcmp(curName, processPath)) && (!processPath || !cleanedCurName || 0 != strcmp(cleanedCurName, processPath)) && mhp != (void *)_dyld_get_image_header(i)) {
                curStr = CFStringCreateWithFileSystemRepresentation(kCFAllocatorSystemDefault, curName);
                if (curStr) {
                    CFArrayAppendValue(result, curStr);
                    CFRelease(curStr);
                }
            }
            if (cleanedCurName) {
                free(cleanedCurName);
                cleanedCurName = NULL;
            }
        }
        _cachedDYLDImageCount = numImages;
    }
    return result;
}
Exemple #4
0
	static const struct mach_header *FindOwnerOfPC(unsigned int pc)
	{
		unsigned int			count,index,offset,cmdex;
		struct segment_command	*seg;
		struct load_command		*cmd;
		const struct mach_header*header;
		
		count = _dyld_image_count();
		for (index = 0;index < count;index += 1)
		{
			header = _dyld_get_image_header(index);
			offset = _dyld_get_image_vmaddr_slide(index);
			cmd = (struct load_command*)((char*)header + sizeof(struct mach_header));
			for (cmdex = 0;cmdex < header->ncmds;cmdex += 1,cmd = (struct load_command*)((char*)cmd + cmd->cmdsize))
			{
				switch(cmd->cmd)
				{
					case LC_SEGMENT:
						seg = (struct segment_command*)cmd;
						if ((pc >= (seg->vmaddr + offset)) && (pc < (seg->vmaddr + offset + seg->vmsize)))
							return header;
						break;
				}
			}
		}
		
		return NULL;
	}
Exemple #5
0
static inline void *getTMCloneTable (const void *f, size_t *tmct_siz)
{
  char *tmct_fixed, *tmct = NULL;
  unsigned int i, img_count; 
  struct mach_header *mh;
  Dl_info info;
  
  if (! dladdr (f, &info) || info.dli_fbase == NULL)
    abort ();
  
  mh = (struct mach_header *) info.dli_fbase;
  tmct_fixed = GET_DATA_TMCT (mh, tmct_siz);
  *tmct_siz /= (sizeof (size_t) * 2);
  /* No tm_clone_table or no clones. */
  if (tmct_fixed == NULL || *tmct_siz == 0)
    return NULL; 

  img_count = _dyld_image_count();
  for (i = 0; i < img_count && tmct == NULL; i++)
    {
      if (mh == _dyld_get_image_header(i))
	tmct = tmct_fixed + (unsigned long)_dyld_get_image_vmaddr_slide(i); 
    }

  return tmct;
}
uint32_t ksdl_imageNamed(const char* const imageName, bool exactMatch)
{
    if(imageName != NULL)
    {
        const uint32_t imageCount = _dyld_image_count();

        for(uint32_t iImg = 0; iImg < imageCount; iImg++)
        {
            const char* name = _dyld_get_image_name(iImg);
            if(exactMatch)
            {
                if(strcmp(name, imageName) == 0)
                {
                    return iImg;
                }
            }
            else
            {
                if(strstr(name, imageName) != NULL)
                {
                    return iImg;
                }
            }
        }
    }
    return UINT32_MAX;
}
static bool isSanitizerEnabled()
{
#if BOS(DARWIN)
    static const char sanitizerPrefix[] = "/libclang_rt.";
    static const char asanName[] = "asan_";
    static const char tsanName[] = "tsan_";
    uint32_t imageCount = _dyld_image_count();
    for (uint32_t i = 0; i < imageCount; ++i) {
        const char* imageName = _dyld_get_image_name(i);
        if (!imageName)
            continue;
        if (const char* s = strstr(imageName, sanitizerPrefix)) {
            const char* sanitizerName = s + sizeof(sanitizerPrefix) - 1;
            if (!strncmp(sanitizerName, asanName, sizeof(asanName) - 1))
                return true;
            if (!strncmp(sanitizerName, tsanName, sizeof(tsanName) - 1))
                return true;
        }
    }
    return false;
#elif BOS(UNIX)
    void* handle = dlopen(nullptr, RTLD_NOW);
    if (!handle)
        return false;
    bool result = !!dlsym(handle, "__asan_init") || !!dlsym(handle, "__tsan_init");
    dlclose(handle);
    return result;
#else
    return false;
#endif
}
void *SubFindSymbol(void *image, const char *name) {
    if (!image) {
        const char *s = "SubFindSymbol: 'any image' specified, which is incredibly slow - like, 2ms on a fast x86.  I'm going to do it since it seems to be somewhat common, but you should be ashamed of yourself.";
        syslog(LOG_WARNING, "%s", s);
        fprintf(stderr, "%s\n", s);
        /* and it isn't thread safe, but neither is MS */
        for(uint32_t i = 0; i < _dyld_image_count(); i++) {
            const char *im_name = _dyld_get_image_name(i);
            struct substitute_image *im = substitute_open_image(im_name);
            if (!im) {
                fprintf(stderr, "(btw, couldn't open %s?)\n", im_name);
                continue;
            }
            void *r = SubFindSymbol(im, name);
            substitute_close_image(im);
            if (r)
                return r;
        }
        return NULL;
    }

    void *ptr;
    if (substitute_find_private_syms(image, &name, &ptr, 1))
        return NULL;
    return ptr;
}
/* Return the image index of the given pointer, or -1 if not found. */
int osx_find_image( const void *p )
{
	unsigned long image_count = _dyld_image_count();

	for( unsigned i = 0; i < image_count; i++ )
	{
		const struct mach_header *header = _dyld_get_image_header(i);
		if( header == NULL )
			continue;

		/* The load commands directly follow the mach_header. */
		const struct load_command *cmd = (struct load_command *) &header[1];

		for( unsigned j = 0; j < header->ncmds; j++ )
		{
			/* We only care about mapped segments. */
			if( cmd->cmd != LC_SEGMENT )
			{
				cmd = next_load_command(cmd);
				continue;
			}

			const segment_command *scmd = (const segment_command *) cmd;

			const unsigned long bottom = scmd->vmaddr + _dyld_get_image_vmaddr_slide( i );
			const unsigned long top = scmd->vmaddr + scmd->vmsize + _dyld_get_image_vmaddr_slide( i );
			if ( (unsigned long) p >= bottom && (unsigned long) p < top )
				return i;

			cmd = next_load_command(cmd);
		}
	}

	return -1;
}
Exemple #10
0
CFStringRef Resources::getResourcesPathFromDyldImage(){
	const mach_header* header;
	header = (mach_header*)&_mh_bundle_header;
	const char* image_name = 0;
	char buffer[PATH_MAX];

	int cnt = _dyld_image_count();
	for (int i = 1; i < cnt; i++)
	{
		if (_dyld_get_image_header((unsigned long)i) == header)
		{
			image_name = _dyld_get_image_name(i);
			break;
		}
	}

	CFURLRef executableURL = CFURLCreateFromFileSystemRepresentation (kCFAllocatorDefault, (const unsigned char*)image_name, strlen (image_name), false);
	CFURLRef bundleContentsMacOSURL = CFURLCreateCopyDeletingLastPathComponent (kCFAllocatorDefault, executableURL);
	CFRelease (executableURL);
    CFURLRef bundleContentsURL = CFURLCreateCopyDeletingLastPathComponent (kCFAllocatorDefault, bundleContentsMacOSURL);
    CFRelease (bundleContentsMacOSURL);
    CFURLRef bundleURL = CFURLCreateCopyDeletingLastPathComponent (kCFAllocatorDefault, bundleContentsURL);
    CFRelease (bundleContentsURL);
    CFBundleRef bundle = CFBundleCreate (kCFAllocatorDefault, bundleURL);
    CFURLRef bundleResourcesURL = CFBundleCopyResourcesDirectoryURL(bundle);
	CFURLGetFileSystemRepresentation(bundleResourcesURL, TRUE, (UInt8*)buffer,PATH_MAX);
	CFStringRef path = CFStringCreateWithCString(NULL,buffer, kCFStringEncodingUTF8);
	return path;
}
Exemple #11
0
// Takes a handle (as returned from dlopen()) and returns the absolute path to the image loaded
JL_DLLEXPORT const char *jl_pathname_for_handle(void *handle)
{
    if (!handle)
        return NULL;

#ifdef __APPLE__
    // Iterate through all images currently in memory
    for (int32_t i = _dyld_image_count() - 1; i >= 0 ; i--) {
        // dlopen() each image, check handle
        const char *image_name = _dyld_get_image_name(i);
        void *probe_lib = jl_load_dynamic_library(image_name, JL_RTLD_DEFAULT);
        jl_dlclose(probe_lib);

        // If the handle is the same as what was passed in (modulo mode bits), return this image name
        if (((intptr_t)handle & (-4)) == ((intptr_t)probe_lib & (-4)))
            return image_name;
    }

#elif defined(_OS_WINDOWS_)

    wchar_t *pth16 = (wchar_t*)malloc(32768); // max long path length
    DWORD n16 = GetModuleFileNameW((HMODULE)handle,pth16,32768);
    if (n16 <= 0) {
        free(pth16);
        return NULL;
    }
    pth16[n16] = L'\0';
    DWORD n8 = WideCharToMultiByte(CP_UTF8, 0, pth16, -1, NULL, 0, NULL, NULL);
    if (n8 == 0) {
        free(pth16);
        return NULL;
    }
    char *filepath = (char*)malloc(++n8);
    if (!WideCharToMultiByte(CP_UTF8, 0, pth16, -1, filepath, n8, NULL, NULL)) {
        free(pth16);
        free(filepath);
        return NULL;
    }
    free(pth16);
    return filepath;

#else // Linux, FreeBSD, ...

    struct link_map *map;
    dlinfo(handle, RTLD_DI_LINKMAP, &map);
#ifdef JL_MSAN_ENABLED
    __msan_unpoison(&map,sizeof(struct link_map*));
    if (map) {
        __msan_unpoison(map, sizeof(struct link_map));
        __msan_unpoison_string(map->l_name);
    }
#endif
    if (map)
        return map->l_name;

#endif
    return NULL;
}
Exemple #12
0
int retrieveAirtunesdIndex() {
    int appLibraryIndex = -1;
    for (int i = 0; i < _dyld_image_count(); ++i) {
        const char *imageName = _dyld_get_image_name(i);
        if (strstr(imageName, "airtunesd")) {
            appLibraryIndex = i;
            break;
        }
    }
    return appLibraryIndex;
}
Exemple #13
0
EXPORT
DWORD GetImageCount()
{
    uint32_t imagecount;
    int i;
    imagecount = _dyld_image_count();
    for (i=0; i < imagecount; i++)
    {
        printf("Image name: %s %x %x\n", _dyld_get_image_name(i), (uint32_t)_dyld_get_image_vmaddr_slide(i), (uint32_t)_dyld_get_image_header(i));
    }
    return imagecount;
}
Exemple #14
0
GSList*
mono_w32process_get_modules (pid_t pid)
{
	GSList *ret = NULL;
	MonoW32ProcessModule *mod;
	guint32 count;
	int i = 0;

	if (pid != getpid ())
		return NULL;

	count = _dyld_image_count ();
	for (i = 0; i < count; i++) {
#if SIZEOF_VOID_P == 8
		const struct mach_header_64 *hdr;
		const struct section_64 *sec;
#else
		const struct mach_header *hdr;
		const struct section *sec;
#endif
		const char *name;

		name = _dyld_get_image_name (i);
#if SIZEOF_VOID_P == 8
		hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
		sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
#else
		hdr = _dyld_get_image_header (i);
		sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
#endif

		/* Some dynlibs do not have data sections on osx (#533893) */
		if (sec == 0)
			continue;

		mod = g_new0 (MonoW32ProcessModule, 1);
		mod->address_start = GINT_TO_POINTER (sec->addr);
		mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
		mod->perms = g_strdup ("r--p");
		mod->address_offset = 0;
		mod->device = makedev (0, 0);
		mod->inode = i;
		mod->filename = g_strdup (name);

		if (g_slist_find_custom (ret, mod, mono_w32process_module_equals) == NULL) {
			ret = g_slist_prepend (ret, mod);
		} else {
			mono_w32process_module_free (mod);
		}
	}

	return g_slist_reverse (ret);
}
Exemple #15
0
int main()
{
// NSCreateObjectFileImageFromMemory is only available on Mac OS X - not iPhone OS
#if __MAC_OS_X_VERSION_MIN_REQUIRED
	NSObjectFileImage ofi;
	if ( NSCreateObjectFileImageFromFile("test.bundle", &ofi) != NSObjectFileImageSuccess ) {
		FAIL("NSCreateObjectFileImageFromFile failed");
		return 1;
	}
	
	// make sure not-yet-linked-ofi is not visible through _dyld_get_image_name
	int count = _dyld_image_count();
	for(int i=0; i < count; ++i) {
	const char* name = _dyld_get_image_name(i);
		if ( strcmp(name, "test.bundle") == 0 ) {
			FAIL("unlinked test.bundle found via _dyld_get_image_name()");
			return 1;
		}
	}

	NSModule mod = NSLinkModule(ofi, "test.bundle", NSLINKMODULE_OPTION_RETURN_ON_ERROR);
	if ( mod != NULL ) {
		FAIL("NSLinkModule succeeded but should have failed");
		return 1;
	}
	
	// make sure link-failed-ofi is not visible through _dyld_get_image_name
	count = _dyld_image_count();
	for(int i=0; i < count; ++i) {
		const char* name = _dyld_get_image_name(i);
		if ( strcmp(name, "test.bundle") == 0 ) {
			FAIL("failed linked test.bundle found via _dyld_get_image_name()");
			return 1;
		}
	}
#endif
	PASS("bundle-unlinkable");
	return 0;
}
Exemple #16
0
	void RegisterAlreadyLoadedClasses()
{
	for (uint32_t i = 0; i < _dyld_image_count(); i++)
	{
		const struct mach_header* hdr = _dyld_get_image_header(i);
		ProcessImageLoad(hdr, 0);
	}

	_dyld_register_func_for_add_image(ProcessImageLoad);
	_dyld_register_func_for_remove_image(ProcessImageUnload);
	
	//std::cout << "Done registering\n";
}
static bool isASanEnabled()
{
#if BOS(DARWIN)
    uint32_t imageCount = _dyld_image_count();
    for (uint32_t i = 0; i < imageCount; ++i) {
        if (strstr(_dyld_get_image_name(i), "/libclang_rt.asan_"))
            return true;
    }
    return false;
#else
    return false;
#endif
}
Exemple #18
0
const void* ksdl_getSymbolAddrInAnyImage(const char* symbolName)
{
    const uint32_t imageCount = _dyld_image_count();

    for(uint32_t iImg = 0; iImg < imageCount; iImg++)
    {
        const void* symbolAddr = ksdl_getSymbolAddrInImage(iImg, symbolName);
        if(symbolAddr != NULL)
        {
            return symbolAddr;
        }
    }
    return NULL;
}
static void MSFindSymbols(MSImageRef image, size_t count, const char *names[], void *values[]) {
    MSSymbolData items[count];

    for (size_t index(0); index != count; ++index) {
        MSSymbolData &item(items[index]);

        item.name_ = names[index];
        item.type_ = 0;
        item.sect_ = 0;
        item.desc_ = 0;
        item.value_ = 0;
    }

    if (image != NULL)
        MSMachONameList_(image, items, count);
    else {
        size_t remain(count);

        for (uint32_t image(0), images(_dyld_image_count()); image != images; ++image) {
            //fprintf(stderr, ":: %s\n", _dyld_get_image_name(image));

            ssize_t result(MSMachONameList_(_dyld_get_image_header(image), items, count));
            if (result == -1)
                continue;

            // XXX: maybe avoid this happening at all? a flag to NSMachONameList_?
            for (size_t index(0); index != count; ++index) {
                MSSymbolData &item(items[index]);
                if (item.name_ == NULL && item.value_ == 0) {
                    ++result;
                    item.name_ = names[index];
                }
            }

            remain -= count - result;
            if (remain == 0)
                break;
        }
    }

    for (size_t index(0); index != count; ++index) {
        MSSymbolData &item(items[index]);
        uintptr_t value(item.value_);
#ifdef __arm__
        if ((item.desc_ & N_ARM_THUMB_DEF) != 0)
            value |= 0x00000001;
#endif
        values[index] = reinterpret_cast<void *>(value);
    }
}
Exemple #20
0
char *config_GetLibDir (void)
{
    /* Get the full program path and name */
    /* First try to see if we are linked to the framework */
    for (unsigned i = 0; i < _dyld_image_count(); i++)
    {
        const char *psz_img_name = _dyld_get_image_name(i);
        const char *p = strstr( psz_img_name, "VLCKit.framework/Versions/" );

        /* Check for "VLCKit.framework/Versions/Current/VLCKit",
         * as well as "VLCKit.framework/Versions/A/VLCKit" and
         * "VLC.framework/Versions/B/VLCKit" */
        if (p != NULL) {
            /* Look for the next forward slash */
            p += 26; /* p_char += strlen(" VLCKit.framework/Versions/" ) */
            p += strcspn( p, "/" );

            /* If the string ends with VLCKit then we've found a winner */
            if (!strcmp( p, "/VLCKit"))
                return strdup( dirname(psz_img_name) );
        }

        /* Do we end by "VLC"? If so we are the legacy VLC.app that doesn't
         * link to VLCKit. */
        size_t len = strlen(psz_img_name);
        if (len >= 3 && !strcmp( psz_img_name + len - 3, "VLC"))
            return strdup( dirname(psz_img_name) );

        /* Do we end by "VLC-Plugin"? oh, we must be the NPAPI plugin */
        if (len >= 10 && !strcmp( psz_img_name + len - 10, "VLC-Plugin"))
            return strdup( dirname(psz_img_name) );
    }

    /* we are not part of any Mac-style package but were installed
     * the UNIX way. let's trick-around a bit */
    Dl_info info;
    if (dladdr(system_Init, &info)) {
        char *incompletepath = strdup(dirname( (char *)info.dli_fname ));
        char *path = NULL;
        asprintf(&path, "%s/"PACKAGE, incompletepath);
        free(incompletepath);
        return path;
    }

    /* should never happen */
    abort ();
}
Exemple #21
0
int rebind_symbols(struct rebinding rebindings[], size_t rebindings_nel) {
  int retval = prepend_rebindings(&_rebindings_head, rebindings, rebindings_nel);
  if (retval < 0) {
    return retval;
  }
  // If this was the first call, register callback for image additions (which is also invoked for
  // existing images, otherwise, just run on existing images
  if (!_rebindings_head->next) {
    _dyld_register_func_for_add_image(_rebind_symbols_for_image);
  } else {
    uint32_t c = _dyld_image_count();
    for (uint32_t i = 0; i < c; i++) {
      _rebind_symbols_for_image(_dyld_get_image_header(i), _dyld_get_image_vmaddr_slide(i));
    }
  }
  return retval;
}
Exemple #22
0
/* Returns the mach_header for the module bu going through all the loaded images
 * and finding the one with the same name as the module. There really ought to be
 * an api for doing this, would be faster, but there isn't one right now
 */
static const struct mach_header *get_mach_header_from_NSModule(NSModule * mod)
{
	const char *mod_name = NSNameOfModule(mod);
	struct mach_header *mh = NULL;
	unsigned long count = _dyld_image_count();
	unsigned long i;
	debug("Module name: %s", mod_name);
	for (i = 0; i < count; i++)
	{
		if (!strcmp(mod_name, _dyld_get_image_name(i)))
		{
			mh = _dyld_get_image_header(i);
			break;
		}
	}
	return mh;
}
Exemple #23
0
std::string get_library_path(ossia::string_view name_part)
{
  std::string s;
  auto num_libs = _dyld_image_count();
  for (unsigned int i = 0; i < num_libs; i++)
  {
    auto path = ossia::string_view(_dyld_get_image_name(i));
    auto pos = path.find(name_part);
    if (pos != std::string::npos)
    {
      auto substr = path.substr(0, pos);
      s = std::string(substr.begin(), substr.end());
      return s;
    }
  }
  return s;
}
Exemple #24
0
/* because this is only used for debugging and error reporting functions, we
 * don't really care about how elegant it is... it could use the load
 * commands to find the install name of the library, but...
 */
static const char *get_lib_name(const struct mach_header *mh)
{
	unsigned long count = _dyld_image_count();
	unsigned long i;
	const char *val = NULL;
	if (mh)
	{
		for (i = 0; i < count; i++)
		{
			if (mh == _dyld_get_image_header(i))
			{
				val = _dyld_get_image_name(i);
				break;
			}
		}
	}
	return val;
}
Exemple #25
0
const char *get_framework_path() {
  int i, c, len;
  const char *s;
  
  c = _dyld_image_count();
  for (i = 0; i < c; i++) {
    s = _dyld_get_image_name(i);
    len = strlen(s);
    if ((len > 7) && !strcmp("/Racket", s + len - 7)) {
      char *s2;
      s2 = strdup(s);
      strcpy(s2 + len - 6, "boot");
      return s2;
    }
  }

  return "???";
}
Exemple #26
0
uint32_t ksdl_imageIndexContainingAddress(const uintptr_t address)
{
    const uint32_t imageCount = _dyld_image_count();
    const struct mach_header* header = 0;

    for(uint32_t iImg = 0; iImg < imageCount; iImg++)
    {
        header = _dyld_get_image_header(iImg);
        if(header != NULL)
        {
            // Look for a segment command with this address within its range.
            uintptr_t addressWSlide = address - (uintptr_t)_dyld_get_image_vmaddr_slide(iImg);
            uintptr_t cmdPtr = ksdl_firstCmdAfterHeader(header);
            if(cmdPtr == 0)
            {
                continue;
            }
            for(uint32_t iCmd = 0; iCmd < header->ncmds; iCmd++)
            {
                const struct load_command* loadCmd = (struct load_command*)cmdPtr;
                if(loadCmd->cmd == LC_SEGMENT)
                {
                    const struct segment_command* segCmd = (struct segment_command*)cmdPtr;
                    if(addressWSlide >= segCmd->vmaddr &&
                       addressWSlide < segCmd->vmaddr + segCmd->vmsize)
                    {
                        return iImg;
                    }
                }
                else if(loadCmd->cmd == LC_SEGMENT_64)
                {
                    const struct segment_command_64* segCmd = (struct segment_command_64*)cmdPtr;
                    if(addressWSlide >= segCmd->vmaddr &&
                       addressWSlide < segCmd->vmaddr + segCmd->vmsize)
                    {
                        return iImg;
                    }
                }
                cmdPtr += loadCmd->cmdsize;
            }
        }
    }
    return UINT_MAX;
}
char *
frida_test_process_backend_filename_of (void * handle)
{
  guint image_count, image_idx;

  g_assert (handle == &frida_magic_self_handle);

  image_count = _dyld_image_count ();
  for (image_idx = 0; image_idx != image_count; image_idx++)
  {
    const gchar * image_path = _dyld_get_image_name (image_idx);

    if (g_str_has_suffix (image_path, "/frida-tests"))
      return g_strdup (image_path);
  }

  g_assert_not_reached ();
  return NULL;
}
Exemple #28
0
/*
 * This routine returns the a pointer to the data for the named section in the
 * named segment if it exist in the named Framework.  Also it returns the size
 * of the section data indirectly through the pointer size.  Otherwise it
 * returns zero for the pointer and the size.  The last component of the path
 * of the Framework is passed as FrameworkName.
 */
void *
getsectdatafromFramework(
    const char *FrameworkName,
    const char *segname,
    const char *sectname,
    unsigned long *size)
{
    uint32_t i, n;
    uintptr_t vmaddr_slide;
#ifndef __LP64__
    struct mach_header *mh;
    const struct section *s;
#else /* defined(__LP64__) */
    struct mach_header_64 *mh;
    const struct section_64 *s;
#endif /* defined(__LP64__) */
    char *name, *p;

    n = _dyld_image_count();
    for(i = 0; i < n ; i++) {
        name = _dyld_get_image_name(i);
        p = strrchr(name, '/');
        if(p != NULL && p[1] != '\0')
            name = p + 1;
        if(strcmp(name, FrameworkName) != 0)
            continue;
        mh = _dyld_get_image_header(i);
        vmaddr_slide = _dyld_get_image_vmaddr_slide(i);
#ifndef __LP64__
        s = getsectbynamefromheader(mh, segname, sectname);
#else /* defined(__LP64__) */
        s = getsectbynamefromheader_64(mh, segname, sectname);
#endif /* defined(__LP64__) */
        if(s == NULL) {
            *size = 0;
            return(NULL);
        }
        *size = s->size;
        return((void *)(s->addr + vmaddr_slide));
    }
    *size = 0;
    return(NULL);
}
static CFStringRef _CFBundleDYLDCopyLoadedImagePathForPointer(void *p) {
    CFStringRef result = NULL;
#if USE_DYLD_PRIV
    const char *name = dyld_image_path_containing_address(p);
    if (name) result = CFStringCreateWithFileSystemRepresentation(kCFAllocatorSystemDefault, name);
#else /* USE_DYLD_PRIV */
    if (!result) {
        uint32_t i, j, n = _dyld_image_count();
        Boolean foundIt = false;
        const char *name;
#if TARGET_RT_64_BIT
#define MACH_HEADER_TYPE struct mach_header_64
#define MACH_SEGMENT_CMD_TYPE struct segment_command_64
#define MACH_SEGMENT_FLAVOR LC_SEGMENT_64
#else
#define MACH_HEADER_TYPE struct mach_header
#define MACH_SEGMENT_CMD_TYPE struct segment_command
#define MACH_SEGMENT_FLAVOR LC_SEGMENT
#endif
        for (i = 0; !foundIt && i < n; i++) {
            const MACH_HEADER_TYPE *mh = (const MACH_HEADER_TYPE *)_dyld_get_image_header(i);
            uintptr_t addr = (uintptr_t)p - _dyld_get_image_vmaddr_slide(i);
            if (mh) {
                struct load_command *lc = (struct load_command *)((char *)mh + sizeof(MACH_HEADER_TYPE));
                for (j = 0; !foundIt && j < mh->ncmds; j++, lc = (struct load_command *)((char *)lc + lc->cmdsize)) {
                    if (MACH_SEGMENT_FLAVOR == lc->cmd && ((MACH_SEGMENT_CMD_TYPE *)lc)->vmaddr <= addr && addr < ((MACH_SEGMENT_CMD_TYPE *)lc)->vmaddr + ((MACH_SEGMENT_CMD_TYPE *)lc)->vmsize) {
                        foundIt = true;
                        name = _dyld_get_image_name(i);
                        if (name) result = CFStringCreateWithFileSystemRepresentation(kCFAllocatorSystemDefault, name);
                    }
                }
            }
        }
#undef MACH_HEADER_TYPE
#undef MACH_SEGMENT_CMD_TYPE
#undef MACH_SEGMENT_FLAVOR
    }
#endif /* USE_DYLD_PRIV */
#if LOG_BUNDLE_LOAD
    printf("dyld image path for pointer %p is %p\n", p, result);
#endif /* LOG_BUNDLE_LOAD */
    return result;
}
DLSyms* dlSymsInit(const char* libPath) 
{
	DLSyms* pSyms = NULL;
	uint32_t iImage, nImages;
	for (iImage = 0, nImages = _dyld_image_count(); iImage < nImages; iImage++)
	{
		const char* name = _dyld_get_image_name(iImage);
		if (name && !strcmp(name, libPath))
		{
			const struct MACH_HEADER_TYPE* pHeader = _dyld_get_image_header(iImage);
			const char* pBase = ((const char*)pHeader);
			if (pHeader->filetype != MH_DYLIB)
				return NULL;
			if (pHeader->flags & MH_SPLIT_SEGS)
				return NULL;

			if (pHeader)
			{
				uint32_t iCmd, nCmds = pHeader->ncmds;
				const struct load_command* cmd = (const struct load_command*)(pBase + sizeof(struct MACH_HEADER_TYPE));
				
				for (iCmd = 0; iCmd < nCmds; iCmd++) 
				{
					if (cmd->cmd == LC_SYMTAB) 
					{
						const struct symtab_command* scmd = (const struct symtab_command*)cmd;
					
						pSyms = (DLSyms*)( dcAllocMem(sizeof(DLSyms)) );
						pSyms->symbolCount = scmd->nsyms;
						pSyms->pStringTable = pBase + scmd->stroff;
						pSyms->pSymbolTable = (struct NLIST_TYPE*)(pBase + scmd->symoff);
						
						return pSyms;
					}
					cmd = (const struct load_command*)(((char*)cmd) + cmd->cmdsize);
				}
			}
			break;
		}
	}
	return NULL;
}