示例#1
0
// CTortoiseMergeApp initialization
BOOL CTortoiseMergeApp::InitInstance()
{
    SetDllDirectory(L"");
    SetTaskIDPerUUID();
    CCrashReport::Instance().AddUserInfoToReport(L"CommandLine", GetCommandLine());

    {
        DWORD len = GetCurrentDirectory(0, nullptr);
        if (len)
        {
            auto originalCurrentDirectory = std::make_unique<TCHAR[]>(len);
            if (GetCurrentDirectory(len, originalCurrentDirectory.get()))
            {
                sOrigCWD = originalCurrentDirectory.get();
                sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD);
            }
        }
    }

    //set the resource dll for the required language
    CRegDWORD loc = CRegDWORD(L"Software\\TortoiseSVN\\LanguageID", 1033);
    long langId = loc;
    CString langDll;
    HINSTANCE hInst = nullptr;
    do
    {
        langDll.Format(L"%sLanguages\\TortoiseMerge%ld.dll", (LPCTSTR)CPathUtils::GetAppParentDirectory(), langId);

        hInst = LoadLibrary(langDll);
        CString sVer = _T(STRPRODUCTVER);
        CString sFileVer = CPathUtils::GetVersionFromFile(langDll);
        if (sFileVer.Compare(sVer)!=0)
        {
            FreeLibrary(hInst);
            hInst = nullptr;
        }
        if (hInst)
            AfxSetResourceHandle(hInst);
        else
        {
            DWORD lid = SUBLANGID(langId);
            lid--;
            if (lid > 0)
            {
                langId = MAKELANGID(PRIMARYLANGID(langId), lid);
            }
            else
                langId = 0;
        }
    } while ((!hInst) && (langId != 0));
    TCHAR buf[6] = { 0 };
    wcscpy_s(buf, L"en");
    langId = loc;
    CString sHelppath;
    sHelppath = this->m_pszHelpFilePath;
    sHelppath = sHelppath.MakeLower();
    sHelppath.Replace(L".chm", L"_en.chm");
    free((void*)m_pszHelpFilePath);
    m_pszHelpFilePath=_wcsdup(sHelppath);
    sHelppath = CPathUtils::GetAppParentDirectory() + L"Languages\\TortoiseMerge_en.chm";
    do
    {
        GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf));
        CString sLang = L"_";
        sLang += buf;
        sHelppath.Replace(L"_en", sLang);
        if (PathFileExists(sHelppath))
        {
            free((void*)m_pszHelpFilePath);
            m_pszHelpFilePath=_wcsdup(sHelppath);
            break;
        }
        sHelppath.Replace(sLang, L"_en");
        GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf));
        sLang += L"_";
        sLang += buf;
        sHelppath.Replace(L"_en", sLang);
        if (PathFileExists(sHelppath))
        {
            free((void*)m_pszHelpFilePath);
            m_pszHelpFilePath=_wcsdup(sHelppath);
            break;
        }
        sHelppath.Replace(sLang, L"_en");

        DWORD lid = SUBLANGID(langId);
        lid--;
        if (lid > 0)
        {
            langId = MAKELANGID(PRIMARYLANGID(langId), lid);
        }
        else
            langId = 0;
    } while (langId);
    setlocale(LC_ALL, "");
    // We need to explicitly set the thread locale to the system default one to avoid possible problems with saving files in its original codepage
    // The problems occures when the language of OS differs from the regional settings
    // See the details here: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100887
    SetThreadLocale(LOCALE_SYSTEM_DEFAULT);

    // InitCommonControls() is required on Windows XP if an application
    // manifest specifies use of ComCtl32.dll version 6 or later to enable
    // visual styles.  Otherwise, any window creation will fail.
    InitCommonControls();

    CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
    CMFCVisualManagerWindows::m_b3DTabsXPTheme = TRUE;
    CMFCButton::EnableWindowsTheming();
    EnableTaskbarInteraction(FALSE);

    // Initialize all Managers for usage. They are automatically constructed
    // if not yet present
    InitContextMenuManager();
    InitKeyboardManager();
    InitTooltipManager ();
    CMFCToolTipInfo params;
    params.m_bVislManagerTheme = TRUE;

    GetTooltipManager ()->SetTooltipParams (
        AFX_TOOLTIP_TYPE_ALL,
        RUNTIME_CLASS (CMFCToolTipCtrl),
        &params);

    CCmdLineParser parser = CCmdLineParser(this->m_lpCmdLine);

    g_sGroupingUUID = parser.GetVal(L"groupuuid");

    if (parser.HasKey(L"?") || parser.HasKey(L"help"))
    {
        CString sHelpText;
        sHelpText.LoadString(IDS_COMMANDLINEHELP);
        MessageBox(nullptr, sHelpText, L"TortoiseMerge", MB_ICONINFORMATION);
        return FALSE;
    }

    // Initialize OLE libraries
    if (!AfxOleInit())
    {
        AfxMessageBox(IDP_OLE_INIT_FAILED);
        return FALSE;
    }
    AfxEnableControlContainer();
    // Standard initialization
    // If you are not using these features and wish to reduce the size
    // of your final executable, you should remove from the following
    // the specific initialization routines you do not need
    // Change the registry key under which our settings are stored
    SetRegistryKey(L"TortoiseMerge");

    if (CRegDWORD(L"Software\\TortoiseMerge\\Debug", FALSE)==TRUE)
        AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION);

    // To create the main window, this code creates a new frame window
    // object and then sets it as the application's main window object
    CMainFrame* pFrame = new CMainFrame;
    if (!pFrame)
        return FALSE;
    m_pMainWnd = pFrame;

    // create and load the frame with its resources
    if (!pFrame->LoadFrame(IDR_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, nullptr, nullptr))
        return FALSE;

    // Fill in the command line options
    pFrame->m_Data.m_baseFile.SetFileName(parser.GetVal(L"base"));
    pFrame->m_Data.m_baseFile.SetDescriptiveName(parser.GetVal(L"basename"));
    pFrame->m_Data.m_baseFile.SetReflectedName(parser.GetVal(L"basereflectedname"));
    pFrame->m_Data.m_theirFile.SetFileName(parser.GetVal(L"theirs"));
    pFrame->m_Data.m_theirFile.SetDescriptiveName(parser.GetVal(L"theirsname"));
    pFrame->m_Data.m_theirFile.SetReflectedName(parser.GetVal(L"theirsreflectedname"));
    pFrame->m_Data.m_yourFile.SetFileName(parser.GetVal(L"mine"));
    pFrame->m_Data.m_yourFile.SetDescriptiveName(parser.GetVal(L"minename"));
    pFrame->m_Data.m_yourFile.SetReflectedName(parser.GetVal(L"minereflectedname"));
    pFrame->m_Data.m_mergedFile.SetFileName(parser.GetVal(L"merged"));
    pFrame->m_Data.m_mergedFile.SetDescriptiveName(parser.GetVal(L"mergedname"));
    pFrame->m_Data.m_mergedFile.SetReflectedName(parser.GetVal(L"mergedreflectedname"));
    pFrame->m_Data.m_sPatchPath = parser.HasVal(L"patchpath") ? parser.GetVal(L"patchpath") : L"";
    pFrame->m_Data.m_sPatchPath.Replace('/', '\\');
    if (parser.HasKey(L"patchoriginal"))
        pFrame->m_Data.m_sPatchOriginal = parser.GetVal(L"patchoriginal");
    if (parser.HasKey(L"patchpatched"))
        pFrame->m_Data.m_sPatchPatched = parser.GetVal(L"patchpatched");
    pFrame->m_Data.m_sDiffFile = parser.GetVal(L"diff");
    pFrame->m_Data.m_sDiffFile.Replace('/', '\\');
    if (parser.HasKey(L"oneway"))
        pFrame->m_bOneWay = TRUE;
    if (parser.HasKey(L"diff"))
        pFrame->m_bOneWay = FALSE;
    if (parser.HasKey(L"reversedpatch"))
        pFrame->m_bReversedPatch = TRUE;
    if (parser.HasKey(L"saverequired"))
        pFrame->m_bSaveRequired = true;
    if (parser.HasKey(L"saverequiredonconflicts"))
        pFrame->m_bSaveRequiredOnConflicts = true;
    if (parser.HasKey(L"nosvnresolve"))
        pFrame->m_bAskToMarkAsResolved = false;
    if (pFrame->m_Data.IsBaseFileInUse() && !pFrame->m_Data.IsYourFileInUse() && pFrame->m_Data.IsTheirFileInUse())
    {
        pFrame->m_Data.m_yourFile.TransferDetailsFrom(pFrame->m_Data.m_theirFile);
    }

    if ((!parser.HasKey(L"patchpath"))&&(parser.HasVal(L"diff")))
    {
        // a patchfile was given, but not folder path to apply the patch to
        // If the patchfile is located inside a working copy, then use the parent directory
        // of the patchfile as the target directory, otherwise ask the user for a path.
        if (parser.HasKey(L"wc"))
            pFrame->m_Data.m_sPatchPath = pFrame->m_Data.m_sDiffFile.Left(pFrame->m_Data.m_sDiffFile.ReverseFind('\\'));
        else
        {
            CBrowseFolder fbrowser;
            fbrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
            if (fbrowser.Show(nullptr, pFrame->m_Data.m_sPatchPath) == CBrowseFolder::CANCEL)
                return FALSE;
        }
    }

    if ((parser.HasKey(L"patchpath"))&&(!parser.HasVal(L"diff")))
    {
        // A path was given for applying a patchfile, but
        // the patchfile itself was not.
        // So ask the user for that patchfile

        HRESULT hr;
        // Create a new common save file dialog
        CComPtr<IFileOpenDialog> pfd;
        hr = pfd.CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER);
        if (SUCCEEDED(hr))
        {
            // Set the dialog options
            DWORD dwOptions;
            if (SUCCEEDED(hr = pfd->GetOptions(&dwOptions)))
            {
                hr = pfd->SetOptions(dwOptions | FOS_FILEMUSTEXIST | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
            }

            // Set a title
            if (SUCCEEDED(hr))
            {
                CString temp;
                temp.LoadString(IDS_OPENDIFFFILETITLE);
                pfd->SetTitle(temp);
            }
            CSelectFileFilter fileFilter(IDS_PATCHFILEFILTER);
            hr = pfd->SetFileTypes(fileFilter.GetCount(), fileFilter);
            bool bAdvised = false;
            DWORD dwCookie = 0;
            CComObjectStackEx<PatchOpenDlgEventHandler> cbk;
            CComQIPtr<IFileDialogEvents> pEvents = cbk.GetUnknown();

            {
                CComPtr<IFileDialogCustomize> pfdCustomize;
                hr = pfd.QueryInterface(&pfdCustomize);
                if (SUCCEEDED(hr))
                {
                    // check if there's a unified diff on the clipboard and
                    // add a button to the fileopen dialog if there is.
                    UINT cFormat = RegisterClipboardFormat(L"TSVN_UNIFIEDDIFF");
                    if ((cFormat) && (OpenClipboard(nullptr)))
                    {
                        HGLOBAL hglb = GetClipboardData(cFormat);
                        if (hglb)
                        {
                            pfdCustomize->AddPushButton(101, CString(MAKEINTRESOURCE(IDS_PATCH_COPYFROMCLIPBOARD)));
                            hr = pfd->Advise(pEvents, &dwCookie);
                            bAdvised = SUCCEEDED(hr);
                        }
                        CloseClipboard();
                    }
                }
            }

            // Show the save file dialog
            if (SUCCEEDED(hr) && SUCCEEDED(hr = pfd->Show(pFrame->m_hWnd)))
            {
                // Get the selection from the user
                CComPtr<IShellItem> psiResult;
                hr = pfd->GetResult(&psiResult);
                if (bAdvised)
                    pfd->Unadvise(dwCookie);
                if (SUCCEEDED(hr))
                {
                    PWSTR pszPath = nullptr;
                    hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
                    if (SUCCEEDED(hr))
                    {
                        pFrame->m_Data.m_sDiffFile = pszPath;
                        CoTaskMemFree(pszPath);
                    }
                }
                else
                {
                    // no result, which means we closed the dialog in our button handler
                    std::wstring sTempFile;
                    if (TrySavePatchFromClipboard(sTempFile))
                        pFrame->m_Data.m_sDiffFile = sTempFile.c_str();
                }
            }
            else
            {
                if (bAdvised)
                    pfd->Unadvise(dwCookie);
                return FALSE;
            }
        }
    }

    if ( pFrame->m_Data.m_baseFile.GetFilename().IsEmpty() && pFrame->m_Data.m_yourFile.GetFilename().IsEmpty() )
    {
        int nArgs;
        LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
        if (!szArglist)
            TRACE("CommandLineToArgvW failed\n");
        else
        {
            if ( nArgs==3 || nArgs==4 )
            {
                // Four parameters:
                // [0]: Program name
                // [1]: BASE file
                // [2]: my file
                // [3]: THEIR file (optional)
                // This is the same format CAppUtils::StartExtDiff
                // uses if %base and %mine are not set and most
                // other diff tools use it too.
                if ( PathFileExists(szArglist[1]) && PathFileExists(szArglist[2]) )
                {
                    pFrame->m_Data.m_baseFile.SetFileName(szArglist[1]);
                    pFrame->m_Data.m_yourFile.SetFileName(szArglist[2]);
                    if ( nArgs == 4 && PathFileExists(szArglist[3]) )
                    {
                        pFrame->m_Data.m_theirFile.SetFileName(szArglist[3]);
                    }
                }
            }
            else if (nArgs == 2)
            {
                // only one path specified: use it to fill the "open" dialog
                if (PathFileExists(szArglist[1]))
                {
                    pFrame->m_Data.m_yourFile.SetFileName(szArglist[1]);
                    pFrame->m_Data.m_yourFile.StoreFileAttributes();
                }
            }
        }

        // Free memory allocated for CommandLineToArgvW arguments.
        LocalFree(szArglist);
    }

    pFrame->m_bReadOnly = !!parser.HasKey(L"readonly");
    if (GetFileAttributes(pFrame->m_Data.m_yourFile.GetFilename()) & FILE_ATTRIBUTE_READONLY)
        pFrame->m_bReadOnly = true;
    pFrame->m_bBlame = !!parser.HasKey(L"blame");
    // diffing a blame means no editing!
    if (pFrame->m_bBlame)
        pFrame->m_bReadOnly = true;

    pFrame->SetWindowTitle();

    if (parser.HasKey(L"createunifieddiff"))
    {
        // user requested to create a unified diff file
        CString origFile = parser.GetVal(L"origfile");
        CString modifiedFile = parser.GetVal(L"modifiedfile");
        if (!origFile.IsEmpty() && !modifiedFile.IsEmpty())
        {
            CString outfile = parser.GetVal(L"outfile");
            if (outfile.IsEmpty())
            {
                CCommonAppUtils::FileOpenSave(outfile, nullptr, IDS_SAVEASTITLE, IDS_COMMONFILEFILTER, false, nullptr);
            }
            if (!outfile.IsEmpty())
            {
                CRegStdDWORD regContextLines(L"Software\\TortoiseMerge\\ContextLines", 0);
                CAppUtils::CreateUnifiedDiff(origFile, modifiedFile, outfile, regContextLines, true, false);
                return FALSE;
            }
        }
    }

    pFrame->resolveMsgWnd    = parser.HasVal(L"resolvemsghwnd")   ? (HWND)parser.GetLongLongVal(L"resolvemsghwnd")     : 0;
    pFrame->resolveMsgWParam = parser.HasVal(L"resolvemsgwparam") ? (WPARAM)parser.GetLongLongVal(L"resolvemsgwparam") : 0;
    pFrame->resolveMsgLParam = parser.HasVal(L"resolvemsglparam") ? (LPARAM)parser.GetLongLongVal(L"resolvemsglparam") : 0;

    // The one and only window has been initialized, so show and update it
    pFrame->ActivateFrame();
    pFrame->ShowWindow(SW_SHOW);
    pFrame->UpdateWindow();
    pFrame->ShowDiffBar(!pFrame->m_bOneWay);
    if (!pFrame->m_Data.IsBaseFileInUse() && pFrame->m_Data.m_sPatchPath.IsEmpty() && pFrame->m_Data.m_sDiffFile.IsEmpty())
    {
        pFrame->OnFileOpen(pFrame->m_Data.m_yourFile.InUse());
        return TRUE;
    }

    int line = -2;
    if (parser.HasVal(L"line"))
    {
        line = parser.GetLongVal(L"line");
        line--; // we need the index
    }

    return pFrame->LoadViews(line);
}
示例#2
0
/* Process the commandline, and create standard argc/argv array. */
static int
ProcessCommandLine(wchar_t ***argw)
{
    WCHAR *cmdline;
    wchar_t *argbuf;
    wchar_t **args;
    int argc_max;
    int i, q, argc;

    cmdline = GetCommandLine();
    i = wcslen(cmdline) + 1;
    argbuf = (wchar_t *)malloc(sizeof(wchar_t)*i);
    wcscpy(argbuf, cmdline);

    argc = 0;
    argc_max = 64;
    args = (wchar_t **)malloc(sizeof(wchar_t *) * argc_max);
    if (args == NULL) {
	free(argbuf);
	return(0);
    }

    /* parse commandline into argc/argv format */
    i = 0;
    while (argbuf[i]) {
	while (argbuf[i] == L' ')
		  i++;

	if (argbuf[i]) {
		if ((argbuf[i] == L'\'') || (argbuf[i] == L'"')) {
			q = argbuf[i++];
			if (!argbuf[i])
				break;
		} else
			q = 0;

		args[argc++] = &argbuf[i];

		if (argc >= argc_max) {
			argc_max += 64;
			args = realloc(args, sizeof(wchar_t *)*argc_max);
			if (args == NULL) {
				free(argbuf);
				return(0);
			}
		}

		while ((argbuf[i]) && ((q)
			? (argbuf[i]!=q) : (argbuf[i]!=L' '))) i++;

		if (argbuf[i]) {
			argbuf[i] = 0;
			i++;
		}
	}
    }

    args[argc] = NULL;
    *argw = args;

    return(argc);
}
示例#3
0
文件: vmquery.c 项目: mingpen/OpenNT
DWORD
_cdecl
main(
    int argc,
    char *argv[],
    char *envp[]
    )
{

    STARTUPINFO	StartupInfo;
    PROCESS_INFORMATION ProcessInfo;
    BOOL Success;
    DWORD st;
    DWORD ProcessCount;
    SMALL_RECT Window;
    MEMORY_BASIC_INFORMATION info;
    PUCHAR address;
    PUCHAR buffer;

    ProcessCount = 0;
    if ( strchr(GetCommandLine(),'+') ) {
        NewProcess();
        }

    GetStartupInfo(&StartupInfo);

    Success = CreateProcess(
                    NULL,
                    "vmread +",
                    NULL,
                    NULL,
                    FALSE,
                    CREATE_NEW_CONSOLE,
                    NULL,
                    NULL,
                    &StartupInfo,
                    &ProcessInfo
                    );

    if (Success) {
        printf("Process Created\n");

        Sleep (1000);


        buffer = VirtualAlloc (NULL, 10*1000*1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);

        if (!buffer) {
            printf("virtual alloc failed at %ld.\n",GetLastError());
            return 1;
        }

        address = NULL;
        do {

            Success = VirtualQueryEx (ProcessInfo.hProcess,
                                      (PVOID)address,
                                      &info,
                                      sizeof(info));

            if (!Success) {
                printf ("virtual query failed at %lx - %ld.\n",address,GetLastError());
                break;
            } else {
                printf("address: %lx size %lx state %lx protect %lx type %lx\n",
                    address,
                    info.RegionSize,
                    info.State,
                    info.Protect,
                    info.Type);
            }

            address += info.RegionSize;
        } while (address < (PUCHAR)0x80000000);

        address = 0x40000000;
        do {

            Success = VirtualQueryEx (ProcessInfo.hProcess,
                                      (PVOID)address,
                                      &info,
                                      sizeof(info));

            if (!Success) {
                printf ("virtual query failed at %lx %ld.\n",address,GetLastError());
                return 1;
            } else {
                if (info.AllocationBase == address) {
                    printf("address: %lx size %lx state %lx protect %lx type %lx\n",
                        address,
                        info.RegionSize,
                        info.State,
                        info.Protect,
                        info.Type);
                }
            }
            address += 4096;
        } while (address < (PUCHAR)0x80000000);

        CloseHandle(ProcessInfo.hProcess);
        CloseHandle(ProcessInfo.hThread);
    }
}
BOOL fsCommandLineParser::Parse()
{
	m_vPars.clear ();

	LPCTSTR pszCmdLine = GetCommandLine ();

	if (*pszCmdLine == _T('"'))
	{
		pszCmdLine = _tcschr (pszCmdLine+1, _T('"'));
		if (pszCmdLine)
			pszCmdLine++;
		else
			return FALSE;
	}
	else
	{
		while (*pszCmdLine && *pszCmdLine != _T(' '))
			pszCmdLine++;
	}

	try
	{
		while (*pszCmdLine)
		{
			TCHAR szParam [10000], szValue [10000];
			*szParam = *szValue = 0;
			bool bHasValue = true;

			
			while (*pszCmdLine && (*pszCmdLine == ' ' || *pszCmdLine == '\r' || *pszCmdLine == '\n'))
				pszCmdLine++;

			if (*pszCmdLine == '/' || *pszCmdLine == '-')
			{
				int i = 0;
				while (*++pszCmdLine && *pszCmdLine != ' ' && *pszCmdLine != '=')
					szParam [i++] = *pszCmdLine;

				szParam [i] = 0;

				while (*pszCmdLine == _T(' '))
					pszCmdLine++;

				
				if (*pszCmdLine == '=')
				{
					pszCmdLine++;
					while (*pszCmdLine == ' ')
						pszCmdLine++;
				}
				else
					bHasValue = false;
			}

			if (bHasValue)
			{
				char cSp = ' ';	
				char cSp1 = '\n', cSp2 = '\r';
				
				if (*pszCmdLine == '"' || *pszCmdLine == '\'')
				{
					cSp = *pszCmdLine++;
					cSp1 = cSp2 = 0;
				}

				
				if (*pszCmdLine != '/' && *pszCmdLine != '-')
				{
					int i = 0;
					while (*pszCmdLine && *pszCmdLine != cSp && *pszCmdLine != cSp1 && *pszCmdLine != cSp2)
						szValue [i++] = *pszCmdLine++;

					szValue [i] = 0;

					while (*pszCmdLine && (*pszCmdLine == cSp || *pszCmdLine == cSp1 || *pszCmdLine == cSp2))
						pszCmdLine++;
				}
			}

			if (*szParam || *szValue)
			{
				fsCmdLineParameter par;
				par.strParam = szParam;
				par.strValue = szValue;
				m_vPars.push_back (par);
			}
		}
	}
	catch (const std::exception& ex)
	{
		ASSERT (FALSE);
		vmsLogger::WriteLog("fsCommandLineParser::Parse " + std::string(ex.what()));
	}
	catch (...)
	{
		ASSERT (FALSE);
		vmsLogger::WriteLog("fsCommandLineParser::Parse unknown exception");
	}

	return TRUE;
}
示例#5
0
void Sys_Error (const char *error, ...)
{
	va_list		argptr;
	char		text[1024];
	double end;
	STARTUPINFO startupinfo;
	PROCESS_INFORMATION processinfo;

	va_start (argptr,error);
	vsnprintf (text,sizeof(text)-1, error,argptr);
	va_end (argptr);


//    MessageBox(NULL, text, "Error", 0 /* MB_OK */ );
	Sys_Printf ("ERROR: %s\n", text);

	Con_Log(text);

	NET_Shutdown();	//free sockets and stuff.

#ifdef USESERVICE
	if (asservice)
		Sys_Quit();
#endif

	if (COM_CheckParm("-noreset"))
	{
		Sys_Quit();
		exit(1);
	}

	Sys_Printf ("A new server will be started in 10 seconds unless you press a key\n");


	//check for a key press, quitting if we get one in 10 secs
	end = Sys_DoubleTime() + 10;
	while(Sys_DoubleTime() < end)
	{
		Sleep(500); // don't burn up CPU with polling
		if (_kbhit())
		{
			Sys_Quit();
			exit(1);
		}
	}

	Sys_Printf("\nLoading new instance of FTE...\n\n\n");
	PR_Deinit();	//this takes a bit more mem
	Rank_Flush();
#ifndef MINGW
	fcloseall();	//make sure all files are written.
#endif

//	system("dqwsv.exe");	//spawn a new server to take over. This way, if debugging, then any key will quit, otherwise the server will just spawn a new one.

	memset(&startupinfo, 0, sizeof(startupinfo));
	memset(&processinfo, 0, sizeof(processinfo));

	CreateProcess(NULL,
		GetCommandLine(),
		NULL,
		NULL,
		false,
		0,
		NULL,
		NULL,
		&startupinfo,
		&processinfo);

	CloseHandle(processinfo.hProcess);
	CloseHandle(processinfo.hThread);

	Sys_Quit ();

	exit (1); // this function is NORETURN type, complains without this
}
示例#6
0
文件: XCSoar.cpp 项目: DRIZO/xcsoar
int WINAPI
WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
#ifdef _WIN32_WCE
        gcc_unused LPWSTR lpCmdLine,
