Exemple #1
15
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
#ifdef UNDER_CE
                     LPWSTR
#else
                     LPSTR
#endif
                     lpCmdLine, int nCmdShow)
#endif
{
    CFileInStream archiveStream;
    CLookToRead lookStream;
    CSzArEx db;
    SRes res = SZ_OK;
    ISzAlloc allocImp;
    ISzAlloc allocTempImp;
    WCHAR sfxPath[MAX_PATH + 2];
    WCHAR path[MAX_PATH * 3 + 2];
    size_t pathLen;
    DWORD winRes;
    const wchar_t *cmdLineParams;
    const char *errorMessage = NULL;
    Bool useShellExecute = True;

#ifdef _CONSOLE
    SetConsoleCtrlHandler(HandlerRoutine, TRUE);
#else
    hInstance = hInstance;
    hPrevInstance = hPrevInstance;
    lpCmdLine = lpCmdLine;
    nCmdShow = nCmdShow;
#endif

    CrcGenerateTable();

    allocImp.Alloc = SzAlloc;
    allocImp.Free = SzFree;

    allocTempImp.Alloc = SzAllocTemp;
    allocTempImp.Free = SzFreeTemp;

    FileInStream_CreateVTable(&archiveStream);
    LookToRead_CreateVTable(&lookStream, False);

    winRes = GetModuleFileNameW(NULL, sfxPath, MAX_PATH);
    if (winRes == 0 || winRes > MAX_PATH)
        return 1;
    {
        cmdLineParams = GetCommandLineW();
#ifndef UNDER_CE
        {
            Bool quoteMode = False;
            for (;; cmdLineParams++)
            {
                wchar_t c = *cmdLineParams;
                if (c == L'\"')
                    quoteMode = !quoteMode;
                else if (c == 0 || (c == L' ' && !quoteMode))
                    break;
            }
        }
#endif
    }

    {
        unsigned i;
        DWORD d;
        winRes = GetTempPathW(MAX_PATH, path);
        if (winRes == 0 || winRes > MAX_PATH)
            return 1;
        pathLen = wcslen(path);
        d = (GetTickCount() << 12) ^ (GetCurrentThreadId() << 14) ^ GetCurrentProcessId();
        for (i = 0;; i++, d += GetTickCount())
        {
            if (i >= 100)
            {
                res = SZ_ERROR_FAIL;
                break;
            }
            wcscpy(path + pathLen, L"7z");

            {
                wchar_t *s = path + wcslen(path);
                UInt32 value = d;
                unsigned k;
                for (k = 0; k < 8; k++)
                {
                    unsigned t = value & 0xF;
                    value >>= 4;
                    s[7 - k] = (char)((t < 10) ? ('0' + t) : ('A' + (t - 10)));
                }
                s[k] = '\0';
            }

            if (DoesFileOrDirExist(path))
                continue;
            if (CreateDirectoryW(path, NULL))
            {
                wcscat(path, L"\\");
                pathLen = wcslen(path);
                break;
            }
            if (GetLastError() != ERROR_ALREADY_EXISTS)
            {
                res = SZ_ERROR_FAIL;
                break;
            }
        }
        if (res != SZ_OK)
            errorMessage = "Can't create temp folder";
    }

    if (res != SZ_OK)
    {
        if (!errorMessage)
            errorMessage = "Error";
        PrintErrorMessage(errorMessage);
        return 1;
    }

    if (InFile_OpenW(&archiveStream.file, sfxPath) != 0)
    {
        errorMessage = "can not open input file";
        res = SZ_ERROR_FAIL;
    }
    else
    {
        UInt64 pos = 0;
        if (!FindSignature(&archiveStream.file, &pos))
            res = SZ_ERROR_FAIL;
        else if (File_Seek(&archiveStream.file, (Int64 *)&pos, SZ_SEEK_SET) != 0)
            res = SZ_ERROR_FAIL;
        if (res != 0)
            errorMessage = "Can't find 7z archive";
    }

    if (res == SZ_OK)
    {
        lookStream.realStream = &archiveStream.s;
        LookToRead_Init(&lookStream);
    }

    SzArEx_Init(&db);
    if (res == SZ_OK)
    {
        res = SzArEx_Open(&db, &lookStream.s, &allocImp, &allocTempImp);
    }
    if (res == SZ_OK)
    {
        UInt32 executeFileIndex = (UInt32)(Int32)-1;
        UInt32 minPrice = 1 << 30;
        UInt32 i;
        UInt32 blockIndex = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */
        Byte *outBuffer = 0; /* it must be 0 before first call for each new archive. */
        size_t outBufferSize = 0;  /* it can have any value before first call (if outBuffer = 0) */

        for (i = 0; i < db.db.NumFiles; i++)
        {
            size_t offset = 0;
            size_t outSizeProcessed = 0;
            const CSzFileItem *f = db.db.Files + i;
            size_t len;
            WCHAR *temp;
            len = SzArEx_GetFileNameUtf16(&db, i, NULL);

            if (len >= MAX_PATH)
            {
                res = SZ_ERROR_FAIL;
                break;
            }

            temp = path + pathLen;

            SzArEx_GetFileNameUtf16(&db, i, temp);
            {
                res = SzArEx_Extract(&db, &lookStream.s, i,
                                     &blockIndex, &outBuffer, &outBufferSize,
                                     &offset, &outSizeProcessed,
                                     &allocImp, &allocTempImp);
                if (res != SZ_OK)
                    break;
            }
            {
                CSzFile outFile;
                size_t processedSize;
                size_t j;
                size_t nameStartPos = 0;
                for (j = 0; temp[j] != 0; j++)
                {
                    if (temp[j] == '/')
                    {
                        temp[j] = 0;
                        MyCreateDir(path);
                        temp[j] = CHAR_PATH_SEPARATOR;
                        nameStartPos = j + 1;
                    }
                }

                if (f->IsDir)
                {
                    MyCreateDir(path);
                    continue;
                }
                else
                {
                    unsigned extLen;
                    const WCHAR *name = temp + nameStartPos;
                    unsigned len = (unsigned)wcslen(name);
                    unsigned nameLen = FindExt(temp + nameStartPos, &extLen);
                    unsigned extPrice = FindItem(kExts, sizeof(kExts) / sizeof(kExts[0]), name + len - extLen, extLen);
                    unsigned namePrice = FindItem(kNames, sizeof(kNames) / sizeof(kNames[0]), name, nameLen);

                    unsigned price = namePrice + extPrice * 64 + (nameStartPos == 0 ? 0 : (1 << 12));
                    if (minPrice > price)
                    {
                        minPrice = price;
                        executeFileIndex = i;
                        useShellExecute = (extPrice != k_EXE_ExtIndex);
                    }

                    if (DoesFileOrDirExist(path))
                    {
                        errorMessage = "Duplicate file";
                        res = SZ_ERROR_FAIL;
                        break;
                    }
                    if (OutFile_OpenW(&outFile, path))
                    {
                        errorMessage = "Can't open output file";
                        res = SZ_ERROR_FAIL;
                        break;
                    }
                }
                processedSize = outSizeProcessed;
                if (File_Write(&outFile, outBuffer + offset, &processedSize) != 0 || processedSize != outSizeProcessed)
                {
                    errorMessage = "Can't write output file";
                    res = SZ_ERROR_FAIL;
                }

#ifdef USE_WINDOWS_FILE
                if (f->MTimeDefined)
                {
                    FILETIME mTime;
                    mTime.dwLowDateTime = f->MTime.Low;
                    mTime.dwHighDateTime = f->MTime.High;
                    SetFileTime(outFile.handle, NULL, NULL, &mTime);
                }
#endif

                {
                    SRes res2 = File_Close(&outFile);
                    if (res != SZ_OK)
                        break;
                    if (res2 != SZ_OK)
                    {
                        res = res2;
                        break;
                    }
                }
#ifdef USE_WINDOWS_FILE
                if (f->AttribDefined)
                    SetFileAttributesW(path, f->Attrib);
#endif
            }
        }

        if (res == SZ_OK)
        {
            if (executeFileIndex == (UInt32)(Int32)-1)
            {
                errorMessage = "There is no file to execute";
                res = SZ_ERROR_FAIL;
            }
            else
            {
                WCHAR *temp = path + pathLen;
                UInt32 j;
                SzArEx_GetFileNameUtf16(&db, executeFileIndex, temp);
                for (j = 0; temp[j] != 0; j++)
                    if (temp[j] == '/')
                        temp[j] = CHAR_PATH_SEPARATOR;
            }
        }
        IAlloc_Free(&allocImp, outBuffer);
    }
    SzArEx_Free(&db, &allocImp);

    File_Close(&archiveStream.file);

    if (res == SZ_OK)
    {
        HANDLE hProcess = 0;
        if (useShellExecute)
        {
            SHELLEXECUTEINFO ei;
            UINT32 executeRes;
            BOOL success;

            memset(&ei, 0, sizeof(ei));
            ei.cbSize = sizeof(ei);
            ei.lpFile = path;
            ei.fMask = SEE_MASK_NOCLOSEPROCESS
#ifndef UNDER_CE
                       | SEE_MASK_FLAG_DDEWAIT
#endif
                       /* | SEE_MASK_NO_CONSOLE */
                       ;
            if (wcslen(cmdLineParams) != 0)
                ei.lpParameters = cmdLineParams;
            ei.nShow = SW_SHOWNORMAL; /* SW_HIDE; */
            success = ShellExecuteEx(&ei);
            executeRes = (UINT32)(UINT_PTR)ei.hInstApp;
            if (!success || (executeRes <= 32 && executeRes != 0))  /* executeRes = 0 in Windows CE */
                res = SZ_ERROR_FAIL;
            else
                hProcess = ei.hProcess;
        }
        else
        {
            STARTUPINFOW si;
            PROCESS_INFORMATION pi;
            WCHAR cmdLine[MAX_PATH * 3];

            wcscpy(cmdLine, path);
            wcscat(cmdLine, cmdLineParams);
            memset(&si, 0, sizeof(si));
            si.cb = sizeof(si);
            if (CreateProcessW(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi) == 0)
                res = SZ_ERROR_FAIL;
            else
            {
                CloseHandle(pi.hThread);
                hProcess = pi.hProcess;
            }
        }
        if (hProcess != 0)
        {
            WaitForSingleObject(hProcess, INFINITE);
            CloseHandle(hProcess);
        }
    }

    path[pathLen] = L'\0';
    RemoveDirWithSubItems(path);

    if (res == SZ_OK)
        return 0;

    {
        if (res == SZ_ERROR_UNSUPPORTED)
            errorMessage = "Decoder doesn't support this archive";
        else if (res == SZ_ERROR_MEM)
            errorMessage = "Can't allocate required memory";
        else if (res == SZ_ERROR_CRC)
            errorMessage = "CRC error";
        else
        {
            if (!errorMessage)
                errorMessage = "ERROR";
        }
        if (errorMessage)
            PrintErrorMessage(errorMessage);
    }
    return 1;
}
Exemple #2
1
/**
 * Entry point from operating system
 **/
