Ejemplo n.º 1
0
static CFBundleRef _CFXBundleCreateFromImageName (CFAllocatorRef allocator, const char* image_name)
{
    CFURLRef myBundleExecutableURL = CFURLCreateFromFileSystemRepresentation (allocator, (const unsigned char*)image_name, strlen (image_name), false);
    if (myBundleExecutableURL == 0)
        return 0;

    CFURLRef myBundleContentsMacOSURL = CFURLCreateCopyDeletingLastPathComponent (allocator, myBundleExecutableURL); // Delete Versions/Current/Executable
    CFRelease (myBundleExecutableURL);
    if (myBundleContentsMacOSURL == 0)
        return 0;

    CFURLRef myBundleContentsURL = CFURLCreateCopyDeletingLastPathComponent (allocator, myBundleContentsMacOSURL); // Delete Current
    CFRelease (myBundleContentsMacOSURL);
    if (myBundleContentsURL == 0)
        return 0;

    CFURLRef theBundleURL = CFURLCreateCopyDeletingLastPathComponent (allocator, myBundleContentsURL); // Delete Versions
    CFRelease (myBundleContentsURL);
    if (theBundleURL == 0)
        return 0;

    CFBundleRef result = CFBundleCreate (allocator, theBundleURL);
    CFRelease (theBundleURL);

    return result;
}
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;
}
Ejemplo n.º 3
0
char* SDMDaodanFindTargetBundleIdentifier(char *targetPath) {
	CFStringRef targetExecutablePath = CFStringCreateWithCString(kCFAllocatorDefault, targetPath, kCFStringEncodingUTF8);
	CFURLRef executableURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, targetExecutablePath, kCFURLPOSIXPathStyle, false);
	CFRelease(targetExecutablePath);
	CFURLRef macOSURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, executableURL);
	CFURLRef contentsURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, macOSURL);
	CFRelease(macOSURL);
	CFURLRef appURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, contentsURL);
	CFRelease(contentsURL);
	CFArrayRef bundles = CFBundleCreateBundlesFromDirectory(kCFAllocatorDefault, appURL, NULL);
	CFRelease(appURL);
	CFStringRef targetIdentifier = NULL;
	for (uint32_t i = 0x0; i < CFArrayGetCount(bundles); i++) {
		CFBundleRef bundleItem = (CFBundleRef)CFArrayGetValueAtIndex(bundles, i);
		targetIdentifier = CFBundleGetIdentifier(bundleItem);
		if (targetIdentifier) {
			break;
		}
	}
	CFRelease(bundles);
	char *bundle;
	if (!targetIdentifier) {
		CFStringRef executableIdentifier = CFURLCopyLastPathComponent(executableURL);
		bundle = SDMCFStringGetString(executableIdentifier);
		CFRelease(executableIdentifier);
	} else {
		bundle = SDMCFStringGetString(targetIdentifier);
	}
	CFRelease(executableURL);
	return bundle;
}
Ejemplo n.º 4
0
void write_gdb_prep_cmds(AMDeviceRef device, CFURLRef disk_app_url) {
    CFMutableStringRef cmds = CFStringCreateMutableCopy(NULL, 0, GDB_PREP_CMDS);
    CFRange range = { 0, CFStringGetLength(cmds) };

    CFStringRef ds_path = copy_device_support_path(device);
    CFStringFindAndReplace(cmds, CFSTR("{ds_path}"), ds_path, range, 0);
    range.length = CFStringGetLength(cmds);

    if (args) {
        CFStringRef cf_args = CFStringCreateWithCString(NULL, args, kCFStringEncodingASCII);
        CFStringFindAndReplace(cmds, CFSTR("{args}"), cf_args, range, 0);
        CFRelease(cf_args);
    } else {
        CFStringFindAndReplace(cmds, CFSTR(" {args}"), CFSTR(""), range, 0);
    }
    range.length = CFStringGetLength(cmds);

    CFStringRef bundle_identifier = copy_disk_app_identifier(disk_app_url);
    CFURLRef device_app_url = copy_device_app_url(device, bundle_identifier);
    CFStringRef device_app_path = CFURLCopyFileSystemPath(device_app_url, kCFURLPOSIXPathStyle);
    CFStringFindAndReplace(cmds, CFSTR("{device_app}"), device_app_path, range, 0);
    range.length = CFStringGetLength(cmds);

    CFStringRef disk_app_path = CFURLCopyFileSystemPath(disk_app_url, kCFURLPOSIXPathStyle);
    CFStringFindAndReplace(cmds, CFSTR("{disk_app}"), disk_app_path, range, 0);
    range.length = CFStringGetLength(cmds);

    CFURLRef device_container_url = CFURLCreateCopyDeletingLastPathComponent(NULL, device_app_url);
    CFStringRef device_container_path = CFURLCopyFileSystemPath(device_container_url, kCFURLPOSIXPathStyle);
    CFMutableStringRef dcp_noprivate = CFStringCreateMutableCopy(NULL, 0, device_container_path);
    range.length = CFStringGetLength(dcp_noprivate);
    CFStringFindAndReplace(dcp_noprivate, CFSTR("/private/var/"), CFSTR("/var/"), range, 0);
    range.length = CFStringGetLength(cmds);
    CFStringFindAndReplace(cmds, CFSTR("{device_container}"), dcp_noprivate, range, 0);
    range.length = CFStringGetLength(cmds);

    CFURLRef disk_container_url = CFURLCreateCopyDeletingLastPathComponent(NULL, disk_app_url);
    CFStringRef disk_container_path = CFURLCopyFileSystemPath(disk_container_url, kCFURLPOSIXPathStyle);
    CFStringFindAndReplace(cmds, CFSTR("{disk_container}"), disk_container_path, range, 0);

    CFDataRef cmds_data = CFStringCreateExternalRepresentation(NULL, cmds, kCFStringEncodingASCII, 0);
    FILE *out = fopen(PREP_CMDS_PATH, "w");
    fwrite(CFDataGetBytePtr(cmds_data), CFDataGetLength(cmds_data), 1, out);
    fclose(out);

    CFRelease(cmds);
    if (ds_path != NULL) CFRelease(ds_path);
    CFRelease(bundle_identifier);
    CFRelease(device_app_url);
    CFRelease(device_app_path);
    CFRelease(disk_app_path);
    CFRelease(device_container_url);
    CFRelease(device_container_path);
    CFRelease(dcp_noprivate);
    CFRelease(disk_container_url);
    CFRelease(disk_container_path);
    CFRelease(cmds_data);
}
Ejemplo n.º 5
0
bool wxApp::Initialize(int& argc, wxChar **argv)
{
    // Mac-specific

#if wxDEBUG_LEVEL && wxOSX_USE_COCOA_OR_CARBON
    InstallDebugAssertOutputHandler( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler ) );
#endif

    /*
     Cocoa supports -Key value options which set the user defaults key "Key"
     to the value "value"  Some of them are very handy for debugging like
     -NSShowAllViews YES.  Cocoa picks these up from the real argv so
     our removal of them from the wx copy of it does not affect Cocoa's
     ability to see them.
     
     We basically just assume that any "-NS" option and its following
     argument needs to be removed from argv.  We hope that user code does
     not expect to see -NS options and indeed it's probably a safe bet
     since most user code accepting options is probably using the
     double-dash GNU-style syntax.
     */
    for(int i=1; i < argc; ++i)
    {
        static const wxChar *ARG_NS = wxT("-NS");
        if( wxStrncmp(argv[i], ARG_NS, wxStrlen(ARG_NS)) == 0 )
        {
            // Only eat this option if it has an argument
            if( (i + 1) < argc )
            {
                memmove(argv + i, argv + i + 2, (argc-i-1)*sizeof(wxChar*));
                argc -= 2;
                // drop back one position so the next run through the loop
                // reprocesses the argument at our current index.
                --i;
            }
        }
    }

    if ( !wxAppBase::Initialize(argc, argv) )
        return false;

#if wxUSE_INTL
    wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
#endif

    // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
    wxString startupCwd = wxGetCwd() ;
    if ( startupCwd == wxT("/") || startupCwd.Right(15) == wxT("/Contents/MacOS") )
    {
        CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
        CFURLRef urlParent = CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault , url ) ;
        CFRelease( url ) ;
        CFStringRef path = CFURLCopyFileSystemPath ( urlParent , kCFURLPOSIXPathStyle ) ;
        CFRelease( urlParent ) ;
        wxString cwd = wxCFStringRef(path).AsString(wxLocale::GetSystemEncoding());
        wxSetWorkingDirectory( cwd ) ;
    }

    return true;
}
Ejemplo n.º 6
0
OSStatus	PosixPathToParentFSRefAndName(const char *path, FSRef &outParentDir, CFStringRef &outFileName)
{
	// convert C string to CFString
#if !TARGET_OS_WIN32
	CFStringRef cfFullPath = CFStringCreateWithCString(NULL, path, kCFStringEncodingUTF8);
#else
	CFStringRef cfFullPath = CFStringCreateWithCString(NULL, path, kCFStringEncodingWindowsLatin1);
#endif
	// convert CF string to URL
	CFURLRef fullurl = CFURLCreateWithFileSystemPath(NULL, cfFullPath, TARGET_OS_WIN32 ? kCFURLWindowsPathStyle : kCFURLPOSIXPathStyle, false);
	CFRelease(cfFullPath);
	// get the directory portion of the URL
	CFURLRef dirurl = CFURLCreateCopyDeletingLastPathComponent(NULL, fullurl);
	// get the directory's FSSpec
	OSStatus err = CFURLGetFSRef(dirurl, &outParentDir) ? OSStatus(noErr) : OSStatus(fnfErr);
	CFRelease(dirurl);
	
	CFStringRef lastPathComponent = CFURLCopyLastPathComponent(fullurl);
	CFRelease(fullurl);
	CFMutableStringRef filename = CFStringCreateMutableCopy(NULL, 0, lastPathComponent);
	CFRelease(lastPathComponent);
	// convert colons (legal in POSIX paths, illegal in File Manager) to slashes
	CFStringFindAndReplace(filename, CFSTR(":"), CFSTR("/"), CFRangeMake(0, CFStringGetLength(filename)), 0);
	
	outFileName = filename;
	
	return err;
}
// Asssumes caller already knows the directory doesn't exist.
static Boolean _createDirectory(CFURLRef dirURL, Boolean worldReadable) {
    CFAllocatorRef alloc = __CFPreferencesAllocator();
    CFURLRef parentURL = CFURLCreateCopyDeletingLastPathComponent(alloc, dirURL);
    CFBooleanRef val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, parentURL, kCFURLFileExists, NULL);
    Boolean parentExists = (val && CFBooleanGetValue(val));
    SInt32 mode;
    Boolean result;
    if (val) CFRelease(val);
    if (!parentExists) {
        CFStringRef path = CFURLCopyPath(parentURL);
        if (!CFEqual(path, CFSTR("/"))) {
            _createDirectory(parentURL, worldReadable);
            val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, parentURL, kCFURLFileExists, NULL);
            parentExists = (val && CFBooleanGetValue(val));
            if (val) CFRelease(val);
        }
        CFRelease(path);
    }
    if (parentURL) CFRelease(parentURL);
    if (!parentExists) return false;

