Exemple #1
0
int main(int argc, const char* argv[])
{
    printf("[BEGIN] crt-vars-libSystem\n");
    bool success = true;

    if ( _NSGetArgv() != &NXArgv ) {
        printf("[FAIL] crt-libSystem: _NSGetArgv() != &NXArgv (%p!=%p) for %s", _NSGetArgv(), &NXArgv, argv[0]);
        success = false;
    }

    if ( _NSGetArgc() != &NXArgc ) {
        printf("[FAIL] crt-libSystem: _NSGetArgc() != &NXArgc (%p!=%p) for %s", _NSGetArgc(), &NXArgc, argv[0]);
        success = false;
    }

    if ( _NSGetEnviron() != &environ ) {
        printf("[FAIL] crt-libSystem: _NSGetEnviron() != &environv (%p!=%p) for %s", _NSGetEnviron(), &environ, argv[0]);
        success = false;
    }

    if ( _NSGetProgname() != &__progname ) {
        printf("[FAIL] crt-libSystem: _NSGetProgname() != &__progname (%p!=%p) for %s", _NSGetProgname(), &__progname, argv[0]);
        success = false;
    }

    if ( _NSGetMachExecuteHeader() != &_mh_execute_header ) {
        printf("[FAIL] crt-libSystem: _NSGetMachExecuteHeader() != &_mh_execute_headerv (%p!=%p) for %s", _NSGetMachExecuteHeader(), &_mh_execute_header, argv[0]);
        success = false;
    }

    if ( sVars->NXArgvPtr != &NXArgv ) {
        printf("[FAIL] crt-libSystem: sVars->NXArgvPtr != &NXArg (%p!=%p) for %s", sVars->NXArgvPtr, &NXArgv, argv[0]);
        success = false;
    }

    if ( sVars->NXArgcPtr != &NXArgc ) {
        printf("[FAIL] crt-libSystem: sVars->NXArgcPtr != &NXArgc (%p!=%p) for %s", sVars->NXArgcPtr, &NXArgc, argv[0]);
        success = false;
    }

    if ( sVars->environPtr != &environ ) {
        printf("[FAIL] crt-libSystem: sVars->environPtr != &environ (%p!=%p) for %s", sVars->environPtr, &environ, argv[0]);
        success = false;
    }

    if ( sVars->__prognamePtr != &__progname ) {
        printf("[FAIL] crt-libSystem: sVars->__prognamePtr != &__progname (%p!=%p) for %s", sVars->__prognamePtr, &__progname, argv[0]);
        success = false;
    }

    if ( sVars->mh != &_mh_execute_header ) {
        printf("[FAIL] crt-libSystem: sVars->mh != &_mh_execute_header (%p!=%p) for %s", sVars->mh, &_mh_execute_header, argv[0]);
        success = false;
    }

    if ( success )
        printf("[PASS] crt-vars-libSystem\n");

    return 0;
}
Exemple #2
0
	char *file_utils::get_exec_filename(char *pPath, size_t dest_len)
	{
	#if VOGL_HAS_PROC_FILESYSTEM
		ssize_t s = readlink("/proc/self/exe", pPath, dest_len);
		if (s >= 0)
		{
			pPath[s] = '\0';
			return pPath;
		}

		VOGL_VERIFY(0);
		pPath[0] = '\0';

		return pPath;

	#elif defined(VOGL_USE_OSX_API)
		char **argv = *_NSGetArgv();
		
		strncpy(pPath, argv[0], dest_len);
	
		vogl_warning_printf("UNTESTED: file_utils::get_exec_filename returning [%s]\n", pPath);
		return pPath;
	
	#elif defined(VOGL_USE_WIN32_API)
		DWORD result = GetModuleFileNameA(0, pPath, safe_int_cast<DWORD>(dest_len));
		VOGL_VERIFY(result != 0);
		return pPath;
	#else
		VOGL_ASSUME(!"Implement get_exec_filename for this platform.");
	#endif
	}
Exemple #3
0
static void
ps_argv_changed(const struct ps_relocation *rel, char **new_argv)
{
	(void)rel;
	(void)new_argv;

#if defined(__GLIBC__)
	program_invocation_name =
		ps_relocate(rel, program_invocation_name);
	program_invocation_short_name =
		ps_relocate(rel, program_invocation_short_name);
#endif

#if defined(HAVE_SETPROGNAME) && defined(HAVE_GETPROGNAME)
	setprogname(ps_relocate(rel, (void *)getprogname()));
#endif

#if defined(__APPLE__)
	/*
	 * Darwin (and perhaps other NeXT-derived platforms?) has a static
	 * copy of the argv pointer, which we may fix like so:
	 */
	*_NSGetArgv() = new_argv;
#endif
}
/*
	static
	
	warning: this method is to be called very early at time when VProcess and VCppMem is not initialized yet.
	Don't create any VObject here nor call any other xbox method.
*/
bool VProcess::_GetCommandLineArgumentAsLongStatic( const char* inArgumentName, sLONG* outValue)
{
	bool isFound = false;
	*outValue = 0;

#if VERSIONWIN
	wchar_t wideArgumentName[256];
	size_t len = strlen(inArgumentName);
	if (len > 255)
		len = 255;
	std::copy( inArgumentName, inArgumentName + len + 1, &wideArgumentName[0]);
	
	int	argc = 0;
	LPWSTR *argv = ::CommandLineToArgvW( ::GetCommandLineW(), &argc);
	for( int i = 0 ; i < argc ; ++i)
	{
		if (wcscmp(argv[i], wideArgumentName) == 0)
		{
			if (++i < argc)
			{
				*outValue = ::_wtol(argv[i]);
				isFound = true;
				break;
			}
		}
	}
	LocalFree( argv);
#else
	#if VERSIONMAC
	int *argc_p = _NSGetArgc();
	char ***argv_p = _NSGetArgv();
	int argc = (argc_p == NULL) ? 0 : *argc_p;
	char **argv = (argv_p == NULL) ? NULL : *argv_p;
	#elif VERSION_LINUX
    // Postponed Linux Implementation !
	//extern int __libc_argc; jmo - Theese symbols are not available for us !
	//extern char ** __libc_argv;
	int argc = 0;
	char **argv = NULL;
	#endif

	for( int i = 0 ; i < argc ; ++i)
	{
		if (strcmp(argv[i], inArgumentName) == 0)
		{
			if (++i < argc)
			{
				*outValue = (sLONG) ::atol(argv[i]);
				isFound = true;
				break;
			}
		}
	}

#endif

	return isFound;
}
Exemple #5
0
/* ZGCMDL -- Get the host system command line used to invoke this process.
 * There does not seem to be any straightforward way to do this for UNIX,
 * but the argc,argv info is evidently pushed on the stack immediately before
 * the environment list, so we can locate the ARGV array by searching back
 * up the stack a bit.  This is very host OS dependent.
 */