#else
        gcc_unused LPSTR lpCmdLine2,
#endif
        int nCmdShow)
#endif
{
#ifdef WIN32
  ResourceLoader::Init(hInstance);
#endif

  Net::Initialise();

  InitialiseDataPath();
  StartupLogFreeRamAndStorage();

  // Write startup note + version to logfile
  LogFormat(_T("Starting XCSoar %s"), XCSoar_ProductToken);

  // Read options from the command line
  {
#ifdef WIN32
    Args args(GetCommandLine(), Usage);
#else
    Args args(argc, argv, Usage);
#endif
    CommandLine::Parse(args);
  }

  ScreenGlobalInit screen_init;

#ifdef WIN32
  /* try to make the UI most responsive */
  SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
#endif

  AllowLanguage();
  InitLanguage();

  InitialiseIOThread();

  // Perform application initialization and run loop
  int ret = EXIT_FAILURE;
  if (Startup())
    ret = CommonInterface::main_window->RunEventLoop();

  if (CommonInterface::main_window != nullptr) {
    CommonInterface::main_window->Destroy();
    delete CommonInterface::main_window;
  }

  DeinitialiseIOThread();

  DisallowLanguage();

  Fonts::Deinitialize();

  DeinitialiseDataPath();
  Net::Deinitialise();

  assert(!ExistsAnyThread());

  return ret;
}
示例#7
0
int main(int argc, char **argv) {
  android::base::InitLogging(argv);

  const std::string cmd_line = GetCommandLine(argc, argv);
  LOG(INFO) << "Service started: " << cmd_line;

  int option_index = 0;
  static const char value_str[] = "value";
  static const char boot_complete_str[] = "record_boot_complete";
  static const char boot_reason_str[] = "record_boot_reason";
  static const char factory_reset_str[] = "record_time_since_factory_reset";
  static const struct option long_options[] = {
    { "help",            no_argument,       NULL,   'h' },
    { "log",             no_argument,       NULL,   'l' },
    { "print",           no_argument,       NULL,   'p' },
    { "record",          required_argument, NULL,   'r' },
    { value_str,         required_argument, NULL,   0 },
    { boot_complete_str, no_argument,       NULL,   0 },
    { boot_reason_str,   no_argument,       NULL,   0 },
    { factory_reset_str, no_argument,       NULL,   0 },
    { NULL,              0,                 NULL,   0 }
  };

  std::string boot_event;
  std::string value;
  int opt = 0;
  while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
    switch (opt) {
      // This case handles long options which have no single-character mapping.
      case 0: {
        const std::string option_name = long_options[option_index].name;
        if (option_name == value_str) {
          // |optarg| is an external variable set by getopt representing
          // the option argument.
          value = optarg;
        } else if (option_name == boot_complete_str) {
          RecordBootComplete();
        } else if (option_name == boot_reason_str) {
          RecordBootReason();
        } else if (option_name == factory_reset_str) {
          RecordFactoryReset();
        } else {
          LOG(ERROR) << "Invalid option: " << option_name;
        }
        break;
      }

      case 'h': {
        ShowHelp(argv[0]);
        break;
      }

      case 'l': {
        LogBootEvents();
        break;
      }

      case 'p': {
        PrintBootEvents();
        break;
      }

      case 'r': {
        // |optarg| is an external variable set by getopt representing
        // the option argument.
        boot_event = optarg;
        break;
      }

      default: {
        DCHECK_EQ(opt, '?');

        // |optopt| is an external variable set by getopt representing
        // the value of the invalid option.
        LOG(ERROR) << "Invalid option: " << optopt;
        ShowHelp(argv[0]);
        return EXIT_FAILURE;
      }
    }
  }

  if (!boot_event.empty()) {
    RecordBootEventFromCommandLine(boot_event, value);
  }

  return 0;
}
示例#8
0
/* exit codes: 0 = ok, 1 = invocation error, 3 = internal error */
int main()
{
    int argc;
    int creationFlags;
    wchar_t **argv;
    wchar_t *env = 0;
    STARTUPINFOW si;
    PROCESS_INFORMATION pi;
    DEBUG_EVENT dbev;
    enum RunMode mode = Run;
    HANDLE image = NULL;

    argv = CommandLineToArgvW(GetCommandLine(), &argc);

    if (argc != ArgCount) {
        fprintf(stderr, "This is an internal helper of Qt Creator. Do not run it manually.\n");
        return 1;
    }

    /* convert message to OEM codepage */
    WideCharToMultiByte(CP_OEMCP, 0, argv[ArgMsg], -1, sleepMsg, sizeof(sleepMsg), NULL, NULL);

    /* Connect to the master, i.e. Creator. */
    if (!(qtcFd = _wfopen(argv[ArgSocket], L"w"))) {
        fprintf(stderr, "Cannot connect creator comm pipe %S: %s\n",
                argv[ArgSocket], strerror(errno));
        doExit(1);
    }

    if (*argv[ArgDir] && !SetCurrentDirectoryW(argv[ArgDir])) {
        /* Only expected error: no such file or direcotry */
        sendMsg("err:chdir %d\n", GetLastError());
        return 1;
    }

    if (*argv[ArgEnv]) {
        FILE *envFd;
        long size;
        if (!(envFd = _wfopen(argv[ArgEnv], L"rb"))) {
            fprintf(stderr, "Cannot read creator env file %S: %s\n",
                    argv[ArgEnv], strerror(errno));
            doExit(1);
        }
        fseek(envFd, 0, SEEK_END);
        size = ftell(envFd);
        rewind(envFd);
        env = malloc(size);
        if (fread(env, 1, size, envFd) != size) {
            perror("Failed to read env file");
            doExit(1);
        }
        fclose(envFd);
    }

    ZeroMemory(&pi, sizeof(pi));
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);

    creationFlags = CREATE_UNICODE_ENVIRONMENT;
    if (!wcscmp(argv[ArgAction], L"debug")) {
        mode = Debug;
    } else if (!wcscmp(argv[ArgAction], L"suspend")) {
        mode = Suspend;
    }

    switch (mode) {
    case Debug:
        creationFlags |= DEBUG_ONLY_THIS_PROCESS;
        break;
    case Suspend:
        creationFlags |= CREATE_SUSPENDED;
        break;
    default:
        break;
    }
    if (!CreateProcessW(0, argv[ArgCmdLine], 0, 0, FALSE, creationFlags, env, 0, &si, &pi)) {
        /* Only expected error: no such file or direcotry, i.e. executable not found */
        sendMsg("err:exec %d\n", GetLastError());
        doExit(1);
    }

    /* This is somewhat convoluted. What we actually want is creating a
       suspended process and letting gdb attach to it. Unfortunately,
       the Windows kernel runs amok when we attempt this.
       So instead we start a debugged process, eat all the initial
       debug events, suspend the process and detach from it. If gdb
       tries to attach *now*, everything goes smoothly. Yay. */
    if (mode == Debug) {
        do {
            if (!WaitForDebugEvent (&dbev, INFINITE))
                systemError("Cannot fetch debug event, error %d\n");
            if (dbev.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT)
                image = dbev.u.CreateProcessInfo.hFile;
            if (dbev.dwDebugEventCode == EXCEPTION_DEBUG_EVENT) {
                /* The first exception to be delivered is a trap
                   which indicates completion of startup. */
                if (SuspendThread(pi.hThread) == (DWORD)-1)
                    systemError("Cannot suspend debugee, error %d\n");
            }
            if (!ContinueDebugEvent(dbev.dwProcessId, dbev.dwThreadId, DBG_CONTINUE))
                systemError("Cannot continue debug event, error %d\n");
        } while (dbev.dwDebugEventCode != EXCEPTION_DEBUG_EVENT);
        if (!DebugActiveProcessStop(dbev.dwProcessId))
            systemError("Cannot detach from debugee, error %d\n");
        if (image)
            CloseHandle(image);
    }

    SetConsoleCtrlHandler(ctrlHandler, TRUE);

    sendMsg("thread %d\n", pi.dwThreadId);
    sendMsg("pid %d\n", pi.dwProcessId);

    if (WaitForSingleObject(pi.hProcess, INFINITE) == WAIT_FAILED)
        systemError("Wait for debugee failed, error %d\n");
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
    free(env);
    doExit(0);
    return 0;
}
示例#9
0
extern "C" int WINAPI _tWinMain(HINSTANCE hInstance, 
    HINSTANCE /*hPrevInstance*/, LPTSTR lpCmdLine, int /*nShowCmd*/)
{
    lpCmdLine = GetCommandLine(); // この行は _ATL_MIN_CRT のために必要です
    
#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)
    HRESULT hRes = CoInitializeEx(NULL, COINIT_MULTITHREADED);
#else
    HRESULT hRes = CoInitialize(NULL);
#endif
    _ASSERTE(SUCCEEDED(hRes));
    _Module.Init(ObjectMap, hInstance, &LIBID_SUBEXELib);
    _Module.dwThreadID = GetCurrentThreadId();
    TCHAR szTokens[] = _T("-/");

    int nRet = 0;
    BOOL bRun = TRUE;
    LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens);
    while (lpszToken != NULL)
    {
        if (lstrcmpi(lpszToken, _T("UnregServer"))==0)
        {
            _Module.UpdateRegistryFromResource(IDR_SubExe, FALSE);
            nRet = _Module.UnregisterServer(TRUE);
            bRun = FALSE;
            break;
        }
        if (lstrcmpi(lpszToken, _T("RegServer"))==0)
        {
            _Module.UpdateRegistryFromResource(IDR_SubExe, TRUE);
            nRet = _Module.RegisterServer(TRUE);
            bRun = FALSE;
            break;
        }
        lpszToken = FindOneOf(lpszToken, szTokens);
    }

    if (bRun)
    {
        _Module.StartMonitor();
#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)
        hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, 
            REGCLS_MULTIPLEUSE | REGCLS_SUSPENDED);
        _ASSERTE(SUCCEEDED(hRes));
        hRes = CoResumeClassObjects();
#else
        hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, 
            REGCLS_MULTIPLEUSE);
