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;
}
Ejemplo n.º 2
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;
}
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;
}
Ejemplo n.º 4
0
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;
}
int32 FApplePlatformStackWalk::GetProcessModuleSignatures(FStackWalkModuleInfo *ModuleSignatures, const int32 ModuleSignaturesSize)
{
	int32 ModuleCount = GetProcessModuleCount();

	int32 SignatureIndex = 0;

	for (int32 ModuleIndex = 0; ModuleIndex < ModuleCount && SignatureIndex < ModuleSignaturesSize; ModuleIndex++)
	{
		const struct mach_header* Header = _dyld_get_image_header(ModuleIndex);
		const ANSICHAR* ImageName = _dyld_get_image_name(ModuleIndex);
		if (Header && ImageName)
		{
			FStackWalkModuleInfo Info;
			Info.BaseOfImage = (uint64)Header;
			FCString::Strcpy(Info.ImageName, ANSI_TO_TCHAR(ImageName));
			Info.ImageSize = GetModuleImageSize( Header );
			FCString::Strcpy(Info.LoadedImageName, ANSI_TO_TCHAR(ImageName));
			FCString::Strcpy(Info.ModuleName, ANSI_TO_TCHAR(ImageName));
			Info.PdbAge = 0;
			Info.PdbSig = 0;
			FMemory::Memzero(&Info.PdbSig70, sizeof(Info.PdbSig70));
			Info.TimeDateStamp = GetModuleTimeStamp( Header );

			ModuleSignatures[SignatureIndex] = Info;
			++SignatureIndex;
		}
	}
	
	return SignatureIndex;
}
Ejemplo n.º 6
0
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;
}
Ejemplo n.º 7
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;
}
Ejemplo n.º 8
0
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
}
Ejemplo n.º 9
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;
}
Ejemplo n.º 10
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;
}
Ejemplo n.º 11
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;
}
Ejemplo n.º 12
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);
}
Ejemplo n.º 13
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;
}
Ejemplo n.º 14
0
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
}
Ejemplo n.º 15
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 ();
}
Ejemplo n.º 16
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;
}
Ejemplo n.º 17
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;
}
Ejemplo n.º 18
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 "???";
}
Ejemplo n.º 19
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;
}
Ejemplo n.º 20
0
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;
}
Ejemplo n.º 21
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);
}
Ejemplo n.º 22
0
DECLHIDDEN(int) rtProcInitExePath(char *pszPath, size_t cchPath)
{
    /*
     * Query the image name from the dynamic linker, convert and return it.
     */
    const char *pszImageName = _dyld_get_image_name(0);
    AssertReturn(pszImageName, VERR_INTERNAL_ERROR);

    char szTmpPath[PATH_MAX + 1];
    const char *psz = realpath(pszImageName, szTmpPath);
    int rc;
    if (psz)
        rc = rtPathFromNativeCopy(pszPath, cchPath, szTmpPath, NULL);
    else
        rc = RTErrConvertFromErrno(errno);
    AssertMsgRCReturn(rc, ("rc=%Rrc pszLink=\"%s\"\nhex: %.*Rhxs\n", rc, pszPath, strlen(pszImageName), pszPath), rc);

    return VINF_SUCCESS;
}
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;
}
Ejemplo n.º 24
0
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;
}
Ejemplo n.º 25
0
extern "C" void CYHandleServer(pid_t pid) {
    Dl_info addr;
    if (dladdr(reinterpret_cast<void *>(&CYHandleServer), &addr) == 0)
        return;

    const char *fname(addr.dli_fname);
    size_t length(strlen(fname));

    const char *target;
#ifdef __APPLE__
    // XXX: THIS IS HORRIBLE OMG I NEED TO FIX THIS ASAP
    bool simulator(false);
    for (uint32_t i(0), e(_dyld_image_count()); i != e; ++i) {
        if (strstr(_dyld_get_image_name(i), "/SDKs/iPhoneSimulator") != NULL)
            simulator = true;
    }
    if (simulator)
        target = "sim";
    else
#endif
    // someone threw a fit about dangling #endif + else
    // the idea that this bothers someone gives me glee
    target = "sys";

    char library[length + 1];
    memcpy(library, fname, length);
    memcpy(library + length - 6 - 3, target, 3);
    library[length] = '\0';

    void *handle(dlopen(library, RTLD_LOCAL | RTLD_LAZY));
    if (handle == NULL) {
        syslog(LOG_ERR, "dlopen() -> %s", dlerror());
        return;
    }

    void *symbol(dlsym(handle, "CYHandleServer"));
    if (symbol == NULL)
        return;

    reinterpret_cast<void (*)(pid_t)>(symbol)(pid);
}
Ejemplo n.º 26
0
/*
 * the image observer allows us to find our injected image
 * and know its base address
 * then it's just a matter of finding the entrypoint and execute it
 */