int
ZGCMDL (
  PKCHAR  *cmd,				/* receives the command line	*/
  XINT	  *maxch,			/* maxch chars out		*/
  XINT	  *status
)
{
	register char	*ip, *op;
	unsigned int	*ep;
	register int	n, narg;
	char	**argv;

#ifdef	MACOSX
	argv = *_NSGetArgv();
	xargc = *_NSGetArgc();
	xargv = argv;

#else
	if (!(argv = xargv)) {
	    /* Locate the ARGV array.  This assumes that argc,argv are
	     * stored in memory immediately preceeding the environment
	     * list, i.e.,
	     *
	     *	argc
	     *	argv[0]
	     *	argv[1]
	     *	  ...
	     *	argv[argc-1]
	     *	NULL
	     *      env[0]			<- environ
	     *      env[1]
	     *	  ...
	     *
	     * !! NOTE !! - This is very system dependent!
	     */
	    ep = ((unsigned int *) *environ) - 1;
	    for (narg=0;  *(ep-1) != (unsigned int)narg;  narg++)
		--ep;
	    xargc = narg;
	    argv = (char **)ep;
	}
#endif

	/* Reconstruct the argument list.
	 */
	for (op=(char *)cmd, n = *maxch, argv++;  n >= 0 && *argv;  argv++) {
	    if (op > (char *)cmd && --n >= 0)
		*op++ = ' ';
	    for (ip = *argv;  --n >= 0 && (*op = *ip++);  op++)
		;
	}

	*op = EOS;
	*status = op - (char *)cmd;

	return (XOK);
}
Exemple #6
0
static void log_meta(void)
{
	char *cwd;

	uncolog_write_action_start(&ufp, "meta", 4);

	// log argv
#ifdef __APPLE__
	do {
		char cmdbuf[4096], **argv;
		int i, argc;
		argc = *_NSGetArgc();
		argv = *_NSGetArgv();
		cmdbuf[0] = '\0';
		for (i = 0; i != argc; ++i)
			snprintf(cmdbuf + strlen(cmdbuf), sizeof(cmdbuf) - strlen(cmdbuf),
			i == 0 ? "%s" : " %s",
			argv[i]);
		uncolog_write_argbuf(&ufp, cmdbuf, strlen(cmdbuf));
	} while (0);
#elif defined(__linux__)
	do {
		int fd;
		char *cmd = NULL;
		size_t cmdlen, i;
		if ((fd = open("/proc/self/cmdline", O_RDONLY)) != -1) {
			cmd = kread_full(fd, &cmdlen);
			close(fd);
		}
		if (cmd != NULL) {
			for (i = 0; i < cmdlen; ++i)
				if (cmd[i] == '\0')
					cmd[i] = ' ';
			uncolog_write_argbuf(&ufp, cmd, cmdlen);
		} else {
			uncolog_write_argbuf(&ufp, "(unknown)", sizeof("(unknown)") - 1);
		}
	} while (0);	
#else
# error "unknown env"
#endif

	// log cwd
	cwd = getcwd(NULL, 0);
	uncolog_write_argbuf(&ufp, cwd != NULL ? cwd : "", cwd != NULL ? strlen(cwd): 0);
	free(cwd);

	// log pid
	uncolog_write_argn(&ufp, getpid());

	// log ppid
	uncolog_write_argn(&ufp, getppid());

	uncolog_write_action_end(&ufp);
}
Exemple #7
0
void
change_pname(const char *new_name)
{
    //http://unixjunkie.blogspot.com/2006/07/access-argc-and-argv-from-anywhere.html
    //uses this _NSGetArgv : tested & working!
    char **argv = *_NSGetArgv();
    unsigned int old_len=strlen(argv[0]);
    //snprintf(argv[0],old_len+1,"%s ",new_name);
    strncpy(argv[0],new_name,old_len);
    if (old_len > 0)
        argv[0][old_len] = '\0';
}
Exemple #8
0
// we move this function to another object file
// to optimize static linkage (avoid unnecessary dependencies)
StArrayList<StString> StProcess::getArguments() {
    StArrayList<StString> aList;
#if (defined(_WIN32) || defined(__WIN32__))
    int argc = 0;
    stUtfWide_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc);
    for(int aParamId = 0; aParamId < argc; ++aParamId) {
        aList.add(StString(argv[aParamId]));
    }
    // free memory allocated for CommandLineToArgvW arguments.
    LocalFree(argv);