#endif
        _ASSERTE(SUCCEEDED(hRes));

        MSG msg;
        while (GetMessage(&msg, 0, 0, 0))
            DispatchMessage(&msg);

        _Module.RevokeClassObjects();
        Sleep(dwPause); //スレッドが終了するまで待ちます
    }

    _Module.Term();
    CoUninitialize();
    return nRet;
}
示例#10
0
//--------------------------------------------------------------------------------------
// Parses the command line for parameters.  See DXUTInit() for list 
//--------------------------------------------------------------------------------------
bool ParseCommandLine( SETTINGS* pSettings )
{
    bool bDisplayError = false;
    bool bDisplayHelp = false;
    WCHAR* strCmdLine;
    WCHAR* strArg;

    int nNumArgs;
    WCHAR** pstrArgList = CommandLineToArgvW( GetCommandLine(), &nNumArgs );
    for( int iArg=1; iArg<nNumArgs; iArg++ )
    {
        strCmdLine = pstrArgList[iArg];

        // Handle flag args
        if( *strCmdLine == L'/' || *strCmdLine == L'-' )
        {
            strCmdLine++;

            if( IsNextArg( strCmdLine, L"y" ) )
            {
                pSettings->bOverwrite = true;
                continue;
            }

            if( IsNextArg( strCmdLine, L"n" ) )
            {
                pSettings->bGenNormals = true;
                continue;
            }

            if( IsNextArg( strCmdLine, L"t" ) )
            {
                pSettings->bGenTangents = true;
                continue;
            }

            if( IsNextArg( strCmdLine, L"tb" ) )
            {
                pSettings->bGenTangents = true;
                pSettings->bGenBinormals = true;
                continue;
            }

            if( IsNextArg( strCmdLine, L"tcount" ) )
            {
                if( iArg+1 < nNumArgs )
                {
                    strArg = pstrArgList[++iArg];
                    pSettings->NumTexCoords = _wtoi(strArg);
                    continue;
                }

                wprintf( L"Incorrect flag usage: /tcount\n" );
                bDisplayError = true;
                continue;
            }

            if( IsNextArg( strCmdLine, L"a" ) )
            {
                pSettings->bRetainAnimation = true;
                continue;
            }

            if( IsNextArg( strCmdLine, L"v" ) )
            {
                pSettings->bVerbose = true;
                continue;
            }

            if( IsNextArg( strCmdLine, L"xt" ) )
            {
                pSettings->outputType = MESH_TYPE_X_TEXT;
                continue;
            }

            if( IsNextArg( strCmdLine, L"x" ) )
            {
                pSettings->outputType = MESH_TYPE_X_BINARY;
                continue;
            }

            if( IsNextArg( strCmdLine, L"sdkmesh" ) )
            {
                pSettings->outputType = MESH_TYPE_SDKMESH;
                continue;
            }

            if( IsNextArg( strCmdLine, L"o" ) )
            {
                if( iArg+1 < nNumArgs )
                {
                    strArg = pstrArgList[++iArg];
                    pSettings->bOutputFileProvided = true;
                    StringCchCopy( pSettings->strOutputFile, 256, strArg );
                    continue;
                }

                wprintf( L"Incorrect flag usage: /o\n" );
                bDisplayError = true;
                continue;
            }

            if( IsNextArg( strCmdLine, L"?" ) )
            {
                DisplayUsage();
                return false;
            }

            // Unrecognized flag
            wprintf( L"Unrecognized or incorrect flag usage: %s\n", strCmdLine );
            bDisplayError = true;
        }
        else
        {
            // Handle non-flag args as seperate input file
            if( pSettings->bInputFileProvided )
            {
                wprintf( L"Too many input files provided: %s\n", strCmdLine );
                bDisplayError = true;
            }
            else
            {
                pSettings->bInputFileProvided = true;
                StringCchCopy( pSettings->strInputFile, 256, strCmdLine );
                continue;
            }
        }
    }

    if( !pSettings->bInputFileProvided )
        bDisplayHelp = true;

    if( pSettings->bInputFileProvided && !pSettings->bOutputFileProvided )
    {
        StringCchCopy( pSettings->strOutputFile, MAX_PATH, pSettings->strInputFile );

    }

    if( bDisplayHelp )
    {
        DisplayUsage();
        return false;
    }

    if( bDisplayError )
    {
        wprintf( L"Type \"MeshConvert.exe /?\" for a complete list of options\n" );
        return false;
    }

    return true;
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{

    LPVOID cdata = NULL;
    DWORD csz = 0;
    int ret = 0, argc;
    HRESULT hr;
    LPWSTR tgt = NULL, dest = NULL, *argv, unpack_dir = NULL;
    BOOL existing = false, launch = false, automated = false;
    WCHAR buf[4*MAX_PATH] = {0}, mb_msg[4*MAX_PATH] = {0}, fdest[4*MAX_PATH] = {0};

    if (!load_data(&cdata, &csz)) return 0;

    hr = CoInitialize(NULL);
    if (FAILED(hr)) { show_error(L"Failed to initialize COM"); return 0; }

    // Get the target directory for installation
    argv = CommandLineToArgvW(GetCommandLine(), &argc);
    if (argv == NULL) { show_last_error(L"Failed to get command line"); return 0; }
    if (argc > 1) {
        tgt = argv[1];
        automated = true;
    } else {
        tgt = get_directory_from_user();
        if (tgt == NULL) goto end;
    }

    if (!directory_exists(tgt)) {
        show_detailed_error(L"The specified directory does not exist: ",
                tgt, 1);
        goto end;
    }

    // Ensure the path to Calibre Portable is not too long
    do {
        if (!find_portable_dir(tgt, &dest, &existing)) goto end;

        if (GetFullPathName(dest, MAX_PATH*4, fdest, NULL) == 0) {
            show_last_error(L"Failed to resolve target folder");
            goto end;
        }
        free(dest); dest = NULL;

        if (wcslen(fdest) > 58) {
            _snwprintf_s(buf, 4*MAX_PATH, _TRUNCATE, 
                L"Path to Calibre Portable (%s) too long. Must be less than 59 characters.", fdest);
            if (!existing) RemoveDirectory(fdest);
            show_error(buf);
            tgt = get_directory_from_user();
            if (tgt == NULL) goto end;
        }
    } while (wcslen(fdest) > 58);

    // Confirm the user wants to upgrade
    if (existing && !automated) {
        _snwprintf_s(mb_msg, 4*MAX_PATH, _TRUNCATE, 
            L"An existing install of Calibre Portable was found at %s. Do you want to upgrade it?",
            fdest);
        if (MessageBox(NULL, mb_msg,
                L"Upgrade Calibre Portable?", MB_ICONEXCLAMATION | MB_YESNO | MB_TOPMOST) != IDYES)
            goto end;
    }

    if (existing) {
        if (!ensure_not_running(fdest)) goto end;
    }

    // Make a temp dir to unpack into
    if (!SetCurrentDirectoryW(fdest)) { show_detailed_error(L"Failed to change to unzip directory: ", fdest, 0); goto end; }

    if ( (unpack_dir = make_unpack_dir()) == NULL ) goto end;
    if (!SetCurrentDirectoryW(unpack_dir)) { show_detailed_error(L"Failed to change to unpack directory: ", fdest, 0); goto end; }

    // Extract files
    if (!extract(cdata, csz)) goto end;

    // Move files from temp dir to the install dir
    if (!move_program()) goto end;

    _snwprintf_s(mb_msg, 4*MAX_PATH, _TRUNCATE, 
        L"Calibre Portable successfully installed to %s. Launch calibre?",
        fdest);
    launch = MessageBox(NULL, mb_msg,
        L"Success", MB_ICONINFORMATION | MB_YESNO | MB_TOPMOST) == IDYES;

end:
    if (unpack_dir != NULL) { SetCurrentDirectoryW(L".."); rmtree(unpack_dir); free(unpack_dir); }
    CoUninitialize();
    if (launch) launch_calibre();
    return 0;
}
示例#12
0
int
main (int argc, char ** argv)
{
  int rc;
  int need_shell;
  char * cmdline;
  char * progname;
  int envsize;
  char **pass_through_args;
  int num_pass_through_args;
  char modname[MAX_PATH];
  char path[MAX_PATH];
  char dir[MAX_PATH];
  int status;

  interactive = TRUE;

  SetConsoleCtrlHandler ((PHANDLER_ROUTINE) console_event_handler, TRUE);

  if (!GetCurrentDirectory (sizeof (dir), dir))
    fail ("error: GetCurrentDirectory failed\n");

  /* We serve double duty: we can be called either as a proxy for the
     real shell (that is, because we are defined to be the user shell),
     or in our role as a helper application for running DOS programs.
     In the former case, we interpret the command line options as if we
     were a Unix shell, but in the latter case we simply pass our
     command line to CreateProcess.  We know which case we are dealing
     with by whether argv[0] refers to ourself or to some other program.
     (This relies on an arcane feature of CreateProcess, where we can
     specify cmdproxy as the module to run, but specify a different
     program in the command line - the MSVC startup code sets argv[0]
     from the command line.)  */

  if (!GetModuleFileName (NULL, modname, sizeof (modname)))
    fail ("error: GetModuleFileName failed\n");

  /* Change directory to location of .exe so startup directory can be
     deleted.  */
  progname = strrchr (modname, '\\');
  *progname = '\0';
  SetCurrentDirectory (modname);
  *progname = '\\';

  /* Due to problems with interaction between API functions that use "OEM"
     codepage vs API functions that use the "ANSI" codepage, we need to
     make things consistent by choosing one and sticking with it.  */
  SetConsoleCP (GetACP ());
  SetConsoleOutputCP (GetACP ());

  /* Although Emacs always sets argv[0] to an absolute pathname, we
     might get run in other ways as well, so convert argv[0] to an
     absolute name before comparing to the module name.  */
  path[0] = '\0';
  /* The call to SearchPath will find argv[0] in the current
     directory, append ".exe" to it if needed, and also canonicalize
     it, to resolve references to ".", "..", etc.  */
  status = SearchPath (NULL, argv[0], ".exe", sizeof (path), path,
				  &progname);
  if (!(status > 0 && stricmp (modname, path) == 0))
    {
      if (status <= 0)
	{
	  char *s;

	  /* Make sure we have argv[0] in path[], as the failed
	     SearchPath might not have copied it there.  */
	  strcpy (path, argv[0]);
	  /* argv[0] could include forward slashes; convert them all
	     to backslashes, for strrchr calls below to DTRT.  */
	  for (s = path; *s; s++)
	    if (*s == '/')
	      *s = '\\';
	}
      /* Perhaps MODNAME and PATH use mixed short and long file names.  */
      if (!(GetShortPathName (modname, modname, sizeof (modname))
	    && GetShortPathName (path, path, sizeof (path))
	    && stricmp (modname, path) == 0))
	{
	  /* Sometimes GetShortPathName fails because one or more
	     directories leading to argv[0] have issues with access
	     rights.  In that case, at least we can compare the
	     basenames.  Note: this disregards the improbable case of
	     invoking a program of the same name from another
	     directory, since the chances of that other executable to
	     be both our namesake and a 16-bit DOS application are nil.  */
	  char *p = strrchr (path, '\\');
	  char *q = strrchr (modname, '\\');
	  char *pdot, *qdot;

	  if (!p)
	    p = strchr (path, ':');
	  if (!p)
	    p = path;
	  else
	    p++;
	  if (!q)
	    q = strchr (modname, ':');
	  if (!q)
	    q = modname;
	  else
	    q++;

	  pdot = strrchr (p, '.');
	  if (!pdot || stricmp (pdot, ".exe") != 0)
	    pdot = p + strlen (p);
	  qdot = strrchr (q, '.');
	  if (!qdot || stricmp (qdot, ".exe") != 0)
	    qdot = q + strlen (q);
	  if (pdot - p != qdot - q || strnicmp (p, q, pdot - p) != 0)
	    {
	      /* We are being used as a helper to run a DOS app; just
		 pass command line to DOS app without change.  */
	      /* TODO: fill in progname.  */
	      if (spawn (NULL, GetCommandLine (), dir, &rc))
		return rc;
	      fail ("Could not run %s\n", GetCommandLine ());
	    }
	}
    }

  /* Process command line.  If running interactively (-c or /c not
     specified) then spawn a real command shell, passing it the command
     line arguments.

     If not running interactively, then attempt to execute the specified
     command directly.  If necessary, spawn a real shell to execute the
     command.

  */

  progname = NULL;
  cmdline = NULL;
  /* If no args, spawn real shell for interactive use.  */
  need_shell = TRUE;
  interactive = TRUE;
  /* Ask command.com to create an environment block with a reasonable
     amount of free space.  */
  envsize = get_env_size () + 300;
  pass_through_args = (char **) alloca (argc * sizeof (char *));
  num_pass_through_args = 0;

  while (--argc > 0)
    {
      ++argv;
      /* Act on switches we recognize (mostly single letter switches,
	 except for -e); all unrecognized switches and extra args are
	 passed on to real shell if used (only really of benefit for
	 interactive use, but allow for batch use as well).  Accept / as
	 switch char for compatibility with cmd.exe.  */
      if (((*argv)[0] == '-' || (*argv)[0] == '/') && (*argv)[1] != '\0')
	{
	  if (((*argv)[1] == 'c' || (*argv)[1] == 'C') && ((*argv)[2] == '\0'))
	    {
	      if (--argc == 0)
		fail ("error: expecting arg for %s\n", *argv);
	      cmdline = *(++argv);
	      interactive = FALSE;
	    }
	  else if (((*argv)[1] == 'i' || (*argv)[1] == 'I') && ((*argv)[2] == '\0'))
	    {
	      if (cmdline)
		warn ("warning: %s ignored because of -c\n", *argv);
	    }
	  else if (((*argv)[1] == 'e' || (*argv)[1] == 'E') && ((*argv)[2] == ':'))
	    {
	      int requested_envsize = atoi (*argv + 3);
	      /* Enforce a reasonable minimum size, as above.  */
	      if (requested_envsize > envsize)
		envsize = requested_envsize;
	      /* For sanity, enforce a reasonable maximum.  */
	      if (envsize > 32768)
		envsize = 32768;
	    }
	  else
	    {
	      /* warn ("warning: unknown option %s ignored", *argv); */
	      pass_through_args[num_pass_through_args++] = *argv;
	    }
	}
      else
	break;
    }

#if 0
  /* I think this is probably not useful - cmd.exe ignores extra
     (non-switch) args in interactive mode, and they cannot be passed on
     when -c was given.  */

  /* Collect any remaining args after (initial) switches.  */
  while (argc-- > 0)
    {
      pass_through_args[num_pass_through_args++] = *argv++;
    }
#else
  /* Probably a mistake for there to be extra args; not fatal.  */
  if (argc > 0)
    warn ("warning: extra args ignored after '%s'\n", argv[-1]);
#endif

  pass_through_args[num_pass_through_args] = NULL;

  /* If -c option, determine if we must spawn a real shell, or if we can
     execute the command directly ourself.  */
  if (cmdline)
    {
      const char *args;

      /* The program name is the first token of cmdline.  Since
         filenames cannot legally contain embedded quotes, the value
         of escape_char doesn't matter.  */
      args = cmdline;
      if (!get_next_token (path, &args))
        fail ("error: no program name specified.\n");

      canon_filename (path);
      progname = make_absolute (path);

      /* If we found the program and the rest of the command line does
         not contain unquoted shell metacharacters, run the program
         directly (if not found it might be an internal shell command,
         so don't fail).  */
      if (progname != NULL && try_dequote_cmdline (cmdline))
        need_shell = FALSE;
      else
        progname = NULL;
    }

 pass_to_shell:
  if (need_shell)
    {
      char * p;
      int    extra_arg_space = 0;
      int    maxlen, remlen;
      int    run_command_dot_com;

      progname = getenv ("COMSPEC");
      if (!progname)
	fail ("error: COMSPEC is not set\n");

      canon_filename (progname);
      progname = make_absolute (progname);

      if (progname == NULL || strchr (progname, '\\') == NULL)
	fail ("error: the program %s could not be found.\n", getenv ("COMSPEC"));

      /* Need to set environment size when running command.com.  */
      run_command_dot_com =
	(stricmp (strrchr (progname, '\\'), "command.com") == 0);

      /* Work out how much extra space is required for
         pass_through_args.  */
      for (argv = pass_through_args; *argv != NULL; ++argv)
	/* We don't expect to have to quote switches.  */
	extra_arg_space += strlen (*argv) + 2;

      if (cmdline)
	{
	  char * buf;

	  /* Convert to syntax expected by cmd.exe/command.com for
	     running non-interactively.  Always quote program name in
	     case path contains spaces (fortunately it can't contain
	     quotes, since they are illegal in path names).  */

	  remlen = maxlen =
	    strlen (progname) + extra_arg_space + strlen (cmdline) + 16;
	  buf = p = alloca (maxlen + 1);

	  /* Quote progname in case it contains spaces.  */
	  p += _snprintf (p, remlen, "\"%s\"", progname);
	  remlen = maxlen - (p - buf);

	  /* Include pass_through_args verbatim; these are just switches
             so should not need quoting.  */
	  for (argv = pass_through_args; *argv != NULL; ++argv)
	    {
	      p += _snprintf (p, remlen, " %s", *argv);
	      remlen = maxlen - (p - buf);
	    }

	  if (run_command_dot_com)
	    _snprintf (p, remlen, " /e:%d /c %s", envsize, cmdline);
	  else
	    _snprintf (p, remlen, " /c %s", cmdline);
	  cmdline = buf;
	}
      else
	{
	  if (run_command_dot_com)
	    {
	      /* Provide dir arg expected by command.com when first
		 started interactively (the "command search path").  To
		 avoid potential problems with spaces in command dir
		 (which cannot be quoted - command.com doesn't like it),
		 we always use the 8.3 form.  */
	      GetShortPathName (progname, path, sizeof (path));
	      p = strrchr (path, '\\');
	      /* Trailing slash is acceptable, so always leave it.  */
	      *(++p) = '\0';
	    }
	  else
	    path[0] = '\0';

	  remlen = maxlen =
	    strlen (progname) + extra_arg_space + strlen (path) + 13;
	  cmdline = p = alloca (maxlen + 1);

	  /* Quote progname in case it contains spaces.  */
	  p += _snprintf (p, remlen, "\"%s\" %s", progname, path);
	  remlen = maxlen - (p - cmdline);

	  /* Include pass_through_args verbatim; these are just switches
             so should not need quoting.  */
	  for (argv = pass_through_args; *argv != NULL; ++argv)
	    {
	      p += _snprintf (p, remlen, " %s", *argv);
	      remlen = maxlen - (p - cmdline);
	    }

	  if (run_command_dot_com)
	    _snprintf (p, remlen, " /e:%d", envsize);
	}
    }

  if (!progname)
    fail ("Internal error: program name not defined\n");

  if (!cmdline)
    cmdline = progname;

  if (spawn (progname, cmdline, dir, &rc))
    return rc;

  if (!need_shell)
    {
      need_shell = TRUE;
      goto pass_to_shell;
    }

  fail ("Could not run %s\n", progname);

  return 0;
}
示例#13
0
// ------------------------------------------------
// 
//  FUNCTION: sys_GetCommandLine( PA_PluginParameters params)
//
//  PURPOSE:	Gets command line used to start 4D
//
//  COMMENTS:	Parse command line. Ends at a negative character value.
//						Returns an array of parameters.
//						Params should be passed unquoted. There can be a space or NULL
//						between parameters. 1st param is delimited by space.  Rest are NULL.
//        
//	DATE:			dcc 04/03/02 dcc
//
//	MODIFICATIONS: Rewritten 06/20/02 to make more concise, less convoluted, etc.
//                 Modified 7/29/03
void sys_GetCommandLine( PA_PluginParameters params )
{
	char				commandLineStr[MAXBUF]; 
	char                paramElement[MAXBUF];
	char				executableString[MAXBUF];
	char				*pMarker;
	LONG_PTR				returnValue = 0, commandLine_len = 0, charsToCopy;
	LPTSTR				pCommandLineStr, pTemp;
	PA_Variable			parameters;
	BOOL				bInQuotes = FALSE, bDone = FALSE;
	LONG_PTR				paramCount = 0;
	LONG_PTR				action = 0;

	memset(commandLineStr, 0, MAXBUF);
	memset(paramElement, 0, MAXBUF);
	memset(executableString, 0, MAXBUF);
	
	parameters = PA_GetVariableParameter( params, 1 );
	action     = PA_GetLongParameter( params, 2 ); 
	
	pCommandLineStr = GetCommandLine();
	
	if (pCommandLineStr == NULL) {
		returnValue = 0;
	} else {

		pMarker = pTemp = pCommandLineStr;
 
		//if first char a doublequote, skip it
		if ( *pMarker == '"') {
            pMarker++;
			bInQuotes = TRUE;
		}
		
		// Find the executable name.
		while (!((*(++pTemp) == ' ' && !bInQuotes) || (*pTemp == '"' && bInQuotes) || *pTemp == '\0'));

		charsToCopy = (pTemp - pMarker);
		strncpy(executableString, pMarker, charsToCopy); 
		commandLine_len = charsToCopy;
	    executableString[charsToCopy] = '\0';

		//skip next quotes and spaces if they are there
		while ((*pTemp == '"') || (*pTemp == ' ')) {
			if ((*pTemp == '"') && (action == CL_DRAGDROP)) {
				bInQuotes = !bInQuotes; // toggle flag
			}
			commandLine_len += 1;
			pTemp++;
		}

		pMarker = pTemp;

		if (action == CL_DRAGDROP) {
			if (bInQuotes) {
				while ((*pTemp != '"') || ((*pTemp != '\0') && ( *(pTemp + 1) != '\0'))) {
					pTemp++;
				}
			} else {
				while (*pTemp != '\0') {
					pTemp++;
				}
			}

			strncpy(paramElement, pMarker, pTemp - pMarker); 
			paramElement[ pTemp - pMarker ] = '\0';
			if (strlen(paramElement) == 0) {
				PA_ResizeArray(&parameters, 1);
				strcpy(commandLineStr, executableString);
				returnValue = 1;
			} else {
				PA_ResizeArray (&parameters, 2);
				PA_SetTextInArray (parameters, 2, paramElement, strlen(paramElement));
				strcpy(commandLineStr, executableString);
				strcat(commandLineStr, " ");
				strcat(commandLineStr, paramElement);
				returnValue = 2;
			}

		} else {

			paramCount = 1;
			strcpy(commandLineStr, executableString);
			PA_ResizeArray (&parameters, paramCount);

			while (!bDone) {
				strcpy(paramElement, "");
				while (*pTemp >= 0) {
					pTemp++;
					//two nulls in a row also end
					//replace nulls with spaces
					if (( *(pTemp) == '\0') || ( *(pTemp) == ' ')) {
						if (( *(pTemp + 1) == '\0') || ( *(pTemp + 1) == ' ')){
							bDone = TRUE;
							paramCount++;							
							break;
						} else {
							paramCount++;
							break;
						}
					}
				} // end while

				strncpy(paramElement, pMarker, pTemp - pMarker); 
				paramElement[ pTemp - pMarker ] = '\0';
				if (strlen(paramElement) > 0) {
					PA_ResizeArray (&parameters, paramCount);
					PA_SetTextInArray (parameters, paramCount, paramElement, strlen(paramElement));
					pMarker = pTemp + 1;
					strcat(commandLineStr, " ");
					strcat(commandLineStr, paramElement);
				} else {
					bDone = TRUE;
				}
			} // end while !done
			returnValue = PA_GetArrayNbElements(parameters);
		}

		PA_SetTextInArray (parameters, 1, executableString, strlen(executableString));
		PA_SetTextInArray (parameters, 0, commandLineStr, strlen(commandLineStr));
		PA_SetVariableParameter( params, 1, parameters, 0 );

	} // (pCommandLineStr == NULL)

	PA_ReturnLong( params, returnValue );
}
示例#14
0
const char* File::getBHDir()
{
  static char dir[MAX_PATH] = {0};
  if(!dir[0])
  {
#if defined(TARGET_SIM) || defined(TARGET_TOOL)

    // determine module file from command line
    const char* commandLine = GetCommandLine();
    int len;
    if(*commandLine == '"')
    {
      commandLine++;
      const char* end = strchr(commandLine, '"');
      if(end)
        len = end - commandLine;
      else
        len = strlen(commandLine);
    }
    else
      len = strlen(commandLine);
    if(len >= sizeof(dir) - 8)
      len = sizeof(dir) - 8;
    memcpy(dir, commandLine, len);
    dir[len] = '\0';

    // if there is no given directory, use the current working dir
    if(!strchr(dir, '\\'))
    {
      len = int(GetCurrentDirectory(sizeof(dir) - 9, dir));
      if(len && dir[len - 1] != '\\')
      {
        dir[len++] = '\\';
        dir[len] = '\0';
      }
    }

    //drive letter in lower case:
    if(len && dir[1] == ':')
      *dir |= tolower(*dir);

    // try to find the config directory
    char* end = dir + len - 1;
    for(;;)
    {
      if(*end == '/' || *end == '\\' || *end == ':' || end == dir - 1)
      {
        if(*end == ':')
          *(end++) = '\\';
        strcpy(end + 1, "Config");
        DWORD attr = GetFileAttributes(dir);
        if(attr != INVALID_FILE_ATTRIBUTES && attr & FILE_ATTRIBUTE_DIRECTORY)
        {
          end[end > dir ? 0 : 1] = '\0';
          for(; end >= dir; end--)
            if(*end == '\\')
              *end = '/';
          return dir;
        }
      }
      if(end < dir)
        break;
      end--;
    }
    ASSERT(false);
#else
    strcpy(dir, ".");
#endif
  }
  return dir;
}
示例#15
0
文件: Main.c 项目: Argimko/Nsis64
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInst,LPTSTR lpszCmdParam, int nCmdShow)
{
  int ret = 0;
  const TCHAR *m_Err = _LANG_ERRORWRITINGTEMP;

#define cl_flags ret // in order to have the same pe entry point with nsis 2.46

  TCHAR *realcmds;
  TCHAR seekchar=_T(' ');
  TCHAR *cmdline;

  InitCommonControls();

  SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);