#if TARGET_OS_OSX || TARGET_OS_LINUX
    mode = worldReadable ? S_IRWXU|S_IRWXG|S_IROTH|S_IXOTH : S_IRWXU;
#else
    mode = 0666;
#endif

    result = CFURLWriteDataAndPropertiesToResource(dirURL, (CFDataRef)dirURL, URLPropertyDictForPOSIXMode(mode), NULL);
    URLPropertyDictRelease();
    return result;
}
void TestController::initializeInjectedBundlePath()
{
    CFStringRef exeContainerPath = CFURLCopyFileSystemPath(CFURLCreateCopyDeletingLastPathComponent(0, CFBundleCopyExecutableURL(CFBundleGetMainBundle())), kCFURLWindowsPathStyle);
    CFMutableStringRef bundlePath = CFStringCreateMutableCopy(0, 0, exeContainerPath);
    CFStringAppendCString(bundlePath, injectedBundleDLL, kCFStringEncodingWindowsLatin1);
    m_injectedBundlePath.adopt(WKStringCreateWithCFString(bundlePath));
}
Ejemplo n.º 9
0
bool getExePath(char *respath)
{
  CFBundleRef appBundle = CFBundleGetMainBundle();
  if (!appBundle)
    return false;

  CFURLRef url = CFBundleCopyExecutableURL(appBundle);
  if (!url)
    return false;
  CFURLRef absurl = nullptr;
  // CFURLRef url2 = url;
  CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(NULL, url);
  CFRelease(url);

  absurl = CFURLCopyAbsoluteURL(url2);
  CFRelease(url2);
  
  char tbuffer[MAXPATHLEN];
  
  CFURLGetFileSystemRepresentation(absurl, true,
				   (UInt8*) tbuffer,
				   sizeof(tbuffer));
  printf("abs exec url = %s\n", tbuffer);
  CFRelease(absurl);

  snprintf(respath, MAXPATHLEN, "%s/XUL", tbuffer);
  return true;
}
Ejemplo n.º 10
0
static OSStatus FindSNESFolder (FSRef *folderRef, char *folderPath, const char *folderName)
{
	OSStatus	err;
	CFURLRef	burl, purl;
	CFStringRef	fstr;
	FSRef		pref;
	UniChar		buffer[PATH_MAX + 1];
	Boolean		r;

	fstr = CFStringCreateWithCString(kCFAllocatorDefault, folderName, CFStringGetSystemEncoding());
	CFStringGetCharacters(fstr, CFRangeMake(0, CFStringGetLength(fstr)), buffer);

	burl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
	purl = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, burl);
	r    = CFURLGetFSRef(purl, &pref);

	err = FSMakeFSRefUnicode(&pref, CFStringGetLength(fstr), buffer, kTextEncodingUnicodeDefault, folderRef);
	if (err == dirNFErr || err == fnfErr)
	{
		err = FSCreateDirectoryUnicode(&pref, CFStringGetLength(fstr), buffer, kFSCatInfoNone, NULL, folderRef, NULL, NULL);
		if (err == noErr)
			AddFolderIcon(folderRef, folderName);
	}

	if (err == noErr)
		err = FSRefMakePath(folderRef, (unsigned char *) folderPath, PATH_MAX);

	CFRelease(purl);
	CFRelease(burl);
	CFRelease(fstr);

	return (err);
}
Ejemplo n.º 11
0
/********************************************************************
*	 MoveFile
*		 lpFromFileName: old file path
*		 lpToFileName: new file path
********************************************************************/
BOOL MoveFile(const char * lpFromFileName, const char * lpToFileName)
{
	OSErr theErr;
	FSRef fromFileRef;
	FSRef toFileRef;
	FSRef parentFolderRef;
	
	// Get the path to the old file
	theErr = FSPathMakeRef((const UInt8 *)lpFromFileName, &fromFileRef, NULL);
	if (theErr != noErr)
	{
		SetLastError(theErr);
		return false;
	}
	
	// Get the path to the new folder for the file
	char folderName[strlen(lpToFileName)];
	CFStringRef folderPathCFString = CFStringCreateWithCString(NULL, lpToFileName, kCFStringEncodingUTF8);
	CFURLRef fileURL = CFURLCreateWithFileSystemPath(NULL, folderPathCFString, kCFURLPOSIXPathStyle, FALSE);
	CFURLRef folderURL = CFURLCreateCopyDeletingLastPathComponent(NULL, fileURL);
	CFURLGetFileSystemRepresentation(folderURL, TRUE, (UInt8 *)folderName, strlen(lpToFileName));
	theErr = FSPathMakeRef((UInt8 *)folderName, &parentFolderRef, NULL);
	CFRelease(fileURL);
	CFRelease(folderURL);
	CFRelease(folderPathCFString);
	
	// Move the old file
	theErr = FSMoveObject(&fromFileRef, &parentFolderRef, &toFileRef);
	if (theErr != noErr)
	{
		SetLastError(theErr);
		return false;
	}
	
	// Get a CFString for the new file name
	CFStringRef newFileNameCFString = CFStringCreateWithCString(NULL, lpToFileName, kCFStringEncodingUTF8);
	fileURL = CFURLCreateWithFileSystemPath(NULL, newFileNameCFString, kCFURLPOSIXPathStyle, FALSE);
	CFRelease(newFileNameCFString);
	newFileNameCFString = CFURLCopyLastPathComponent(fileURL);
	CFRelease(fileURL);
	
	// Convert CFString to Unicode and rename the file
	UniChar unicodeFileName[256];
	CFStringGetCharacters(newFileNameCFString, CFRangeMake(0, CFStringGetLength(newFileNameCFString)), 
						  unicodeFileName);
	theErr = FSRenameUnicode(&toFileRef, CFStringGetLength(newFileNameCFString), unicodeFileName, 
							 kTextEncodingUnknown, NULL);
	if (theErr != noErr)
	{
		SetLastError(theErr);
		CFRelease(newFileNameCFString);
		return false;
	}
	
	CFRelease(newFileNameCFString);
	
	SetLastError(theErr);
	return true;
}
void TestController::initializeTestPluginDirectory()
{
    RetainPtr<CFURLRef> bundleURL = adoptCF(CFBundleCopyExecutableURL(CFBundleGetMainBundle()));
    RetainPtr<CFURLRef> bundleDirectoryURL = adoptCF(CFURLCreateCopyDeletingLastPathComponent(0, bundleURL.get()));
    RetainPtr<CFStringRef> testPluginDirectoryNameString = adoptCF(CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar*>(testPluginDirectoryName), wcslen(testPluginDirectoryName)));
    RetainPtr<CFURLRef> testPluginDirectoryURL = adoptCF(CFURLCreateCopyAppendingPathComponent(0, bundleDirectoryURL.get(), testPluginDirectoryNameString.get(), true));
    RetainPtr<CFStringRef> testPluginDirectoryPath = adoptCF(CFURLCopyFileSystemPath(testPluginDirectoryURL.get(), kCFURLWindowsPathStyle));
    m_testPluginDirectory.adopt(WKStringCreateWithCFString(testPluginDirectoryPath.get()));
}
int dir_Create(char *pathString, int pathStringLength) {
	/* Create a new directory with the given path. By default, this
	   directory is created in the current directory. Use
	   a full path name such as "MyDisk:Working:New Folder" to
	   create folders elsewhere. */

    char cFileName[1001];

    if (pathStringLength >= 1000) {
        return false;
    }

    /* copy the file name into a null-terminated C string */
    sqFilenameFromString((char *) cFileName, (int) pathString, pathStringLength);
    
#if defined(__MWERKS__)
	{
        CFStringRef 	filePath,lastFilePath;
        CFURLRef 	    sillyThing,sillyThing2;
        FSRef	        parentFSRef;
        UniChar         buffer[1024];
        long            tokenLength;
		int err;
        
        filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *)cFileName,strlen(cFileName),gCurrentVMEncoding,false);
        if (filePath == nil) 
            return false;
        sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,filePath,kCFURLHFSPathStyle,true);
        CFRelease(filePath);

        lastFilePath = CFURLCopyLastPathComponent(sillyThing);
        tokenLength = CFStringGetLength(lastFilePath);
        if (tokenLength > 1024)
            return false;
        CFStringGetCharacters(lastFilePath,CFRangeMake(0,tokenLength),buffer);
        CFRelease(lastFilePath);

        sillyThing2 = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault,sillyThing);

        err = CFURLGetFSRef(sillyThing2,&parentFSRef);
        CFRelease(sillyThing);
        CFRelease(sillyThing2);
        if (err == 0) {
            return false;  
        }
		err = FSCreateDirectoryUnicode(&parentFSRef,tokenLength,buffer,kFSCatInfoNone,NULL,NULL,NULL,NULL);
		
    	return (err == noErr ? 1 : 0);
    }
#else
    return mkdir(cFileName, 0777) == 0;