#elif (defined(__APPLE__))
    if(_NSGetArgc() == NULL || _NSGetArgv() == NULL) {
        return aList; // is it possible?
    }
    int anArgsNb = *_NSGetArgc();
    char** anArgVec = *_NSGetArgv();
    for(int aParamId = 0; aParamId < anArgsNb; ++aParamId) {
        // automatically convert filenames from decomposed form used by Mac OS X file systems
        aList.add(stFromUtf8Mac(anArgVec[aParamId]));
    }
#elif (defined(__linux__) || defined(__linux))
    stUtf8_t aCmdlineInfoFile[4096];
    sprintf(aCmdlineInfoFile, "/proc/%d/cmdline", getpid());
    std::ifstream iFile;
    iFile.open(aCmdlineInfoFile);
    if(iFile.is_open()) {
        char aCmdlineInfoBuff[4096];
        while(!iFile.eof()) {
            stMemSet(aCmdlineInfoBuff, 0, sizeof(aCmdlineInfoBuff));
            iFile.getline(aCmdlineInfoBuff, 4096, '\0');
            if(aCmdlineInfoBuff[0] != '\0') {
                aList.add(StString(aCmdlineInfoBuff));
            }
        }
        iFile.close();
    }
#endif
    return aList;
}
Exemple #9
0
// GetExePath
//------------------------------------------------------------------------------
void Env::GetExePath( AString & output )
{
	#if defined( __WINDOWS__ )
		HMODULE hModule = GetModuleHandleA( nullptr );
		char path[ MAX_PATH ];
		GetModuleFileNameA( hModule, path, MAX_PATH );
		output = path;
	#elif defined( __APPLE__ )
        const char ** argv = const_cast< const char ** >( *_NSGetArgv() ); 
        output = argv[0];
    #else
        char path[ PATH_MAX ];
        VERIFY( readlink( "/proc/self/exe", path, PATH_MAX ) != -1 );
        output = path;
	#endif
}
Exemple #10
0
std::vector<u8string> getargv() {
#if defined(_WIN32)
    int argc;
    wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
    std::vector<u8string> result;
    result.reserve(argc);
    for(int i = 0; i < argc; ++i)
        result.push_back(u8string::from_wide(wargv[i]));
    LocalFree(static_cast<void *>(wargv));
    return result;
#elif defined(__APPLE__) && defined(__MACH__)
    int argc = *_NSGetArgc();
    char **argv = *_NSGetArgv();
    std::vector<u8string> result;
    result.reserve(argc);
    for(int i = 0; i < argc; ++i)
        result.push_back(u8string(argv[i]));
    return result;
#else
    std::ifstream cmdline("/proc/self/cmdline");
    if(cmdline.is_open()) {
        std::vector<u8string> result;
        for(;;) {
            u8string argi;
            for(;;) {
                char c;
                if(cmdline.get(c))
                    if(c != '\0')
                        argi.push_back(c);
                    else
                        break;
                else if(cmdline.eof() && argi.empty())
                    return result;
                else
                    throw std::runtime_error("Unable to get commandline arguments");
            }
            result.push_back(std::move(argi));
        }
    } else
        throw std::runtime_error("Unable to get commandline arguments");
#endif
}
/*
	static
*/
void VProcess::_FetchCommandLineArguments( VectorOfVString& outArguments)
{
	VectorOfVString arguments;

#if VERSIONWIN

	int	nbArgs = 0;
	LPWSTR *tabArgs = ::CommandLineToArgvW( ::GetCommandLineW(), &nbArgs);
	for( int i = 0 ; i < nbArgs ; ++i)
	{
		arguments.push_back( VString( tabArgs[i]));
	}
	LocalFree( tabArgs);

#else

	#if VERSIONMAC
	int *argc_p = _NSGetArgc();
	char ***argv_p = _NSGetArgv();
	int argc = (argc_p == NULL) ? 0 : *argc_p;
	char **argv = (argv_p == NULL) ? NULL : *argv_p;
	#elif VERSION_LINUX
    // Postponed Linux Implementation !
	//extern int __libc_argc; jmo - Theese symbols are not available for us !
	//extern char ** __libc_argv;
	int argc = 0;
	char **argv = NULL;
	#endif
	
	VToUnicodeConverter_UTF8 converter;
	for( int i = 0 ; i < argc ; ++i)
	{
		VString s;
		converter.ConvertString( argv[i], strlen( argv[i]), NULL, s);
		arguments.push_back( s);
	}

#endif

	outArguments.swap( arguments);
}
Exemple #12
0
void
mac_fork_and_reexec_self()
{
	int argc = *_NSGetArgc();
	char ** argv = *_NSGetArgv();
	char * newargv[argc+2];
	char progname[PATH_MAX];
	uint32_t buflen = PATH_MAX;
	_NSGetExecutablePath(progname, &buflen);
	bool found_psn = false;

	for (int i = 0; i < argc; i++) {
		newargv[i] = argv[i];
	}

	newargv[argc] = "--nofork";
	newargv[argc+1] = NULL;

	int x_fork_result = fork();
	switch(x_fork_result) {

		case -1:
#ifndef NDEBUG
			fprintf(stderr, "Mac OS X workaround fork() failed!\n");
#endif
			::_exit(255);
			break;

		case 0:
			// Child
			execvp(progname, newargv);
			break;

		default:
			// Parent
			_exit(0);
			break;

	}
}
Exemple #13
0
// GetCmdLine
//------------------------------------------------------------------------------
/*static*/ void Env::GetCmdLine( AString & cmdLine )
{
	#if defined( __WINDOWS__ )
        cmdLine = ::GetCommandLine();
	#elif defined( __APPLE__ )
        int argc = *_NSGetArgc();
        const char ** argv = const_cast< const char ** >( *_NSGetArgv() ); 
        for ( int i=0; i<argc; ++i )
        {
            if ( i > 0 )
            {
                cmdLine += ' ';
            }            
            cmdLine += argv[i];
        }
	#else
        FILE* f = fopen( "/proc/self/cmdline", "rb" );
        VERIFY( f != 0 );
        char buffer[ 4096 ];
        for (;;)
        {
            int size = fread( buffer, 1, 4096, f );
            if ( size == 0 )
            {
                break;
            }
        
            // Append
            for ( int i=0; i<size; ++i )
            {
                const char c = buffer[ i ];
                cmdLine += ( c ? c : ' ' ); // convert nulls in between args back into spaces
            }
        }
        VERIFY( fclose( f ) == 0 );

	#endif
}
Exemple #14
0
aslclient
asl_open_from_file(int fd, const char *ident, const char *facility)
{
	char *name, *x;
	asl_client_t *asl;
	uint32_t status;

	asl = (asl_client_t *)calloc(1, sizeof(asl_client_t));
	if (asl == NULL)
	{
		errno = ENOMEM;
		return NULL;
	}

	asl->options = ASL_OPT_NO_REMOTE;
	asl->sock = -1;

	asl->pid = getpid();
	asl->uid = getuid();
	asl->gid = getgid();

	asl->filter = ASL_FILTER_MASK_UPTO(ASL_LEVEL_DEBUG);

	if (ident != NULL)
	{
		asl->name = strdup(ident);
		if (asl->name == NULL)
		{
			free(asl);
			return NULL;
		}
	}
	else
	{
		name = *(*_NSGetArgv());
		if (name != NULL)
		{
			x = strrchr(name, '/');
			if (x != NULL) x++;
			else x = name;
			asl->name = strdup(x);
			if (asl->name == NULL)
			{
				free(asl);
				return NULL;
			}
		}
	}

	asl->facility = NULL;
	if (facility != NULL) asl->facility = strdup(facility);
	else asl->facility = strdup(asl_syslog_faciliy_num_to_name(LOG_USER));
	if (asl->facility == NULL)
	{
		if (asl->name != NULL) free(asl->name);
		free(asl);
		return NULL;
	}

	status = asl_file_open_write_fd(fd, &(asl->aslfile));
	if (status != ASL_STATUS_OK)
	{
		if (asl->name != NULL) free(asl->name);
		if (asl->facility != NULL) free(asl->facility);
		free(asl);
		return NULL;
	}

	asl->aslfileid = 1;
	asl->refcount = 1;

	return (aslclient)asl;
}
Exemple #15
0
static
#elif DEPLOYMENT_TARGET_WINDOWS
CF_EXPORT
#endif
void __CFInitialize(void) {
    static int __done = 0;

    if (!__done) {
        __done = 1;

#if defined(DEBUG) || defined(ENABLE_ZOMBIES)
        const char *value = getenv("NSZombieEnabled");
        if (value && (*value == 'Y' || *value == 'y')) __CFZombieEnabled = 0xff;
        value = getenv("NSDeallocateZombies");
        if (value && (*value == 'Y' || *value == 'y')) __CFDeallocateZombies = 0xff;

        value = getenv("CFZombieLevel");
        if (NULL != value) {
#if DEPLOYMENT_TARGET_MACOSX
            __CFZombieLevel = (uint32_t)strtoul_l(value, NULL, 0, NULL);
#else
            __CFZombieLevel = (uint32_t)strtoul(value, NULL, 0);
#endif
        }
        if (0x0 == __CFZombieLevel) __CFZombieLevel = 0x0000FC00; // default
#endif

        __CFRuntimeClassTableSize = 1024;
        __CFRuntimeClassTable = (CFRuntimeClass **)calloc(__CFRuntimeClassTableSize, sizeof(CFRuntimeClass *));
        __CFBaseInitialize();

        /* Here so that two runtime classes get indices 0, 1. */
        __kCFNotATypeTypeID = _CFRuntimeRegisterClass(&__CFNotATypeClass);
        __kCFTypeTypeID = _CFRuntimeRegisterClass(&__CFTypeClass);

        /* Here so that __kCFAllocatorTypeID gets index 2. */
        __CFAllocatorInitialize();

#if DEPLOYMENT_TARGET_MACOSX
        {
            CFIndex idx, cnt;
            char **args = *_NSGetArgv();
            cnt = *_NSGetArgc();
            for (idx = 1; idx < cnt - 1; idx++) {
                if (NULL == args[idx]) continue;
                if (0 == strcmp(args[idx], "-AppleLanguages") && args[idx + 1]) {
                    CFIndex length = strlen(args[idx + 1]);
                    __CFAppleLanguages = malloc(length + 1);
                    memmove(__CFAppleLanguages, args[idx + 1], length + 1);
                    break;
                }
            }
        }
#endif


        /* CFBag needs to be up before CFString. */
        __CFBagInitialize();

#if !__LP64__
        // Creating this lazily in CFRetain causes recursive call to CFRetain
        __CFRuntimeExternRefCountTable = CFBagCreateMutable(kCFAllocatorSystemDefault, 0, NULL);
#endif

        /*** _CFRuntimeCreateInstance() can finally be called generally after this line. ***/

        __CFRuntimeClassTableCount = 7;
        __CFStringInitialize();		// CFString's TypeID must be 0x7, now and forever
        __CFRuntimeClassTableCount = 16;
        __CFDictionaryInitialize();
        __CFArrayInitialize();
        __CFDataInitialize();
        __CFSetInitialize();
        __CFNullInitialize();		// See above for hard-coding of this position
        __CFBooleanInitialize();	// See above for hard-coding of this position
        __CFNumberInitialize();		// See above for hard-coding of this position


        __CFDateInitialize();	// just initializes the time goo
//	_CFRuntimeBridgeClasses(CFDateGetTypeID(), objc_lookUpClass("NSCFDate") ? "NSCFDate" : "__NSCFDate");
        __CFTimeZoneInitialize();
//	_CFRuntimeBridgeClasses(CFTimeZoneGetTypeID(), "NSCFTimeZone");
        __CFBinaryHeapInitialize();
        __CFBitVectorInitialize();
        __CFCharacterSetInitialize();
#if DEPLOYMENT_TARGET_WINDOWS
        __CFLocaleInitialize();
#endif
        __CFStorageInitialize();
        __CFErrorInitialize();
        __CFTreeInitialize();
        __CFURLInitialize();
        __CFBundleInitialize();
#if DEPLOYMENT_TARGET_MACOSX
        __CFPlugInInitialize();
        __CFPlugInInstanceInitialize();
#endif //__MACH__
        __CFUUIDInitialize();
#if DEPLOYMENT_TARGET_MACOSX
        __CFMessagePortInitialize();
        __CFMachPortInitialize();
#endif
        __CFStreamInitialize();
        __CFPreferencesDomainInitialize();
#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX
        __CFRunLoopInitialize();
        __CFRunLoopObserverInitialize();
        __CFRunLoopSourceInitialize();
        __CFRunLoopTimerInitialize();
        __CFSocketInitialize();
#endif
        __CFFileDescriptorInitialize();
        __CFNotificationCenterInitialize();

#if DEPLOYMENT_TARGET_MACOSX
        {
            CFIndex idx, cnt;
            char **args;
            args = *_NSGetArgv();
            cnt = *_NSGetArgc();
            CFIndex count;
            CFStringRef *list, buffer[256];
            list = (cnt <= 256) ? (CFStringRef*)buffer : (CFStringRef*)malloc(cnt * sizeof(CFStringRef));
            for (idx = 0, count = 0; idx < cnt; idx++) {
                if (NULL == args[idx]) continue;
                list[count] = CFStringCreateWithCString(kCFAllocatorSystemDefault, args[idx], kCFStringEncodingUTF8);
                if (NULL == list[count]) {
                    list[count] = CFStringCreateWithCString(kCFAllocatorSystemDefault, args[idx], kCFStringEncodingISOLatin1);
                    // We CANNOT use the string SystemEncoding here;
                    // Do not argue: it is not initialized yet, but these
                    // arguments MUST be initialized before it is.
                    // We should just ignore the argument if the UTF-8
                    // conversion fails, but out of charity we try once
                    // more with ISO Latin1, a standard unix encoding.
                }
                if (NULL != list[count]) count++;
            }
            __CFArgStuff = CFArrayCreate(kCFAllocatorSystemDefault, (const void **)list, count, &kCFTypeArrayCallBacks);
        }
#endif
        _CFProcessPath();	// cache this early

        if (__CFRuntimeClassTableCount < 256) __CFRuntimeClassTableCount = 256;

#if defined(DEBUG) && !DEPLOYMENT_TARGET_WINDOWS
        CFLog(kCFLogLevelWarning, CFSTR("Assertions enabled"));
#endif
    }
}
Exemple #16
0
/**
 * fork current process into the background.
 *
 * This function forks a process into the background, in order to
 * become a daemon process. It does a few things along the way:
 *
 * - becoming a process/session group leader, and  forking a second time so
 *   that process/session group leader can exit.
 *
 * - changing the working directory to /
 *
 * - closing stdin, stdout and stderr (unless stderr_log is set) and
 *   redirecting them to /dev/null
 *
 * @param quit_immediately : indicates if the parent process should
 *                           exit after a successful fork.
 * @param stderr_log       : indicates if stderr is being used for
 *                           logging and shouldn't be closed
 * @returns -1 : fork error
 *           0 : child process returning
 *          >0 : parent process returning. returned value is the child PID.
 */