#if defined(NSIS_SUPPORT_ACTIVEXREG) || defined(NSIS_SUPPORT_CREATESHORTCUT)
  {
    extern HRESULT g_hres;
    g_hres=OleInitialize(NULL);
  }
#endif

  // load shfolder.dll before any script code is executed to avoid
  // weird situations where SetOutPath or even the extraction of 
  // shfolder.dll will cause unexpected behavior.
  //
  // this also prevents the following:
  //
  //  SetOutPath "C:\Program Files\NSIS" # maybe read from reg
  //  File shfolder.dll
  //  Delete $PROGRAMFILES\shfolder.dll # can't be deleted, as the
  //                                    # new shfolder.dll is used
  //                                    # to find its own path.
  g_SHGetFolderPath = myGetProcAddress(MGA_SHGetFolderPath);

  {
    // workaround for bug #1008632
    // http://sourceforge.net/tracker/index.php?func=detail&aid=1008632&group_id=22049&atid=373085
    //
    // without this, SHGetSpecialFolderLocation doesn't always recognize
    // some special folders, like the desktop folder for all users, on
    // Windows 9x. unlike SHGetSpecialFolderPath, which is not available
    // on all versions of Windows, SHGetSpecialFolderLocation doesn't try
    // too hard to make sure the caller gets what he asked for. so we give
    // it a little push in the right direction by doing part of the work
    // for it.
    //
    // part of what SHGetFileInfo does, is to convert a path into an idl.
    // to do this conversion, it first needs to initialize the list of 
    // special idls, which are exactly the idls we use to get the paths
    // of special folders (CSIDL_*).

    SHFILEINFO shfi;
    SHGetFileInfo(_T(""), 0, &shfi, sizeof(SHFILEINFO), 0);
  }

  mystrcpy(g_caption,_LANG_GENERIC_ERROR);

  mystrcpy(state_command_line, GetCommandLine());

#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
  g_hInstance = GetModuleHandle(NULL);
#endif//NSIS_CONFIG_VISIBLE_SUPPORT

  cmdline = state_command_line;
  if (*cmdline == _T('\"')) seekchar = *cmdline++;

  cmdline=findchar(cmdline, seekchar);
  cmdline=CharNext(cmdline);
  realcmds=cmdline;

  while (*cmdline)
  {
    // skip over any spaces
    while (*cmdline == _T(' ')) cmdline++;
    
    // get char we should look for to get the next parm
    seekchar = _T(' ');
    if (cmdline[0] == _T('\"'))
    {
      cmdline++;
      seekchar = _T('\"');
    }

    // is it a switch?
    if (cmdline[0] == _T('/'))
    {
      cmdline++;

#define END_OF_ARG(c) (c == _T(' ') || c == _T('\0'))

#if defined(NSIS_CONFIG_VISIBLE_SUPPORT) && defined(NSIS_CONFIG_SILENT_SUPPORT)
      if (cmdline[0] == _T('S') && END_OF_ARG(cmdline[1]))
        cl_flags |= FH_FLAGS_SILENT;
#endif//NSIS_CONFIG_SILENT_SUPPORT && NSIS_CONFIG_VISIBLE_SUPPORT
#ifdef NSIS_CONFIG_CRC_SUPPORT
      if (CMP4CHAR(cmdline, _T("NCRC")) && END_OF_ARG(cmdline[4]))
        cl_flags |= FH_FLAGS_NO_CRC;
#endif//NSIS_CONFIG_CRC_SUPPORT

      if (CMP4CHAR(cmdline-2, _T(" /D=")))
      {
        *(cmdline-2)=_T('\0'); // keep this from being passed to uninstaller if necessary
        mystrcpy(state_install_directory,cmdline+2);
        break; // /D= must always be last
      }
    }

    // skip over our parm
    cmdline = findchar(cmdline, seekchar);
    // skip the quote
    if (*cmdline == _T('\"'))
      cmdline++;
  }

  GetTempPath(NSIS_MAX_STRLEN, state_temp_dir);
  if (!ValidateTempDir())
  {
    GetWindowsDirectory(state_temp_dir, NSIS_MAX_STRLEN - 5); // leave space for \Temp
    mystrcat(state_temp_dir, _T("\\Temp"));
    if (!ValidateTempDir())
    {
      // There does not seem to be a API to get the low temp dir directly, so we build the path on our own

      GetTempPath(NSIS_MAX_STRLEN - 4, state_temp_dir); // leave space for \Low
      mystrcat(state_temp_dir, _T("Low"));

      // If we don't call SetEnvironmentVariable 
      // child processes will use %temp% and not %temp%\Low
      // and some apps probably can't handle a read only %temp%
      // Do it before ValidateTempDir() because it appends a backslash.
      // TODO: Should this be moved to ValidateTempDir() so it also updates for %windir%\Temp?
      SetEnvironmentVariable(_T("TEMP"), state_temp_dir);
      SetEnvironmentVariable(_T("TMP"), state_temp_dir);

      if (!ValidateTempDir())
      {
        goto end;
      }
    }
  }
  DeleteFile(state_language);

  m_Err = loadHeaders(cl_flags);
  if (m_Err) goto end;

#ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
  if (g_is_uninstaller)
  {
    TCHAR *p = findchar(state_command_line, 0);

    // state_command_line has state_install_directory right after it in memory, so reading
    // a bit over state_command_line won't do any harm
    while (p >= state_command_line && !CMP4CHAR(p, _T(" _?="))) p--;

    m_Err = _LANG_UNINSTINITERROR;

    if (p >= state_command_line)
    {
      *p=0; // terminate before "_?="
      p+=4; // skip over " _?="
      if (is_valid_instpath(p))
      {
        mystrcpy(state_install_directory, p);
        mystrcpy(state_output_directory, p);
        m_Err = 0;
      }
      else
      {
        goto end;
      }
    }
    else
    {
      int x;

      mystrcat(state_temp_dir,_T("~nsu.tmp"));

      // check if already running from uninstaller temp dir
      // this prevents recursive uninstaller calls
      if (!lstrcmpi(state_temp_dir,state_exe_directory))
        goto end;

      CreateDirectory(state_temp_dir,NULL);
      SetCurrentDirectory(state_temp_dir);

      if (!state_install_directory[0])
        mystrcpy(state_install_directory,state_exe_directory);

      mystrcpy(g_usrvars[0], realcmds);
      SET2CHAR(g_usrvars[1], _T("A\0"));

      for (x = 0; x < 26; x ++)
      {
        static TCHAR buf2[NSIS_MAX_STRLEN];

        GetNSISString(buf2,g_header->str_uninstchild); // $TEMP\$1u_.exe

        DeleteFile(buf2); // clean up after all the other ones if they are there

        if (m_Err) // not done yet
        {
          // copy file
          if (CopyFile(state_exe_path,buf2,TRUE))
          {
            HANDLE hProc;
#ifdef NSIS_SUPPORT_MOVEONREBOOT
            MoveFileOnReboot(buf2,NULL);
#endif
            GetNSISString(buf2,g_header->str_uninstcmd); // '"$TEMP\$1u_.exe" $0 _?=$INSTDIR\'
            hProc=myCreateProcess(buf2);
            if (hProc)
            {
              CloseHandle(hProc);
              // success
              m_Err = 0;
            }
          }
        }
        g_usrvars[1][0]++;
      }

#ifdef NSIS_SUPPORT_MOVEONREBOOT
      MoveFileOnReboot(state_temp_dir,NULL);
#endif

      goto end;
    }
  }
#endif//NSIS_CONFIG_UNINSTALL_SUPPORT

  g_exec_flags.errlvl = -1;
  ret = ui_doinstall();

#ifdef NSIS_CONFIG_LOG
#if !defined(NSIS_CONFIG_LOG_ODS) && !defined(NSIS_CONFIG_LOG_STDOUT)
  log_write(1);
#endif//!NSIS_CONFIG_LOG_ODS && !NSIS_CONFIG_LOG_STDOUT
#endif//NSIS_CONFIG_LOG
end:

  CleanUp();

#if defined(NSIS_SUPPORT_ACTIVEXREG) || defined(NSIS_SUPPORT_CREATESHORTCUT)
  OleUninitialize();
#endif

  if (m_Err)
  {
    my_MessageBox(m_Err, MB_OK | MB_ICONSTOP | (IDOK << 21));
    ExitProcess(2);
    return 0;
  }