#endif
}
Ejemplo n.º 14
0
sdmmd_return_t SDMMD_AMDeviceSecureInstallApplication(SDMMD_AMConnectionRef conn, SDMMD_AMDeviceRef device, CFURLRef path, CFDictionaryRef options, CallBack installCallback, void *unknown)
{
	sdmmd_return_t result = kAMDSuccess;
	SDMMD_AMConnectionRef connection = NULL;
	bool hasConnection = (conn ? true : false);
	if (device) {
		result = SDMMD_AMDeviceSecureStartService(device, CFSTR(AMSVC_INSTALLATION_PROXY), NULL, &connection);
		if (result == 0) {
			hasConnection = true;
		}
		else {
			printf("%s: Was unable to start the install service on the device 0x%x.\n", __FUNCTION__, result);
		}
	}
	if (hasConnection) {
		CFStringRef lastComp = CFURLCopyLastPathComponent(path);
		if (CFStringGetLength(lastComp) == 0) {
			CFSafeRelease(lastComp);
			CFURLRef pathURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, path);
			lastComp = CFURLCopyLastPathComponent(pathURL);
			CFSafeRelease(pathURL);
		}
		if (lastComp) {
			CFStringRef format = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("PublicStaging/%@"), lastComp);
			if (format) {
				char *appName = SDMCFStringGetString(format);
				printf("%s: Attempting install of %s.\n", __FUNCTION__, appName);
				result = SDMMD_perform_command(connection, CFSTR("Install"), 0, installCallback, 4, unknown, CFSTR("PackagePath"), format, CFSTR("ClientOptions"), options);
				if (result) {
					printf("%s: Old style of install failed for (%s).\n", __FUNCTION__, appName);
				}
				Safe(free, appName);
			}
			else {
				printf("%s: Unable to create CFString!\n", __FUNCTION__);
			}
			CFSafeRelease(format);
		}
		else {
			char *lastCompString = SDMCFStringGetString(lastComp);
			printf("%s: Could not copy last path component from url %s.\n", __FUNCTION__, lastCompString);
			Safe(free, lastCompString);
		}
		CFSafeRelease(lastComp);
	}
	CFSafeRelease(connection);
	char *pathString = SDMCFURLGetString(path);
	printf("%s: Installation of package %s returned 0x%x.\n", __FUNCTION__, pathString, result);
	Safe(free, pathString);
	return result;
}
// Windows user assets path
void GetWorkingFileName (const char* const name, char* const outPathName)
{
#ifdef _MSC_VER
	char path[256]; 
	GetModuleFileNameA(NULL, path, 256);

	char* ptr = strstr (path, "newtonDemos");
	ptr [0] = 0;
	sprintf (outPathName, "%smedia/%s", path, name);
#endif


#ifdef _MAC_VER
	//strcpy(outPathName, "/Users/admin_user/Developer/NGD/svn (trunk)/applications/media/");
	//strcat(outPathName, name);
	
	CFURLRef appURL = CFBundleCopyBundleURL( CFBundleGetMainBundle() ); 
	CFURLRef appDirURL = CFURLCreateCopyDeletingLastPathComponent( NULL, appURL); 
	CFStringRef fileName = CFStringCreateWithCString( NULL, name, kCFStringEncodingUTF8 ); 
	CFURLRef fileURL = CFURLCreateCopyAppendingPathComponent( NULL, appDirURL, fileName, false ); 
	CFStringRef filePath = CFURLCopyFileSystemPath( fileURL, kCFURLPOSIXPathStyle ); 
	CFStringGetCString (filePath, outPathName, PATH_MAX, kCFStringEncodingUTF8); 
	
	char* const ptr = strstr (outPathName, "applications");
	sprintf (ptr, "applications/media/%s", name);

	// Clean up 
	CFRelease( appURL ); 
	CFRelease( appDirURL ); 
	CFRelease( fileName ); 
	CFRelease( fileURL ); 
	CFRelease( filePath );
	
#endif

#ifdef _LINUX_VER
	char id[2048];
	char path[2048];

	sprintf(id, "/proc/%d/exe", getpid());
	memset (path, 0, sizeof (path));
	readlink(id, path, 1024);
	char* const end = strstr (path, "/applications");
	*end = 0;
	sprintf (outPathName, "%s/applications/media/%s", path, name);
#endif
}
Ejemplo n.º 16
0
// taken from a post from http://www.gamedev.net/topic/459511-something-like-getmodulefilename-in-linux/
std::string GetProgramDir(void)
{
#if PLATFORM == PLATFORM_WIN32
    char szPath[1024];
    uint32 len = GetModuleFileName( NULL, szPath, 1024 );
    if(!len)
        return "";
    std::string path(szPath);
    std::string::size_type t = path.find_last_of("/\\");
    path = path.substr(0,t);
    _FixFileName(path);
    return path;

#elif PLATFORM == PLATFORM_UNIX

    std::stringstream ss;
    ss << "/proc/" << getpid() << "/exe";
    char proc[1024];
    int ch = readlink(ss.str().c_str(), proc, 1024);
    std::string path;
    if (ch != -1)
    {
        proc[ch] = 0;
        path = proc;
        std::string::size_type t = path.find_last_of("/");
        path = path.substr(0,t);
    }
    return path;

#elif PLATFORM == PLATFORM_APPLE

    char parentdir[MAXPATHLEN];
    std::string path;
    CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
    CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url);
    if (CFURLGetFileSystemRepresentation(url2, 1, (UInt8 *)parentdir, MAXPATHLEN))
    {
        path = parentdir;   /* chdir to the binary app's parent */
    }
    CFRelease(url);
    CFRelease(url2);
    return path;

#endif
}
Ejemplo n.º 17
0
bool wxApp::Initialize(int& argc, wxChar **argv)
{
    // Mac-specific

#if wxDEBUG_LEVEL && wxOSX_USE_COCOA_OR_CARBON
    InstallDebugAssertOutputHandler( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler ) );
#endif

    // Mac OS X passes a process serial number command line argument when
    // the application is launched from the Finder. This argument must be
    // removed from the command line arguments before being handled by the
    // application (otherwise applications would need to handle it)
    if ( argc > 1 )
    {
        static const wxChar *ARG_PSN = wxT("-psn_");
        if ( wxStrncmp(argv[1], ARG_PSN, wxStrlen(ARG_PSN)) == 0 )
        {
            // remove this argument
            --argc;
            memmove(argv + 1, argv + 2, argc * sizeof(char *));
        }
    }

    if ( !wxAppBase::Initialize(argc, argv) )
        return false;

#if wxUSE_INTL
    wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
#endif

    // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
    wxString startupCwd = wxGetCwd() ;
    if ( startupCwd == wxT("/") || startupCwd.Right(15) == wxT("/Contents/MacOS") )
    {
        CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
        CFURLRef urlParent = CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault , url ) ;
        CFRelease( url ) ;
        CFStringRef path = CFURLCopyFileSystemPath ( urlParent , kCFURLPOSIXPathStyle ) ;
        CFRelease( urlParent ) ;
        wxString cwd = wxCFStringRef(path).AsString(wxLocale::GetSystemEncoding());
        wxSetWorkingDirectory( cwd ) ;
    }

    return true;
}
Ejemplo n.º 18
0
 void URL::DeleteLastPathComponent( void )
 {
     CFURLRef url;
     
     if( this->_cfObject == NULL )
     {
         return;
     }
     
     url             = this->_cfObject;
     this->_cfObject = CFURLCreateCopyDeletingLastPathComponent
     (
         static_cast< CFAllocatorRef >( NULL ),
         url
     );
     
     CFRelease( url );
 }
Ejemplo n.º 19
0
std::string GetBinaryPath()
{
#ifdef linux
	char file[256];
	const int ret = readlink("/proc/self/exe", file, 255);
	if (ret >= 0)
	{
		file[ret] = '\0';
		std::string path(file);
		return path.substr(0, path.find_last_of('/'));
	}
	else
		return "";

#elif WIN32
	TCHAR currentDir[MAX_PATH+1];
	int ret = ::GetModuleFileName(0, currentDir, sizeof(currentDir));
	if (ret == 0 || ret == sizeof(currentDir))
		return "";
	char drive[MAX_PATH], dir[MAX_PATH], file[MAX_PATH], ext[MAX_PATH];
	_splitpath(currentDir, drive, dir, file, ext);
	_makepath(currentDir, drive, dir, NULL, NULL);
	return std::string(currentDir);

#elif MACOSX_BUNDLE
	char cPath[1024];
	CFBundleRef mainBundle = CFBundleGetMainBundle();
	
	CFURLRef mainBundleURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault , CFBundleCopyBundleURL(mainBundle));
	
	CFStringRef cfStringRef = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
	
	CFStringGetCString(cfStringRef, cPath, 1024, kCFStringEncodingASCII);
	
	CFRelease(mainBundleURL);
	CFRelease(cfStringRef);
	
	return std::string(cPath);

#else
	return "";

#endif
}
Ejemplo n.º 20
0
static CFBundleRef createWebKitBundle()
{
    if (CFBundleRef existingBundle = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.WebKit"))) {
        CFRetain(existingBundle);
        return existingBundle;
    }

    wchar_t dllPathBuffer[MAX_PATH];
    DWORD length = ::GetModuleFileNameW(instanceHandle(), dllPathBuffer, WTF_ARRAY_LENGTH(dllPathBuffer));
    ASSERT(length);
    ASSERT(length < WTF_ARRAY_LENGTH(dllPathBuffer));

    RetainPtr<CFStringRef> dllPath(AdoptCF, CFStringCreateWithCharactersNoCopy(0, reinterpret_cast<const UniChar*>(dllPathBuffer), length, kCFAllocatorNull));
    RetainPtr<CFURLRef> dllURL(AdoptCF, CFURLCreateWithFileSystemPath(0, dllPath.get(), kCFURLWindowsPathStyle, false));
    RetainPtr<CFURLRef> dllDirectoryURL(AdoptCF, CFURLCreateCopyDeletingLastPathComponent(0, dllURL.get()));
    RetainPtr<CFURLRef> resourcesDirectoryURL(AdoptCF, CFURLCreateCopyAppendingPathComponent(0, dllDirectoryURL.get(), CFSTR("WebKit.resources"), true));

    return CFBundleCreate(0, resourcesDirectoryURL.get());
}
Ejemplo n.º 21
0
std::string GetBinaryPath()
{
#ifdef linux
	std::string path(GetBinaryFile());
	size_t pathlength = path.find_last_of('/');
	if (pathlength != std::string::npos)
		return path.substr(0, pathlength);
	else
		return path;

#elif WIN32
	TCHAR currentDir[MAX_PATH+1];
	int ret = ::GetModuleFileName(0, currentDir, sizeof(currentDir));
	if (ret == 0 || ret == sizeof(currentDir))
		return "";
	char drive[MAX_PATH], dir[MAX_PATH], file[MAX_PATH], ext[MAX_PATH];
	_splitpath(currentDir, drive, dir, file, ext);
	_makepath(currentDir, drive, dir, NULL, NULL);
	return std::string(currentDir);

#elif MACOSX_BUNDLE
	char cPath[1024];
	CFBundleRef mainBundle = CFBundleGetMainBundle();

	CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
	CFURLRef binaryPathURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault , mainBundleURL);

	CFStringRef cfStringRef = CFURLCopyFileSystemPath(binaryPathURL, kCFURLPOSIXPathStyle);

	CFStringGetCString(cfStringRef, cPath, 1024, kCFStringEncodingASCII);

	CFRelease(mainBundleURL);
	CFRelease(binaryPathURL);
	CFRelease(cfStringRef);

	return std::string(cPath);