int
netsnmp_daemonize(int quit_immediately, int stderr_log)
{
    int i = 0;
    DEBUGMSGT(("daemonize","deamonizing...\n"));
#if HAVE_FORK
#if defined(darwin9)
     char            path [PATH_MAX] = "";
     uint32_t        size = sizeof (path);

     /*
      * if we are already launched in a "daemonized state", just
      * close & redirect the file descriptors
      */
     if(getppid() <= 2) {
         _daemon_prep(stderr_log);
         return 0;
     }

     if (_NSGetExecutablePath (path, &size))
         return -1;
#endif
    /*
     * Fork to return control to the invoking process and to
     * guarantee that we aren't a process group leader.
     */
#if HAVE_FORKALL
    i = forkall();
#else
    i = fork();
#endif
    if (i != 0) {
        /* Parent. */
        DEBUGMSGT(("daemonize","first fork returned %d.\n", i));
        if(i == -1) {
            snmp_log(LOG_ERR,"first fork failed (errno %d) in "
                     "netsnmp_daemonize()\n", errno);
            return -1;
        }
        if (quit_immediately) {
            DEBUGMSGT(("daemonize","parent exiting\n"));
            exit(0);
        }
    } else {
        /* Child. */
#ifdef HAVE_SETSID
        /* Become a process/session group leader. */
        setsid();
#endif
        /*
         * Fork to let the process/session group leader exit.
         */
#if HAVE_FORKALL
	i = forkall();
#else
	i = fork();
#endif
        if (i != 0) {
            DEBUGMSGT(("daemonize","second fork returned %d.\n", i));
            if(i == -1) {
                snmp_log(LOG_ERR,"second fork failed (errno %d) in "
                         "netsnmp_daemonize()\n", errno);
            }
            /* Parent. */
            exit(0);
        }
#ifndef WIN32
        else {
            /* Child. */
            
            DEBUGMSGT(("daemonize","child continuing\n"));

#if ! defined(darwin9)
            _daemon_prep(stderr_log);
#else
             /*
              * Some darwin calls (using mach ports) don't work after
              * a fork. So, now that we've forked, we re-exec ourself
              * to ensure that the child's mach ports are all set up correctly,
              * the getppid call above will prevent the exec child from
              * forking...
              */
             char * const *argv = *_NSGetArgv ();
             DEBUGMSGT(("daemonize","re-execing forked child\n"));
             execv (path, argv);
             snmp_log(LOG_ERR,"Forked child unable to re-exec - %s.\n", strerror (errno));
             exit (0);
#endif
        }
#endif /* !WIN32 */
    }
#endif /* HAVE_FORK */
    return i;
}
int _environment_initialize( const application_t application )
{
#if FOUNDATION_PLATFORM_WINDOWS
	int ia;
	int num_args = 0;
	DWORD ret = 0;
	wchar_t module_filename[FOUNDATION_MAX_PATHLEN];
	LPWSTR* arg_list = CommandLineToArgvW( GetCommandLineW(), &num_args );
	if( !arg_list )
		return -1;

	for( ia = 0; ia < num_args; ++ia )
		array_push( _environment_argv, string_allocate_from_wstring( arg_list[ia], 0 ) );

	LocalFree( arg_list );

	if( GetModuleFileNameW( 0, module_filename, FOUNDATION_MAX_PATHLEN ) )
	{
		char* exe_path = string_allocate_from_wstring( module_filename, 0 );
		char* dir_path = path_make_absolute( exe_path );

		_environment_set_executable_paths( dir_path );

		string_deallocate( dir_path );
		string_deallocate( exe_path );
	}
	else
	{
		log_errorf( ERROR_SYSTEM_CALL_FAIL, "Unable to get module filename" );
		return -1;
	}
	
#elif FOUNDATION_PLATFORM_APPLE
	
	int ia;
	int* argc_ptr = _NSGetArgc();
	char*** argv_ptr = _NSGetArgv();

	for( ia = 0; ia < *argc_ptr; ++ia )
		array_push( _environment_argv, string_clone( (*argv_ptr)[ia] ) );

	FOUNDATION_ASSERT( *argc_ptr > 0 );
	char* exe_path = path_make_absolute( (*argv_ptr)[0] );

	_environment_set_executable_paths( exe_path );

	string_deallocate( exe_path );
	
#elif FOUNDATION_PLATFORM_POSIX

	stream_t* cmdline = fs_open_file( "/proc/self/cmdline", STREAM_IN | STREAM_BINARY );
	if( !cmdline )
	{
		log_errorf( ERROR_SYSTEM_CALL_FAIL, "Unable to read /proc/self/cmdline" );
		return -1;
	}

	while( true )
	{
		char* arg = stream_read_string( cmdline );
		if( !string_length( arg ) )
		{
			string_deallocate( arg );
			break;
		}

		array_push( _environment_argv, arg );
	}

	char exelink[FOUNDATION_MAX_PATHLEN] = {0};
	if( readlink( "/proc/self/exe", exelink, FOUNDATION_MAX_PATHLEN ) < 0 )
	{
		log_errorf( ERROR_SYSTEM_CALL_FAIL, "Unable to read /proc/self/exe link" );
		return -1;
	}

	char* exe_path;
	char* dir_path;

	exe_path = path_clean( string_clone( exelink ), path_is_absolute( exelink ) );
	dir_path = path_make_absolute( exe_path );

	_environment_set_executable_paths( dir_path );

	string_deallocate( dir_path );
	string_deallocate( exe_path );

#else
#  error Not implemented
	/*if( array_size( _environment_argv ) > 0 )
	{
		char* exe_path = path_clean( string_clone( _environment_argv[0] ), path_is_absolute( _environment_argv[0] ) );
		char* dir_path = path_make_absolute( exe_path );

		_environment_set_executable_paths( dir_path );

		string_deallocate( dir_path );
		string_deallocate( exe_path );
	}
	else if( !string_length( _environment_executable_dir ) )
	   	string_copy( _environment_executable_dir, environment_current_working_directory(), FOUNDATION_MAX_PATHLEN ); */
#endif

   	_environment_app = application;

	if( uuid_is_null( _environment_app.instance ) )
		_environment_app.instance = uuid_generate_random();

   	string_copy( _environment_initial_working_dir, environment_current_working_directory(), FOUNDATION_MAX_PATHLEN );

	environment_temporary_directory();

	return 0;
}
Exemple #18
0
bool
mm_GetGameName(char *buffer, size_t size)
{
	buffer[0] = '\0';

#if defined _WIN32
	static char game[128];

	LPWSTR pCmdLine = GetCommandLineW();
	int argc;
	LPWSTR *wargv = CommandLineToArgvW(pCmdLine, &argc);
	for (int i = 0; i < argc; ++i)
	{
		if (wcscmp(wargv[i], L"-game") != 0)
			continue;

		if (++i >= argc)
			break;

		wcstombs(buffer, wargv[i], size);
		buffer[size-1] = '\0';
		break;
	}

	LocalFree(wargv);

	return buffer[0] != 0;
#elif defined __APPLE__
	int argc = *_NSGetArgc();
	char **argv = *_NSGetArgv();
	for (int i = 0; i < argc; ++i)
	{
		if (strcmp(argv[i], "-game") != 0)
			continue;

		if (++i >= argc)
			break;

		strncpy(buffer, argv[i], size);
		buffer[size-1] = '\0';
		break;
	}

	return buffer[0] != 0;
#elif defined __linux__
	FILE *pFile = fopen("/proc/self/cmdline", "rb");
	if (!pFile)
		return false;

	char *arg = NULL;
	size_t argsize = 0;
	bool bNextIsGame = false;

	while (getdelim(&arg, &argsize, 0, pFile) != -1)
	{
		if (bNextIsGame)
		{
			strncpy(buffer, arg, size);
			buffer[size-1] = '\0';
			break;
		}

		if (strcmp(arg, "-game") == 0)
		{
			bNextIsGame = true;
		}
	}

	free(arg);
	fclose(pFile);

	return buffer[0] != 0;
#else
#error unsupported platform
#endif
}
Exemple #19
0
aslclient
asl_open(const char *ident, const char *facility, uint32_t opts)
{
	char *name, *x;
	asl_client_t *asl;

	asl = (asl_client_t *)calloc(1, sizeof(asl_client_t));
	if (asl == NULL)
	{
		errno = ENOMEM;
		return NULL;
	}

	asl->options = opts;

	asl->sock = -1;

	_asl_global_init();

	asl->pid = getpid();
	asl->uid = getuid();
	asl->gid = getgid();

	asl->filter = ASL_FILTER_MASK_UPTO(ASL_LEVEL_NOTICE);

	if (ident != NULL)
	{
		asl->name = strdup(ident);
		if (asl->name == NULL)
		{
			if (asl->sock >= 0) close(asl->sock);
			free(asl);
			return NULL;
		}
	}
	else
	{
		name = *(*_NSGetArgv());
		if (name != NULL)
		{
			x = strrchr(name, '/');
			if (x != NULL) x++;
			else x = name;
			asl->name = strdup(x);
			if (asl->name == NULL)
			{
				if (asl->sock >= 0) close(asl->sock);
				free(asl);
				return NULL;
			}
		}
	}

	asl->facility = NULL;
	if (facility != NULL) asl->facility = strdup(facility);
	else asl->facility = strdup(asl_syslog_faciliy_num_to_name(LOG_USER));
	if (asl->facility == NULL)
	{
		if (asl->sock >= 0) close(asl->sock);
		if (asl->name != NULL) free(asl->name);
		free(asl);
		return NULL;
	}

	if (!(asl->options & ASL_OPT_NO_REMOTE)) _asl_notify_open(1);

	if (asl->options & ASL_OPT_STDERR) asl_add_output((aslclient)asl, fileno(stderr), ASL_MSG_FMT_STD, ASL_TIME_FMT_LCL, ASL_ENCODE_SAFE);

	asl->refcount = 1;

	return (aslclient)asl;
}
static int reexec(cpu_type_t cputype, const char *guardenv)
{
	posix_spawnattr_t  attr;
	int                ret, envcount;
	size_t             copied = 0;
	char			   **argv, **oldenvp, **newenvp;
	char			   execpath[MAXPATHLEN+1];
	uint32_t		   execsize;
	char               guardstr[32];

	argv = *_NSGetArgv();
	oldenvp = *_NSGetEnviron();
	for (envcount = 0; oldenvp[envcount]; envcount++);
	// if there are 4 elements and a NULL, envcount will be 4

	newenvp = calloc(envcount+2, sizeof(newenvp[0]));
	for (envcount = 0; oldenvp[envcount]; envcount++) {
		newenvp[envcount] = oldenvp[envcount];
	}

	snprintf(guardstr, sizeof(guardstr), "%s=1", guardenv);
	newenvp[envcount++] = guardstr;
	newenvp[envcount] = NULL;

	execsize = (uint32_t)sizeof(execpath);
	ret = _NSGetExecutablePath(execpath, &execsize);
	if (ret != 0) {
		return -1;
	}

	ret = posix_spawnattr_init(&attr);
	if (ret != 0) {
		return -1;
	}
	ret = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETEXEC);
	if (ret != 0) {
		return -1;
	}
	ret = posix_spawnattr_setbinpref_np(&attr, 1, &cputype, &copied);
	if (ret != 0 || copied != 1) {
		return -1;
	}