#ifdef NSIS_SUPPORT_REBOOT
  if (g_exec_flags.reboot_called)
  {
    BOOL (WINAPI *OPT)(HANDLE, DWORD,PHANDLE);
    BOOL (WINAPI *LPV)(LPCTSTR,LPCTSTR,PLUID);
    BOOL (WINAPI *ATP)(HANDLE,BOOL,PTOKEN_PRIVILEGES,DWORD,PTOKEN_PRIVILEGES,PDWORD);
    OPT=myGetProcAddress(MGA_OpenProcessToken);
    LPV=myGetProcAddress(MGA_LookupPrivilegeValue);
    ATP=myGetProcAddress(MGA_AdjustTokenPrivileges);
    if (OPT && LPV && ATP)
    {
      HANDLE hToken;
      TOKEN_PRIVILEGES tkp;
      if (OPT(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
      {
        LPV(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);
        tkp.PrivilegeCount = 1;
        tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
        ATP(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
      }
    }

    if (!ExitWindowsEx(EWX_REBOOT,0))
      ExecuteCallbackFunction(CB_ONREBOOTFAILED);
  }
#endif//NSIS_SUPPORT_REBOOT

  if (g_exec_flags.errlvl != -1)
    ret = g_exec_flags.errlvl;

  ExitProcess(ret);
  return 0;
}
示例#16
0
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prevInstance, LPWSTR cmdParamarg, int cmdShow) {
    openLog();

#ifdef _NEED_WIN_GENERATE_DUMP
    _oldWndExceptionFilter = SetUnhandledExceptionFilter(_exceptionFilter);
#endif

    writeLog(L"Updaters started..");

    LPWSTR *args;
    int argsCount;

    bool needupdate = false, autostart = false, debug = false, writeprotected = false, startintray = false, testmode = false;
    args = CommandLineToArgvW(GetCommandLine(), &argsCount);
    if (args) {
        for (int i = 1; i < argsCount; ++i) {
            if (equal(args[i], L"-update")) {
                needupdate = true;
            } else if (equal(args[i], L"-autostart")) {
                autostart = true;
            } else if (equal(args[i], L"-debug")) {
                debug = _debug = true;
                openLog();
            } else if (equal(args[i], L"-startintray")) {
                startintray = true;
            } else if (equal(args[i], L"-testmode")) {
                testmode = true;
            } else if (equal(args[i], L"-writeprotected") && ++i < argsCount) {
                writeprotected = true;
                updateTo = args[i];
                for (int i = 0, l = updateTo.size(); i < l; ++i) {
                    if (updateTo[i] == L'/') {
                        updateTo[i] = L'\\';
                    }
                }
            }
        }
        if (needupdate) writeLog(L"Need to update!");
        if (autostart) writeLog(L"From autostart!");
        if (writeprotected) writeLog(L"Write Protected folder!");

        exeName = args[0];
        writeLog(L"Exe name is: " + exeName);
        if (exeName.size() > 11) {
            if (equal(exeName.substr(exeName.size() - 11), L"Updater.exe")) {
                exeDir = exeName.substr(0, exeName.size() - 11);
                writeLog(L"Exe dir is: " + exeDir);
                if (!writeprotected) {
                    updateTo = exeDir;
                }
                writeLog(L"Update to: " + updateTo);
                if (needupdate && update()) {
                    updateRegistry();
                }
                if (writeprotected) { // if we can't clear all tupdates\ready (Updater.exe is there) - clear only version
                    if (DeleteFile(L"tupdates\\temp\\tdata\\version") || DeleteFile(L"tupdates\\ready\\tdata\\version")) {
                        writeLog(L"Version file deleted!");
                    } else {
                        writeLog(L"Error: could not delete version file");
                    }
                }
            } else {
                writeLog(L"Error: bad exe name!");
            }
        } else {
            writeLog(L"Error: short exe name!");
        }
        LocalFree(args);
    } else {
        writeLog(L"Error: No command line arguments!");
    }

    wstring targs;
    if (autostart) targs += L" -autostart";
    if (debug) targs += L" -debug";
    if (startintray) targs += L" -startintray";
    if (testmode) targs += L" -testmode";

    bool executed = false;
    if (writeprotected) { // run un-elevated
        writeLog(L"Trying to run un-elevated by temp.lnk");

        HRESULT hres = CoInitialize(0);
        if (SUCCEEDED(hres)) {
            IShellLink* psl;
            HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
            if (SUCCEEDED(hres)) {
                IPersistFile* ppf;

                wstring exe = updateTo + L"Telegram.exe", dir = updateTo;
                psl->SetArguments((targs.size() ? targs.substr(1) : targs).c_str());
                psl->SetPath(exe.c_str());
                psl->SetWorkingDirectory(dir.c_str());
                psl->SetDescription(L"");

                hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);

                if (SUCCEEDED(hres)) {
                    wstring lnk = L"tupdates\\temp\\temp.lnk";
                    hres = ppf->Save(lnk.c_str(), TRUE);
                    if (!SUCCEEDED(hres)) {
                        lnk = L"tupdates\\ready\\temp.lnk"; // old
                        hres = ppf->Save(lnk.c_str(), TRUE);
                    }
                    ppf->Release();

                    if (SUCCEEDED(hres)) {
                        writeLog(L"Executing un-elevated through link..");
                        ShellExecute(0, 0, L"explorer.exe", lnk.c_str(), 0, SW_SHOWNORMAL);
                        executed = true;
                    } else {
                        writeLog(L"Error: ppf->Save failed");
                    }
                } else {
                    writeLog(L"Error: Could not create interface IID_IPersistFile");
                }
                psl->Release();
            } else {
                writeLog(L"Error: could not create instance of IID_IShellLink");
            }
            CoUninitialize();
        } else {
            writeLog(L"Error: Could not initialize COM");
        }
    }
    if (!executed) {
        ShellExecute(0, 0, (updateTo + L"Telegram.exe").c_str(), (L"-noupdate" + targs).c_str(), 0, SW_SHOWNORMAL);
    }

    writeLog(L"Executed Telegram.exe, closing log and quiting..");
    closeLog();

    return 0;
}
示例#17
0
INT
WINAPI
WinMain(
    _In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPSTR lpCmdLine,
    _In_ int nShowCmd
    )
{
    LPWSTR *ArgList;
    INT NumArgs;
    WCHAR MediaRootDirectory[MAX_PATH];
    LPWSTR FileNamePart;
    DWORD DirPathLength;

    g_hInstance = hInstance;

    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);
    UNREFERENCED_PARAMETER(nShowCmd);

    //
    // Windows 2000 doesn't suppress auto-run applications when media (e.g.,
    // a CD) is inserted while a "Found New Hardware" popup is onscreen.  This
    // means that, by default, inserting a CD in order to supply PnP with the
    // necessary INF and driver files will result in the autorun app launching,
    // and obscuring the wizard, causing user confusion, etc.
    //
    // To avoid this, we retrieve an entrypoint to a Windows 2000 (and later)
    // Configuration Manager (CM) API that allows us to detect when a device
    // installation is in-progress, and suppress our own application from
    // starting.
    //
    if(IsDeviceInstallInProgress()) {
        //
        // We don't want to startup right now.  Don't worry--the value-added
        // software part of the device installation will be invoked (if
        // necessary) by our device co-installer during finish-install
        // processing.
        //
        return 0;
    }

    //
    // Retrieve the full directory path from which our setup program was
    // invoked.
    //
    ArgList = CommandLineToArgvW(GetCommandLine(), &NumArgs);

    if(ArgList && (NumArgs >= 1)) {

        DirPathLength = GetFullPathName(ArgList[0],
                                        MAX_PATH,
                                        MediaRootDirectory,
                                        &FileNamePart
                                       );

        if(DirPathLength >= MAX_PATH) {
            //
            // The directory is too large for our buffer.  Set our directory
            // path length to zero so we'll simply bail out in this rare case.
            //
            DirPathLength = 0;
        }

        if(DirPathLength) {
            //
            // Strip the filename off the path.
            //
            *FileNamePart = L'\0';

            DirPathLength = (DWORD)(FileNamePart - MediaRootDirectory);
        }

    } else {
        //
        // For some reason, we couldn't get the command line arguments that
        // were used when invoking our setup app.  Assume current directory
        // instead.
        //
        DirPathLength = GetCurrentDirectory(MAX_PATH, MediaRootDirectory);

        if(DirPathLength >= MAX_PATH) {
            //
            // The current directory is too large for our buffer.  Set our
            // directory path length to zero so we'll simply bail out in this
            // rare case.
            //
            DirPathLength = 0;
        }

        if(DirPathLength) {
            //
            // Ensure that path ends in a path separator character.
            //
            if((MediaRootDirectory[DirPathLength-1] != L'\\') &&
               (MediaRootDirectory[DirPathLength-1] != L'/'))
            {
                MediaRootDirectory[DirPathLength++] = L'\\';

                if(DirPathLength < MAX_PATH) {
                    MediaRootDirectory[DirPathLength] = L'\0';
                } else {
                    //
                    // Not enough room in buffer to add path separator char
                    //
                    DirPathLength = 0;
                }
            }
        }
    }

    if(ArgList) {
        GlobalFree(ArgList);
    }

    if(!DirPathLength) {
        //
        // Couldn't figure out what the root directory of our installation
        // media was.  Bail out.
        //
        return 0;
    }

    //
    // If we're being invoked from a platform-specific subdirectory (i.e.,
    // \i386 or \ia64), then strip off that subdirectory to get the true media
    // root path.
    //
    if(DirPathLength > TOASTVA_PLATFORM_SUBDIRECTORY_SIZE) {
        //
        // We know that the last character in our MediaRootDirectory string is
        // a path separator character.  Check to see if the preceding
        // characters match our platform-specific subdirectory.
        //
        if(!_wcsnicmp(&(MediaRootDirectory[DirPathLength - TOASTVA_PLATFORM_SUBDIRECTORY_SIZE]),
                      TOASTVA_PLATFORM_SUBDIRECTORY,
                      TOASTVA_PLATFORM_SUBDIRECTORY_SIZE - 1)) {
            //
            // Platform-specific part matches, just make sure preceding char
            // is a path separator char.
            //
            if((MediaRootDirectory[DirPathLength - TOASTVA_PLATFORM_SUBDIRECTORY_SIZE - 1] == L'\\') ||
               (MediaRootDirectory[DirPathLength - TOASTVA_PLATFORM_SUBDIRECTORY_SIZE - 1] == L'/')) {

                MediaRootDirectory[DirPathLength - TOASTVA_PLATFORM_SUBDIRECTORY_SIZE] = L'\0';
            }
        }
    }

    DoValueAddWizard(MediaRootDirectory);

    return 0;
}
示例#18
0
int main (int argc, char const * argv[])
#endif
{
    int nArgs;
    LPTSTR * szArglist = CommandLineToArgvW(GetCommandLine(), &nArgs);
    if ( NULL == szArglist )
        return 0;

    if (nArgs > 1)
    {
        is_gui = false;
        Init();
        bool logout = false;
        for (int i = 1; i < nArgs; ++i)
        {
            if (szArglist[i][0] != '-')
            {
                continue;
            }

            // if there's a flag but no argument following, ignore it
            if (nArgs == i) continue;
            TCHAR  const * arg = szArglist[i + 1];
            switch (szArglist[i][1])
            {
                case 'h':
                    usage();
                    return 0;
                case 'l':
                    logout = true;
                    break;
                case 'u':
                    is_per_user = true;
                    break;
                case 'a':
                    if (is_usingNT && !is_admin)
                        error(MB_OK, TEXT("Error: for setting for ALL users you need admin rights!"));
                    is_per_user = false;
                    break;
                case 'b':
                    is_blackbox = true;
                    break;
                case 'e':
                    is_blackbox = false;
                    break;
                case 'd':
                    is_debug = true;
                    break;
                default:
                    usage();
                    return 0;
            }
        }

        SetAsShell(is_blackbox ? szBlackbox : szExplorer);

        dbg_printf(TEXT("shell set, quitting..."));
        // Free memory allocated for CommandLineToArgvW arguments.
        LocalFree(szArglist);

        if (logout)
            ExitWindowsEx(EWX_LOGOFF, 0);
        return 1;
    }
    else
    {
        HINSTANCE hInstance = GetModuleHandle(NULL);
        is_gui = false;
        INT_PTR const result = DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_DLG1), NULL, (DLGPROC)dlgfunc, (LONG_PTR)hInstance);
        if (result == -1)
        {
          DWORD r = GetLastError();
          //char buff[1024];
          //win_error(buff, sizeof buff);
          return 1;
        }

        switch (result)
        {
            case 0:
                return 1;
            case 1:
                message(MB_OK,
                    TEXT("'%s' has been set as shell.\n")
                    TEXT("\nTo make this work correctly, you need to run ")
                    APPNAME
                    TEXT(" as ")
                    TEXT("\nadministrator and enable individual shells too.")
                    , shellpath);
                break;
            case 2:
                ExitWindowsEx(EWX_LOGOFF, 0);
                break;
            case 3:
                message(MB_OK, TEXT("You will have the default system shell. Logout to apply."));
                break;
            case 4:
                message(MB_OK, TEXT("'%s' has been set as shell. Logout to apply."), shellpath);
                break;
            }
    }
    return 0;
}
示例#19
0
extern "C" int WINAPI _tWinMain(HINSTANCE hInstance,
    HINSTANCE /*hPrevInstance*/, LPTSTR lpCmdLine, int /*nShowCmd*/)
{
    lpCmdLine = GetCommandLine(); //this line necessary for _ATL_MIN_CRT

    HRESULT hRes = CoInitializeEx(NULL, COINIT_MULTITHREADED);

    _ASSERTE(SUCCEEDED(hRes));
    _Module.Init(ObjectMap, hInstance, &LIBID_HYPERFEEDPROVIDERSLib);
    _Module.dwThreadID = GetCurrentThreadId();
    TCHAR szTokens[] = _T("-/");

    int nRet = 0;
    BOOL bRun = TRUE;
    LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens);
    while (lpszToken != NULL)
    {
        if (lstrcmpi(lpszToken, _T("UnregServer"))==0)
        {
            _Module.UpdateRegistryFromResource(IDR_HyperFeedProviders, FALSE);
            nRet = _Module.UnregisterServer(TRUE);
            bRun = FALSE;
            break;
        }
        if (lstrcmpi(lpszToken, _T("RegServer"))==0)
        {
            _Module.UpdateRegistryFromResource(IDR_HyperFeedProviders, TRUE);
            nRet = _Module.RegisterServer(TRUE);
            bRun = FALSE;
            break;
        }
        lpszToken = FindOneOf(lpszToken, szTokens);
    }

    if (bRun)
    {
		// Starting with trace
		EgStd::g_pTrace = new CHyperFeedTrace();
		EgStd::g_pTrace->Init();


#ifndef _DEBUG 
		SetMiniDumpDefaultCrashHandler();
#endif
		ATLVERIFY(SUCCEEDED(_Module.LoadExchangeCodes()));
		ATLVERIFY(SUCCEEDED(_Module.LoadProviderSettings()));

       _Module.StartMonitor();
#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)
        hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER,
            REGCLS_MULTIPLEUSE | REGCLS_SUSPENDED);
        _ASSERTE(SUCCEEDED(hRes));
        hRes = CoResumeClassObjects();
#else
        hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER,
            REGCLS_MULTIPLEUSE);