#else
	return "";

#endif
}
Ejemplo n.º 22
0
OSStatus SetVMPathFromApplicationDirectory() {
	CFBundleRef mainBundle;
	CFURLRef	bundleURL,bundleURLPrefix;
	CFStringRef filePath;

	CFMutableStringRef vmPathString;
	mainBundle = CFBundleGetMainBundle();   
	bundleURL = CFBundleCopyBundleURL(mainBundle);
	bundleURLPrefix = CFURLCreateCopyDeletingLastPathComponent(NULL,bundleURL);
	CFRelease(bundleURL);	
	filePath = CFURLCopyFileSystemPath (bundleURLPrefix, kCFURLPOSIXPathStyle);
	CFRelease(bundleURLPrefix);	
	vmPathString = CFStringCreateMutableCopy(NULL, 0, filePath);
	CFStringAppendCString(vmPathString, "/", kCFStringEncodingMacRoman);
	SetVMPathFromCFString(vmPathString);
	CFRelease(filePath);
	CFRelease(vmPathString);
	
	return 0;		
}
Ejemplo n.º 23
0
URL_TYPE createURLByMakingDirectoryAtURLWithName(URL_TYPE parent, STRING_TYPE name) {
	CFURLRef newDirectory = NULL;

	CFAllocatorRef allocator = parent ? CFGetAllocator(parent) : name ? CFGetAllocator(name) : kCFAllocatorDefault;

	if (parent) parent = CFRetain(parent);
	else {
		char *cwdBytes = alloca(PATH_MAX);
		getcwd(cwdBytes, PATH_MAX);
		parent = CFURLCreateFromFileSystemRepresentation(allocator, (const unsigned char *)cwdBytes, strlen(cwdBytes), /*isDirectory*/ true);
		if (!name) {
			newDirectory = parent;
			goto end;
		}
	}
	if (!parent)
		NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: parent directory URL is NULL (please tell the Growl developers)\n"), parent);
	else {
		if (name)
			name = CFRetain(name);
		else {
			name = CFURLCopyLastPathComponent(parent);
			CFURLRef newParent = CFURLCreateCopyDeletingLastPathComponent(allocator, parent);
			CFRelease(parent);
			parent = newParent;
		}

		if (!name)
			NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: name of directory to create is NULL (please tell the Growl developers)\n"), parent);
		else {
			FSRef parentRef;
			if (!CFURLGetFSRef(parent, &parentRef))
				NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: could not create FSRef for parent directory at %@ (please tell the Growl developers)\n"), parent);
			else {
				FSRef newDirectoryRef;

				struct HFSUniStr255 nameUnicode;
				CFRange range = { 0, MIN(CFStringGetLength(name), USHRT_MAX) };
				CFStringGetCharacters(name, range, nameUnicode.unicode);
				nameUnicode.length = range.length;

				struct FSRefParam refPB = {
					.ref              = &parentRef,
					.nameLength       = nameUnicode.length,
					.name             = nameUnicode.unicode,
					.whichInfo        = kFSCatInfoNone,
					.catInfo          = NULL,
					.textEncodingHint = kTextEncodingUnknown,
					.newRef           = &newDirectoryRef,
				};
				
				OSStatus err = PBCreateDirectoryUnicodeSync(&refPB);
				if (err == dupFNErr) {
					//dupFNErr == file (or folder) exists already. this is fine.
					err = PBMakeFSRefUnicodeSync(&refPB);
				}
				if (err == noErr) {
					NSLog(CFSTR("PBCreateDirectoryUnicodeSync or PBMakeFSRefUnicodeSync returned %li; calling CFURLCreateFromFSRef"), (long)err); //XXX
					newDirectory = CFURLCreateFromFSRef(allocator, &newDirectoryRef);
					NSLog(CFSTR("CFURLCreateFromFSRef returned %@"), newDirectory); //XXX
				} else
					NSLog(CFSTR("in createURLByMakingDirectoryAtURLWithName in CFGrowlAdditions: could not create directory '%@' in parent directory at %@: FSCreateDirectoryUnicode returned %li (please tell the Growl developers)"), name, parent, (long)err);
			}

			CFRelease(parent);
		} //if (name)
		CFRelease(name);
	} //if (parent)

end:
	return newDirectory;
}

#ifndef COPYFORK_BUFSIZE
#	define COPYFORK_BUFSIZE 5242880U /*5 MiB*/
#endif

static OSStatus copyFork(const struct HFSUniStr255 *forkName, const FSRef *srcFile, const FSRef *destDir, const struct HFSUniStr255 *destName, FSRef *outDestFile) {
	OSStatus err, closeErr;
	struct FSForkIOParam srcPB = {
		.ref = srcFile,
		.forkNameLength = forkName->length,
		.forkName = forkName->unicode,
		.permissions = fsRdPerm,
	};
	unsigned char debuggingPathBuf[PATH_MAX] = "";
	OSStatus debuggingPathErr;

	err = PBOpenForkSync(&srcPB);
	if (err != noErr) {
		debuggingPathErr = FSRefMakePath(srcFile, debuggingPathBuf, PATH_MAX);
		if (debuggingPathErr != noErr)
			snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr);
		NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBOpenForkSync (source: %s) returned %li"), debuggingPathBuf, (long)err);
	} else {
		FSRef destFile;

		/*the first thing to do is get the name of the destination file, if one
		 *	wasn't provided.
		 *and while we're at it, we get the catalogue info as well.
		 */
		struct FSCatalogInfo catInfo;
		struct FSRefParam refPB = {
			.ref       = srcFile,
			.whichInfo = kFSCatInfoGettableInfo & kFSCatInfoSettableInfo,
			.catInfo   = &catInfo,
			.spec      = NULL,
			.parentRef = NULL,
			.outName   = destName ? NULL : (struct HFSUniStr255 *)(destName = alloca(sizeof(struct HFSUniStr255))),
		};

		err = PBGetCatalogInfoSync(&refPB);
		if (err != noErr) {
			debuggingPathErr = FSRefMakePath(srcFile, debuggingPathBuf, PATH_MAX);
			if (debuggingPathErr != noErr)
				snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr);
			NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBGetCatalogInfoSync (source: %s) returned %li"), debuggingPathBuf, (long)err);
		} else {
			refPB.ref              = destDir;
			refPB.nameLength       = destName->length;
			refPB.name             = destName->unicode;
			refPB.textEncodingHint = kTextEncodingUnknown;
			refPB.newRef           = &destFile;

			const char *functionName = "PBMakeFSRefUnicodeSync"; //for error-reporting message

			err = PBMakeFSRefUnicodeSync(&refPB);
			if ((err != noErr) && (err != fnfErr)) {
			handleMakeFSRefError:
				debuggingPathErr = FSRefMakePath(destDir, debuggingPathBuf, PATH_MAX);
				if (debuggingPathErr != noErr)
					snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for destination directory: FSRefMakePath returned %li)", (long)debuggingPathErr);

				//get filename too
				CFStringRef debuggingFilename = CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
																				   destName->unicode,
																				   destName->length,
																				   /*contentsDeallocator*/ kCFAllocatorNull);
				if (!debuggingFilename)
					debuggingFilename = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, "(could not get filename for destination file: CFStringCreateWithCharactersNoCopy returned NULL)", kCFStringEncodingASCII, /*contentsDeallocator*/ kCFAllocatorNull);

				NSLog(CFSTR("in copyFork in CFGrowlAdditions: %s (destination: %s/%@) returned %li"), functionName, debuggingPathBuf, debuggingFilename, (long)err);

				if (debuggingFilename) CFRelease(debuggingFilename);
			} else {
				//that file doesn't exist in that folder; create it.
				err = PBCreateFileUnicodeSync(&refPB);
				if (err == noErr) {
					/*make sure the Finder knows about the new file.
					 *FNNotify returns a status code too, but this isn't an
					 *	essential step, so we just ignore it.
					 */
					FNNotify(destDir, kFNDirectoryModifiedMessage, kNilOptions);
				} else if (err == dupFNErr) {
					/*dupFNErr: the file already exists.
					 *we can safely ignore this error.
					 */
					err = noErr;
				} else {
					functionName = "PBCreateFileUnicodeSync";
					goto handleMakeFSRefError;
				}
			}
		}
		if (err == noErr) {
			if (outDestFile)
				memcpy(outDestFile, &destFile, sizeof(destFile));

			struct FSForkIOParam destPB = {
				.ref            = &destFile,
				.forkNameLength = forkName->length,
				.forkName       = forkName->unicode,
				.permissions    = fsWrPerm,
			};
			err = PBOpenForkSync(&destPB);
			NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBOpenForkSync (dest) returned %li"), (long)err);
			if (err != noErr) {
				debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX);
				if (debuggingPathErr != noErr)
					snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for dest file: FSRefMakePath returned %li)", (long)debuggingPathErr);
				NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBOpenForkSync (destination: %s) returned %li"), debuggingPathBuf, (long)err);
			} else {
				void *buf = malloc(COPYFORK_BUFSIZE);
				if (buf) {
					srcPB.buffer = destPB.buffer = buf;
					srcPB.requestCount = COPYFORK_BUFSIZE;
					while (err == noErr) {
						err = PBReadForkSync(&srcPB);
						if (err == eofErr) {
							err = noErr;
							if (srcPB.actualCount == 0)
								break;
						}
						if (err != noErr) {
							debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX);
							if (debuggingPathErr != noErr)
								snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr);
							NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBReadForkSync (source: %s) returned %li"), debuggingPathBuf, (long)err);
						} else {
							destPB.requestCount = srcPB.actualCount;
							err = PBWriteForkSync(&destPB);
							if (err != noErr) {
								debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX);
								if (debuggingPathErr != noErr)
									snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for dest file: FSRefMakePath returned %li)", (long)debuggingPathErr);
								NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBWriteForkSync (destination: %s) returned %li"), debuggingPathBuf, (long)err);
							}
						}
					}

					free(buf);
				}

				closeErr = PBCloseForkSync(&destPB);
				if (closeErr != noErr) {
					debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX);
					if (debuggingPathErr != noErr)
						snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for dest file: FSRefMakePath returned %li)", (long)debuggingPathErr);
					NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBCloseForkSync (destination: %s) returned %li"), debuggingPathBuf, (long)err);
				}
				if (err == noErr) err = closeErr;
			}
		}

		closeErr = PBCloseForkSync(&srcPB);
		if (closeErr != noErr) {
			debuggingPathErr = FSRefMakePath(&destFile, debuggingPathBuf, PATH_MAX);
			if (debuggingPathErr != noErr)
				snprintf((char *)debuggingPathBuf, PATH_MAX, "(could not get path for source file: FSRefMakePath returned %li)", (long)debuggingPathErr);
			NSLog(CFSTR("in copyFork in CFGrowlAdditions: PBCloseForkSync (source: %s) returned %li"), debuggingPathBuf, (long)err);
		}
		if (err == noErr) err = closeErr;
	}

	return err;
}