#if 0
	fprintf(stderr, "reexec: %s (arch=%d)\n", execpath, cputype);
	for (envcount=0; newenvp[envcount]; envcount++) {
		fprintf(stderr, "env[%d] = %s\n", envcount, newenvp[envcount]);
	}
	for (envcount=0; argv[envcount]; envcount++) {
		fprintf(stderr, "argv[%d] = %s\n", envcount, argv[envcount]);
	}
#endif

	ret = posix_spawn(NULL, execpath, NULL, &attr, argv, newenvp);
	if (ret != 0) {
		errno = ret;
		return -1;
	}

	/* should not be reached */
	return 0;
}
Exemple #21
0
const char *_CFProcessPath(void) {
#if !defined(__LINUX__)
    CFAllocatorRef alloc = NULL;
    char *thePath = NULL;
    int execIndex = 0;
    
    if (__CFProcessPath) return __CFProcessPath;
    if (!__CFProcessPath) {
        thePath = getenv("CFProcessPath");
        
        alloc = CFRetain(__CFGetDefaultAllocator());
        
	if (thePath) {
	    int len = strlen(thePath);
	    __CFProcessPath = CFAllocatorAllocate(alloc, len+1, 0);
            if (__CFOASafe) __CFSetLastAllocationEventName((void *)__CFProcessPath, "CFUtilities (process-path)");
	    memmove((char *)__CFProcessPath, thePath, len + 1);
	}
    }

#if defined(__MACH__)
    {
	struct stat exec, lcfm;
        unsigned long size = CFMaxPathSize;
        char buffer[CFMaxPathSize];
        if (0 == _NSGetExecutablePath(buffer, &size) &&
            strcasestr(buffer, "LaunchCFMApp") != NULL &&
                0 == stat("/System/Library/Frameworks/Carbon.framework/Versions/Current/Support/LaunchCFMApp", &lcfm) &&
                0 == stat(buffer, &exec) &&
                (lcfm.st_dev == exec.st_dev) &&
                (lcfm.st_ino == exec.st_ino)) {
            // Executable is LaunchCFMApp, take special action
            execIndex = 1;
            __CFIsCFM = true;
        }
    }
#endif
    
    if (!__CFProcessPath && NULL != (*_NSGetArgv())[execIndex]) {
	char buf[CFMaxPathSize] = {0};
#if defined(__WIN32__)
	HINSTANCE hinst = GetModuleHandle(NULL);
	DWORD rlen = hinst ? GetModuleFileName(hinst, buf, 1028) : 0;
	thePath = rlen ? buf : NULL;
#else
	struct stat statbuf;
        const char *arg0 = (*_NSGetArgv())[execIndex];
        if (arg0[0] == '/') {
            // We've got an absolute path; look no further;
            thePath = (char *)arg0;
        } else {
            char *theList = getenv("PATH");
            if (NULL != theList && NULL == strrchr(arg0, '/')) {
                thePath = _CFSearchForNameInPath(alloc, arg0, theList);
                if (thePath) {
                    // User could have "." or "../bin" or other relative path in $PATH
                    if (('/' != thePath[0]) && _CFGetCurrentDirectory(buf, CFMaxPathSize)) {
                        strlcat(buf, "/", CFMaxPathSize);
                        strlcat(buf, thePath, CFMaxPathSize);
                        if (0 == stat(buf, &statbuf)) {
                            CFAllocatorDeallocate(alloc, (void *)thePath);
                            thePath = buf;
                        }
                    }
                    if (thePath != buf) {
                        strlcpy(buf, thePath, CFMaxPathSize);
                        CFAllocatorDeallocate(alloc, (void *)thePath);
                        thePath = buf;
                    }
                }
            }
        }
        
	// After attempting a search through $PATH, if existant,
	// try prepending the current directory to argv[0].
        if (!thePath && _CFGetCurrentDirectory(buf, CFMaxPathSize)) {
            if (buf[strlen(buf)-1] != '/') {
                strlcat(buf, "/", CFMaxPathSize);
            }
	    strlcat(buf, arg0, CFMaxPathSize);
            if (0 == stat(buf, &statbuf)) {
		thePath = buf;
            }
	}

        if (thePath) {
            // We are going to process the buffer replacing all "/./" with "/"
            CFIndex srcIndex = 0, dstIndex = 0;
            CFIndex len = strlen(thePath);
            for (srcIndex=0; srcIndex<len; srcIndex++) {
                thePath[dstIndex] = thePath[srcIndex];
                dstIndex++;
                if ((srcIndex < len-2) && (thePath[srcIndex] == '/') && (thePath[srcIndex+1] == '.') && (thePath[srcIndex+2] == '/')) {
                    // We are at the first slash of a "/./"  Skip the "./"
                    srcIndex+=2;
                }
            }
            thePath[dstIndex] = 0;
        }
#endif
        if (!thePath) {
	    thePath = (*_NSGetArgv())[execIndex];
        }
	if (thePath) {
	    int len = strlen(thePath);
	    __CFProcessPath = CFAllocatorAllocate(alloc, len + 1, 0);
            if (__CFOASafe) __CFSetLastAllocationEventName((void *)__CFProcessPath, "CFUtilities (process-path)");
            memmove((char *)__CFProcessPath, thePath, len + 1);
	}
	if (__CFProcessPath) {
	    const char *p = 0;
	    int i;
	    for (i = 0; __CFProcessPath[i] != 0; i++){
		if (__CFProcessPath[i] == '/')
		    p = __CFProcessPath + i; 
	    }
	    if (p != 0)
		__CFprogname = p + 1;
	    else
		__CFprogname = __CFProcessPath;
	}
    }
#endif
    if (!__CFProcessPath) {
	__CFProcessPath = "";
    }
    return __CFProcessPath;
}
Exemple #22
0
static __attribute__((constructor)) void myInit() 
{
	libSystemAlreadyInited = ( _NSGetArgv() != NULL );
}