#endif
        _ASSERTE(SUCCEEDED(hRes));

        MSG msg;
        while (GetMessage(&msg, 0, 0, 0))
            DispatchMessage(&msg);

        _Module.RevokeClassObjects();
        Sleep(dwPause); //wait for any threads to finish

		// Exit the tracing
		EgStd::g_pTrace->Exit();

		if (EgStd::g_pTrace != NULL)
			delete EgStd::g_pTrace;
    }

    _Module.Term();
    CoUninitialize();
    return nRet;
}
示例#20
0
// returns true only if pipes have been initialised successfully
bool initStdHandles()
{
	if (initialisedStdHandles)
		return true;

#if 0
	// Get I/O redirection arguments from command-line
	char*	stdoutFilename;
	char*	stderrFilename;
	char*	stdinFilename;
	BOOL	stdoutAppend;
	BOOL	stderrAppend;
	BOOL	stdinAppend;
	if (getRedirArgs(GetCommandLine(),
			&stdinFilename, &stdoutFilename, &stderrFilename, &stdinAppend, &stdoutAppend, &stderrAppend))
	{
	}
#endif

	TCHAR			name[100];
	HANDLE			hFileMapping = NULL;
	unsigned char*	pBuffer = NULL;

	_stprintf(name, TEXT("wcecompat.%08x.child_data"), GetCurrentProcessId());
	hFileMapping = CreateFileMapping((HANDLE)INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 1, name);
	if (hFileMapping == NULL)
		goto cleanup;
	else if (GetLastError() != ERROR_ALREADY_EXISTS)
	{
		CloseHandle(hFileMapping);
		hFileMapping = NULL;

		HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, TEXT("wcecompat.starting_child"));
		if (hEvent == NULL)
		{	// failed to create named event
		}
		else if (GetLastError() == ERROR_ALREADY_EXISTS)
		{	// we're in DllMain, so do nothing
		}
		else
		{
			CloseHandle(hEvent);
		}
	}
	else
	{
		pBuffer = (unsigned char*)MapViewOfFile(hFileMapping, FILE_MAP_WRITE, 0, 0, 0);
		if (pBuffer == NULL)
		{	// failed to map buffer
		}
		else
		{
			g_childData = new ChildData;
			if (g_childData == NULL)
				goto cleanup;
			if (!g_childData->decode(pBuffer))//, 16384);
				goto cleanup;
			g_childData->restoreEnvironment();
			RedirArg* stdinRedir = g_childData->getRedirArg(0);
			RedirArg* stdoutRedir = g_childData->getRedirArg(1);
			RedirArg* stderrRedir = g_childData->getRedirArg(2);
			if (stdinRedir != NULL && stdinRedir->redirType != RT_NONE)
			{
				if (stdinRedir->redirType == RT_PIPE_UNSPEC)
				{
					_FD_STRUCT* fds = fds_from_index(STDIN);
					if (fds == NULL)
						goto cleanup;
					fds->pipe = createPipe(stdinRedir->filename, OPEN_EXISTING);
					if (fds->pipe == NULL)
					{	// failed to open stdin pipe
						goto cleanup;
					}
					fds->pipeChannel = (unsigned char)stdinRedir->fd2;
				}
				else if (stdinRedir->redirType == RT_HANDLE)
				{
				}
				else if (stdinRedir->redirType == RT_FILE)
				{
//					WCHAR*	mode = L"r";	// default to "r" for the cases we don't know how to handle
					bool	r = stdinRedir->openForRead;
					bool	w = stdinRedir->openForWrite;
					bool	a = stdinRedir->append;
/*
					// rwa	mode
					// 010	"w"
					// 011	"a"
					// 100	"r"
					// 110	"r+"
					// 111	"a+"
					if (a)
					{
						if (r)
							mode = L"a+";
						else
							mode = L"a";
					}
					else if (r)
					{
						if (w)
							mode = L"r+";
						else
							mode = L"r";
					}
					else if (w)
						mode = L"w";
					FILE*	f = _wfopen(stdinRedir->filename, mode);
					if (f == NULL)
						goto cleanup;
					memcpy(&mystdin, f, sizeof(_FD_STRUCT));
					free(f);
*/
					// rwa	mode
					// 010	"w"		w,   CREATE_ALWAYS					O_WRONLY				O_CREAT|O_TRUNC
					// 011	"a"		w,   OPEN_ALWAYS   (APPEND DATA)	O_WRONLY	O_APPEND	O_CREAT
					// 100	"r"		r,   OPEN_EXISTING					O_RDONLY
					// 110	"r+"	r/w, OPEN_EXISTING					O_RDWR
					// 111	"a+"	r/w, OPEN_ALWAYS   (APPEND DATA)	O_RDWR		O_APPEND	O_CREAT
					int	flags = 0;
					int	mode = 0;
					if (r && w)
						flags |= O_RDWR;
					else if (r)
						flags |= O_RDONLY;
					else if (w)
						flags |= O_WRONLY;
					if (w)
					{
						if (!(r && !a))
						{
							flags |= O_CREAT;
							mode = S_IREAD | S_IWRITE;
						}
						if (!r && !a)
							flags |= O_TRUNC;
					}
					if (a)
						flags |= O_APPEND;
					_FD_STRUCT* fds = fds_from_index(STDIN);
					if (fds == NULL)
						goto cleanup;
					if (!_wopen_fds(stdinRedir->filename, flags, mode, fds))
						goto cleanup;
				}
			}
			if (stdoutRedir != NULL && stdoutRedir->redirType != RT_NONE)
			{
				if (stdoutRedir->redirType == RT_PIPE_UNSPEC)
				{
					_FD_STRUCT* fds = fds_from_index(STDOUT);
					if (fds == NULL)
						goto cleanup;
					fds->pipe = createPipe(stdoutRedir->filename, OPEN_EXISTING);
					if (fds->pipe == NULL)
					{	// failed to open stdout pipe
						goto cleanup;
					}
					fds->pipeChannel = (unsigned char)stdoutRedir->fd2;
				}
				else if (stdoutRedir->redirType == RT_HANDLE)
				{
				}
				else if (stdoutRedir->redirType == RT_FILE)
				{
//					WCHAR*	mode = L"r";	// default to "r" for the cases we don't know how to handle
					bool	r = stdoutRedir->openForRead;
					bool	w = stdoutRedir->openForWrite;
					bool	a = stdoutRedir->append;
/*
					// rwa	mode
					// 010	"w"
					// 011	"a"
					// 100	"r"
					// 110	"r+"
					// 111	"a+"
					if (a)
					{
						if (r)
							mode = L"a+";
						else
							mode = L"a";
					}
					else if (r)
					{
						if (w)
							mode = L"r+";
						else
							mode = L"r";
					}
					else if (w)
						mode = L"w";
					FILE*	f = _wfopen(stdoutRedir->filename, mode);
					if (f == NULL)
						goto cleanup;
					memcpy(&mystdout, f, sizeof(_FD_STRUCT));
					free(f);
*/
					// rwa	mode
					// 010	"w"		w,   CREATE_ALWAYS					O_WRONLY				O_CREAT|O_TRUNC
					// 011	"a"		w,   OPEN_ALWAYS   (APPEND DATA)	O_WRONLY	O_APPEND	O_CREAT
					// 100	"r"		r,   OPEN_EXISTING					O_RDONLY
					// 110	"r+"	r/w, OPEN_EXISTING					O_RDWR
					// 111	"a+"	r/w, OPEN_ALWAYS   (APPEND DATA)	O_RDWR		O_APPEND	O_CREAT
					int	flags = 0;
					int	mode = 0;
					if (r && w)
						flags |= O_RDWR;
					else if (r)
						flags |= O_RDONLY;
					else if (w)
						flags |= O_WRONLY;
					if (w)
					{
						if (!(r && !a))
						{
							flags |= O_CREAT;
							mode = S_IREAD | S_IWRITE;
						}
						if (!r && !a)
							flags |= O_TRUNC;
					}
					if (a)
						flags |= O_APPEND;
					_FD_STRUCT* fds = fds_from_index(STDOUT);
					if (fds == NULL)
						goto cleanup;
					if (!_wopen_fds(stdoutRedir->filename, flags, mode, fds))
						goto cleanup;
				}
			}
			if (stderrRedir != NULL && stderrRedir->redirType != RT_NONE)
			{
				if (stderrRedir->redirType == RT_PIPE_UNSPEC)
				{
					_FD_STRUCT* fds = fds_from_index(STDERR);
					if (fds == NULL)
						goto cleanup;
					if (stdoutRedir != NULL && stdoutRedir->redirType == RT_PIPE_UNSPEC &&
							wcscmp(stderrRedir->filename, stdoutRedir->filename) == 0)
					{
						_FD_STRUCT* fds_stdout = fds_from_index(STDOUT);
						if (fds_stdout == NULL)
							goto cleanup;
						fds->pipe = fds_stdout->pipe;
					}
					else
					{
						fds->pipe = createPipe(stderrRedir->filename, OPEN_EXISTING);
						if (fds->pipe == NULL)
						{	// failed to open stderr pipe
							goto cleanup;
						}
					}
					fds->pipeChannel = (unsigned char)stderrRedir->fd2;
				}
				else if (stderrRedir->redirType == RT_HANDLE)
				{
				}
				else if (stderrRedir->redirType == RT_FILE)
				{
//					WCHAR*	mode = L"r";	// default to "r" for the cases we don't know how to handle
					bool	r = stderrRedir->openForRead;
					bool	w = stderrRedir->openForWrite;
					bool	a = stderrRedir->append;
/*
					// rwa	mode
					// 010	"w"
					// 011	"a"
					// 100	"r"
					// 110	"r+"
					// 111	"a+"
					if (a)
					{
						if (r)
							mode = L"a+";
						else
							mode = L"a";
					}
					else if (r)
					{
						if (w)
							mode = L"r+";
						else
							mode = L"r";
					}
					else if (w)
						mode = L"w";
					FILE*	f = _wfopen(stderrRedir->filename, mode);
					if (f == NULL)
						goto cleanup;
					memcpy(&mystderr, f, sizeof(_FD_STRUCT));
					free(f);
*/
					// rwa	mode
					// 010	"w"		w,   CREATE_ALWAYS					O_WRONLY				O_CREAT|O_TRUNC
					// 011	"a"		w,   OPEN_ALWAYS   (APPEND DATA)	O_WRONLY	O_APPEND	O_CREAT
					// 100	"r"		r,   OPEN_EXISTING					O_RDONLY
					// 110	"r+"	r/w, OPEN_EXISTING					O_RDWR
					// 111	"a+"	r/w, OPEN_ALWAYS   (APPEND DATA)	O_RDWR		O_APPEND	O_CREAT
					int	flags = 0;
					int	mode = 0;
					if (r && w)
						flags |= O_RDWR;
					else if (r)
						flags |= O_RDONLY;
					else if (w)
						flags |= O_WRONLY;
					if (w)
					{
						if (!(r && !a))
						{
							flags |= O_CREAT;
							mode = S_IREAD | S_IWRITE;
						}
						if (!r && !a)
							flags |= O_TRUNC;
					}
					if (a)
						flags |= O_APPEND;
					_FD_STRUCT* fds = fds_from_index(STDERR);
					if (fds == NULL)
						goto cleanup;
					if (!_wopen_fds(stderrRedir->filename, flags, mode, fds))
						goto cleanup;
				}
			}
		}
	}

	initialisedStdHandles = true;
	atexit(shutdownIo);

cleanup:

	if (!initialisedStdHandles)
		uninitStdHandles();

	if (pBuffer != NULL)
		UnmapViewOfFile(pBuffer);
	if (hFileMapping != NULL)
		CloseHandle(hFileMapping);

	return initialisedStdHandles;
}
int WINAPI
WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
#ifdef _WIN32_WCE
        LPWSTR lpCmdLine,
#else
        LPSTR lpCmdLine2,
#endif
        int nCmdShow)
#endif
{
#ifdef WIN32
#ifndef _WIN32_WCE
  /* on Windows (non-CE), the lpCmdLine argument is narrow, and we
     have to use GetCommandLine() to get the UNICODE string */
  LPCTSTR lpCmdLine = GetCommandLine();
#endif

#ifdef _WIN32_WCE
  int argc = 2;

  WCHAR arg0[] = _T("");
  LPWSTR argv[] = { arg0, lpCmdLine, NULL };
#else
  int argc;
  LPWSTR* argv = CommandLineToArgvW(lpCmdLine, &argc);
#endif

  ResourceLoader::Init(hInstance);
#endif

  if (argc < 2) {
    fprintf(stderr, "Usage: RunDialog XMLFILE [-portrait]\n");
    return 1;
  }

  unsigned screen_width = 320, screen_height = 240;
  if (argc > 2 && _tcscmp(argv[2], _T("-portrait")) == 0) {
    screen_width = 240;
    screen_height = 320;
  }

  ScreenGlobalInit screen_init;

  Layout::Initialize(screen_width, screen_height);
  SingleWindow main_window;
  main_window.set(_T("STATIC"), _T("RunDialog"),
                  0, 0, screen_width, screen_height);
  main_window.show();

  WndForm *form = LoadDialog(NULL, main_window, argv[1]);
  if (form == NULL) {
    fprintf(stderr, "Failed to load resource '%s'\n",
            (const char *)NarrowPathName(argv[1]));
    return 1;
  }

  form->ShowModal();
  delete form;

  return 0;
}
示例#22
0
文件: loader.c 项目: Shondoit/loader
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	exitCode = ERROR_SUCCESS;

	LPTSTR cmdline = GetCommandLine();
	LPSTR *argv = __argv;
	int argc = __argc;
	if (argc < 2) {
		showUsage();
		return ERROR_INVALID_PARAMETER;
	}
	cmdline = PathGetArgs(cmdline);
	int index = 1;
	BOOL switchMatch;
	while (index < argc) {
		switchMatch = FALSE;
		LPSTR arg = argv[index];
		if (strlen(arg) >= 2) {
			switch (arg[0]) {
				case '-':
				case '/':
					switch (tolower(arg[1])) {
						case 's':
						case 'q':
							if (strlen(arg) == 2) {
								switchMatch = TRUE;
								silentFlag = TRUE;
							}
							break;
						case 'u':
							if (strlen(arg) == 2) {
								switchMatch = TRUE;
								uninstallFlag = TRUE;
							}
							break;
						case 't':
							if (strlen(arg) > 3 && arg[2] == '=') {
								switchMatch = TRUE;
								estTime = atoi(arg + 3);
							}
							break;
					}
					break;
			}
		}
		if (switchMatch) {
			cmdline = PathGetArgs(cmdline);
			index++;
		} else {
			index = argc;
		}
	}

	STARTUPINFO startInfo;
	PROCESS_INFORMATION procInfo;
	ZeroMemory(&startInfo, sizeof(startInfo));
	startInfo.cb = sizeof(startInfo);
	ZeroMemory(&procInfo, sizeof(procInfo));

	if (!CreateProcess(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &startInfo, &procInfo)) {
		exitCode = GetLastError();
		MessageBox(NULL, _tcserror(exitCode), NULL, MB_ICONERROR);
		return exitCode;
	}
	hChildProc = procInfo.hProcess;

	DialogBox(hInstance, MAKEINTRESOURCE(IDD_LOADER), 0, (DLGPROC)DlgProc);

	CloseHandle(procInfo.hProcess);
	CloseHandle(procInfo.hThread);

	return exitCode;
}
示例#23
0
文件: main.cpp 项目: crftwr/cmemo
int AppMain()
{
	std::wstring exe_dir;

	// Get exe's directory
	{
		wchar_t exe_path_buf[MAX_PATH + 1];
		GetModuleFileName(NULL, exe_path_buf, MAX_PATH);

		exe_dir = exe_path_buf;

		size_t last_backslash_pos = exe_dir.find_last_of(L"\\/");
		if (last_backslash_pos >= 0)
		{
			exe_dir = exe_dir.substr(0, last_backslash_pos);
		}
		else
		{
			exe_dir = L"";
		}
	}

	// Setup environment variable "PATH"
	{
		std::wstring env_path;

		wchar_t tmp_buf[1];
		DWORD ret = GetEnvironmentVariable(L"PATH", tmp_buf, 0);
		if (ret > 0)
		{
			DWORD len = ret;
			wchar_t * buf = (wchar_t*)malloc((len + 1) * sizeof(wchar_t));

			GetEnvironmentVariable(L"PATH", buf, (len + 1) * sizeof(wchar_t));

			env_path = buf;

			free(buf);
		}

		env_path = exe_dir + L"/lib;" + env_path;

		SetEnvironmentVariable(L"PATH", env_path.c_str());
	}

	// Python home
	{
#if defined(_DEBUG)
		Py_SetPythonHome(PYTHON_INSTALL_PATH);
#else
		Py_SetPythonHome(const_cast<wchar_t*>(exe_dir.c_str()));
#endif //_DEBUG
	}

	// Python module search path
	{
		std::wstring python_path;

		python_path += exe_dir + L"/extension;";
		
		#if defined(_DEBUG)
		python_path += exe_dir + L";";
		python_path += exe_dir + L"/..;";
		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\Lib;";
		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\Lib\\site-packages;";
		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\DLLs;";
		#else
		python_path += exe_dir + L"/library.zip;";
		python_path += exe_dir + L"/lib;";
		#endif
		
		Py_SetPath(python_path.c_str());
	}

	// Initialization
	Py_Initialize();

	// Setup sys.argv
	{
		wchar_t * cmdline = GetCommandLine();

		int argc;
		wchar_t ** argv = CommandLineToArgvW(cmdline, &argc);

		PySys_SetArgv(argc, argv);

		LocalFree(argv);
	}

	// Execute python side main script
	{
		PyObject * module = PyImport_ImportModule("cmemo_main");
		if (module == NULL)
		{
			PyErr_Print();
		}

		Py_XDECREF(module);
		module = NULL;
	}

	// Termination
	Py_Finalize();

	return 0;
}
示例#24
0
/*--------------------------------------------------------------------------
 Launches NetShell, waits for Netshell and all of NetShell's launched
   processes to die and then relaunches NetShell if nothing exited with
   non-zero exit status.
--------------------------------------------------------------------------*/
int WINAPI WinMain(HINSTANCE hinstExe, HINSTANCE hinstExePrev, LPSTR lpszCmdLine, int nCmdShow)
{
	int firsttime = 1;
	char cmd[2*MAX_PATH];
	char args[MAX_PATH];
	char cwd[MAX_PATH];
	char strhandle[MAX_HSTR];
	DWORD nhandles = 0;
	DWORD exitCode = 0;
	DWORD dwThreadId, iSignal;
	HANDLE hpipeRead, hpipeWrite, hSelf;
	HANDLE *hArray, *hStartArr;
	SECURITY_ATTRIBUTES saAttr;
	STARTUPINFO si;
	PROCESS_INFORMATION pi;

#ifdef DEBUG
#ifndef PRINT_STDOUT
	{	char logfile[MAX_PATH];
		sprintf(logfile, "%x", time(NULL));
		strcat(logfile, ".log");
		flog = fopen(logfile, "w");
	}
#endif
#endif
	/* Pick random session id for benefit of serial and modem drivers */
	sprintf(strhandle, "%x", GetTickCount());
	if (!SetEnvironmentVariable(DPSTUBID, strhandle)) {
		DPRINT(("stub: set environment variable error %x.\n", GetLastError()));
		exit(1);
	}
	hArray = (HANDLE *)malloc(MAXIMUM_WAIT_OBJECTS * sizeof(HANDLE));
	hStartArr = hArray;
	saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
	saAttr.bInheritHandle = TRUE;
	saAttr.lpSecurityDescriptor = NULL;
	if (!DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(), &hSelf,  0, TRUE, DUPLICATE_SAME_ACCESS)) {
		DPRINT(("stub: error duplicating own handle\n"));
		exit(1);
	}
	sprintf(strhandle, "%x", hSelf);
	if (!SetEnvironmentVariable(DPSTUB, strhandle)) {
		DPRINT(("stub: set environment variable error %x.\n", GetLastError()));
		exit(1);
	}
//	DPRINT(("stub: current process handle is %s\n", strhandle));

	/* create event so read thread can signal when it's read a new process */
	if (!(hreadEvent = CreateEvent(NULL, FALSE, FALSE, "ReadEvent"))) {
		DPRINT(("stub: create read event error %x.\n", GetLastError()));
		exit(1);
	}
	*hArray++ = hreadEvent;
	nhandles++;
//	DPRINT(("stub: read event handle is %x\n", *(hArray - 1)));

	/* create event so read thread knows main thread has finished processing
	   hSpawn and can continue to get new processes */
	if (!(hcontEvent = CreateEvent(NULL, FALSE, FALSE, "ContinueReadEvent"))) {
		DPRINT(("stub: create continue read event error %x.\n", GetLastError()));
		exit(1);
	}
//	DPRINT(("stub: continue read event handle is %x\n", hcontEvent));

	/* create a pipe with read end uninheritable and write end inheritable*/
	if(!CreatePipe(&hpipeRead, &hpipeWrite, &saAttr, sizeof(HANDLE))) {
		DPRINT(("stub: create pipe error %x.\n", GetLastError()));
		exit(1);
	}
	sprintf(strhandle, "%x", hpipeWrite);
	if (!SetEnvironmentVariable(DPSTUBWPIPE, strhandle)) {
		DPRINT(("stub: set environment variable error %x.\n", GetLastError()));
		exit(1);
	}
	if (!DuplicateHandle(GetCurrentProcess(), hpipeRead, GetCurrentProcess(), &hpipeReadDup,  0, FALSE, DUPLICATE_SAME_ACCESS)) {
		DPRINT(("stub: error duplicating uninheritable handle\n"));
		exit(1);
	}
	CloseHandle(hpipeRead);