static OSStatus GrowlCopyObjectSync(const FSRef *fileRef, const FSRef *destRef, FSRef *destFileRef) {
	OSStatus err;
	struct HFSUniStr255 forkName;
	struct FSForkIOParam forkPB = {
		.ref = fileRef,
		.forkIterator = {
			.initialize = 0L
		},
		.outForkName = &forkName,
	};
	
	do {
		err = PBIterateForksSync(&forkPB);
		NSLog(CFSTR("PBIterateForksSync returned %li"), (long)err);
		if (err != noErr) {
			if (err != errFSNoMoreItems)
				NSLog(CFSTR("in GrowlCopyObjectSync in CFGrowlAdditions: PBIterateForksSync returned %li"), (long)err);
		} else {
			err = copyFork(&forkName, fileRef, destRef, /*destName*/ NULL, /*outDestFile*/ destFileRef);
			//copyFork prints its own error messages
		}
	} while (err == noErr);
	if (err == errFSNoMoreItems) err = noErr;

	return err;
}

CFURLRef createURLByCopyingFileFromURLToDirectoryURL(CFURLRef file, CFURLRef dest) {
	CFURLRef destFileURL = NULL;

	FSRef fileRef, destRef, destFileRef;
	Boolean gotFileRef = CFURLGetFSRef(file, &fileRef);
	Boolean gotDestRef = CFURLGetFSRef(dest, &destRef);
	if (!gotFileRef)
		NSLog(CFSTR("in createURLByCopyingFileFromURLToDirectoryURL in CFGrowlAdditions: CFURLGetFSRef failed with source URL %@"), file);
	else if (!gotDestRef)
		NSLog(CFSTR("in createURLByCopyingFileFromURLToDirectoryURL in CFGrowlAdditions: CFURLGetFSRef failed with destination URL %@"), dest);
	else {
		OSStatus err;

		/*
		 * 10.2 has a problem with weak symbols in frameworks so we use
		 * MAC_OS_X_VERSION_MIN_REQUIRED >= 10.3.
		 */
#if defined(NSAppKitVersionNumber10_3) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3
		if (FSCopyObjectSync) {
			err = FSCopyObjectSync(&fileRef, &destRef, /*destName*/ NULL, &destFileRef, kFSFileOperationOverwrite);
		} else {
#endif
			err = GrowlCopyObjectSync(&fileRef, &destRef, &destFileRef);
#if defined(NSAppKitVersionNumber10_3) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3
		}
#endif

		if (err == noErr)
			destFileURL = CFURLCreateFromFSRef(kCFAllocatorDefault, &destFileRef);
		else
			NSLog(CFSTR("in createURLByCopyingFileFromURLToDirectoryURL in CFGrowlAdditions: CopyObjectSync returned %li for source URL %@"), (long)err, file);
	}

	return destFileURL;
}
Ejemplo n.º 24
0
void StartDebuggingAndDetach(char *udid, char *app_path) {
	SDMMD_AMDeviceRef device = FindDeviceFromUDID(udid);
	if (device) {

		CFStringRef bundleId = CFStringCreateWithBytes(kCFAllocatorDefault, (UInt8 *)app_path, strlen(app_path), kCFStringEncodingUTF8, false);
		CFURLRef relative_url = CFURLCreateWithFileSystemPath(NULL, bundleId, kCFURLPOSIXPathStyle, false);
		CFURLRef disk_app_url = CFURLCopyAbsoluteURL(relative_url);
		CFStringRef bundle_identifier = copy_disk_app_identifier(disk_app_url);

		
		SDMMD_AMDebugConnectionRef debug = SDMMD_AMDebugConnectionCreateForDevice(device);
		SDMMD_AMDebugConnectionStart(debug);
		
		uintptr_t socket = SDMMD_AMDServiceConnectionGetSocket(debug->connection);
		CFSocketContext context = { 0, (void*)socket, NULL, NULL, NULL };
		CFSocketRef fdvendor = CFSocketCreate(NULL, AF_UNIX, 0, 0, kCFSocketAcceptCallBack, &socket_callback, &context);
		
		int yes = 1;
		setsockopt(CFSocketGetNative(fdvendor), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
		
		struct sockaddr_un address;
		memset(&address, 0, sizeof(address));
		address.sun_family = AF_UNIX;
		strcpy(address.sun_path, SDM_LLDB_SOCKET);
		address.sun_len = SUN_LEN(&address);
		CFDataRef address_data = CFDataCreate(NULL, (const UInt8 *)&address, sizeof(address));
		
		unlink(SDM_LLDB_SOCKET);
		
		CFSocketSetAddress(fdvendor, address_data);
		CFRelease(address_data);
		CFRunLoopAddSource(CFRunLoopGetMain(), CFSocketCreateRunLoopSource(NULL, fdvendor, 0), kCFRunLoopCommonModes);
		
		SDMMD_AMDeviceRef device = SDMMD_AMDServiceConnectionGetDevice(debug->connection);
		CFMutableStringRef cmds = CFStringCreateMutableCopy(NULL, 0, LLDB_PREP_CMDS);
		CFRange range = { 0, CFStringGetLength(cmds) };
		
		CFURLRef device_app_url = copy_device_app_url(device, bundle_identifier);
		CFStringRef device_app_path = CFURLCopyFileSystemPath(device_app_url, kCFURLPOSIXPathStyle);
		CFStringFindAndReplace(cmds, CFSTR("{DEVICE_PATH}"), device_app_path, range, 0);
		range.length = CFStringGetLength(cmds);
		
		CFStringRef disk_app_path = CFURLCopyFileSystemPath(disk_app_url, kCFURLPOSIXPathStyle);
		CFStringFindAndReplace(cmds, CFSTR("{APP_PATH}"), disk_app_path, range, 0);
		range.length = CFStringGetLength(cmds);
		
		CFURLRef device_container_url = CFURLCreateCopyDeletingLastPathComponent(NULL, device_app_url);
		CFStringRef device_container_path = CFURLCopyFileSystemPath(device_container_url, kCFURLPOSIXPathStyle);
		CFMutableStringRef dcp_noprivate = CFStringCreateMutableCopy(NULL, 0, device_container_path);
		range.length = CFStringGetLength(dcp_noprivate);
		CFStringFindAndReplace(dcp_noprivate, CFSTR("/private/var/"), CFSTR("/var/"), range, 0);
		range.length = CFStringGetLength(cmds);
		CFStringFindAndReplace(cmds, CFSTR("{device_container}"), dcp_noprivate, range, 0);
		range.length = CFStringGetLength(cmds);
		
		CFURLRef disk_container_url = CFURLCreateCopyDeletingLastPathComponent(NULL, disk_app_url);
		CFStringRef disk_container_path = CFURLCopyFileSystemPath(disk_container_url, kCFURLPOSIXPathStyle);
		CFStringFindAndReplace(cmds, CFSTR("{disk_container}"), disk_container_path, range, 0);
		
		CFDataRef cmds_data = CFStringCreateExternalRepresentation(NULL, cmds, kCFStringEncodingASCII, 0);
		FILE *out = fopen(PREP_CMDS_PATH, "w");
		fwrite(CFDataGetBytePtr(cmds_data), CFDataGetLength(cmds_data), 1, out);
		fclose(out);
		
		CFSafeRelease(cmds);
		CFSafeRelease(bundle_identifier);
		CFSafeRelease(device_app_url);
		CFSafeRelease(device_app_path);
		CFSafeRelease(disk_app_path);
		CFSafeRelease(device_container_url);
		CFSafeRelease(device_container_path);
		CFSafeRelease(dcp_noprivate);
		CFSafeRelease(disk_container_url);
		CFSafeRelease(disk_container_path);
		CFSafeRelease(cmds_data);
		
		signal(SIGHUP, exit);
		
		pid_t parent = getpid();
		int pid = fork();
		if (pid == 0) {
			system("xcrun -sdk iphoneos lldb /tmp/sdmmd-lldb-prep");
			kill(parent, SIGHUP);
			_exit(0);
		}
		CFRunLoopRun();
	}
}
Ejemplo n.º 25
0
LLDir_Mac::LLDir_Mac()
{
	mDirDelimiter = "/";
	mCurrentDirIndex = -1;
	mCurrentDirCount = -1;
	
	CFBundleRef		mainBundleRef = NULL;
	CFURLRef		executableURLRef = NULL;
	CFStringRef		stringRef = NULL;
	OSStatus		error = noErr;
	FSRef			fileRef;
	CFStringRef		secondLifeString = CFSTR("SecondLife");
	
	mainBundleRef = CFBundleGetMainBundle();
		
	executableURLRef = CFBundleCopyExecutableURL(mainBundleRef);
	
	if (executableURLRef != NULL)
	{
		// mExecutablePathAndName
		CFURLRefToLLString(executableURLRef, mExecutablePathAndName, false);
		
		// mExecutableFilename
		stringRef = CFURLCopyLastPathComponent(executableURLRef);
		CFStringRefToLLString(stringRef, mExecutableFilename, true);
		
		// mExecutableDir
		CFURLRef	executableParentURLRef = CFURLCreateCopyDeletingLastPathComponent(NULL, executableURLRef);
		CFURLRefToLLString(executableParentURLRef, mExecutableDir, true);
		
		// mAppRODataDir
		CFURLRef	resourcesURLRef = CFBundleCopyResourcesDirectoryURL(mainBundleRef);
		CFURLRefToLLString(resourcesURLRef, mAppRODataDir, true);
		
		// mOSUserDir
		error = FSFindFolder(kUserDomain, kApplicationSupportFolderType, true, &fileRef);
		if (error == noErr)
		{
			FSRef	newFileRef;
			
			// Create the directory
			error = CFCreateDirectory(&fileRef, secondLifeString, &newFileRef);
			if (error == noErr)
			{
				// Save the full path to the folder
				FSRefToLLString(&newFileRef, mOSUserDir);
				
				// Create our sub-dirs
				(void) CFCreateDirectory(&newFileRef, CFSTR("data"), NULL);
				//(void) CFCreateDirectory(&newFileRef, CFSTR("cache"), NULL);
				(void) CFCreateDirectory(&newFileRef, CFSTR("logs"), NULL);
				(void) CFCreateDirectory(&newFileRef, CFSTR("user_settings"), NULL);
				(void) CFCreateDirectory(&newFileRef, CFSTR("browser_profile"), NULL);
			}
		}
		
		//mOSCacheDir
		FSRef cacheDirRef;
		error = FSFindFolder(kUserDomain, kCachedDataFolderType, true, &cacheDirRef);
		if (error == noErr)
		{
			FSRefToLLString(&cacheDirRef, mOSCacheDir);
			(void)CFCreateDirectory(&cacheDirRef, CFSTR("SecondLife"),NULL);
		}
		
		// mOSUserAppDir
		mOSUserAppDir = mOSUserDir;
		
		// mTempDir
		error = FSFindFolder(kOnAppropriateDisk, kTemporaryFolderType, true, &fileRef);
		if (error == noErr)
		{
			FSRef	tempRef;
			error = CFCreateDirectory(&fileRef, secondLifeString, &tempRef);
			if (error == noErr)
				FSRefToLLString(&tempRef, mTempDir);
		}
		
		mWorkingDir = getCurPath();

		mLLPluginDir = mAppRODataDir + mDirDelimiter + "llplugin";
				
		CFRelease(executableURLRef);
		executableURLRef = NULL;
	}
}
Ejemplo n.º 26
0
//----------------------------------------------------------------------------------------
nsresult 
nsDirectoryService::GetCurrentProcessDirectory(nsILocalFile** aFile)
//----------------------------------------------------------------------------------------
{
    NS_ENSURE_ARG_POINTER(aFile);
    *aFile = nsnull;
    
   //  Set the component registry location:
    if (!gService)
        return NS_ERROR_FAILURE;

    nsresult rv; 
 
    nsCOMPtr<nsIProperties> dirService;
    rv = nsDirectoryService::Create(nsnull, 
                                    NS_GET_IID(nsIProperties), 
                                    getter_AddRefs(dirService));  // needs to be around for life of product

    if (dirService)
    {
      nsCOMPtr <nsILocalFile> aLocalFile;
      dirService->Get(NS_XPCOM_INIT_CURRENT_PROCESS_DIR, NS_GET_IID(nsILocalFile), getter_AddRefs(aLocalFile));
      if (aLocalFile)
      {
        *aFile = aLocalFile;
        NS_ADDREF(*aFile);
        return NS_OK;
      }
    }

    nsLocalFile* localFile = new nsLocalFile;

    if (localFile == nsnull)
        return NS_ERROR_OUT_OF_MEMORY;
    NS_ADDREF(localFile);



#ifdef XP_WIN
    PRUnichar buf[MAX_PATH];
    if ( ::GetModuleFileNameW(0, buf, sizeof(buf)) )
    {
        // chop off the executable name by finding the rightmost backslash
        PRUnichar* lastSlash = wcsrchr(buf, L'\\');
        if (lastSlash)
            *(lastSlash + 1) = L'\0';

        localFile->InitWithPath(nsDependentString(buf));
        *aFile = localFile;
        return NS_OK;
    }

#elif defined(MOZ_WIDGET_COCOA)
    // Works even if we're not bundled.
    CFBundleRef appBundle = CFBundleGetMainBundle();
    if (appBundle != nsnull)
    {
        CFURLRef bundleURL = CFBundleCopyExecutableURL(appBundle);
        if (bundleURL != nsnull)
        {
            CFURLRef parentURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, bundleURL);
            if (parentURL)
            {
                // Pass PR_TRUE for the "resolveAgainstBase" arg to CFURLGetFileSystemRepresentation.
                // This will resolve the relative portion of the CFURL against it base, giving a full
                // path, which CFURLCopyFileSystemPath doesn't do.
                char buffer[PATH_MAX];
                if (CFURLGetFileSystemRepresentation(parentURL, PR_TRUE, (UInt8 *)buffer, sizeof(buffer)))
                {
#ifdef DEBUG_conrad
                    printf("nsDirectoryService - CurrentProcessDir is: %s\n", buffer);
#endif
                    rv = localFile->InitWithNativePath(nsDependentCString(buffer));
                    if (NS_SUCCEEDED(rv))
                        *aFile = localFile;
                }
                CFRelease(parentURL);
            }
            CFRelease(bundleURL);
        }
    }
    
    NS_ASSERTION(*aFile, "nsDirectoryService - Could not determine CurrentProcessDir.\n");
    if (*aFile)
        return NS_OK;

#elif defined(XP_UNIX)

    // In the absence of a good way to get the executable directory let
    // us try this for unix:
    //    - if MOZILLA_FIVE_HOME is defined, that is it
    //    - else give the current directory
    char buf[MAXPATHLEN];

    // The MOZ_DEFAULT_MOZILLA_FIVE_HOME variable can be set at configure time with
    // a --with-default-mozilla-five-home=foo autoconf flag.
    // 
    // The idea here is to allow for builds that have a default MOZILLA_FIVE_HOME
    // regardless of the environment.  This makes it easier to write apps that
    // embed mozilla without having to worry about setting up the environment 
    //
    // We do this by putenv()ing the default value into the environment.  Note that
    // we only do this if it is not already set.
#ifdef MOZ_DEFAULT_MOZILLA_FIVE_HOME
    const char *home = PR_GetEnv("MOZILLA_FIVE_HOME");
    if (!home || !*home)
    {
        putenv("MOZILLA_FIVE_HOME=" MOZ_DEFAULT_MOZILLA_FIVE_HOME);
    }
#endif

    char *moz5 = PR_GetEnv("MOZILLA_FIVE_HOME");
    if (moz5 && *moz5)
    {
        if (realpath(moz5, buf)) {
            localFile->InitWithNativePath(nsDependentCString(buf));
            *aFile = localFile;
            return NS_OK;
        }
    }
#if defined(DEBUG)
    static bool firstWarning = true;

    if((!moz5 || !*moz5) && firstWarning) {
        // Warn that MOZILLA_FIVE_HOME not set, once.
        printf("Warning: MOZILLA_FIVE_HOME not set.\n");
        firstWarning = PR_FALSE;
    }
#endif /* DEBUG */

    // Fall back to current directory.
    if (getcwd(buf, sizeof(buf)))
    {
        localFile->InitWithNativePath(nsDependentCString(buf));
        *aFile = localFile;
        return NS_OK;
    }

#elif defined(XP_OS2)
    PPIB ppib;
    PTIB ptib;
    char buffer[CCHMAXPATH];
    DosGetInfoBlocks( &ptib, &ppib);
    DosQueryModuleName( ppib->pib_hmte, CCHMAXPATH, buffer);
    *strrchr( buffer, '\\') = '\0'; // XXX DBCS misery
    localFile->InitWithNativePath(nsDependentCString(buffer));
    *aFile = localFile;
    return NS_OK;

#endif
    
    NS_RELEASE(localFile);

    NS_ERROR("unable to get current process directory");
    return NS_ERROR_FAILURE;
} // GetCurrentProcessDirectory()
Ejemplo n.º 27
0
//----------------------------------------------------------------------------------------
nsresult
nsDirectoryService::GetCurrentProcessDirectory(nsILocalFile** aFile)
//----------------------------------------------------------------------------------------
{
    NS_ENSURE_ARG_POINTER(aFile);
    *aFile = nsnull;

   //  Set the component registry location:
    if (!mService)
        return NS_ERROR_FAILURE;

    nsresult rv;

    nsCOMPtr<nsIProperties> dirService;
    rv = nsDirectoryService::Create(nsnull,
                                    NS_GET_IID(nsIProperties),
                                    getter_AddRefs(dirService));  // needs to be around for life of product

    if (dirService)
    {
      nsCOMPtr <nsILocalFile> aLocalFile;
      dirService->Get(NS_XPCOM_INIT_CURRENT_PROCESS_DIR, NS_GET_IID(nsILocalFile), getter_AddRefs(aLocalFile));
      if (aLocalFile)
      {
        *aFile = aLocalFile;
        NS_ADDREF(*aFile);
        return NS_OK;
      }
    }

    nsLocalFile* localFile = new nsLocalFile;

    if (localFile == nsnull)
        return NS_ERROR_OUT_OF_MEMORY;
    NS_ADDREF(localFile);



#ifdef XP_WIN
    char buf[MAX_PATH];
    if ( ::GetModuleFileName(0, buf, sizeof(buf)) ) {
        // chop of the executable name by finding the rightmost backslash
        char* lastSlash = PL_strrchr(buf, '\\');
        if (lastSlash)
            *(lastSlash + 1) = '\0';

        localFile->InitWithNativePath(nsDependentCString(buf));
        *aFile = localFile;
        return NS_OK;
    }

#elif defined(XP_MAC)
    // get info for the the current process to determine the directory
    // its located in
    OSErr err;
    ProcessSerialNumber psn = {kNoProcess, kCurrentProcess};
    ProcessInfoRec pInfo;
    FSSpec         tempSpec;

    // initialize ProcessInfoRec before calling
    // GetProcessInformation() or die horribly.
    pInfo.processName = nil;
    pInfo.processAppSpec = &tempSpec;
    pInfo.processInfoLength = sizeof(ProcessInfoRec);

    err = GetProcessInformation(&psn, &pInfo);
    if (!err)
    {
        // create an FSSpec from the volume and dirid of the app.
        FSSpec appFSSpec;
        ::FSMakeFSSpec(pInfo.processAppSpec->vRefNum, pInfo.processAppSpec->parID, 0, &appFSSpec);

        nsCOMPtr<nsILocalFileMac> localFileMac = do_QueryInterface((nsIFile*)localFile);
        if (localFileMac)
        {
            localFileMac->InitWithFSSpec(&appFSSpec);
            *aFile = localFile;
            return NS_OK;
        }
    }
#elif defined(XP_MACOSX)
# ifdef MOZ_DEFAULT_VBOX_XPCOM_HOME
    rv = localFile->InitWithNativePath(nsDependentCString(MOZ_DEFAULT_VBOX_XPCOM_HOME));
    if (NS_SUCCEEDED(rv))
        *aFile = localFile;
# else
    // Works even if we're not bundled.
    CFBundleRef appBundle = CFBundleGetMainBundle();
    if (appBundle != nsnull)
    {
        CFURLRef bundleURL = CFBundleCopyExecutableURL(appBundle);
        if (bundleURL != nsnull)
        {
            CFURLRef parentURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, bundleURL);
            if (parentURL)
            {
                // Pass PR_TRUE for the "resolveAgainstBase" arg to CFURLGetFileSystemRepresentation.
                // This will resolve the relative portion of the CFURL against it base, giving a full
                // path, which CFURLCopyFileSystemPath doesn't do.
                char buffer[PATH_MAX];
                if (CFURLGetFileSystemRepresentation(parentURL, PR_TRUE, (UInt8 *)buffer, sizeof(buffer)))
                {
#ifdef DEBUG_conrad
                    printf("nsDirectoryService - CurrentProcessDir is: %s\n", buffer);
#endif
                    rv = localFile->InitWithNativePath(nsDependentCString(buffer));
                    if (NS_SUCCEEDED(rv))
                        *aFile = localFile;
                }
                CFRelease(parentURL);
            }
            CFRelease(bundleURL);
        }
    }