int WINAPI
WinMain(HINSTANCE hInstance, HINSTANCE hLastInstance, LPSTR lpcli, int ncmd)
{
    char **argv = NULL;
    int argc = 0, argctemp = 0;
    size_t len;
    LPWSTR *argvw;
    char *messages;
    nserror ret;
    struct browser_window *bw;
    const char *addr = NETSURF_HOMEPAGE;

    if (SLEN(lpcli) > 0) {
        argvw = CommandLineToArgvW(GetCommandLineW(), &argc);
    }

    setbuf(stderr, NULL);

    /* Construct a unix style argc/argv */
    argv = malloc(sizeof(char *) * argc);
    while (argctemp < argc) {
        len = wcstombs(NULL, argvw[argctemp], 0) + 1;
        if (len > 0) {
            argv[argctemp] = malloc(len);
        }

        if (argv[argctemp] != NULL) {
            wcstombs(argv[argctemp], argvw[argctemp], len);
            /* alter windows-style forward slash flags to
             * hyphen flags.
             */
            if (argv[argctemp][0] == '/')
                argv[argctemp][0] = '-';
        }
        argctemp++;
    }

    respaths = nsws_init_resource("${APPDATA}\\NetSurf:${HOME}\\.netsurf:${NETSURFRES}:${PROGRAMFILES}\\NetSurf\\res:"NETSURF_WINDOWS_RESPATH);

    messages = filepath_find(respaths, "messages");

    options_file_location = filepath_find(respaths, "preferences");

    /* initialise netsurf */
    netsurf_init(&argc, &argv, options_file_location, messages);

    free(messages);

    ret = nsws_create_main_class(hInstance);
    ret = nsws_create_drawable_class(hInstance);
    ret = nsws_create_localhistory_class(hInstance);

    nsoption_set_bool(target_blank, false);

    nsws_window_init_pointers(hInstance);

    /* ensure homepage option has a default */
    nsoption_setnull_charp(homepage_url, strdup(NETSURF_HOMEPAGE));

    /* If there is a url specified on the command line use it */
    if (argc > 1) {
        addr = argv[1];
    } else {
        addr = nsoption_charp(homepage_url);
    }

    LOG(("calling browser_window_create"));
    bw = browser_window_create(addr, 0, 0, true, false);

    netsurf_main_loop();

    netsurf_exit();

    free(options_file_location);

    return 0;
}
int main(int argc,char**argv)
{
	WCHAR res[4096];
	WCHAR res2[4096];
	WCHAR command[4096];
	WCHAR mshta[MAX_PATH];
	WCHAR curdir[MAX_PATH];
	WCHAR curdirBin[MAX_PATH];
	WCHAR s[MAX_PATH];

	_setmode(_fileno(stdout), _O_U16TEXT);

	int nargs;
	WCHAR **arglist = CommandLineToArgvW(GetCommandLineW(), &nargs);

	SetEnvironmentVariable(L"SEE_MASK_NOZONECHECKS",L"1");

	//Путь до mshta.exe
	GetWindowsDirectory(mshta, MAX_PATH);
	wsprintf(mshta,L"%s\\System32\\mshta.exe",mshta);
	wprintf(L"mshtaPath: %s\n", mshta);


	//Полный путь до нашего EXE
	GetModuleFileNameW(GetModuleHandleW(NULL), s, MAX_PATH);
	wprintf(L"GetModuleFileName=%s\n", s);

	//Обрезаем имя EXE, чтобы получить именно текущую директорию
	PathRemoveFileSpec(s);
	wcscpy(curdir,s);
	wprintf(L"curdir=%s\n", curdir);



	//Собираем все параметры полученные через командную строку
	wcscpy(command,L"");
	if (argc>1){
		int i;
		for(i=1; i<argc; ++i) {
			wcscat(command,L" ");
			wcscat(command,L"\"");
			wcscat(command,arglist[i]);
			wcscat(command,L"\"");
		}
	}
	_putws(command);



	//Устанавливаем текущую директорию
	wsprintf(curdirBin,L"%s"_CURR_DIR_,curdir);
	SetCurrentDirectory(curdirBin);
	wprintf(L"curdirBin: %s\n",curdirBin);

	//Собираем параметры, которые будем передавать в mshta.exe
	wsprintf(res,L"\"%s"_HTA_PATH_"\"%s",curdirBin,command);

	//Если запускаем не через SMB, а локально
	if(!(curdirBin[0]=='\\'&&curdirBin[1]=='\\'))
	{
		//Запускаем HTA-приложение
		run(mshta, res);
		return 0;
	}


	//Подключаем сетевой диск
	SetCurrentDirectory(curdir);
	_wsystem(L"NET USE \"Z:\" /DELETE /YES");
	wsprintf(res2,L"SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION & FOR /F \"tokens=2\" \%\%D IN ('NET USE * \"%s\" /PERSISTENT:NO^|FINDSTR /I 'unidad') DO SET DRIVELETTER=\%\%D",curdir);
	wprintf(L"NetUse: %s\n",res2);
	_wsystem(res2);


	//Запускаем HTA-приложение
	SetCurrentDirectory(L"Z:"_CURR_DIR_"\\");
	run(mshta, res);
	return 0;
}
Exemple #4
0
extern "C" __declspec(dllexport) int WINAPI dllLauncherEntryPoint(HINSTANCE, HINSTANCE, LPTSTR, int nCmdShow)
{
#ifdef _CRTDBG_MAP_ALLOC
    _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
#endif

     // TODO: Place code here.
    MSG msg = {0};
    HACCEL hAccelTable;

    INITCOMMONCONTROLSEX InitCtrlEx;

    InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
    InitCtrlEx.dwICC  = 0x00004000; //ICC_STANDARD_CLASSES;
    InitCommonControlsEx(&InitCtrlEx);

    _bstr_t requestedURL;
    int argc = 0;
    WCHAR** argv = CommandLineToArgvW(GetCommandLineW(), &argc);
    for (int i = 1; i < argc; ++i) {
        if (!wcsicmp(argv[i], L"--transparent"))
            s_usesLayeredWebView = true;
        else if (!wcsicmp(argv[i], L"--desktop"))
            s_fullDesktop = true;
        else if (!requestedURL)
            requestedURL = argv[i];
    }

    // Initialize global strings
    LoadString(hInst, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
    LoadString(hInst, IDC_WINLAUNCHER, szWindowClass, MAX_LOADSTRING);
    MyRegisterClass(hInst);

    if (shouldUseFullDesktop())
        computeFullDesktopFrame();

    // Init COM
    OleInitialize(NULL);

    if (usesLayeredWebView()) {
        hURLBarWnd = CreateWindow(L"EDIT", L"Type URL Here",
                    WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_AUTOVSCROLL, 
                    s_windowPosition.x, s_windowPosition.y + s_windowSize.cy, s_windowSize.cx, URLBAR_HEIGHT,
                    0,
                    0,
                    hInst, 0);
    } else {
        hMainWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
                       CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, 0, 0, hInst, 0);

        if (!hMainWnd)
            return FALSE;

        hBackButtonWnd = CreateWindow(L"BUTTON", L"<", WS_CHILD | WS_VISIBLE  | BS_TEXT, 0, 0, 0, 0, hMainWnd, 0, hInst, 0);
        hForwardButtonWnd = CreateWindow(L"BUTTON", L">", WS_CHILD | WS_VISIBLE  | BS_TEXT, CONTROLBUTTON_WIDTH, 0, 0, 0, hMainWnd, 0, hInst, 0);
        hURLBarWnd = CreateWindow(L"EDIT", 0, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_AUTOVSCROLL, CONTROLBUTTON_WIDTH * 2, 0, 0, 0, hMainWnd, 0, hInst, 0);

        ShowWindow(hMainWnd, nCmdShow);
        UpdateWindow(hMainWnd);
    }

    DefEditProc = reinterpret_cast<WNDPROC>(GetWindowLongPtr(hURLBarWnd, GWLP_WNDPROC));
    DefButtonProc = reinterpret_cast<WNDPROC>(GetWindowLongPtr(hBackButtonWnd, GWLP_WNDPROC));
    SetWindowLongPtr(hURLBarWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(EditProc));
    SetWindowLongPtr(hBackButtonWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(BackButtonProc));
    SetWindowLongPtr(hForwardButtonWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(ForwardButtonProc));

    SetFocus(hURLBarWnd);

    RECT clientRect = { s_windowPosition.x, s_windowPosition.y, s_windowPosition.x + s_windowSize.cx, s_windowPosition.y + s_windowSize.cy };

    IWebPreferencesPtr tmpPreferences;
    if (FAILED(WebKitCreateInstance(CLSID_WebPreferences, 0, IID_IWebPreferences, reinterpret_cast<void**>(&tmpPreferences.GetInterfacePtr()))))
        goto exit;

    if (FAILED(tmpPreferences->standardPreferences(&gStandardPreferences.GetInterfacePtr())))
        goto exit;

    if (!setToDefaultPreferences())
        goto exit;

    HRESULT hr = WebKitCreateInstance(CLSID_WebView, 0, IID_IWebView, reinterpret_cast<void**>(&gWebView.GetInterfacePtr()));
    if (FAILED(hr))
        goto exit;

    hr = gWebView->QueryInterface(IID_IWebViewPrivate, reinterpret_cast<void**>(&gWebViewPrivate.GetInterfacePtr()));
    if (FAILED(hr))
        goto exit;

    hr = WebKitCreateInstance(CLSID_WebHistory, 0, __uuidof(gWebHistory), reinterpret_cast<void**>(&gWebHistory.GetInterfacePtr()));
    if (FAILED(hr))
        goto exit;

    gWebHost = new WinLauncherWebHost();
    gWebHost->AddRef();
    hr = gWebView->setFrameLoadDelegate(gWebHost);
    if (FAILED(hr))
        goto exit;

    gPrintDelegate = new PrintWebUIDelegate;
    gPrintDelegate->AddRef();
    hr = gWebView->setUIDelegate(gPrintDelegate);
    if (FAILED (hr))
        goto exit;

    gAccessibilityDelegate = new AccessibilityDelegate;
    gAccessibilityDelegate->AddRef();
    hr = gWebView->setAccessibilityDelegate(gAccessibilityDelegate);
    if (FAILED (hr))
        goto exit;

    hr = gWebView->setHostWindow(reinterpret_cast<OLE_HANDLE>(hMainWnd));
    if (FAILED(hr))
        goto exit;

    hr = gWebView->initWithFrame(clientRect, 0, 0);
    if (FAILED(hr))
        goto exit;

    if (!requestedURL) {
        IWebFramePtr frame;
        hr = gWebView->mainFrame(&frame.GetInterfacePtr());
        if (FAILED(hr))
            goto exit;

        _bstr_t defaultHTML(L"<p style=\"background-color: #00FF00\">Testing</p><img id=\"webkit logo\" src=\"http://webkit.org/images/icon-gold.png\" alt=\"Face\"><div style=\"border: solid blue; background: white;\" contenteditable=\"true\">div with blue border</div><ul><li>foo<li>bar<li>baz</ul>");
        frame->loadHTMLString(defaultHTML.GetBSTR(), 0);
    }

    hr = gWebViewPrivate->setTransparent(usesLayeredWebView());
    if (FAILED(hr))
        goto exit;

    hr = gWebViewPrivate->setUsesLayeredWindow(usesLayeredWebView());
    if (FAILED(hr))
        goto exit;

    hr = gWebViewPrivate->viewWindow(reinterpret_cast<OLE_HANDLE*>(&gViewWindow));
    if (FAILED(hr) || !gViewWindow)
        goto exit;

    if (usesLayeredWebView())
        subclassForLayeredWindow();

    resizeSubViews();

    ShowWindow(gViewWindow, nCmdShow);
    UpdateWindow(gViewWindow);

    hAccelTable = LoadAccelerators(hInst, MAKEINTRESOURCE(IDC_WINLAUNCHER));

    if (requestedURL.length())
        loadURL(requestedURL.GetBSTR());

    // Main message loop:
#if USE(CF)
    _CFRunLoopSetWindowsMessageQueueMask(CFRunLoopGetMain(), QS_ALLINPUT | QS_ALLPOSTMESSAGE, kCFRunLoopDefaultMode);
    CFRunLoopRun();
#else
    while (GetMessage(&msg, NULL, 0, 0)) {
        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
#endif

exit:
    gPrintDelegate->Release();

    shutDownWebKit();
#ifdef _CRTDBG_MAP_ALLOC
    _CrtDumpMemoryLeaks();
#endif

    // Shut down COM.
    OleUninitialize();
    
    return static_cast<int>(msg.wParam);
}
Exemple #5
0
/**
 * Creates the default logger instance for a VBox process.
 *
 * @returns Pointer to the logger instance.
 */
RTDECL(PRTLOGGER) RTLogDefaultInit(void)
{
    /*
     * Initialize the default logger instance.
     * Take care to do this once and not recursively.
     */
    static volatile uint32_t fInitializing = 0;
    PRTLOGGER pLogger;
    int rc;

    if (g_pLogger || !ASMAtomicCmpXchgU32(&fInitializing, 1, 0))
        return g_pLogger;

#ifdef IN_RING3
    /*
     * Assert the group definitions.
     */
#define ASSERT_LOG_GROUP(grp)  ASSERT_LOG_GROUP2(LOG_GROUP_##grp, #grp)
#define ASSERT_LOG_GROUP2(def, str) \
    do { if (strcmp(g_apszGroups[def], str)) {printf("%s='%s' expects '%s'\n", #def, g_apszGroups[def], str); RTAssertDoPanic(); } } while (0)
    ASSERT_LOG_GROUP(DEFAULT);
    ASSERT_LOG_GROUP(CFGM);
    ASSERT_LOG_GROUP(CPUM);
    ASSERT_LOG_GROUP(CSAM);
    ASSERT_LOG_GROUP(DBGC);
    ASSERT_LOG_GROUP(DBGF);
    ASSERT_LOG_GROUP(DBGF_INFO);
    ASSERT_LOG_GROUP(DEV);
    ASSERT_LOG_GROUP(DEV_ACPI);
    ASSERT_LOG_GROUP(DEV_APIC);
    ASSERT_LOG_GROUP(DEV_AUDIO);
    ASSERT_LOG_GROUP(DEV_FDC);
    ASSERT_LOG_GROUP(DEV_HPET);
    ASSERT_LOG_GROUP(DEV_IDE);
    ASSERT_LOG_GROUP(DEV_KBD);
    ASSERT_LOG_GROUP(DEV_LPC);
    ASSERT_LOG_GROUP(DEV_NE2000);
    ASSERT_LOG_GROUP(DEV_PC);
    ASSERT_LOG_GROUP(DEV_PC_ARCH);
    ASSERT_LOG_GROUP(DEV_PC_BIOS);
    ASSERT_LOG_GROUP(DEV_PCI);
    ASSERT_LOG_GROUP(DEV_PCNET);
    ASSERT_LOG_GROUP(DEV_PIC);
    ASSERT_LOG_GROUP(DEV_PIT);
    ASSERT_LOG_GROUP(DEV_RTC);
    ASSERT_LOG_GROUP(DEV_SERIAL);
    ASSERT_LOG_GROUP(DEV_SMC);
    ASSERT_LOG_GROUP(DEV_USB);
    ASSERT_LOG_GROUP(DEV_VGA);
    ASSERT_LOG_GROUP(DEV_VMM);
    ASSERT_LOG_GROUP(DEV_VMM_STDERR);
    ASSERT_LOG_GROUP(DIS);
    ASSERT_LOG_GROUP(DRV);
    ASSERT_LOG_GROUP(DRV_ACPI);
    ASSERT_LOG_GROUP(DRV_BLOCK);
    ASSERT_LOG_GROUP(DRV_FLOPPY);
    ASSERT_LOG_GROUP(DRV_HOST_DVD);
    ASSERT_LOG_GROUP(DRV_HOST_FLOPPY);
    ASSERT_LOG_GROUP(DRV_ISO);
    ASSERT_LOG_GROUP(DRV_KBD_QUEUE);
    ASSERT_LOG_GROUP(DRV_MOUSE_QUEUE);
    ASSERT_LOG_GROUP(DRV_NAT);
    ASSERT_LOG_GROUP(DRV_RAW_IMAGE);
    ASSERT_LOG_GROUP(DRV_TUN);
    ASSERT_LOG_GROUP(DRV_USBPROXY);
    ASSERT_LOG_GROUP(DRV_VBOXHDD);
    ASSERT_LOG_GROUP(DRV_VSWITCH);
    ASSERT_LOG_GROUP(DRV_VUSB);
    ASSERT_LOG_GROUP(EM);
    ASSERT_LOG_GROUP(GUI);
    ASSERT_LOG_GROUP(HGCM);
    ASSERT_LOG_GROUP(HM);
    ASSERT_LOG_GROUP(IOM);
    ASSERT_LOG_GROUP(MAIN);
    ASSERT_LOG_GROUP(MM);
    ASSERT_LOG_GROUP(MM_HEAP);
    ASSERT_LOG_GROUP(MM_HYPER);
    ASSERT_LOG_GROUP(MM_HYPER_HEAP);
    ASSERT_LOG_GROUP(MM_PHYS);
    ASSERT_LOG_GROUP(MM_POOL);
    ASSERT_LOG_GROUP(NAT_SERVICE);
    ASSERT_LOG_GROUP(NET_SERVICE);
    ASSERT_LOG_GROUP(PATM);
    ASSERT_LOG_GROUP(PDM);
    ASSERT_LOG_GROUP(PDM_DEVICE);
    ASSERT_LOG_GROUP(PDM_DRIVER);
    ASSERT_LOG_GROUP(PDM_LDR);
    ASSERT_LOG_GROUP(PDM_QUEUE);
    ASSERT_LOG_GROUP(PGM);
    ASSERT_LOG_GROUP(PGM_POOL);
    ASSERT_LOG_GROUP(REM);
    ASSERT_LOG_GROUP(REM_DISAS);
    ASSERT_LOG_GROUP(REM_HANDLER);
    ASSERT_LOG_GROUP(REM_IOPORT);
    ASSERT_LOG_GROUP(REM_MMIO);
    ASSERT_LOG_GROUP(REM_PRINTF);
    ASSERT_LOG_GROUP(REM_RUN);
    ASSERT_LOG_GROUP(SELM);
    ASSERT_LOG_GROUP(SSM);
    ASSERT_LOG_GROUP(STAM);
    ASSERT_LOG_GROUP(SUP);
    ASSERT_LOG_GROUP(TM);
    ASSERT_LOG_GROUP(TRPM);
    ASSERT_LOG_GROUP(VM);
    ASSERT_LOG_GROUP(VMM);
    ASSERT_LOG_GROUP(VRDP);
#undef ASSERT_LOG_GROUP
#undef ASSERT_LOG_GROUP2
#endif /* IN_RING3 */

    /*
     * Create the default logging instance.
     */
#ifdef IN_RING3
# ifndef IN_GUEST
    char szExecName[RTPATH_MAX];
    if (!RTProcGetExecutablePath(szExecName, sizeof(szExecName)))
        strcpy(szExecName, "VBox");
    RTTIMESPEC TimeSpec;
    RTTIME Time;
    RTTimeExplode(&Time, RTTimeNow(&TimeSpec));
    rc = RTLogCreate(&pLogger, 0, NULL, "VBOX_LOG", RT_ELEMENTS(g_apszGroups), &g_apszGroups[0], RTLOGDEST_FILE,
                     "./%04d-%02d-%02d-%02d-%02d-%02d.%03d-%s-%d.log",
                     Time.i32Year, Time.u8Month, Time.u8MonthDay, Time.u8Hour, Time.u8Minute, Time.u8Second, Time.u32Nanosecond / 10000000,
                     RTPathFilename(szExecName), RTProcSelf());
    if (RT_SUCCESS(rc))
    {
        /*
         * Write a log header.
         */
        char szBuf[RTPATH_MAX];
        RTTimeSpecToString(&TimeSpec, szBuf, sizeof(szBuf));
        RTLogLoggerEx(pLogger, 0, ~0U, "Log created: %s\n", szBuf);
        RTLogLoggerEx(pLogger, 0, ~0U, "Executable: %s\n", szExecName);

        /* executable and arguments - tricky and all platform specific. */
#  if defined(RT_OS_WINDOWS)
        RTLogLoggerEx(pLogger, 0, ~0U, "Commandline: %ls\n", GetCommandLineW());

#  elif defined(RT_OS_SOLARIS)
        psinfo_t psi;
        char szArgFileBuf[80];
        RTStrPrintf(szArgFileBuf, sizeof(szArgFileBuf), "/proc/%ld/psinfo", (long)getpid());
        FILE* pFile = fopen(szArgFileBuf, "rb");
        if (pFile)
        {
            if (fread(&psi, sizeof(psi), 1, pFile) == 1)
            {
#   if 0     /* 100% safe:*/
                RTLogLoggerEx(pLogger, 0, ~0U, "Args: %s\n", psi.pr_psargs);
#   else     /* probably safe: */
                const char * const *argv = (const char * const *)psi.pr_argv;
                for (int iArg = 0; iArg < psi.pr_argc; iArg++)
                    RTLogLoggerEx(pLogger, 0, ~0U, "Arg[%d]: %s\n", iArg, argv[iArg]);
#   endif

            }
            fclose(pFile);
        }

#  elif defined(RT_OS_LINUX)
        FILE *pFile = fopen("/proc/self/cmdline", "r");
        if (pFile)
        {
            /* braindead */
            unsigned iArg = 0;
            int ch;
            bool fNew = true;
            while (!feof(pFile) && (ch = fgetc(pFile)) != EOF)
            {
                if (fNew)
                {
                    RTLogLoggerEx(pLogger, 0, ~0U, "Arg[%u]: ", iArg++);
                    fNew = false;
                }
                if (ch)
                    RTLogLoggerEx(pLogger, 0, ~0U, "%c", ch);
                else
                {
                    RTLogLoggerEx(pLogger, 0, ~0U, "\n");
                    fNew = true;
                }
            }
            if (!fNew)
                RTLogLoggerEx(pLogger, 0, ~0U, "\n");
            fclose(pFile);
        }

#  elif defined(RT_OS_HAIKU)
        team_info info;
        if (get_team_info(0, &info) == B_OK)
        {
            /* there is an info.argc, but no way to know arg boundaries */
            RTLogLoggerEx(pLogger, 0, ~0U, "Commandline: %.64s\n", info.args);
        }

#  elif defined(RT_OS_FREEBSD)
        /* Retrieve the required length first */
        int aiName[4];
        aiName[0] = CTL_KERN;
        aiName[1] = KERN_PROC;
        aiName[2] = KERN_PROC_ARGS;     /* Introduced in FreeBSD 4.0 */
        aiName[3] = getpid();
        size_t cchArgs = 0;
        int rcBSD = sysctl(aiName, RT_ELEMENTS(aiName), NULL, &cchArgs, NULL, 0);
        if (cchArgs > 0)
        {
            char *pszArgFileBuf = (char *)RTMemAllocZ(cchArgs + 1 /* Safety */);
            if (pszArgFileBuf)
            {
                /* Retrieve the argument list */
                rcBSD = sysctl(aiName, RT_ELEMENTS(aiName), pszArgFileBuf, &cchArgs, NULL, 0);
                if (!rcBSD)
                {
                    unsigned    iArg = 0;
                    size_t      off = 0;
                    while (off < cchArgs)
                    {
                        size_t cchArg = strlen(&pszArgFileBuf[off]);
                        RTLogLoggerEx(pLogger, 0, ~0U, "Arg[%u]: %s\n", iArg, &pszArgFileBuf[off]);

                        /* advance */
                        off += cchArg + 1;
                        iArg++;
                    }
                }
                RTMemFree(pszArgFileBuf);
            }
        }

#  elif defined(RT_OS_OS2) || defined(RT_OS_DARWIN)
        /* commandline? */
#  else
#   error needs porting.
#  endif
    }

# else  /* IN_GUEST */
    /* The user destination is backdoor logging. */
    rc = RTLogCreate(&pLogger, 0, NULL, "VBOX_LOG", RT_ELEMENTS(g_apszGroups), &g_apszGroups[0], RTLOGDEST_USER, "VBox.log");
# endif /* IN_GUEST */

#else /* IN_RING0 */
# ifndef IN_GUEST
    rc = RTLogCreate(&pLogger, 0, NULL, "VBOX_LOG", RT_ELEMENTS(g_apszGroups), &g_apszGroups[0], RTLOGDEST_FILE, "VBox-ring0.log");
# else  /* IN_GUEST */
    rc = RTLogCreate(&pLogger, 0, NULL, "VBOX_LOG", RT_ELEMENTS(g_apszGroups), &g_apszGroups[0], RTLOGDEST_USER, "VBox-ring0.log");
# endif /* IN_GUEST */
    if (RT_SUCCESS(rc))
    {
        /*
         * This is where you set your ring-0 logging preferences.
         *
         * On platforms which don't differ between debugger and kernel
         * log printing, STDOUT is gonna be a stub and the DEBUGGER
         * destination is the one doing all the work. On platforms
         * that do differ (like Darwin), STDOUT is the kernel log.
         */
# if defined(DEBUG_bird)
        /*RTLogGroupSettings(pLogger, "all=~0 -default.l6.l5.l4.l3");*/
        RTLogFlags(pLogger, "enabled unbuffered pid tid");
#  ifndef IN_GUEST
        pLogger->fDestFlags |= RTLOGDEST_DEBUGGER | RTLOGDEST_STDOUT;
#  endif
# endif
# if defined(DEBUG_sandervl) && !defined(IN_GUEST)
        RTLogGroupSettings(pLogger, "+all");
        RTLogFlags(pLogger, "enabled unbuffered");
        pLogger->fDestFlags |= RTLOGDEST_DEBUGGER;
# endif
# if defined(DEBUG_ramshankar)  /* Guest ring-0 as well */
        RTLogGroupSettings(pLogger, "+all.e.l.f");
        RTLogFlags(pLogger, "enabled unbuffered");
        pLogger->fDestFlags |= RTLOGDEST_DEBUGGER;
# endif
# if defined(DEBUG_aleksey)  /* Guest ring-0 as well */
        RTLogGroupSettings(pLogger, "+net_adp_drv.e.l.f+net_flt_drv.e.l.l2.l3.l4.l5.f");
        RTLogFlags(pLogger, "enabled unbuffered");
        pLogger->fDestFlags |= RTLOGDEST_DEBUGGER | RTLOGDEST_STDOUT;
# endif
# if defined(DEBUG_andy)  /* Guest ring-0 as well */
        RTLogGroupSettings(pLogger, "+all.e.l.f");
        RTLogFlags(pLogger, "enabled unbuffered pid tid");
        pLogger->fDestFlags |= RTLOGDEST_DEBUGGER | RTLOGDEST_STDOUT;
# endif
# if defined(DEBUG_misha) /* Guest ring-0 as well */
        RTLogFlags(pLogger, "enabled unbuffered");
        pLogger->fDestFlags |= RTLOGDEST_DEBUGGER;
# endif
# if defined(DEBUG_leo) /* Guest ring-0 as well */
        RTLogGroupSettings(pLogger, "+drv_mouse.e.l.f+drv_miniport.e.l.f+drv_display.e.l.f");
        RTLogFlags(pLogger, "enabled unbuffered");
        pLogger->fDestFlags |= RTLOGDEST_DEBUGGER;
# endif
# if 0 /* vboxdrv logging - ATTENTION: this is what we're referring to guys! Change to '# if 1'. */
        RTLogGroupSettings(pLogger, "all=~0 -default.l6.l5.l4.l3");
        RTLogFlags(pLogger, "enabled unbuffered tid");
        pLogger->fDestFlags |= RTLOGDEST_DEBUGGER | RTLOGDEST_STDOUT;
# endif
    }
#endif /* IN_RING0 */
    return g_pLogger = RT_SUCCESS(rc) ? pLogger : NULL;
}
Exemple #6
-1
int main( int argc, char *argv[] )
{
    extern HANDLE CDECL __wine_make_process_system(void);
    static const WCHAR RunW[] = {'R','u','n',0};
    static const WCHAR RunOnceW[] = {'R','u','n','O','n','c','e',0};
    static const WCHAR RunServicesW[] = {'R','u','n','S','e','r','v','i','c','e','s',0};
    static const WCHAR RunServicesOnceW[] = {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0};
    static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};

    /* First, set the current directory to SystemRoot */
    int optc;
    BOOL end_session, force, init, kill, restart, shutdown, update;
    HANDLE event;
    SECURITY_ATTRIBUTES sa;
    BOOL is_wow64;

    end_session = force = init = kill = restart = shutdown = update = FALSE;
    GetWindowsDirectoryW( windowsdir, MAX_PATH );
    if( !SetCurrentDirectoryW( windowsdir ) )
        WINE_ERR("Cannot set the dir to %s (%d)\n", wine_dbgstr_w(windowsdir), GetLastError() );

    if (IsWow64Process( GetCurrentProcess(), &is_wow64 ) && is_wow64)
    {
        STARTUPINFOW si;
        PROCESS_INFORMATION pi;
        WCHAR filename[MAX_PATH];
        void *redir;
        DWORD exit_code;

        memset( &si, 0, sizeof(si) );
        si.cb = sizeof(si);
        GetModuleFileNameW( 0, filename, MAX_PATH );

        Wow64DisableWow64FsRedirection( &redir );
        if (CreateProcessW( filename, GetCommandLineW(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
        {
            WINE_TRACE( "restarting %s\n", wine_dbgstr_w(filename) );
            WaitForSingleObject( pi.hProcess, INFINITE );
            GetExitCodeProcess( pi.hProcess, &exit_code );
            ExitProcess( exit_code );
        }
        else WINE_ERR( "failed to restart 64-bit %s, err %d\n", wine_dbgstr_w(filename), GetLastError() );
        Wow64RevertWow64FsRedirection( redir );
    }

    while ((optc = getopt_long(argc, argv, short_options, long_options, NULL )) != -1)
    {
        switch(optc)
        {
        case 'e': end_session = TRUE; break;
        case 'f': force = TRUE; break;
        case 'i': init = TRUE; break;
        case 'k': kill = TRUE; break;
        case 'r': restart = TRUE; break;
        case 's': shutdown = TRUE; break;
        case 'u': update = TRUE; break;
        case 'h': usage(); return 0;
        case '?': usage(); return 1;
        }
    }

    if (end_session)
    {
        if (kill)
        {
            if (!shutdown_all_desktops( force )) return 1;
        }
        else if (!shutdown_close_windows( force )) return 1;
    }

    if (kill) kill_processes( shutdown );

    if (shutdown) return 0;

    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;  /* so that services.exe inherits it */
    event = CreateEventW( &sa, TRUE, FALSE, wineboot_eventW );

    ResetEvent( event );  /* in case this is a restart */

    create_hardware_registry_keys();
    create_dynamic_registry_keys();
    create_environment_registry_keys();
    wininit();
    pendingRename();

    ProcessWindowsFileProtection();
    ProcessRunKeys( HKEY_LOCAL_MACHINE, RunServicesOnceW, TRUE, FALSE );

    if (init || (kill && !restart))
    {
        ProcessRunKeys( HKEY_LOCAL_MACHINE, RunServicesW, FALSE, FALSE );
        start_services_process();
    }
    if (init || update) update_wineprefix( update );

    create_volatile_environment_registry_key();

    ProcessRunKeys( HKEY_LOCAL_MACHINE, RunOnceW, TRUE, TRUE );

    if (!init && !restart)
    {
        ProcessRunKeys( HKEY_LOCAL_MACHINE, RunW, FALSE, FALSE );
        ProcessRunKeys( HKEY_CURRENT_USER, RunW, FALSE, FALSE );
        ProcessStartupItems();
    }

    WINE_TRACE("Operation done\n");

    SetEvent( event );
    return 0;
}