//	DPRINT(("stub: uninheritable pipe handle is %x.\n", hpipeReadDup));

	/* create a thread to read from pipe about new processes*/
	if (CreateThread(NULL, 0, readThread, 0, 0, &dwThreadId) < 0) {
		DPRINT(("stub: create thread error %x.\n", GetLastError()));
		exit(1);
	}

	/* set command and current working directory for CreateProcess() */
	{	char *buf;
		char path[2*MAX_PATH];
		char cmdline[1024];
		if (getinfo(path, args, cwd) != 0) {
			CHAR title[TITLELEN];
			CHAR msg[MSGLEN];
			LoadString(NULL, IDS_NO_JRE_TITLE, title, TITLELEN);
			LoadString(NULL, IDS_NO_JRE_MSG, msg, MSGLEN);
			MessageBox(NULL, msg, title,
				MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND);
			exit(1);
		}
		strcat(cmd, "\"");
		strcat(cmd, path);
		strcat(cmd, "\" ");
		strcat(cmd, args);

		buf = GetCommandLine();
		if (!buf) {
			DPRINT(("stub: error getting commandline args; quitting\n"));
			exit(1);
		}
		strcpy(cmdline, buf);
#ifdef DEFAULTARGS
		/* If no switches given, append default args */
		if (!strstr(cmdline, " -")) {
			strcat(cmdline, " ");
			strcat(cmdline, DEFAULTARGS);
		}
#endif
		buf = cmdline;
		DPRINT(("args: %s\n", buf));
		{
			OSVERSIONINFO VersionInfo;
			VersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
			if (!GetVersionEx(&VersionInfo)) {
				DPRINT(("stub: cannot determine OS; quitting\n"));
				exit(1); 
			}
			if (VersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT || VersionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
				while (' ' == *buf || '\t' == *buf) buf++;
				if (*buf == '\"') {
					buf++;
					if (!(buf = strchr(buf, '\"'))) {
						DPRINT(("stub: cannot get commandline args; quitting\n"));
						exit(1);
					}
					buf++;
				} else {
					if (buf = strchr(buf, ' ')) {
						buf++;
					} else {
						buf = "\0";
					}
				}
			} else {
				CHAR title[TITLELEN];
				CHAR msg[MSGLEN];
				LoadString(NULL, IDS_UNSP_OS_TITLE, title, TITLELEN);
				LoadString(NULL, IDS_UNSP_OS_MSG, msg, MSGLEN);
				MessageBox(NULL, msg, title,
					MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND);
				DPRINT(("OS not supported; quitting\n"));
				exit(1);
			}
			while (' ' == *buf || '\t' == *buf) buf++;
			if (2 * MAX_PATH < strlen(cmd) + strlen(buf) + 2) {
				DPRINT(("stub: cmd buffer not large enough to hold args; quitting\n"));
				exit(1);
			}
			strcat(cmd, " ");
			strcat(cmd, buf);
		}
	}
	DPRINT(("cmd: %s\n", cmd));

	/* launch NetShell then wait for NetShell and all its launched processes
	   to die, then if all exit status are zero, relaunch NetShell */
	do {
		memset(&pi, 0, sizeof(pi));
		memset(&si, 0, sizeof(si));
		si.cb = sizeof(si);
		/* launch NetShell */
    	DPRINT(("stub: Launching %s from %s.\n", cmd, cwd));
		if (!CreateProcess(NULL, cmd, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, cwd, &si, &pi)) {
			DPRINT(("stub: Error launching %s from %s; quitting\n", cmd, cwd));
			DPRINT(("stub: GetLastError returns %x", GetLastError()));
			exit(1);
		}
		if (firsttime) {
			char *buf = " -r";
			if (2 * MAX_PATH < strlen(cmd) + strlen(buf) + 1) {
				DPRINT(("stub: cmd buffer not large enough to hold args\n"));
				exit(1);
			}
			strcat(cmd, buf);
			firsttime = 0;
		}
		CloseHandle(pi.hThread);
		*hArray++ = pi.hProcess;
		nhandles++;
		DPRINT(("stub: Launch complete; shell handle %x.\n", *(hArray-1)));

		/* Wait for NetShell and all its launched processes to exit */
		do {
			iSignal = WaitForMultipleObjects(nhandles, hStartArr, FALSE, INFINITE);
			if (WAIT_FAILED == iSignal) {
				DPRINT(("stub: wait error %x.\n", GetLastError()));
				exit(1);
			}
			iSignal -= WAIT_OBJECT_0;
			if (iSignal >= 0 && iSignal < nhandles) {
				if (*(hStartArr + iSignal) != hreadEvent) {
					if (!GetExitCodeProcess(*(hStartArr + iSignal), &exitCode)) {
						DPRINT(("stub: Error reading spawned process\n"));
						exit(1);
					}
					DPRINT(("stub: deleting handle %x, exit code %d.\n", *(hStartArr + iSignal), exitCode));
					if (exitCode) break;
					CloseHandle(*(hStartArr + iSignal));
					if (nhandles && iSignal < nhandles - 1) {
						*(hStartArr + iSignal) = *(hStartArr + nhandles - 1);
					}
					nhandles--;
					hArray = hStartArr + nhandles;
				} else {
					// DPRINT(("stub: got new handle %x\n", hSpawn));
					if (hSpawn != 0) {
						if (hSpawn < 0) {
							DPRINT(("stub: Error reading spawned process; hSpawn %x\n", hSpawn));
							exit(1);
						}
						DPRINT(("stub: adding handle %x.\n", hSpawn));
						*hArray++ = hSpawn;
						nhandles++;
						hSpawn = 0;
					} else if (hSerial != 0) {
						char *pstrhandle;
						if (hSerial < 0 && hSerial != INVALID_HANDLE_VALUE) {
							DPRINT(("stub: Error reading serial handle; hSerial %x\n", hSerial));
							exit(1);
						}
						if (hSerial == INVALID_HANDLE_VALUE) {
							if (GetEnvironmentVariable(DPSTUBMODEM, strhandle, 256)) {
								HANDLE baseadr;
								sscanf(strhandle, "%x", &baseadr);
								CloseHandle(baseadr);
								DPRINT(("stub: deleted serial h:%x\n",baseadr));
								pstrhandle = NULL;
							}
						} else {
							DPRINT(("stub: setting serial h:%x.\n", hSerial));
							sprintf(strhandle, "%x", hSerial);
							pstrhandle = strhandle;
						}
						if (!SetEnvironmentVariable(DPSTUBMODEM, pstrhandle)) {
							DPRINT(("stub: set environment variable error %x.\n", GetLastError()));
							exit(1);
						}
						hSerial = 0;
					} else {
						DPRINT(("stub: Error no handle set\n"));
						exit(1);
					}
					if (!SetEvent(hcontEvent)) {
						DPRINT(("stub: set continue read event error %x.\n", GetLastError()));
						exit(1);
					}
				}
			} else {
				DPRINT(("stub: error wait returned invalid handle %d\n", iSignal));
				exit(1);
			}
//			DPRINT(("stub: nhandles = %d\n", nhandles));
		} while (nhandles > 1);
//		DPRINT(("stub: exited inside loop\n"));
#ifdef NOLOOP		
		break;
#endif
	} while (!exitCode);
	return 0;
}
示例#25
0
/*
 * Check that we're linked as a GUI application. Depending on how
 * we where started, we create or attach to parent console before
 * using printf() etc. If using GTK interface (option "-G"), don't
 * create a console.
 */
static void setup_console (void)
{
#if !defined(BUILDING_UTILS)
  BOOL (WINAPI *_AttachConsole)(DWORD) = NULL;
  HMODULE mod;
  DWORD   rc = 0;
  STARTUPINFO inf;
  const char *cmd_line = GetCommandLine();
  BOOL  is_ec   = (cmd_line && strstr(cmd_line,"ettercap"));
  BOOL  use_gtk = (is_ec && strstr(cmd_line,"-G") != NULL);

  if (!is_ec || use_gtk)  /* GTK UI shouldn't need a console */
     return;

  /* Note: this is true even when started minimized
   * (nCmdShow == SW_MINIMISED), but fails if program started as
   * another user
   */
  memset (&inf, 0, sizeof(inf));
  GetStartupInfo (&inf);

  started_from_a_gui = (inf.dwFlags & STARTF_USESHOWWINDOW);

  /* check if correct linker option used
   */
  if (!is_gui_app()) {
     MessageBox (NULL, "You must relink this application with\n"
                 "\"-Wl,--subsystem,windows\"\n", "Error",
                 MB_ICONEXCLAMATION | MB_SETFOREGROUND);
     exit (-1);
  }

  mod = GetModuleHandle ("kernel32.dll");
  if (mod)
     _AttachConsole = (BOOL (WINAPI*)(DWORD)) GetProcAddress((HINSTANCE)mod, "AttachConsole");

  attached_to_console = FALSE;

  /* If parent doesn't have a console, AttachConsole() will fail and
   * we use AllocConsole() instead.
   * Note: AttachConsole() was introduced in Win-2000, so for Win-ME/9x,
   *       we simply try AllocConsole().
   */
  if (_AttachConsole) {
     if ((*_AttachConsole)(ATTACH_PARENT_PROCESS))
        attached_to_console = TRUE;
     else
        rc = GetLastError();
  }

  if (!attached_to_console && !AllocConsole()) {
     char error[256];

     snprintf (error, 256, "AllocConsole failed; error %lu", GetLastError());
     MessageBox (NULL, error, "Fatal", MB_ICONEXCLAMATION | MB_SETFOREGROUND);
     exit (-1);
  }

  /* Synchronise std-handles with the new console
   */
  freopen ("CONIN$", "rt", stdin);
  freopen ("CONOUT$", "wt", stdout);
  freopen ("CONOUT$", "wt", stderr);

#if 0
  printf ("_AttachConsole %p, rc %lu, started_from_a_gui %d, attached_to_console %d\n",
          _AttachConsole, rc, started_from_a_gui, attached_to_console);
#endif

  has_console = TRUE;
#endif /* BUILDING_UTILS */
}
示例#26
0
/* ********************************************************************************************** */
int WINAPI _tWinMain(HINSTANCE instance, HINSTANCE previousInstance, LPTSTR commandLine,
		int showCommand)
{
	int argc;
	LPWSTR *argv = CommandLineToArgvW(GetCommandLine(), &argc);
	if(argc > 2)
	{
		MessageBox(NULL, _T("CreepWrap accepts a single, optional, argument, which should be the ")
					_T("path to Minecraft.exe.\n\nIn the absence of this argument, CreepWrap will ")
					_T("attempt to load Minecraft.exe from the current working directory."),
				_T("CreepWrap usage"), MB_ICONWARNING | MB_OK);
		return 1;

	}

	try
	{
		jvminvoke::JavaVM javaVM;

		const std::string mainClass("net/minecraft/LauncherFrame");
		if(argc == 1)
		{
			javaVM.executeJAR("Minecraft.exe", mainClass);

		}
		else
		{
			LPSTR jarPathBuffer = static_cast<LPSTR>(std::malloc((std::wcslen(argv[1]) + 1) *
						sizeof(char)));
			jarPathBuffer[std::wcslen(argv[1])] = '\0';
			CharToOemBuff(argv[1], jarPathBuffer, static_cast<DWORD>(std::wcslen(argv[1])));
			std::string jarPath(jarPathBuffer);
			std::free(jarPathBuffer);
			javaVM.executeJAR(jarPath, mainClass);

		}

	}
	catch(const jvminvoke::JavaException &e)
	{
		std::wstring message = e.wideMessage() + L"\n\nJava exception details:\n" + e.javaMessage();
		MessageBoxW(NULL, message.c_str(), L"Error", MB_ICONERROR | MB_OK);
		return -2;

	}
	catch(const jvminvoke::RuntimeException &e)
	{
		MessageBoxA(NULL, e.message().c_str(), "Error", MB_ICONERROR | MB_OK);
		return e.returnCode();

	}
	catch(const jvminvoke::Exception &e)
	{
		MessageBoxA(NULL, e.message().c_str(), "Error", MB_ICONERROR | MB_OK);
		return -1;

	}

	return 0;

} // _tWinMain
示例#27
0
EXTERN_C int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR, int nShowCmd)
{
    QT_USE_NAMESPACE 

    qAxOutProcServer = true;
    GetModuleFileName(0, qAxModuleFilename, MAX_PATH);
    qAxInstance = hInstance;

    QByteArray cmdParam = QString::fromWCharArray(GetCommandLine()).toLocal8Bit();
    QList<QByteArray> cmds = cmdParam.split(' ');
    QByteArray unprocessed;

    int nRet = 0;
    bool run = true;
    bool runServer = false;
    for (int i = 0; i < cmds.count(); ++i) {
        QByteArray cmd = cmds.at(i).toLower();
        if (cmd == "-activex" || cmd == "/activex" || cmd == "-embedding" || cmd == "/embedding") {
            runServer = true;
        } else if (cmd == "-unregserver" || cmd == "/unregserver") {
            nRet = UpdateRegistry(false);
            run = false;
            break;
        } else if (cmd == "-regserver" || cmd == "/regserver") {
            nRet = UpdateRegistry(true);
            run = false;
            break;
        } else if (cmd == "-dumpidl" || cmd == "/dumpidl") {
            ++i;
            if (i < cmds.count()) {
                QByteArray outfile = cmds.at(i);
                ++i;
                QByteArray version;
                if (i < cmds.count() && (cmds.at(i) == "-version" || cmds.at(i) == "/version")) {
                    ++i;
                    if (i < cmds.count())
                        version = cmds.at(i);
                    else
                        version = "1.0";
                }
                
                nRet = DumpIDL(QString::fromLatin1(outfile.constData()), QString::fromLatin1(version.constData()));
            } else {
                qWarning("Wrong commandline syntax: <app> -dumpidl <idl file> [-version <x.y.z>]");
            }
            run = false;
            break;
        } else {
            unprocessed += cmds.at(i) + ' ';
        }
    }
    
    if (run) {
        HRESULT hRes = CoInitialize(0);

        int argc;
        QVector<char*> argv(8);
        qWinMain(hInstance, hPrevInstance, unprocessed.data(), nShowCmd, argc, argv);
        qAxInit();
        if (runServer)
            QAxFactory::startServer();
        nRet = ::main(argc, argv.data());
        QAxFactory::stopServer();
        qAxCleanup();
        CoUninitialize();
        
    }
    
    return nRet;
}
示例#28
0
/*
 * Given a path to a jre to execute, this routine checks if this process
 * is indeed that jre.  If not, it exec's that jre.
 *
 * We want to actually check the paths rather than just the version string
 * built into the executable, so that given version specification will yield
 * the exact same Java environment, regardless of the version of the arbitrary
 * launcher we start with.
 */