#endif

    NS_ASSERTION(*aFile, "nsDirectoryService - Could not determine CurrentProcessDir.\n");
    if (*aFile)
        return NS_OK;

#elif defined(XP_UNIX)

    // In the absence of a good way to get the executable directory let
    // us try this for unix:
    //	- if VBOX_XPCOM_HOME is defined, that is it
    //	- else give the current directory
    char buf[MAXPATHLEN];

#if 0 /* we need .so location. */
    // Actually we have a way on linux.
    static volatile bool fPathSet = false;
    static char szPath[MAXPATHLEN];
    if (!fPathSet)
    {
        char buf2[MAXPATHLEN + 3];
        buf2[0] = '\0';

        /*
         * Env.var. VBOX_XPCOM_HOME first.
         */
        char *psz = PR_GetEnv("VBOX_XPCOM_HOME");
        if (psz)
        {
            if (strlen(psz) < MAXPATHLEN)
            {
                if (!realpath(psz, buf2))
                    strcpy(buf2, psz);
                strcat(buf2, "/x"); /* for the filename stripping */
            }
        }

        /*
         * The dynamic loader.
         */
        if (!buf2[0])
        {
            Dl_info DlInfo = {0};
            if (    !dladdr((void *)nsDirectoryService::mService, &DlInfo)
                &&  DlInfo.dli_fname)
            {
                if (!realpath(DlInfo.dli_fname, buf2))
                    buf2[0] = '\0';
            }
        }

        /*
         * Executable location.
         */
        if (!buf2[0])
        {
            char buf[MAXPATHLEN];
            int cchLink = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
            if (cchLink > 0 || cchLink != sizeof(buf) - 1)
             {
                buf[cchLink] = '\0';
                if (!realpath(buf, buf2))
                    buf2[0] = '\0';
            }
        }

        /*
         * Copy to static buffer on success.
         */
        if (buf2[0])
        {
            char *p = strrchr(buf2, '/');
            if (p)
            {
                p[p == buf2] = '\0';
            #ifdef DEBUG
                printf("debug: (1) VBOX_XPCOM_HOME=%s\n", buf2);
            #endif
                strcpy(szPath, buf2);
                fPathSet = true;
            }
        }
    }
    if (fPathSet)
    {
        localFile->InitWithNativePath(nsDependentCString(szPath));
        *aFile = localFile;
        return NS_OK;
    }