static void
image_observer(const struct mach_header* mh, intptr_t vmaddr_slide)
{
    static int image_counter = 0;
    char *image_name = (char*)_dyld_get_image_name(image_counter);
    if (image_name == NULL)
    {
        image_counter++;
        return;
    }
    
    image_counter++;
    if (strcmp(image_name, INJECTED_MODULE_NAME) == 0)
    {
        DEBUG_MSG("Found image %s at address %p with slide %p!", image_name, (void*)mh, (void*)vmaddr_slide);
        /* locate the entrypoint of the injected binary */
        uint64_t entrypoint_offset = 0;
        find_entrypoint((void*)mh, &entrypoint_offset);
        
        /* set the function pointer that we use to start the injected code */
        /* NOTE: the prototype assumes no arguments to the injected code! */
        EntryPoint f = (EntryPoint)((char*)mh + entrypoint_offset);
        DEBUG_MSG("Injected binary entrypoint: %p", (void*)f);
        
        if (f == NULL)
        {
            fprintf(stderr, "Could not get address of symbol.\n");
            return;
        }
        /* just launch the injected module by calling the entrypoint*/
        else
        {
            DEBUG_MSG("Executing injected code...");
            f();
            DEBUG_MSG("End of injected code...");
        }
        /* XXX: cleanup */
    }
    return;
}
Ejemplo n.º 27
0
/* There should probably be an apple dyld api for this. */
static const mach_header *
lt__nsmodule_get_header (NSModule module)
{
  int i = _dyld_image_count();
  const char *modname = NSNameOfModule (module);
  const mach_header *mh = 0;

  if (!modname)
    return NULL;

  while (i > 0)
    {
      --i;
      if (strneq (_dyld_get_image_name (i), modname))
	{
	  mh = _dyld_get_image_header (i);
	  break;
	}
    }

  return mh;
}
Ejemplo n.º 28
0
void InitMachOLibrary ()
{
    const mach_header* header = &_mh_bundle_header;
    if (header == 0)
        return;

    const char* imagename = 0;
    /* determine the image name, TODO: ther have to be a better way */
    int cnt = _dyld_image_count();
    for (int idx1 = 1; idx1 < cnt; idx1++)
    {
        if (_dyld_get_image_header(idx1) == header)
        {
            imagename = _dyld_get_image_name(idx1);
            break;
        }
    }
    if (imagename == 0)
        return;
    /* get the bundle of a header, TODO: ther have to be a better way */
    VSTGUI_BUNDLEREF = _CFXBundleCreateFromImageName (NULL, imagename);
}
CF_PRIVATE CFArrayRef _CFBundleDYLDCopyLoadedImagePathsForHint(CFStringRef hint) {
    uint32_t i, numImages = _dyld_image_count();
    CFMutableArrayRef result = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks);
    CFRange range = CFRangeMake(0, CFStringGetLength(hint)), altRange = CFRangeMake(0, 0), testRange = CFRangeMake(0, 0);
    const char *processPath = _CFProcessPath();
    const void *mhp = (const void *)_NSGetMachExecuteHeader();
    
    if (range.length > 14) {
        // handle some common variations on framework bundle identifiers
        if (CFStringFindWithOptions(hint, CFSTR(".framework"), range, kCFCompareAnchored|kCFCompareBackwards|kCFCompareCaseInsensitive, &testRange) && testRange.location > 0 && testRange.length > 0) {
            // identifier has .framework appended
            altRange.length = testRange.location;
        } else if (CFStringFindWithOptions(hint, CFSTR("framework"), range, kCFCompareAnchored|kCFCompareBackwards|kCFCompareCaseInsensitive, &testRange) && testRange.location > 0 && testRange.length > 0) {
            // identifier has Framework appended
            altRange.length = testRange.location;
        } else if (CFStringFindWithOptions(hint, CFSTR("fw"), range, kCFCompareAnchored|kCFCompareBackwards|kCFCompareCaseInsensitive, &testRange) && testRange.location > 0 && testRange.length > 0) {
            // identifier has FW appended
            altRange.length = testRange.location;
        }
    }
    for (i = 0; i < numImages; i++) {
        const char *curName = _dyld_get_image_name(i), *lastComponent = NULL;
        if (curName && (!processPath || 0 != strcmp(curName, processPath)) && mhp != (void *)_dyld_get_image_header(i)) lastComponent = strrchr(curName, '/');
        if (lastComponent) {
            CFStringRef str = CFStringCreateWithFileSystemRepresentation(kCFAllocatorSystemDefault, lastComponent + 1);
            if (str) {
                if (CFStringFindWithOptions(hint, str, range, kCFCompareAnchored|kCFCompareBackwards|kCFCompareCaseInsensitive, NULL) || (altRange.length > 0 && CFStringFindWithOptions(hint, str, altRange, kCFCompareAnchored|kCFCompareBackwards|kCFCompareCaseInsensitive, NULL))) {
                    CFStringRef curStr = CFStringCreateWithFileSystemRepresentation(kCFAllocatorSystemDefault, curName);
                    if (curStr) {
                        CFArrayAppendValue(result, curStr);
                        CFRelease(curStr);
                    }
                }
                CFRelease(str);
            }
        }
    }
    return result;
}
Ejemplo n.º 30
0
static const struct mach_header *my_find_image(const char *name)
{
	const struct mach_header *mh = 0;
	const char *id = NULL;
	int i = _dyld_image_count();
	int j;
	mh = (struct mach_header *)
		dyld_NSAddImage(name, NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED |
						NSADDIMAGE_OPTION_RETURN_ON_ERROR);
	if (!mh)
	{
		for (j = 0; j < i; j++)
		{
			id = _dyld_get_image_name(j);
			if (!strcmp(id, name))
			{
				mh = _dyld_get_image_header(j);
				break;
			}
		}
	}
	return mh;
}