void
ExecJRE(char *jre, char **argv) {
    int     len;
    char    *progname;
    char    path[MAXPATHLEN + 1];

    /*
     * Determine the executable we are building (or in the rare case, running).
     */
#ifdef JAVA_ARGS  /* javac, jar and friends. */
    progname = "java";
#else             /* java, oldjava, javaw and friends */
#ifdef PROGNAME
    progname = PROGNAME;
#else
    {
        char *s;
        progname = *argv;
        if ((s = strrchr(progname, FILE_SEPARATOR)) != 0) {
            progname = s + 1;
        }
    }
#endif /* PROGNAME */
#endif /* JAVA_ARGS */

    /*
     * Resolve the real path to the currently running launcher.
     */
    len = GetModuleFileName(NULL, path, MAXPATHLEN + 1);
    if (len == 0 || len > MAXPATHLEN) {
        ReportSysErrorMessage2(
          "Unable to resolve path to current %s executable: %s",
          progname, JNI_TRUE);
        exit(1);
    }

    if (_launcher_debug) {
        printf("ExecJRE: old: %s\n", path);
        printf("ExecJRE: new: %s\n", jre);
    }

    /*
     * If the path to the selected JRE directory is a match to the initial
     * portion of the path to the currently executing JRE, we have a winner!
     * If so, just return. (strnicmp() is the Windows equiv. of strncasecmp().)
     */
    if (strnicmp(jre, path, strlen(jre)) == 0)
        return;                 /* I am the droid you were looking for */

    /*
     * If this isn't the selected version, exec the selected version.
     */
    (void)strcat(strcat(strcpy(path, jre), "\\bin\\"), progname);
    (void)strcat(path, ".exe");

    /*
     * Although Windows has an execv() entrypoint, it doesn't actually
     * overlay a process: it can only create a new process and terminate
     * the old process.  Therefore, any processes waiting on the initial
     * process wake up and they shouldn't.  Hence, a chain of pseudo-zombie
     * processes must be retained to maintain the proper wait semantics.
     * Fortunately the image size of the launcher isn't too large at this
     * time.
     *
     * If it weren't for this semantic flaw, the code below would be ...
     *
     *     execv(path, argv);
     *     ReportErrorMessage2("Exec of %s failed\n", path, JNI_TRUE);
     *     exit(1);
     *
     * The incorrect exec semantics could be addressed by:
     *
     *     exit((int)spawnv(_P_WAIT, path, argv));
     *
     * Unfortunately, a bug in Windows spawn/exec impementation prevents
     * this from completely working.  All the Windows POSIX process creation
     * interfaces are implemented as wrappers around the native Windows
     * function CreateProcess().  CreateProcess() takes a single string
     * to specify command line options and arguments, so the POSIX routine
     * wrappers build a single string from the argv[] array and in the
     * process, any quoting information is lost.
     *
     * The solution to this to get the original command line, to process it
     * to remove the new multiple JRE options (if any) as was done for argv
     * in the common SelectVersion() routine and finally to pass it directly
     * to the native CreateProcess() Windows process control interface.
     */
    {
        char    *cmdline;
        char    *p;
        char    *np;
        char    *ocl;
        char    *ccl;
        char    *unquoted;
        DWORD   exitCode;
        STARTUPINFO si;
        PROCESS_INFORMATION pi;

        /*
         * The following code block gets and processes the original command
         * line, replacing the argv[0] equivalent in the command line with
         * the path to the new executable and removing the appropriate
         * Multiple JRE support options. Note that similar logic exists
         * in the platform independent SelectVersion routine, but is
         * replicated here due to the syntax of CreateProcess().
         *
         * The magic "+ 4" characters added to the command line length are
         * 2 possible quotes around the path (argv[0]), a space after the
         * path and a terminating null character.
         */
        ocl = GetCommandLine();
        np = ccl = JLI_StringDup(ocl);
        p = nextarg(&np);               /* Discard argv[0] */
        cmdline = (char *)JLI_MemAlloc(strlen(path) + strlen(np) + 4);
        if (strchr(path, (int)' ') == NULL && strchr(path, (int)'\t') == NULL)
            cmdline = strcpy(cmdline, path);
        else
            cmdline = strcat(strcat(strcpy(cmdline, "\""), path), "\"");

        while (*np != (char)0) {                /* While more command-line */
            p = nextarg(&np);
            if (*p != (char)0) {                /* If a token was isolated */
                unquoted = unquote(p);
                if (*unquoted == '-') {         /* Looks like an option */
                    if (strcmp(unquoted, "-classpath") == 0 ||
                      strcmp(unquoted, "-cp") == 0) {   /* Unique cp syntax */
                        cmdline = strcat(strcat(cmdline, " "), p);
                        p = nextarg(&np);
                        if (*p != (char)0)      /* If a token was isolated */
                            cmdline = strcat(strcat(cmdline, " "), p);
                    } else if (strncmp(unquoted, "-version:", 9) != 0 &&
                      strcmp(unquoted, "-jre-restrict-search") != 0 &&
                      strcmp(unquoted, "-no-jre-restrict-search") != 0) {
                        cmdline = strcat(strcat(cmdline, " "), p);
                    }
                } else {                        /* End of options */
                    cmdline = strcat(strcat(cmdline, " "), p);
                    cmdline = strcat(strcat(cmdline, " "), np);
                    JLI_MemFree((void *)unquoted);
                    break;
                }
                JLI_MemFree((void *)unquoted);
            }
        }
        JLI_MemFree((void *)ccl);

        if (_launcher_debug) {
            np = ccl = JLI_StringDup(cmdline);
            p = nextarg(&np);
            printf("ReExec Command: %s (%s)\n", path, p);
            printf("ReExec Args: %s\n", np);
            JLI_MemFree((void *)ccl);
        }
        (void)fflush(stdout);
        (void)fflush(stderr);

        /*
         * The following code is modeled after a model presented in the
         * Microsoft Technical Article "Moving Unix Applications to
         * Windows NT" (March 6, 1994) and "Creating Processes" on MSDN
         * (Februrary 2005).  It approximates UNIX spawn semantics with
         * the parent waiting for termination of the child.
         */
        memset(&si, 0, sizeof(si));
        si.cb =sizeof(STARTUPINFO);
        memset(&pi, 0, sizeof(pi));

        if (!CreateProcess((LPCTSTR)path,       /* executable name */
          (LPTSTR)cmdline,                      /* command line */
          (LPSECURITY_ATTRIBUTES)NULL,          /* process security attr. */
          (LPSECURITY_ATTRIBUTES)NULL,          /* thread security attr. */
          (BOOL)TRUE,                           /* inherits system handles */
          (DWORD)0,                             /* creation flags */
          (LPVOID)NULL,                         /* environment block */
          (LPCTSTR)NULL,                        /* current directory */
          (LPSTARTUPINFO)&si,                   /* (in) startup information */
          (LPPROCESS_INFORMATION)&pi)) {        /* (out) process information */
            ReportSysErrorMessage2("CreateProcess(%s, ...) failed: %s",
              path, JNI_TRUE);
              exit(1);
        }

        if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_FAILED) {
            if (GetExitCodeProcess(pi.hProcess, &exitCode) == FALSE)
                exitCode = 1;
        } else {
            ReportErrorMessage("WaitForSingleObject() failed.", JNI_TRUE);
            exitCode = 1;
        }

        CloseHandle(pi.hThread);
        CloseHandle(pi.hProcess);

        exit(exitCode);
    }

}
示例#29
0
int WINAPI WinMain( HINSTANCE cur, HINSTANCE prev, LPSTR cmd, int show)
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    HANDLE testFile;
    char sn_loc[MAXPATHLEN];
    char hyper_cmd_line[MAXPATHLEN];
    char etc_dir[MAXPATHLEN];
    char tmp[MAXPATHLEN];
    char installDir[MAXPATHLEN];
    char *cmdLine;
    char *relativePtr;

    /*
     * Get the name of the executable.
     */

    cmdLine = GetCommandLine();
    sn_next_cmd_argument(cmdLine, sn_loc, sizeof(sn_loc));

    if (GetFullPathName(sn_loc, MAXPATHLEN, sn_loc, 0)) {
        if (strstr(strlwr(sn_loc), "snpdbg.exe")) {
            sn_loc[strlen(sn_loc) - strlen("snpdbg.exe")] = 0;
        } else if (strstr(strlwr(sn_loc), "snpdbg")) {
            sn_loc[strlen(sn_loc) - strlen("snpdbg")] = 0;
        }
    } else {
        /*
         * set path to current directory
         */
        if (!GetCurrentDirectory(MAXPATHLEN, sn_loc)) {
            MessageBox(0, "Failed to start snpdbg", "Error", MB_OK|MB_ICONERROR);
            exit(1);
        }
    }

    if (sn_loc[strlen(sn_loc) - 1] == '\\') {
        sn_loc[strlen(sn_loc) - 1] = '\0';
    }

    /*
     * Now, we have to find the etc/snpdbg file.
     */

    strcpy(tmp, sn_loc);

    relativePtr = strrchr(tmp, '\\');
    if (relativePtr == NULL) {
        MessageBox(0, "Failed to start snpdbg", "Error", MB_OK|MB_ICONERROR);
        exit(1);
    }
    strcpy(relativePtr, "\\share\\snavigator\\etc\\snpdbg");

    testFile = CreateFile(tmp, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
    if (INVALID_HANDLE_VALUE == testFile) {
        strcpy(tmp, sn_loc);
        relativePtr = strrchr(tmp, '\\');
        relativePtr[0] = '\0';
        relativePtr = strrchr(tmp, '\\');
        if (NULL == relativePtr) {
            MessageBox(0, "Failed to start snpdbg", "Error", MB_OK|MB_ICONERROR);
            exit(1);
        }

        strcpy(relativePtr, "\\share\\etc\\snpdbg");
        testFile = CreateFile(tmp, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
        if (INVALID_HANDLE_VALUE == testFile) {
            MessageBox(0, "Failed to start snpdbg", "Error", MB_OK|MB_ICONERROR);
            exit(1);
        }
    }
    CloseHandle(testFile);

    strcpy(etc_dir, tmp);

    /*
     * relativePtr is still set to "\\share\\etc\\snpdbg"
     */

    relativePtr[0] = '\0';

    /*
     * Make sure all slashes are POSIX style.
     */
    sn_internal_convert_path(tmp, SN_PATH_UNIX);
    SetEnvironmentVariable("SN_INSTALL_DIR", tmp);


    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);

    /*
     * Allow SN to understand parameters also,
     * do not use relative paths
     *
     * construct a command "hyper -f <file>"
     */
    hyper_cmd_line[0] = 0;
    sprintf (tmp, "%s\\%s", sn_loc, "hyper");
    sn_append_option_to_command_line (hyper_cmd_line, tmp);
    sn_append_option_to_command_line (hyper_cmd_line, "-f");
    sn_append_option_to_command_line (hyper_cmd_line, etc_dir);

    /* add "--" after -file to make sure that SN parameters
     * don't colapse with wish parameters
     * as example: SN -c == -colormap for wish
     */
    sn_append_option_to_command_line (hyper_cmd_line, "--");

    /*
     * Command line arguments are already quoted with ".." when they
     * contain blanks, so no need to rework them.
     */
    if (cmd != NULL && cmd[0])
    {
        strcat (hyper_cmd_line, " ");
        strcat (hyper_cmd_line, cmd);
    }

    if(CreateProcess(
                NULL,
                hyper_cmd_line	/*"hyper -f share\\etc\\snpdbg"*/ , /* pointer to command line string */
                NULL,	/* pointer to process security attributes */
                NULL,	/* pointer to thread security attributes */
                FALSE,	/* handle inheritance flag */
                0,		/* creation flags */
                NULL,	/* pointer to new environment block */
                NULL,	/* pointer to current directory name */
                &si,	/* pointer to STARTUPINFO */
                &pi 	/* pointer to PROCESS_INFORMATION   */
            ) == 0) {
        MessageBox(0, "Failed to start snpdbg", "Error", MB_OK|MB_ICONERROR);
        return GetLastError();
    }

    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

    return 0;
}
示例#30
0
文件: WINFLY.CPP 项目: gondur/mig_src
int WINAPI WinMain (HANDLE hInstance, HANDLE hPrevInstance, LPSTR lpszCmdParam, int iCmdShow)
{

	// Temp Code is not Complete ARM 17 Dec 1996

//TempCode ARM 17Dec96 	// fix msdsound.inf bug
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 	
//TempCode ARM 17Dec96 	// find required file
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 	char SearchString [] = SEARCH_STRING;
//TempCode ARM 17Dec96 	char SearchString2 [] = SEARCH_STRING2;
//TempCode ARM 17Dec96 	char NewLine [] = NEW_LINE;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 	char FileName [128];
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 	GetWindowsDirectory (FileName, 128);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 	strcat (FileName, INF_FILE);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 	HANDLE file;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 	SECURITY_ATTRIBUTES SecurityAttributes;
//TempCode ARM 17Dec96 	SECURITY_DESCRIPTOR SecurityDescriptor;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 	InitializeSecurityDescriptor (&SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96   	SecurityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
//TempCode ARM 17Dec96   	SecurityAttributes.lpSecurityDescriptor = &SecurityDescriptor;
//TempCode ARM 17Dec96   	SecurityAttributes.bInheritHandle = TRUE;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 	file = CreateFile (FileName,
//TempCode ARM 17Dec96 		GENERIC_READ,
//TempCode ARM 17Dec96 		0,
//TempCode ARM 17Dec96 		&SecurityAttributes,
//TempCode ARM 17Dec96 		OPEN_EXISTING,
//TempCode ARM 17Dec96 		FILE_ATTRIBUTE_NORMAL,
//TempCode ARM 17Dec96 		NULL);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 	if (file != NULL)
//TempCode ARM 17Dec96 	{
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 		DWORD losize,hisize;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 		losize = GetFileSize (file, &hisize);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 //TempCode ARM 17Dec96 		char asd [64];
//TempCode ARM 17Dec96 //TempCode ARM 17Dec96 		wsprintf (asd, "%s %ld,%ld", FileName, hisize, losize);
//TempCode ARM 17Dec96 //TempCode ARM 17Dec96 		MessageBox (NULL, asd, "Size", MB_OK);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 		if (losize != 0xffffffffl)
//TempCode ARM 17Dec96 		{
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 			char* Buffer;
//TempCode ARM 17Dec96 			Buffer = NULL;
//TempCode ARM 17Dec96 			Buffer = new char [losize + sizeof(NEW_LINE) + 1];
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 			if (Buffer != NULL)
//TempCode ARM 17Dec96 			{
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 				// read in file to memory
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 				DWORD readin;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 				ReadFile (file,
//TempCode ARM 17Dec96 					Buffer,
//TempCode ARM 17Dec96 					losize,
//TempCode ARM 17Dec96 					&readin,
//TempCode ARM 17Dec96 					NULL);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 				CloseHandle (file);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 				if (readin == losize)
//TempCode ARM 17Dec96 				{
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 					// find SEARCH_STRING
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 					DWORD n,m,l;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 					BOOL foundit = FALSE;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 					for (n=0; n<losize; n++)
//TempCode ARM 17Dec96 					{
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 						for (m=0; m<strlen(SEARCH_STRING); m++)
//TempCode ARM 17Dec96 						{
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 							if (*(Buffer+n+m) != SearchString[m])
//TempCode ARM 17Dec96 								break;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 						}
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 						// *(n+m) should == '\n' or '\r'
//TempCode ARM 17Dec96 						if ((*(Buffer + n + m) != '\n') && (*(Buffer + n + m) != '\r'))
//TempCode ARM 17Dec96 							m = 0;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 						if (m == strlen(SEARCH_STRING))
//TempCode ARM 17Dec96 						{
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 							m += 2;	// go past last char in SEARCH_STRING & newline character
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 							// search for SEARCH_STRING2
//TempCode ARM 17Dec96 							// must be directly after above
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 							for (l=0; l<strlen(SEARCH_STRING2); l++)
//TempCode ARM 17Dec96 							{
//TempCode ARM 17Dec96 								if (*(Buffer+n+m+l) != SearchString2[l])
//TempCode ARM 17Dec96 									break;
//TempCode ARM 17Dec96 							}
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 							if (l == strlen(SEARCH_STRING2))
//TempCode ARM 17Dec96 							{
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 								// move remaining data forward
//TempCode ARM 17Dec96 								// from end to n + 1
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 								l += 2;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 //TempCode ARM 17Dec96 								char poo [256];
//TempCode ARM 17Dec96 //TempCode ARM 17Dec96 								for (DWORD h=0; h<64; h++)
//TempCode ARM 17Dec96 //TempCode ARM 17Dec96 									poo[h+1] = *(Buffer + n + m + l+h);
//TempCode ARM 17Dec96 //TempCode ARM 17Dec96 								poo[h] = 0;
//TempCode ARM 17Dec96 //TempCode ARM 17Dec96 								poo[0] = 'X';
//TempCode ARM 17Dec96 //TempCode ARM 17Dec96 								MessageBox (NULL, poo, "Search 2", MB_OK);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 								DWORD k;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 								DWORD shft1,shft2, size;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 								shft1 = n + m + l;
//TempCode ARM 17Dec96 								size = losize - shft1;
//TempCode ARM 17Dec96 								shft2 = shft1 + sizeof (NEW_LINE) + 1;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 								for (k=shft2; k>=shft1; k--)
//TempCode ARM 17Dec96 									*(Buffer + k + strlen (NEW_LINE)) = *(Buffer + k);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 								// put in new text
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 								for (k=shft1; k<strlen(NEW_LINE); k++)
//TempCode ARM 17Dec96 									*(Buffer + k) = NewLine[k];
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 								foundit = TRUE;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 								break;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 							}
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 						}
//TempCode ARM 17Dec96 					}
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 					if (foundit)
//TempCode ARM 17Dec96 					{
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 						MessageBox (NULL, SEARCH_STRING, FileName, MB_OK);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 						file = CreateFile (FileName,
//TempCode ARM 17Dec96 							GENERIC_WRITE,
//TempCode ARM 17Dec96 							0,
//TempCode ARM 17Dec96 							&SecurityAttributes,
//TempCode ARM 17Dec96 							OPEN_EXISTING,
//TempCode ARM 17Dec96 							FILE_ATTRIBUTE_NORMAL,
//TempCode ARM 17Dec96 							NULL);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 						if (file != NULL)
//TempCode ARM 17Dec96 						{
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 							// write new file from memory
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 							DWORD writeout;
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 							WriteFile (file,
//TempCode ARM 17Dec96 								Buffer,
//TempCode ARM 17Dec96 								losize + sizeof (NEW_LINE) + 1,
//TempCode ARM 17Dec96 								&writeout,
//TempCode ARM 17Dec96 								NULL);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 							if (writeout != (losize + sizeof (NEW_LINE) + 1))
//TempCode ARM 17Dec96 								MessageBox (NULL, "Failed to write whole file", "Message", MB_OK);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 							CloseHandle (file);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 						}
//TempCode ARM 17Dec96 						else
//TempCode ARM 17Dec96 							MessageBox (NULL, "Failed to open Write File", "Message", MB_OK);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 					}
//TempCode ARM 17Dec96 					else
//TempCode ARM 17Dec96 						MessageBox (NULL, "Failed to find string", "Message", MB_OK);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 				}
//TempCode ARM 17Dec96 				else
//TempCode ARM 17Dec96 					MessageBox (NULL, "Failed to read whole file", "Message", MB_OK);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 				delete (Buffer);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 			}
//TempCode ARM 17Dec96 			else
//TempCode ARM 17Dec96 				MessageBox (NULL, "Failed to get Buffer memory", "Message", MB_OK);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 		}
//TempCode ARM 17Dec96 		else
//TempCode ARM 17Dec96 			MessageBox (NULL, "Failed to get file size", "Message", MB_OK);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 	}
//TempCode ARM 17Dec96 	else
//TempCode ARM 17Dec96 		MessageBox (NULL, "Failed to open file", "Message", MB_OK);
//TempCode ARM 17Dec96 
//TempCode ARM 17Dec96 	return 0;

	hInstance = hInstance;
	hPrevInstance = hPrevInstance;
	lpszCmdParam = lpszCmdParam;
	iCmdShow = iCmdShow;

	char* ProcName;

	ProcName = GetCommandLine ();

	if (*ProcName == '"')
		ProcName++;

	ChopPathName (ProcName);

	char ExeName [INSTALL_MAXCHARS];
	char DirName [INSTALL_MAXCHARS];

	STARTUPINFO StartUpInfo;
	PROCESS_INFORMATION ProcessInfo;

	// launch slave16.exe

	strcpy (ExeName, ProcName);
	strcat (ExeName, "\\");
	strcat (ExeName, "slave16.exe");

	strcpy (DirName, ProcName);

	StartUpInfo.cb = sizeof (STARTUPINFO);
	StartUpInfo.lpReserved = NULL;
	StartUpInfo.lpDesktop = NULL;
	StartUpInfo.lpTitle = NULL;
	StartUpInfo.dwX = 0;
	StartUpInfo.dwY = 0;
	StartUpInfo.dwXSize = 0;
	StartUpInfo.dwYSize = 0;
	StartUpInfo.dwXCountChars = 0;
	StartUpInfo.dwYCountChars = 0;
	StartUpInfo.dwFillAttribute = NULL;
	StartUpInfo.dwFlags = 0;
	StartUpInfo.wShowWindow = 0;
	StartUpInfo.cbReserved2 = 0;
	StartUpInfo.lpReserved2 = NULL;
	StartUpInfo.hStdInput = NULL;
	StartUpInfo.hStdOutput = NULL;
	StartUpInfo.hStdError = NULL;

	CreateProcess (
		ExeName,
		NULL,
		NULL,
		NULL,
		FALSE,
		CREATE_DEFAULT_ERROR_MODE | NORMAL_PRIORITY_CLASS,
		NULL,
		DirName,
		&StartUpInfo,
		&ProcessInfo);

	// launch wfly.exe

	strcpy (ExeName, ProcName);
	strcat (ExeName, "\\");
	strcat (ExeName, "wfly.exe");

	strcpy (DirName, ProcName);

	StartUpInfo.cb = sizeof (STARTUPINFO);
	StartUpInfo.lpReserved = NULL;
	StartUpInfo.lpDesktop = NULL;
	StartUpInfo.lpTitle = NULL;
	StartUpInfo.dwX = 0;
	StartUpInfo.dwY = 0;
	StartUpInfo.dwXSize = 0;
	StartUpInfo.dwYSize = 0;
	StartUpInfo.dwXCountChars = 0;
	StartUpInfo.dwYCountChars = 0;
	StartUpInfo.dwFillAttribute = NULL;
	StartUpInfo.dwFlags = 0;
	StartUpInfo.wShowWindow = 0;
	StartUpInfo.cbReserved2 = 0;
	StartUpInfo.lpReserved2 = NULL;
	StartUpInfo.hStdInput = NULL;
	StartUpInfo.hStdOutput = NULL;
	StartUpInfo.hStdError = NULL;

	CreateProcess (
		ExeName,
		NULL,
		NULL,
		NULL,
		FALSE,
		CREATE_DEFAULT_ERROR_MODE | NORMAL_PRIORITY_CLASS,
		NULL,
		DirName,
		&StartUpInfo,
		&ProcessInfo);

	return 0;

}