#endif


    // The MOZ_DEFAULT_VBOX_XPCOM_HOME variable can be set at configure time with
    // a --with-default-mozilla-five-home=foo autoconf flag.
    //
    // The idea here is to allow for builds that have a default VBOX_XPCOM_HOME
    // regardless of the environment.  This makes it easier to write apps that
    // embed mozilla without having to worry about setting up the environment
    //
    // We do this py putenv()ing the default value into the environment.  Note that
    // we only do this if it is not already set.
#ifdef MOZ_DEFAULT_VBOX_XPCOM_HOME
    if (PR_GetEnv("VBOX_XPCOM_HOME") == nsnull)
    {
        putenv("VBOX_XPCOM_HOME=" MOZ_DEFAULT_VBOX_XPCOM_HOME);
    }
#endif

    char *moz5 = PR_GetEnv("VBOX_XPCOM_HOME");

    if (moz5)
    {
        if (realpath(moz5, buf)) {
            localFile->InitWithNativePath(nsDependentCString(buf));
            *aFile = localFile;
            return NS_OK;
        }
    }
#if defined(DEBUG)
    static PRBool firstWarning = PR_TRUE;

    if(!moz5 && firstWarning) {
        // Warn that VBOX_XPCOM_HOME not set, once.
        printf("Warning: VBOX_XPCOM_HOME not set.\n");
        firstWarning = PR_FALSE;
    }
#endif /* DEBUG */

    // Fall back to current directory.
    if (getcwd(buf, sizeof(buf)))
    {
        localFile->InitWithNativePath(nsDependentCString(buf));
        *aFile = localFile;
        return NS_OK;
    }

#elif defined(XP_OS2)
    PPIB ppib;
    PTIB ptib;
    char buffer[CCHMAXPATH];
    DosGetInfoBlocks( &ptib, &ppib);
    DosQueryModuleName( ppib->pib_hmte, CCHMAXPATH, buffer);
    *strrchr( buffer, '\\') = '\0'; // XXX DBCS misery
    localFile->InitWithNativePath(nsDependentCString(buffer));
    *aFile = localFile;
    return NS_OK;

#elif defined(XP_BEOS)

    char *moz5 = getenv("VBOX_XPCOM_HOME");
    if (moz5)
    {
        localFile->InitWithNativePath(nsDependentCString(moz5));
        localFile->Normalize();
        *aFile = localFile;
        return NS_OK;
    }
    else
    {
      static char buf[MAXPATHLEN];
      int32 cookie = 0;
      image_info info;
      char *p;
      *buf = 0;
      if(get_next_image_info(0, &cookie, &info) == B_OK)
      {
        strcpy(buf, info.name);
        if((p = strrchr(buf, '/')) != 0)
        {
          *p = 0;
          localFile->InitWithNativePath(nsDependentCString(buf));
          *aFile = localFile;
          return NS_OK;
        }
      }
    }

#endif

    NS_RELEASE(localFile);

    NS_ERROR("unable to get current process directory");
    return NS_ERROR_FAILURE;
} // GetCurrentProcessDirectory()
int	__open_file(const char * name, __file_modes mode, __file_handle * handle)
{
	FSSpec					spec;
	OSErr						ioResult;
	HParamBlockRec	pb;
	
	ioResult = __path2fss(name, &spec);
	
	if (ioResult) 
		gSqueakFileLastError = ioResult;
		
	if (__system7present())												/* mm 980424 */
	{																	/* mm 980424 */
		Boolean targetIsFolder, wasAliased;								/* mm 980424 */
		ResolveAliasFile(&spec, true, &targetIsFolder, &wasAliased);	/* mm 980424 */
	}																	/* mm 980424 */
	
	if (ioResult && (ioResult != fnfErr || mode.open_mode == __must_exist))
		return(__io_error);
	
	
#if TARGET_API_MAC_CARBON
	if (ioResult) {
        CFStringRef 	filePath;
        CFURLRef 	    sillyThing, sillyThing2;
        FSRef	        parentFSRef;
    	short int       fileRefNum;
        OSErr           err;
        UniChar         buffer[1024];
        long            tokenLength;
        
		
        filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *)name,strlen(name),gCurrentVMEncoding,false);
        if (filePath == nil) 
            return __io_error;
        sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,filePath,kCFURLHFSPathStyle,false);
        CFRelease(filePath);
        sillyThing2 = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault,sillyThing);
        err = CFURLGetFSRef(sillyThing2,&parentFSRef);
        if (err == 0) {
            CFRelease(sillyThing);
            CFRelease(sillyThing2);
            return fnfErr;  
        }
        filePath = CFURLCopyLastPathComponent(sillyThing);
        tokenLength = CFStringGetLength(filePath);
        if (tokenLength > 1024) {
            CFRelease(filePath);
            CFRelease(sillyThing);
            CFRelease(sillyThing2);
            return(__io_error);
        }
            
        CFStringGetCharacters(filePath,CFRangeMake(0,tokenLength),buffer);

        CFRelease(filePath);
        CFRelease(sillyThing);
        CFRelease(sillyThing2);

		ioResult = FSCreateFileUnicode(&parentFSRef,tokenLength,buffer,kFSCatInfoNone,NULL,NULL,&spec);  
    	if (ioResult)
			gSqueakFileLastError = ioResult;
    	if (ioResult)
	    	return(__io_error);
	    	
        pb.ioParam.ioNamePtr    = spec.name;
    	pb.ioParam.ioVRefNum    = spec.vRefNum;
    	pb.ioParam.ioPermssn    = (mode.io_mode == __read) ? fsRdPerm : fsRdWrPerm;
    	pb.ioParam.ioMisc       = 0;
    	pb.fileParam.ioFVersNum = 0;
    	pb.fileParam.ioDirID    = spec.parID;
		set_file_type(&spec, mode.binary_io);
		ioResult = PBHOpenDFSync(&pb);  /* HH 10/25/97  was PBHOpenSync */
    	    	
    	if (ioResult)
    		return(__io_error);
    	
    	*handle = pb.ioParam.ioRefNum;
	
	    return(__no_io_error);
	}
#endif
    pb.ioParam.ioNamePtr    = spec.name;
	pb.ioParam.ioVRefNum    = spec.vRefNum;
	pb.ioParam.ioPermssn    = (mode.io_mode == __read) ? fsRdPerm : fsRdWrPerm;
	pb.ioParam.ioMisc       = 0;
	pb.fileParam.ioFVersNum = 0;
	pb.fileParam.ioDirID    = spec.parID;
	
	if (ioResult)
	{
		if (!(ioResult = PBHCreateSync(&pb)))
		{
			if (ioResult) 
				gSqueakFileLastError = ioResult;
			set_file_type(&spec, mode.binary_io);
			ioResult = PBHOpenDFSync(&pb);  /* HH 10/25/97  was PBHOpenSync */
			if (ioResult) 
				gSqueakFileLastError = ioResult;
		}
	}
	else
	{
		if (!(ioResult = PBHOpenDFSync(&pb)) && mode.open_mode == __create_or_truncate)  
		                                  /* HH 10/25/97  was PBHOpenSync */
		{
			pb.ioParam.ioMisc = 0;
			
			ioResult = PBSetEOFSync((ParmBlkPtr) &pb);
			
			if (ioResult)
				gSqueakFileLastError = ioResult;

			if (ioResult)
				PBCloseSync((ParmBlkPtr) &pb);
		} else {
			if (ioResult) 
				gSqueakFileLastError = ioResult;

		}
	}
	
	if (ioResult)
		return(__io_error);
	
	*handle = pb.ioParam.ioRefNum;
	
	return(__no_io_error);
}
Ejemplo n.º 29
0
static int quicklyMakePath(char *pathString, int pathStringLength,char *dst, Boolean resolveAlias) {
	CFStringRef 	filePath;
        CFURLRef 	sillyThing,firstPartOfPath;
        FSRef		theFSRef;   
        Boolean		isFolder,isAlias;
        OSErr		err;
        
        filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,
                    (UInt8 *)pathString,pathStringLength,gCurrentVMEncoding,false);
        if (filePath == nil)
            return -1;
		CFMutableStringRef str= CFStringCreateMutableCopy(NULL, 0, filePath);
		// HFS+ imposes Unicode2.1 decomposed UTF-8 encoding on all path elements
		if (gCurrentVMEncoding == kCFStringEncodingUTF8) 
			CFStringNormalize(str, kCFStringNormalizationFormKC); // canonical decomposition

		sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault, str, kCFURLHFSPathStyle,false);
		if (sillyThing == NULL) {
			CFRelease(filePath);
			return -2;
		}
		CFRelease(str);
        
        if (!CFURLGetFSRef(sillyThing,&theFSRef)) {
            firstPartOfPath = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault,sillyThing);
            if (!CFURLGetFSRef(firstPartOfPath,&theFSRef)) {
                CFRelease(firstPartOfPath);
                CFRelease(filePath);
                CFRelease(sillyThing);
                return -1;
            } else {
                CFStringRef lastPathPart;
                char	 lastpart[256];
                
                CFRelease(filePath);
                CFRelease(firstPartOfPath);
                lastPathPart = CFURLCopyLastPathComponent(sillyThing);
                CFRelease(sillyThing);
                
                err = noErr;
                if (resolveAlias) 
                    err = FSResolveAliasFile (&theFSRef,true,&isFolder,&isAlias);

                if (err) 
                    return 2;
                
                err = FSRefMakePath(&theFSRef,(UInt8 *)dst,1000); 
                CFStringGetCString(lastPathPart,lastpart,256, kCFStringEncodingUTF8);
                CFRelease(lastPathPart);
                if (strlen(dst)+1+strlen(lastpart) < 1000) {
                    strcat(dst,"/");
                    strcat(dst,lastpart);
                    
#if defined(__MWERKS__) && !defined(__APPLE__) && !defined(__MACH__)
        filePath   = CFStringCreateWithBytes(kCFAllocatorDefault,(UInt8 *)dst,strlen(dst),gCurrentVMEncoding,false);
        if (filePath == nil) 
            return 2;
        sillyThing = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,filePath,kCFURLPOSIXPathStyle,true);
		CFRelease(filePath);
        filePath = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle);
        CFStringGetCString (filePath,dst,1000, gCurrentVMEncoding);
		CFRelease(sillyThing);
        CFRelease(filePath);        
#endif

                    return 0;
                } else
                    return 2;
            }
        }
        
        CFRelease(filePath);
        CFRelease(sillyThing);
        
        if (resolveAlias) 
            err = FSResolveAliasFile (&theFSRef,true,&isFolder,&isAlias);

#if defined(__MWERKS__) && !defined(__APPLE__) && !defined(__MACH__)
		sillyThing = CFURLCreateFromFSRef(kCFAllocatorDefault,&theFSRef);
        filePath = CFURLCopyFileSystemPath (sillyThing, kCFURLHFSPathStyle);
        CFStringGetCString (filePath,dst,1000, gCurrentVMEncoding);
		CFRelease(sillyThing);
        CFRelease(filePath);        
        return 0;
#else
        err = FSRefMakePath(&theFSRef,(UInt8 *)dst,1000); 
        return err;
#endif 
}
Ejemplo n.º 30
0
/*
=================
main
=================
*/
int main(int argc, char **argv)
{
	int  i;
	char commandLine[MAX_STRING_CHARS] = { 0 };

#ifndef DEDICATED
	// SDL version check

	// Compile time
#   if !SDL_VERSION_ATLEAST(MINSDL_MAJOR, MINSDL_MINOR, MINSDL_PATCH)
#       error A more recent version of SDL is required
#   endif

	// Run time
	const SDL_version *ver = SDL_Linked_Version();

#define MINSDL_VERSION \
	XSTRING(MINSDL_MAJOR) "." \
	XSTRING(MINSDL_MINOR) "." \
	XSTRING(MINSDL_PATCH)

	if (SDL_VERSIONNUM(ver->major, ver->minor, ver->patch) <
	    SDL_VERSIONNUM(MINSDL_MAJOR, MINSDL_MINOR, MINSDL_PATCH))
	{
		Sys_Dialog(DT_ERROR, va("SDL version " MINSDL_VERSION " or greater is required, "
		                                                      "but only version %d.%d.%d was found. You may be able to obtain a more recent copy "
		                                                      "from http://www.libsdl.org/.", ver->major, ver->minor, ver->patch), "SDL Library Too Old");

		Sys_Exit(1);
	}
#endif

#ifdef __MORPHOS__
	// don't let locales with decimal comma screw up the string to float conversions
	setlocale(LC_NUMERIC, "C");

	DynLoadBase = OpenLibrary("dynload.library", 51);

	if (DynLoadBase && DynLoadBase->lib_Revision < 3)
	{
		CloseLibrary(DynLoadBase);
		DynLoadBase = NULL;
	}

	if (!DynLoadBase)
	{
		Sys_Dialog(DT_ERROR, "Unable to open dynload.library version 51.3 or newer", "dynload.library error");
		Sys_Exit(1);
	}
#endif

	Sys_PlatformInit();

	// Set the initial time base
	Sys_Milliseconds();

	Sys_ParseArgs(argc, argv);


#if defined(__APPLE__) && !defined(DEDICATED)
	// argv[0] would be /Users/seth/etlegacy/etl.app/Contents/MacOS
	// But on OS X we want to pretend the binary path is the .app's parent
	// So that way the base folder is right next to the .app allowing
	{
		char     parentdir[1024];
		CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
		if (!url)
		{
			Sys_Dialog(DT_ERROR, "A CFURL for the app bundle could not be found.", "Can't set Sys_SetBinaryPath");
			Sys_Exit(1);
		}

		CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url);
		if (!url2 || !CFURLGetFileSystemRepresentation(url2, 1, (UInt8 *)parentdir, 1024))
		{
			Sys_Dialog(DT_ERROR, "CFURLGetFileSystemRepresentation returned an error when finding the app bundle's parent directory.", "Can't set Sys_SetBinaryPath");
			Sys_Exit(1);
		}

		Sys_SetBinaryPath(parentdir);

		CFRelease(url);
		CFRelease(url2);
	}
#else
	Sys_SetBinaryPath(Sys_Dirname(argv[0]));
#endif

	Sys_SetDefaultInstallPath(DEFAULT_BASEDIR); // Sys_BinaryPath() by default


	// Concatenate the command line for passing to Com_Init
	for (i = 1; i < argc; i++)
	{
		const qboolean containsSpaces = (qboolean)(strchr(argv[i], ' ') != NULL);
		if (containsSpaces)
		{
			Q_strcat(commandLine, sizeof(commandLine), "\"");
		}

		Q_strcat(commandLine, sizeof(commandLine), argv[i]);

		if (containsSpaces)
		{
			Q_strcat(commandLine, sizeof(commandLine), "\"");
		}

		Q_strcat(commandLine, sizeof(commandLine), " ");
	}

	Com_Init(commandLine);
	NET_Init();

#ifdef FEATURE_CURSES
	if (nocurses)
	{
		CON_Init_tty();
	}
	else
	{
		CON_Init();
	}
#else
	CON_Init();
#endif

	signal(SIGILL, Sys_SigHandler);
	signal(SIGFPE, Sys_SigHandler);
	signal(SIGSEGV, Sys_SigHandler);
	signal(SIGTERM, Sys_SigHandler);
	signal(SIGINT, Sys_SigHandler);

	while (1)
	{
		IN_Frame();
		Com_Frame();
	}

	return 0;
}