Example #1
0
/*@C
   PetscDLOpen - opens dynamic library

   Not Collective

   Input Parameters:
+    name - name of library
-    flags - options on how to open library

   Output Parameter:
.    handle

   Level: developer

@*/
PetscErrorCode  PetscDLOpen(const char name[],int flags,PetscDLHandle *handle)
{
  PETSC_UNUSED int dlflags1,dlflags2; /* There are some preprocessor paths where these variables are set, but not used */
  dlhandle_t dlhandle;

  PetscFunctionBegin;
  PetscValidCharPointer(name,1);
  PetscValidPointer(handle,3);

  dlflags1 = 0;
  dlflags2 = 0;
  dlhandle = (dlhandle_t) 0;
  *handle  = (PetscDLHandle) 0;

  /* 
     --- LoadLibrary ---
  */  
#if defined(PETSC_HAVE_WINDOWS_H) && defined(PETSC_HAVE_LOADLIBRARY)
  dlhandle = LoadLibrary(name);
  if (!dlhandle) {
#if defined(PETSC_HAVE_GETLASTERROR)
    PetscErrorCode ierr;
    DWORD erc;
    char  *buff = NULL;
    erc = GetLastError();
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
		  NULL,erc,MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),(LPSTR)&buff,0,NULL);
    ierr = PetscError(PETSC_COMM_SELF,__LINE__,__FUNCT__,__FILE__,__SDIR__,PETSC_ERR_FILE_OPEN,PETSC_ERROR_REPEAT,
		      "Unable to open dynamic library:\n  %s\n  Error message from LoadLibrary() %s\n",name,buff);
    LocalFree(buff);
    PetscFunctionReturn(ierr);
#else
    SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Unable to open dynamic library:\n  %s\n  Error message from LoadLibrary() %s\n",name,"unavailable");
#endif
  }

  /* 
     --- dlopen ---
  */  
#elif defined(PETSC_HAVE_DLFCN_H) && defined(PETSC_HAVE_DLOPEN)
  /*
      Mode indicates symbols required by symbol loaded with dlsym() 
     are only loaded when required (not all together) also indicates
     symbols required can be contained in other libraries also opened
     with dlopen()
  */
#if defined(PETSC_HAVE_RTLD_LAZY)
  dlflags1 = RTLD_LAZY;
#endif
#if defined(PETSC_HAVE_RTLD_NOW)
  if (flags & PETSC_DL_NOW)
    dlflags1 = RTLD_NOW;
#endif
#if defined(PETSC_HAVE_RTLD_GLOBAL)
  dlflags2 = RTLD_GLOBAL;
#endif
#if defined(PETSC_HAVE_RTLD_LOCAL)
  if (flags & PETSC_DL_LOCAL)
    dlflags2 = RTLD_LOCAL;
#endif
#if defined(PETSC_HAVE_DLERROR)
  dlerror(); /* clear any previous error */
#endif
  dlhandle = dlopen(name,dlflags1|dlflags2);
  if (!dlhandle) {
#if defined(PETSC_HAVE_DLERROR)
    const char *errmsg = dlerror();
#else
    const char *errmsg = "unavailable";
#endif
    SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Unable to open dynamic library:\n  %s\n  Error message from dlopen() %s\n",name,errmsg);
  }

  /* 
     --- unimplemented ---
  */  
#else
  SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP_SYS, "Cannot use dynamic libraries on this platform");
#endif

  *handle = (PetscDLHandle) dlhandle;

  PetscFunctionReturn(0);
}
bool CDropTargetController::PutValue(TCHAR *szFileName)
{
	IMeter *iMeter = 0;
	get_meter(&iMeter);
	if (iMeter)
	{
		DISPID id;
		HRESULT hr;
		LPOLESTR name;
#ifdef notdef
		name = L"PutValue";   
		hr = iMeter->GetIDsOfNames(IID_NULL, 
                               &name, 
                               1, 
                               LOCALE_USER_DEFAULT, 
                               &id);

		if (SUCCEEDED(hr))
		{
			AtlTrace("DropTargetController: Found PutValue method\n");
			CComVariant varResult;
			CComVariant* pvars = new CComVariant[2];

			VariantClear(&varResult);
			pvars[0] = (BSTR)value;
			pvars[1] = (BSTR)selector;
			DISPPARAMS disp = { pvars, NULL, 2, 0 };
			hr = iMeter->Invoke(id, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL);
			delete[] pvars;

			if (SUCCEEDED(hr))
			{
				AtlTrace("DropTargetController: Set Value via PutValue\n");
				return true;
			}
		}
#endif
		name = L"Value";   
		hr = iMeter->GetIDsOfNames(IID_NULL, 
                               &name, 
                               1, 
                               MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT), 
                               &id);

		if (SUCCEEDED(hr))
		{
			AtlTrace("ValueSetter: Found Value Property\n");
			CComVariant varResult;
			CComVariant* pvars = new CComVariant[1];

			VariantClear(&varResult);
			DISPID dispidNamed = DISPID_PROPERTYPUT;
			DISPPARAMS disp = { pvars, &dispidNamed, 1, 1 };
			_bstr_t value(szFileName);
			pvars[0] = (BSTR)value;
			hr = iMeter->Invoke(id, 
									IID_NULL, 
									MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT), 
									DISPATCH_PROPERTYPUT, 
									&disp, 
									&varResult, 
									NULL, 
									NULL);
			delete[] pvars;

			if (SUCCEEDED(hr))
			{
				AtlTrace("CDropTargetController: Set Value Property\n");
				return true;
			}
		}
	}

	return false;
}
Example #3
0
//--------------------------------------------------------------------------------------
_Use_decl_annotations_
void CDXUTIMEEditBox::RenderCandidateReadingWindow( bool bReading )
{
    RECT rc;
    UINT nNumEntries = bReading ? 4 : MAX_CANDLIST;
    int nX, nXFirst, nXComp;
    m_Buffer.CPtoX( m_nCaret, FALSE, &nX );
    m_Buffer.CPtoX( m_nFirstVisible, FALSE, &nXFirst );

    DWORD TextColor, TextBkColor, SelTextColor, SelBkColor;
    if( bReading )
    {
        TextColor = m_ReadingColor;
        TextBkColor = m_ReadingWinColor;
        SelTextColor = m_ReadingSelColor;
        SelBkColor = m_ReadingSelBkColor;
    }
    else
    {
        TextColor = m_CandidateColor;
        TextBkColor = m_CandidateWinColor;
        SelTextColor = m_CandidateSelColor;
        SelBkColor = m_CandidateSelBkColor;
    }

    // For Japanese IME, align the window with the first target converted character.
    // For all other IMEs, align with the caret.  This is because the caret
    // does not move for Japanese IME.
    if( GetLanguage() == MAKELANGID( LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL ) && !GetImeId() )
        nXComp = 0;
    else if( GetPrimaryLanguage() == LANG_JAPANESE )
        s_CompString.CPtoX( s_nFirstTargetConv, FALSE, &nXComp );
    else
        s_CompString.CPtoX( ImeUi_GetImeCursorChars(), FALSE, &nXComp );

    // Compute the size of the candidate window
    int nWidthRequired = 0;
    int nHeightRequired = 0;
    int nSingleLineHeight = 0;

    if( ( ImeUi_IsVerticalCand() && !bReading ) ||
        ( !ImeUi_IsHorizontalReading() && bReading ) )
    {
        // Vertical window
        for( UINT i = 0; i < nNumEntries; ++i )
        {
            if( *( ImeUi_GetCandidate( i ) ) == L'\0' )
                break;
            SetRect( &rc, 0, 0, 0, 0 );
            m_pDialog->CalcTextRect( ImeUi_GetCandidate( i ), m_Elements[ 1 ], &rc );
            nWidthRequired = std::max<int>( nWidthRequired, rc.right - rc.left );
            nSingleLineHeight = std::max<int>( nSingleLineHeight, rc.bottom - rc.top );
        }
        nHeightRequired = nSingleLineHeight * nNumEntries;
    }
    else
    {
        // Horizontal window
        SetRect( &rc, 0, 0, 0, 0 );
        if( bReading )
            m_pDialog->CalcTextRect( s_wszReadingString, m_Elements[ 1 ], &rc );
        else
        {

            WCHAR wszCand[256] = L"";

            s_CandList.nFirstSelected = 0;
            s_CandList.nHoriSelectedLen = 0;
            for( UINT i = 0; i < MAX_CANDLIST; ++i )
            {
                if( *ImeUi_GetCandidate( i ) == L'\0' )
                    break;

                WCHAR wszEntry[32];
                swprintf_s( wszEntry, 32, L"%s ", ImeUi_GetCandidate( i ) );
                // If this is the selected entry, mark its char position.
                if( ImeUi_GetCandidateSelection() == i )
                {
                    s_CandList.nFirstSelected = (int)wcslen( wszCand );
                    s_CandList.nHoriSelectedLen = (int)wcslen( wszEntry ) - 1;  // Minus space
                }
                wcscat_s( wszCand, 256, wszEntry );
            }
            wszCand[wcslen( wszCand ) - 1] = L'\0';  // Remove the last space
            s_CandList.HoriCand.SetText( wszCand );
			
            m_pDialog->CalcTextRect( s_CandList.HoriCand.GetBuffer(), m_Elements[ 1 ], &rc );
        }
        nWidthRequired = rc.right - rc.left;
        nSingleLineHeight = nHeightRequired = rc.bottom - rc.top;
    }

    // Now that we have the dimension, calculate the location for the candidate window.
    // We attempt to fit the window in this order:
    // bottom, top, right, left.

    bool bHasPosition = false;

    // Bottom
    SetRect( &rc, s_ptCompString.x + nXComp, s_ptCompString.y + m_rcText.bottom - m_rcText.top,
             s_ptCompString.x + nXComp + nWidthRequired, s_ptCompString.y + m_rcText.bottom - m_rcText.top +
             nHeightRequired );
    // if the right edge is cut off, move it left.
    if( rc.right > m_pDialog->GetWidth() )
    {
        rc.left -= rc.right - m_pDialog->GetWidth();
        rc.right = m_pDialog->GetWidth();
    }
    if( rc.bottom <= m_pDialog->GetHeight() )
        bHasPosition = true;

    // Top
    if( !bHasPosition )
    {
        SetRect( &rc, s_ptCompString.x + nXComp, s_ptCompString.y - nHeightRequired,
                 s_ptCompString.x + nXComp + nWidthRequired, s_ptCompString.y );
        // if the right edge is cut off, move it left.
        if( rc.right > m_pDialog->GetWidth() )
        {
            rc.left -= rc.right - m_pDialog->GetWidth();
            rc.right = m_pDialog->GetWidth();
        }
        if( rc.top >= 0 )
            bHasPosition = true;
    }

    // Right
    if( !bHasPosition )
    {
        int nXCompTrail;
        s_CompString.CPtoX( ImeUi_GetImeCursorChars(), TRUE, &nXCompTrail );
        SetRect( &rc, s_ptCompString.x + nXCompTrail, 0,
                 s_ptCompString.x + nXCompTrail + nWidthRequired, nHeightRequired );
        if( rc.right <= m_pDialog->GetWidth() )
            bHasPosition = true;
    }

    // Left
    if( !bHasPosition )
    {
        SetRect( &rc, s_ptCompString.x + nXComp - nWidthRequired, 0,
                 s_ptCompString.x + nXComp, nHeightRequired );
        if( rc.right >= 0 )
            bHasPosition = true;
    }

    if( !bHasPosition )
    {
        // The dialog is too small for the candidate window.
        // Fall back to render at 0, 0.  Some part of the window
        // will be cut off.
        rc.left = 0;
        rc.right = nWidthRequired;
    }

    // If we are rendering the candidate window, save the position
    // so that mouse clicks are checked properly.
    if( !bReading )
        s_CandList.rcCandidate = rc;

    // Render the elements
    m_pDialog->DrawRect( &rc, TextBkColor );
    if( ( ImeUi_IsVerticalCand() && !bReading ) ||
        ( !ImeUi_IsHorizontalReading() && bReading ) )
    {
        // Vertical candidate window
        for( UINT i = 0; i < nNumEntries; ++i )
        {
            // Here we are rendering one line at a time
            rc.bottom = rc.top + nSingleLineHeight;
            // Use a different color for the selected string
            if( ImeUi_GetCandidateSelection() == i )
            {
                m_pDialog->DrawRect( &rc, SelBkColor );
                m_Elements[ 1 ]->FontColor.SetCurrent( SelTextColor );
            }
            else
                m_Elements[ 1 ]->FontColor.SetCurrent( TextColor );

            m_pDialog->DrawText( ImeUi_GetCandidate( i ), m_Elements[ 1 ], &rc );

            rc.top += nSingleLineHeight;
        }
    }
    else
    {
        // Horizontal candidate window
        m_Elements[ 1 ]->FontColor.SetCurrent( TextColor );
        if( bReading )
            m_pDialog->DrawText( s_wszReadingString, m_Elements[ 1 ], &rc );
        else
            m_pDialog->DrawText( s_CandList.HoriCand.GetBuffer(), m_Elements[ 1 ], &rc );

        // Render the selected entry differently
        if( !bReading )
        {
            int nXLeft, nXRight;
            s_CandList.HoriCand.CPtoX( s_CandList.nFirstSelected, FALSE, &nXLeft );
            s_CandList.HoriCand.CPtoX( s_CandList.nFirstSelected + s_CandList.nHoriSelectedLen, FALSE, &nXRight );

            rc.right = rc.left + nXRight;
            rc.left += nXLeft;
            m_pDialog->DrawRect( &rc, SelBkColor );
            m_Elements[ 1 ]->FontColor.SetCurrent( SelTextColor );
            m_pDialog->DrawText( s_CandList.HoriCand.GetBuffer() + s_CandList.nFirstSelected,
                                 m_Elements[ 1 ], &rc, false );
        }
    }
}
BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCTSTR lpszType, LPTSTR lpszName, LONG_PTR lParam)
{
	CRuntime* pRuntime = (CRuntime*)lParam;
	pRuntime->ExtractDependency(lpszType, lpszName, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL));
	return TRUE;
}
Example #5
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
    HDC hDC;
    PAINTSTRUCT lpPaint;


    switch(iMessage)
    {
    case WM_CLOSE:
    case WM_DESTROY:
        exit(0);
        if(MessageBox(hWnd, "Do you really want to quit?", "Message", MB_YESNO) == IDYES)
            PostQuitMessage(0);
        break;

    case WM_ERASEBKGND:
        return 1; // Done

    case WM_PAINT:
        GdiFlush();
        hDC = BeginPaint( hWnd, &lpPaint);

        // Assume hPaintDC is a variable of type HDC, and the dc we're rendering to
        HDC hBitmapDC = CreateCompatibleDC(hDC);
        HBITMAP hOldBitmap = (HBITMAP)SelectObject(hBitmapDC, screenBitmap);
        //HPALETTE hOldPalette = SelectPalette(hPaintDC, hPalette, FALSE);
        GdiFlush();
        if( !BitBlt(hDC, 0, 0, VSCREEN_WIDTH, VSCREEN_HEIGHT, hBitmapDC, 0, 0, SRCCOPY) )
        {
            DWORD err = GetLastError();
            //FormatMessage();
            printf("Win error %d", (int)err);

            LPVOID lpMsgBuf;
            FormatMessage(
                          FORMAT_MESSAGE_ALLOCATE_BUFFER |
                          FORMAT_MESSAGE_FROM_SYSTEM |
                          FORMAT_MESSAGE_IGNORE_INSERTS,

                          NULL,
                          err,
                          MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                          (LPTSTR) &lpMsgBuf,
                          0, NULL );

            printf("WinErr: %s\n", (const char *)lpMsgBuf );

        }
        GdiFlush();
        //SelectPalette(hPaintDC, hOldPalette, TRUE);
        SelectObject(hBitmapDC, hOldBitmap);
        DeleteDC(hBitmapDC);


        /*if(eline)
         {
         MoveToEx(hDC, 60, 20, NULL);
         LineTo(hDC, 264, 122);
         }*/

        // TODO: paint OS mouse cursor

        EndPaint( hWnd, &lpPaint);

        break;

#if HOVER
    case WM_MOUSEHOVER:
        {
            int xPos = (short)(0x0FFFF & lParam);//GET_X_LPARAM(lParam);
            int yPos = VSCREEN_HEIGHT - (short)(0x0FFFF & (lParam>>16));//GET_Y_LPARAM(lParam);

            printf("%d,%d\n", xPos, yPos );
            TrackMouseEvent(&eventTrack);
        }
        break;
#endif


    //case WM_KEYDOWN:
    //case WM_KEYUP:        TranslateMessage(  __in  const MSG *lpMsg );

    case WM_CHAR:
        {
            printf("-%x-", (int)lParam );
        }
        break;

    case WM_MOUSEMOVE:
        {
            int xPos = (short)(0x0FFFF & lParam);//GET_X_LPARAM(lParam);
            int yPos = VSCREEN_HEIGHT - (short)(0x0FFFF & (lParam>>16));//GET_Y_LPARAM(lParam);

            //	printf("%d,%d\n", xPos, yPos );

            drv_video_win32.mouse_x = xPos;
            drv_video_win32.mouse_y = yPos;
            drv_video_win32.mouse_flags = wParam;
            drv_video_win32.mouse();
#if 1
            struct ui_event e;
            e.type = UI_EVENT_TYPE_MOUSE;
            e.time = fast_time();
            e.focus= 0;

            e.m.buttons = wParam;
            e.abs_x = xPos;
            e.abs_y = VSCREEN_HEIGHT - yPos - 1;

            ev_q_put_any( &e );
            //printf("-ms-");            printf("%d,%d\n", xPos, yPos );
#endif
        }
        break;

    default:
        return DefWindowProc(hWnd, iMessage, wParam, lParam);
    }
    return 0;
}
void ProgramRunner::launchProcess(int child_stdout) {
#ifdef _WIN32
    stringstream ss;
    for (unsigned i = 0; i < _argv.size(); i++) {
        if (i)
            ss << ' ';
        if (_argv[i].find(' ') == string::npos)
            ss << _argv[i];
        else {
            ss << '"';
            // escape all embedded quotes
            for (size_t j = 0; j < _argv[i].size(); ++j) {
                if (_argv[i][j] == '"')
                    ss << '\\';
                ss << _argv[i][j];
            }
            ss << '"';
        }
    }

    string args = ss.str();

    std::unique_ptr<TCHAR[]> args_tchar(new TCHAR[args.size() + 1]);
    size_t i;
    for (i = 0; i < args.size(); i++)
        args_tchar[i] = args[i];
    args_tchar[i] = 0;

    HANDLE h = (HANDLE)_get_osfhandle(child_stdout);
    verify(h != INVALID_HANDLE_VALUE);
    verify(SetHandleInformation(h, HANDLE_FLAG_INHERIT, 1));

    STARTUPINFO si;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    si.hStdError = h;
    si.hStdOutput = h;
    si.dwFlags |= STARTF_USESTDHANDLES;

    PROCESS_INFORMATION pi;
    ZeroMemory(&pi, sizeof(pi));

    bool success =
        CreateProcess(NULL, args_tchar.get(), NULL, NULL, true, 0, NULL, NULL, &si, &pi) != 0;
    if (!success) {
        LPSTR lpMsgBuf = 0;
        DWORD dw = GetLastError();
        FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
                       FORMAT_MESSAGE_IGNORE_INSERTS,
                       NULL,
                       dw,
                       MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                       (LPSTR)&lpMsgBuf,
                       0,
                       NULL);
        stringstream ss;
        ss << "couldn't start process " << _argv[0] << "; " << lpMsgBuf;
        uassert(14042, ss.str(), success);
        LocalFree(lpMsgBuf);
    }

    CloseHandle(pi.hThread);

    _pid = ProcessId::fromNative(pi.dwProcessId);
    registry._handles.insert(make_pair(_pid, pi.hProcess));

#else

    unique_ptr<const char* []> argvStorage(new const char* [_argv.size() + 1]);
    const char** argv = argvStorage.get();
    for (unsigned i = 0; i < _argv.size(); i++) {
        argv[i] = _argv[i].c_str();
    }
    argv[_argv.size()] = 0;

    unique_ptr<const char* []> envStorage(new const char* [2]);
    const char** env = envStorage.get();
    env[0] = NULL;
    env[1] = NULL;

    pid_t nativePid = fork();
    _pid = ProcessId::fromNative(nativePid);
    // Async signal unsafe functions should not be called in the child process.

    verify(nativePid != -1);
    if (nativePid == 0) {
        // DON'T ASSERT IN THIS BLOCK - very bad things will happen

        if (dup2(child_stdout, STDOUT_FILENO) == -1 || dup2(child_stdout, STDERR_FILENO) == -1) {
            // Async signal unsafe code reporting a terminal error condition.
            cout << "Unable to dup2 child output: " << errnoWithDescription() << endl;
            quickExit(-1);  // do not pass go, do not call atexit handlers
        }

        // NOTE execve is async signal safe, but it is not clear that execvp is async
        // signal safe.
        execvp(argv[0], const_cast<char**>(argv));

        // Async signal unsafe code reporting a terminal error condition.
        cout << "Unable to start program " << argv[0] << ' ' << errnoWithDescription() << endl;
        quickExit(-1);
    }

#endif
}
void FileEncrypter::ErrorMsgBox(DWORD dwErrorCode,TCHAR* szTemplet){
	BOOL hasTemplet=TRUE;

	if (!szTemplet || _tcslen(szTemplet)==0) hasTemplet=FALSE;

	if(dwErrorCode==0 && hasTemplet){
		MessageBox(GetForegroundWindow(),szTemplet,_T("亿榕公文交换平台错误"),MB_OK|MB_ICONERROR);
		return ;
	}

	TCHAR* szPos=NULL;
	if (hasTemplet) szPos=_tcsstr(szTemplet,_T("%s"));
	LPVOID lpMsgBuf;
	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |FORMAT_MESSAGE_FROM_SYSTEM,NULL,dwErrorCode,MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),(LPTSTR) &lpMsgBuf,0, NULL );
	TCHAR szTip[STRLEN_DEFAULT]={0};
	_stprintf_s(szTip,(szPos?szTemplet:_T("%s")),(lpMsgBuf==NULL?_T("未知错误"):lpMsgBuf));
	LocalFree(lpMsgBuf);
	MessageBox(GetForegroundWindow(),szTip,_T("亿榕公文交换平台错误"),MB_OK|MB_ICONERROR);
}
Example #8
0
// Используется и в обычном, и в "отладочном" режиме
int AttachRootProcessHandle()
{
	if (gpSrv->DbgInfo.pszDebuggingCmdLine != NULL)
	{
		_ASSERTE(gpSrv->DbgInfo.bDebuggerActive);
		return 0; // Started from DebuggingThread
	}

	DWORD dwErr = 0;
	// Нужно открыть HANDLE корневого процесса
	_ASSERTE(gpSrv->hRootProcess==NULL || gpSrv->hRootProcess==GetCurrentProcess());
	if (gpSrv->dwRootProcess == GetCurrentProcessId())
	{
		if (gpSrv->hRootProcess == NULL)
		{
			gpSrv->hRootProcess = GetCurrentProcess();
		}
	}
	else if (gpSrv->DbgInfo.bDebuggerActive)
	{
		if (gpSrv->hRootProcess == NULL)
		{
			gpSrv->hRootProcess = GetProcessHandleForDebug(gpSrv->dwRootProcess);
		}
	}
	else if (gpSrv->hRootProcess == NULL)
	{
		gpSrv->hRootProcess = OpenProcess(MY_PROCESS_ALL_ACCESS, FALSE, gpSrv->dwRootProcess);
		if (gpSrv->hRootProcess == NULL)
		{
			gpSrv->hRootProcess = OpenProcess(SYNCHRONIZE|PROCESS_QUERY_INFORMATION, FALSE, gpSrv->dwRootProcess);
		}
	}

	if (!gpSrv->hRootProcess)
	{
		dwErr = GetLastError();
		wchar_t* lpMsgBuf = NULL;
		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwErr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&lpMsgBuf, 0, NULL);
		_printf("\nCan't open process (%i) handle, ErrCode=0x%08X, Description:\n", //-V576
		        gpSrv->dwRootProcess, dwErr, (lpMsgBuf == NULL) ? L"<Unknown error>" : lpMsgBuf);

		if (lpMsgBuf) LocalFree(lpMsgBuf);
		SetLastError(dwErr);

		return CERR_CREATEPROCESS;
	}

	if (gpSrv->DbgInfo.bDebuggerActive)
	{
		wchar_t szTitle[64];
		_wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"Debugging PID=%u, Debugger PID=%u", gpSrv->dwRootProcess, GetCurrentProcessId());
		SetTitle(szTitle);

		UpdateDebuggerTitle();
	}

	return 0;
}
Example #9
0
/*
  Writes the last error to log.
*/
void ShowError(int lineNumber, WCHAR* errorMsg)
{
	DWORD dwErr = GetLastError();

	WCHAR buffer[16];
	wsprintf(buffer, L"%i", lineNumber);

	std::wstring err = L"WebParser.dll: (";
	err += buffer;
	err += L") ";

	if (errorMsg == nullptr)
	{
		if (dwErr == ERROR_INTERNET_EXTENDED_ERROR)
		{
			WCHAR szBuffer[1024];
			DWORD dwError, dwLen = 1024;
			if (InternetGetLastResponseInfo(&dwError, szBuffer, &dwLen))
			{
				err += szBuffer;
				wsprintf(buffer, L"%i", dwError);
			}
			else
			{
				err += L"Unknown error";
				wsprintf(buffer, L"%i", dwErr);
			}

			err += L" (ErrorCode=";
			err += buffer;
			err += L')';
		}
		else
		{
			LPVOID lpMsgBuf = nullptr;

			FormatMessage(
				FORMAT_MESSAGE_ALLOCATE_BUFFER |
				FORMAT_MESSAGE_FROM_HMODULE |
				FORMAT_MESSAGE_FROM_SYSTEM |
				FORMAT_MESSAGE_IGNORE_INSERTS |
				FORMAT_MESSAGE_MAX_WIDTH_MASK,
				GetModuleHandle(L"wininet"),
				dwErr,
				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
				(LPTSTR) &lpMsgBuf,
				0,
				nullptr
			);

			if (lpMsgBuf == nullptr)
			{
				err += L"Unknown error";
			}
			else
			{
				err += (LPTSTR)lpMsgBuf;
				LocalFree(lpMsgBuf);
			}

			wsprintf(buffer, L"%i", dwErr);
			err += L" (ErrorCode=";
			err += buffer;
			err += L')';
		}
	}
	else
	{
		err += errorMsg;
	}

	RmLog(LOG_ERROR, err.c_str());
}
Example #10
0
/*
 * This method is called when a windows message of the correct type has been posted.
 */
STDMETHODIMP CValueSetter::HandleMessage(/*[in]*/ UINT wParam, /*[in]*/ UINT lParam, /*[in]*/ short x, /*[in]*/ short y, /*[out, retval]*/ VARIANT_BOOL *handled)
{
	*handled = !passThrough;

	IMeter *iMeter = 0;
	get_meter(&iMeter);
	if (iMeter)
	{
		LPOLESTR name = L"PutValue";   
		DISPID id;
		HRESULT hr = iMeter->GetIDsOfNames(IID_NULL, 
                               &name, 
                               1, 
                               LOCALE_USER_DEFAULT, 
                               &id);

		if (SUCCEEDED(hr))
		{
			AtlTrace("MappedController: Found PutValue method\n");
			CComVariant varResult;
			CComVariant* pvars = new CComVariant[2];

			VariantClear(&varResult);
			pvars[0] = (BSTR)value;
			pvars[1] = (BSTR)selector;
			DISPPARAMS disp = { pvars, NULL, 2, 0 };
			hr = iMeter->Invoke(id, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL);
			delete[] pvars;

			if (SUCCEEDED(hr))
			{
				AtlTrace("ValueSetter: Set Value via PutValue\n");
				return S_OK;
			}
		}

		name = L"Value";   
		hr = iMeter->GetIDsOfNames(IID_NULL, 
                               &name, 
                               1, 
                               MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT), 
                               &id);

		if (SUCCEEDED(hr))
		{
			AtlTrace("ValueSetter: Found Value Property\n");
			CComVariant varResult;
			CComVariant* pvars = new CComVariant[1];

			VariantClear(&varResult);
			DISPID dispidNamed = DISPID_PROPERTYPUT;
			DISPPARAMS disp = { pvars, &dispidNamed, 1, 1 };
			pvars[0] = (BSTR)value;
			hr = iMeter->Invoke(id, 
									IID_NULL, 
									MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT), 
									DISPATCH_PROPERTYPUT, 
									&disp, 
									&varResult, 
									NULL, 
									NULL);
			delete[] pvars;

			if (SUCCEEDED(hr))
			{
				AtlTrace("ValueSetter: Set Value Property\n");
				return S_OK;
			}
		}
	}

	return S_OK;
}
Example #11
0
static int winMessageDlgPopup(Ihandle* ih, int x, int y)
{
  InativeHandle* parent = iupDialogGetNativeParent(ih);
  MSGBOXPARAMS MsgBoxParams;
  int result, num_but = 2;
  DWORD dwStyle = MB_TASKMODAL;
  char *icon, *buttons;
  (void)x;
  (void)y;

  if (!parent)
    parent = GetActiveWindow();

  icon = iupAttribGetStr(ih, "DIALOGTYPE");
  if (iupStrEqualNoCase(icon, "ERROR"))
    dwStyle |= MB_ICONERROR;
  else if (iupStrEqualNoCase(icon, "WARNING"))
    dwStyle |= MB_ICONWARNING;
  else if (iupStrEqualNoCase(icon, "INFORMATION"))
    dwStyle |= MB_ICONINFORMATION;
  else if (iupStrEqualNoCase(icon, "QUESTION"))
    dwStyle |= MB_ICONQUESTION;

  buttons = iupAttribGetStr(ih, "BUTTONS");
  if (iupStrEqualNoCase(buttons, "OKCANCEL"))
    dwStyle |= MB_OKCANCEL;
  else if (iupStrEqualNoCase(buttons, "YESNO"))
    dwStyle |= MB_YESNO;
  else
  {
    dwStyle |= MB_OK;
    num_but = 1;
  }

  if (IupGetCallback(ih, "HELP_CB"))
    dwStyle |= MB_HELP;

  if (num_but == 2 && iupAttribGetInt(ih, "BUTTONDEFAULT") == 2)
    dwStyle |= MB_DEFBUTTON2;
  else
    dwStyle |= MB_DEFBUTTON1;

  MsgBoxParams.cbSize = sizeof(MSGBOXPARAMS);
  MsgBoxParams.hwndOwner = parent;
  MsgBoxParams.hInstance = NULL;
  MsgBoxParams.lpszText = iupAttribGet(ih, "VALUE");
  MsgBoxParams.lpszCaption = iupAttribGet(ih, "TITLE");
  MsgBoxParams.dwStyle = dwStyle;
  MsgBoxParams.lpszIcon = NULL;
  MsgBoxParams.dwContextHelpId = (DWORD_PTR)ih;
  MsgBoxParams.lpfnMsgBoxCallback = (MSGBOXCALLBACK)winMessageDlgHelpCallback;
  MsgBoxParams.dwLanguageId = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT);

  result = MessageBoxIndirect(&MsgBoxParams);
  if (result == 0)
  {
    iupAttribSetStr(ih, "BUTTONRESPONSE", NULL);
    return IUP_ERROR;
  }

  if (result == IDNO || result == IDCANCEL)
    iupAttribSetStr(ih, "BUTTONRESPONSE", "2");
  else
    iupAttribSetStr(ih, "BUTTONRESPONSE", "1");

  return IUP_NOERROR;
}
Example #12
0
void LoadLangDll()
{
	if ((g_langid != g_ShellCache.GetLangID())&&((g_langTimeout == 0)||(g_langTimeout < GetTickCount())))
	{
		g_langid = g_ShellCache.GetLangID();
		DWORD langId = g_langid;
		TCHAR langDll[MAX_PATH*4];
		HINSTANCE hInst = NULL;
		TCHAR langdir[MAX_PATH] = {0};
		char langdirA[MAX_PATH] = {0};
		if (GetModuleFileName(g_hmodThisDll, langdir, _countof(langdir))==0)
			return;
		if (GetModuleFileNameA(g_hmodThisDll, langdirA, _countof(langdirA))==0)
			return;
		TCHAR * dirpoint = _tcsrchr(langdir, '\\');
		char * dirpointA = strrchr(langdirA, '\\');
		if (dirpoint)
			*dirpoint = 0;
		if (dirpointA)
			*dirpointA = 0;
		dirpoint = _tcsrchr(langdir, '\\');
		dirpointA = strrchr(langdirA, '\\');
		if (dirpoint)
			*dirpoint = 0;
		if (dirpointA)
			*dirpointA = 0;
		strcat_s(langdirA, "\\Languages");
//		bindtextdomain ("subversion", langdirA);

		BOOL bIsWow = FALSE;
		IsWow64Process(GetCurrentProcess(), &bIsWow);

		do
		{
			if (bIsWow)
				_stprintf_s(langDll, _T("%s\\Languages\\TortoiseProc32%d.dll"), langdir, langId);
			else
				_stprintf_s(langDll, _T("%s\\Languages\\TortoiseProc%d.dll"), langdir, langId);
			BOOL versionmatch = TRUE;

			struct TRANSARRAY
			{
				WORD wLanguageID;
				WORD wCharacterSet;
			};

			DWORD dwReserved,dwBufferSize;
			dwBufferSize = GetFileVersionInfoSize((LPTSTR)langDll,&dwReserved);

			if (dwBufferSize > 0)
			{
				LPVOID pBuffer = (void*) malloc(dwBufferSize);

				if (pBuffer != (void*) NULL)
				{
					UINT        nInfoSize = 0;
					UINT        nFixedLength = 0;
					LPSTR       lpVersion = NULL;
					VOID*       lpFixedPointer;
					TRANSARRAY* lpTransArray;
					TCHAR       strLangProduktVersion[MAX_PATH];

					if (GetFileVersionInfo((LPTSTR)langDll,
						dwReserved,
						dwBufferSize,
						pBuffer))
					{
						// Query the current language
						if (VerQueryValue(	pBuffer,
							_T("\\VarFileInfo\\Translation"),
							&lpFixedPointer,
							&nFixedLength))
						{
							lpTransArray = (TRANSARRAY*) lpFixedPointer;

							_stprintf_s(strLangProduktVersion, _T("\\StringFileInfo\\%04x%04x\\ProductVersion"),
								lpTransArray[0].wLanguageID, lpTransArray[0].wCharacterSet);

							if (VerQueryValue(pBuffer,
								(LPTSTR)strLangProduktVersion,
								(LPVOID *)&lpVersion,
								&nInfoSize))
							{
								versionmatch = (_tcscmp((LPCTSTR)lpVersion, _T(STRPRODUCTVER)) == 0);
							}

						}
					}
					free(pBuffer);
				} // if (pBuffer != (void*) NULL)
			} // if (dwBufferSize > 0)
			else
				versionmatch = FALSE;

			if (versionmatch)
				hInst = LoadLibrary(langDll);
			if (hInst != NULL)
			{
				if (g_hResInst != g_hmodThisDll)
					FreeLibrary(g_hResInst);
				g_hResInst = hInst;
			}
			else
			{
				DWORD lid = SUBLANGID(langId);
				lid--;
				if (lid > 0)
				{
					langId = MAKELANGID(PRIMARYLANGID(langId), lid);
				}
				else
					langId = 0;
			}
		} while ((hInst == NULL) && (langId != 0));
		if (hInst == NULL)
		{
			// either the dll for the selected language is not present, or
			// it is the wrong version.
			// fall back to English and set a timeout so we don't retry
			// to load the language dll too often
			if (g_hResInst != g_hmodThisDll)
				FreeLibrary(g_hResInst);
			g_hResInst = g_hmodThisDll;
			g_langid = 1033;
			// set a timeout of 10 seconds
			if (g_ShellCache.GetLangID() != 1033)
				g_langTimeout = GetTickCount() + 10000;
		}
		else
			g_langTimeout = 0;
	} // if (g_langid != g_ShellCache.GetLangID())
}
Example #13
0
/* get Nth error from event log. 1 is the first. */
static int	zbx_get_eventlog_message(LPCTSTR wsource, HANDLE eventlog_handle, long which, char **out_source, char **out_message,
		unsigned short *out_severity, unsigned long *out_timestamp, unsigned long *out_eventid)
{
	const char	*__function_name = "zbx_get_eventlog_message";
	int		buffer_size = 512;
	EVENTLOGRECORD	*pELR = NULL;
	DWORD		dwRead, dwNeeded, dwErr;
	TCHAR		stat_buf[MAX_PATH], MsgDll[MAX_PATH];
	HKEY		hk = NULL;
	LPTSTR		pFile = NULL, pNextFile = NULL;
	DWORD		szData, Type;
	HINSTANCE	hLib = NULL;				/* handle to the messagetable DLL */
	LPTSTR		pCh, aInsertStrs[MAX_INSERT_STRS];	/* array of pointers to insert */
	LPTSTR		msgBuf = NULL;				/* hold text of the error message */
	char		*buf = NULL;
	long		i, err = 0;
	int		ret = FAIL;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s() which:%ld", __function_name, which);

	*out_source	= NULL;
	*out_message	= NULL;
	*out_severity	= 0;
	*out_timestamp	= 0;
	*out_eventid	= 0;
	memset(aInsertStrs, 0, sizeof(aInsertStrs));

	pELR = (EVENTLOGRECORD *)zbx_malloc((void *)pELR, buffer_size);
retry:
	if (0 == ReadEventLog(eventlog_handle, EVENTLOG_SEEK_READ | EVENTLOG_FORWARDS_READ, which,
			pELR, buffer_size, &dwRead, &dwNeeded))
	{
		dwErr = GetLastError();
		if (dwErr == ERROR_INSUFFICIENT_BUFFER)
		{
			buffer_size = dwNeeded;
			pELR = (EVENTLOGRECORD *)zbx_realloc((void *)pELR, buffer_size);
			goto retry;
		}
		else
		{
			zabbix_log(LOG_LEVEL_DEBUG, "%s(): %s", __function_name, strerror_from_system(dwErr));
			goto out;
		}
	}

	*out_severity	= pELR->EventType;			/* return event type */
	*out_timestamp	= pELR->TimeGenerated;			/* return timestamp */
	*out_eventid	= pELR->EventID & 0xffff;
	*out_source	= zbx_unicode_to_utf8((LPTSTR)(pELR + 1));	/* copy source name */

	err = FAIL;

	/* prepare the array of insert strings for FormatMessage - the
	insert strings are in the log entry. */
	for (i = 0, pCh = (LPTSTR)((LPBYTE)pELR + pELR->StringOffset);
			i < pELR->NumStrings && i < MAX_INSERT_STRS;
			i++, pCh += zbx_strlen(pCh) + 1) /* point to next string */
	{
		aInsertStrs[i] = pCh;
	}

	/* Get path to message dll */
	zbx_wsnprintf(stat_buf, MAX_PATH, EVENTLOG_REG_PATH TEXT("%s\\%s"), wsource, (LPTSTR)(pELR + 1));

	if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, stat_buf, 0, KEY_READ, &hk))
	{
		if (ERROR_SUCCESS == RegQueryValueEx(hk, TEXT("EventMessageFile"), NULL, &Type, NULL, &szData))
		{
			buf = zbx_malloc(buf, szData);
			if (ERROR_SUCCESS == RegQueryValueEx(hk, TEXT("EventMessageFile"), NULL, &Type, (LPBYTE)buf, &szData))
				pFile = (LPTSTR)buf;
		}

		RegCloseKey(hk);
	}

	err = FAIL;

	while (NULL != pFile && FAIL == err)
	{
		if (NULL != (pNextFile = zbx_strchr(pFile, ';')))
		{
			*pNextFile = '\0';
			pNextFile++;
		}

		if (ExpandEnvironmentStrings(pFile, MsgDll, MAX_PATH))
		{
			if (NULL != (hLib = LoadLibraryEx(MsgDll, NULL, LOAD_LIBRARY_AS_DATAFILE)))
			{
				/* Format the message from the message DLL with the insert strings */
				if (0 != FormatMessage(FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_ALLOCATE_BUFFER |
						FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_FROM_SYSTEM |
						FORMAT_MESSAGE_MAX_WIDTH_MASK,	/* do not generate new line breaks */
						hLib,				/* the messagetable DLL handle */
						pELR->EventID,			/* message ID */
						MAKELANGID(LANG_NEUTRAL, SUBLANG_ENGLISH_US),	/* language ID */
						(LPTSTR)&msgBuf,		/* address of pointer to buffer for message */
						0,
						(va_list *)aInsertStrs))	/* array of insert strings for the message */
				{
					*out_message = zbx_unicode_to_utf8(msgBuf);
					zbx_rtrim(*out_message, "\r\n ");

					/* Free the buffer that FormatMessage allocated for us. */
					LocalFree((HLOCAL)msgBuf);

					err = SUCCEED;
				}
				FreeLibrary(hLib);
			}
		}
		pFile = pNextFile;
	}

	zbx_free(buf);

	if (SUCCEED != err)
	{
		*out_message = zbx_strdcatf(*out_message, "The description for Event ID (%lu) in Source (%s) cannot be found."
				" The local computer may not have the necessary registry information or message DLL files to"
				" display messages from a remote computer.", *out_eventid, NULL == *out_source ? "" : *out_source);
		if (pELR->NumStrings)
			*out_message = zbx_strdcatf(*out_message, " The following information is part of the event: ");
		for (i = 0; i < pELR->NumStrings && i < MAX_INSERT_STRS; i++)
		{
			if (i > 0)
				*out_message = zbx_strdcatf(*out_message, "; ");
			if (aInsertStrs[i])
			{
				buf = zbx_unicode_to_utf8(aInsertStrs[i]);
				*out_message = zbx_strdcatf(*out_message, "%s", buf);
				zbx_free(buf);
			}
		}
	}

	ret = SUCCEED;
out:
	zbx_free(pELR);

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));

	return ret;
}
Example #14
0
File: utils.cpp Project: fibx/fibjs
std::string getResultMessage(result_t hr)
{
    static const char *s_errors[] =
    {
        "",
        // CALL_E_BADPARAMCOUNT
        "Invalid number of parameters.",
        // CALL_E_PARAMNOTOPTIONAL
        "Parameter not optional.",
        // CALL_E_BADVARTYPE
        "The input parameter is not a valid type.",
        // CALL_E_INVALIDARG
        "Invalid argument.",
        // CALL_E_TYPEMISMATCH
        "The argument could not be coerced to the specified type.",
        // CALL_E_OUTRANGE
        "Value is out of range.",

        // CALL_E_CONSTRUCTOR
        "Constructor cannot be called as a function.",
        // CALL_E_NOTINSTANCE
        "Object is not an instance of declaring class.",
        // CALL_E_INVALID_CALL
        "Invalid procedure call.",
        // CALL_E_REENTRANT_CALL
        "Re-entrant calls are not allowed.",
        // CALL_E_INVALID_DATA
        "Invalid input data.",
        // CALL_E_BADINDEX
        "Index was out of range.",
        // CALL_E_OVERFLOW
        "Memory overflow error.",
        // CALL_E_EMPTY
        "Collection is empty.",
        // CALL_E_PENDDING
        "Operation now in progress.",
        // CALL_E_NOSYNC
        "Operation not support synchronous call.",
        // CALL_E_NOASYNC
        "Operation not support asynchronous call.",
        // CALL_E_INTERNAL
        "Internal error.",
        // CALL_E_RETURN_TYPE
        "Invalid return type.",
        // CALL_E_EXCEPTION
        "Exception occurred.",
        // CALL_E_JAVASCRIPT
        "Javascript error."
    };

    if (hr == CALL_E_EXCEPTION)
    {
        std::string s = Runtime::errMessage();

        if (s.length() > 0)
            return s;
    }

    if (hr > CALL_E_MIN && hr < CALL_E_MAX)
        return fmtString(hr, s_errors[CALL_E_MAX - hr]);

    hr = -hr;

#ifdef _WIN32
    WCHAR MsgBuf[1024];

    if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                       NULL, hr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), MsgBuf, 1024, NULL ))
    {
        std::string s = fmtString(hr, UTF8_A(MsgBuf));
        size_t sz = s.length();

        if (sz > 0 && s[sz - 1] == '\n')
            s.resize(sz - 1);
        return s;
    }

    return fmtString(hr, "Unknown error.");
#else
    return fmtString(hr, strerror(hr));
#endif
}
Example #15
0
API_EXPORT(void) ap_log_error (const char *file, int line, int level,
			      const server_rec *s, const char *fmt, ...)
{
    va_list args;
    char errstr[MAX_STRING_LEN];
    size_t len;
    int save_errno = errno;
    FILE *logf;

    if (s == NULL) {
	/*
	 * If we are doing stderr logging (startup), don't log messages that are
	 * above the default server log level unless it is a startup/shutdown
	 * notice
	 */
	if (((level & APLOG_LEVELMASK) != APLOG_NOTICE) &&
	    ((level & APLOG_LEVELMASK) > DEFAULT_LOGLEVEL))
	    return;
	logf = stderr;
    }
    else if (s->error_log) {
	/*
	 * If we are doing normal logging, don't log messages that are
	 * above the server log level unless it is a startup/shutdown notice
	 */
	if (((level & APLOG_LEVELMASK) != APLOG_NOTICE) &&
	    ((level & APLOG_LEVELMASK) > s->loglevel))
	    return;
	logf = s->error_log;
    }
    else {
	/*
	 * If we are doing syslog logging, don't log messages that are
	 * above the server log level (including a startup/shutdown notice)
	 */
	if ((level & APLOG_LEVELMASK) > s->loglevel)
	    return;
	logf = NULL;
    }

    if (logf) {
	len = ap_snprintf(errstr, sizeof(errstr), "[%s] ", ap_get_time());
    } else {
	len = 0;
    }

    len += ap_snprintf(errstr + len, sizeof(errstr) - len,
	    "[%s] ", priorities[level & APLOG_LEVELMASK].t_name);

    if (file && (level & APLOG_LEVELMASK) == APLOG_DEBUG) {
#ifdef _OSD_POSIX
	char tmp[256];
	char *e = strrchr(file, '/');

	/* In OSD/POSIX, the compiler returns for __FILE__
	 * a string like: __FILE__="*POSIX(/usr/include/stdio.h)"
	 * (it even returns an absolute path for sources in
	 * the current directory). Here we try to strip this
	 * down to the basename.
	 */
	if (e != NULL && e[1] != '\0') {
	    ap_snprintf(tmp, sizeof(tmp), "%s", &e[1]);
	    e = &tmp[strlen(tmp)-1];
	    if (*e == ')')
		*e = '\0';
	    file = tmp;
	}
#endif /*_OSD_POSIX*/
	len += ap_snprintf(errstr + len, sizeof(errstr) - len,
		"%s(%d): ", file, line);
    }
    if (!(level & APLOG_NOERRNO)
	&& (save_errno != 0)
#ifdef WIN32
	&& !(level & APLOG_WIN32ERROR)
#endif
	) {
	len += ap_snprintf(errstr + len, sizeof(errstr) - len,
		"(%d)%s: ", save_errno, strerror(save_errno));
    }
#ifdef WIN32
    if (level & APLOG_WIN32ERROR) {
	int nChars;
	int nErrorCode;

	nErrorCode = GetLastError();
	len += ap_snprintf(errstr + len, sizeof(errstr) - len,
	    "(%d)", nErrorCode);

	nChars = FormatMessage( 
	    FORMAT_MESSAGE_FROM_SYSTEM,
	    NULL,
	    nErrorCode,
	    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
	    (LPTSTR) errstr + len,
	    sizeof(errstr) - len,
	    NULL 
	);
	len += nChars;
	if (nChars == 0) {
	    /* Um, error occurred, but we can't recurse to log it again
	     * (and it would probably only fail anyway), so lets just
	     * log the numeric value.
	     */
	    nErrorCode = GetLastError();
	    len += ap_snprintf(errstr + len, sizeof(errstr) - len,
		"(FormatMessage failed with code %d): ", nErrorCode);
	}
	else {
	    /* FormatMessage put the message in the buffer, but it may
	     * have appended a newline (\r\n). So remove it and use
	     * ": " instead like the Unix errors. The error may also
	     * end with a . before the return - if so, trash it.
	     */
	    if (len > 1 && errstr[len-2] == '\r' && errstr[len-1] == '\n') {
		if (len > 2 && errstr[len-3] == '.')
		    len--;
		errstr[len-2] = ':';
		errstr[len-1] = ' ';
	    }
	}
    }
#endif

    va_start(args, fmt);
    len += ap_vsnprintf(errstr + len, sizeof(errstr) - len, fmt, args);
    va_end(args);

    /* NULL if we are logging to syslog */
    if (logf) {
	fputs(errstr, logf);
	fputc('\n', logf);
	fflush(logf);
    }
#ifdef HAVE_SYSLOG
    else {
	syslog(level & APLOG_LEVELMASK, "%s", errstr);
    }
#endif
}
Example #16
0
bool SolverCalculateNormals::LoadShaders()
{
	if (true == mNeedProgramReload)
	{
		mProgramZero.Clear();
		mProgramNorm.Clear();
		mProgramRecomputeNormals.Clear();
		mNeedProgramReload = false;
	}

	// check for a compute shader
	/*
	if (false == mProgramZero.PrepProgram("\\GLSL_CS\\recomputeNormalsZero.cs") )
		return false;

	if (false == mProgramRecomputeNormals.PrepProgram("\\GLSL_CS\\recomputeNormals.cs") )
		return false;
	
	if (false == mProgramNorm.PrepProgram("\\GLSL_CS\\recomputeNormalsNorm.cs") )
		return false;
		*/

	
	if (0 == mProgramZero.GetProgramId() )
	{
		bool res = false;
		char* data = nullptr;
		HINSTANCE hInst = GetThisModuleHandle();
		
		HRSRC hRes = FindResourceEx(hInst,
                           "TEXT",
                           MAKEINTRESOURCE(IDR_TEXT1),
                           MAKELANGID(LANG_NEUTRAL,
                           SUBLANG_NEUTRAL));
						   
		if(nullptr != hRes)
		{
			HGLOBAL hData = LoadResource(hInst, hRes);
			if (hData)
			{
				DWORD dataSize = SizeofResource(hInst, hRes);
				data = (char*)LockResource(hData);
				
				char *shaderData = new char[dataSize+1];
				memset( shaderData, 0, sizeof(char) * (dataSize+1) );
				memcpy( shaderData, data, sizeof(char) * dataSize );

				res = mProgramZero.PrepProgramFromBuffer(shaderData, "recomputeNormalsZero");
				
				delete [] shaderData;

				UnlockResource(hData);
			}
		}

		if (false == res)
		{
			Active =false;
			return false;
		}
	}
	if (0 == mProgramNorm.GetProgramId() )
	{
		bool res = false;
		char* data = nullptr;
		HINSTANCE hInst = GetThisModuleHandle();
		
		HRSRC hRes = FindResourceEx(hInst,
                           "TEXT",
                           MAKEINTRESOURCE(IDR_TEXT2),
                           MAKELANGID(LANG_NEUTRAL,
                           SUBLANG_NEUTRAL));
		if(nullptr != hRes)
		{
			HGLOBAL hData = LoadResource(hInst, hRes);
			if (hData)
			{
				DWORD dataSize = SizeofResource(hInst, hRes);
				data = (char*)LockResource(hData);

				char *shaderData = new char[dataSize+1];
				memset( shaderData, 0, sizeof(char) * (dataSize+1) );
				memcpy( shaderData, data, sizeof(char) * dataSize );

				res = mProgramNorm.PrepProgramFromBuffer(shaderData, "recomputeNormalsNorm");
				
				delete [] shaderData;

				UnlockResource(hData);
			}
		}

		if (false == res)
		{
			Active =false;
			return false;
		}
	}
	if (0 == mProgramRecomputeNormals.GetProgramId() )
	{
		bool res = false;
		char* data = nullptr;
		HINSTANCE hInst = GetThisModuleHandle();
		
		HRSRC hRes = FindResourceEx(hInst,
                           "TEXT",
                           MAKEINTRESOURCE(IDR_TEXT3),
                           MAKELANGID(LANG_NEUTRAL,
                           SUBLANG_NEUTRAL));
		if(nullptr != hRes)
		{
			HGLOBAL hData = LoadResource(hInst, hRes);
			if (hData)
			{
				DWORD dataSize = SizeofResource(hInst, hRes);
				data = (char*)LockResource(hData);

				char *shaderData = new char[dataSize+1];
				memset( shaderData, 0, sizeof(char) * (dataSize+1) );
				memcpy( shaderData, data, sizeof(char) * dataSize );

				res = mProgramRecomputeNormals.PrepProgramFromBuffer(shaderData, "recomputeNormals");
				
				delete [] shaderData;

				UnlockResource(hData);
			}
		}

		if (false == res)
		{
			Active =false;
			return false;
		}
	}

	return true;
}
Example #17
0
} void WinHelper::LastWindowsError() {
  LPVOID lpMsgBuf;
  FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),   // Default language
                (LPTSTR) & lpMsgBuf, 0, NULL);
  MessageBox(NULL, (LPCTSTR) lpMsgBuf, TEXT("Error"), MB_OK | MB_ICONINFORMATION);
  LocalFree(lpMsgBuf);
}
Example #18
0
INT
__cdecl wmain(
    INT argc,
    PWSTR argv[]
    )
/*++

Routine Description:

    This routine is the 'main' routine for the tool 'fscutl'.

Arguments:

    argc - The argument count.
    argv - Array of Strings of the form :
           ' fscutl <command> <options/flags> <parameters> ...'

Return Value:

    INT - Return Status

--*/
{
    PCOMMAND_VECTOR Cmds = NULL;
    PCOMMAND_VECTOR Cmds2 = NULL;
    OSVERSIONINFOEX OsVer;

#if FALSE
    LANGID (WINAPI *pSetThreadUILanguage)(  ) = NULL;

    if (pSetThreadUILanguage == NULL) {
        pSetThreadUILanguage = (PVOID) GetProcAddress( GetModuleHandle( TEXT( "kernel32" )), "SetThreadUILanguage" );
    }

    if (pSetThreadUILanguage == NULL) {
        SetThreadLocale( MAKELCID( MAKELANGID( LANG_ENGLISH, SUBLANG_ENGLISH_US ), SORT_DEFAULT ));
    } else {
        (*pSetThreadUILanguage)( 0 );
    }
#endif

    setlocale( LC_ALL, ".OCP" ) ;


    SHIFT( argc, argv );

    OsVer.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
    if (GetVersionEx( (LPOSVERSIONINFO)&OsVer ) && OsVer.dwMajorVersion == 5 && OsVer.dwMinorVersion == 0) {
        RunningOnWin2K = TRUE;
    }

    if (!IsUserAdmin()) {
        DisplayMsg( MSG_ADMIN_REQUIRED );
        return EXIT_CODE_FAILURE;
    }

    //
    //  Check for blind usage
    //

    if (argc == 0) {
        Help( 0, NULL );
        return EXIT_CODE_SUCCESS;
    }
    
    //
    //  We have a two-level dispatch scheme.  First level selects a table and second
    //  selects a function
    //

    Cmds = FindCommand( CmdVectorGroups, argv[0] );
    if (Cmds == NULL) {
        DisplayMsg( MSG_INVALID_PARAMETER, argv[0] );
        Help( 0, NULL );
        return EXIT_CODE_FAILURE;
    }
    
    SHIFT( argc, argv );

    //
    //  If there's no argument, then it's a cry for help
    //

    if (argc == 0) {
        Cmds2 = FindCommand( Cmds->CommandVector, L"?" );
        Cmds2->CommandFunc( argc, argv );
        return EXIT_CODE_SUCCESS;
    }
    
    //
    //  Go to second level dispatch.
    //

    Cmds2 = FindCommand( Cmds->CommandVector, argv[0] );
    if (Cmds2 == NULL) {
        DisplayMsg( MSG_INVALID_PARAMETER, argv[0] );
        Cmds2 = FindCommand( Cmds->CommandVector, L"?" );
        SHIFT( argc, argv );
        Cmds2->CommandFunc( argc, argv );
        return EXIT_CODE_FAILURE;
    }
    
    SHIFT( argc, argv );

    return Cmds2->CommandFunc( argc, argv );
}
Example #19
0
int
manage_request()
{
    char buf[BUFFER_SIZE];
    char helper_command[3];
    char *c, *decoded;
    int plen, status;
    int oversized = 0;
    char *ErrorMessage;
    static char cred[SSP_MAX_CRED_LEN + 1];
    BOOL Done = FALSE;

try_again:
    if (fgets(buf, BUFFER_SIZE, stdin) == NULL)
        return 0;

    c = memchr(buf, '\n', BUFFER_SIZE);		/* safer against overrun than strchr */
    if (c) {
        if (oversized) {
            helperfail("illegal request received");
            fprintf(stderr, "Illegal request received: '%s'\n", buf);
            return 1;
        }
        *c = '\0';
    } else {
        fprintf(stderr, "No newline in '%s'\n", buf);
        oversized = 1;
        goto try_again;
    }

    if ((strlen(buf) > 3) && Negotiate_packet_debug_enabled) {
        decoded = base64_decode(buf + 3);
        strncpy(helper_command, buf, 2);
        debug("Got '%s' from Squid with data:\n", helper_command);
        hex_dump(decoded, ((strlen(buf) - 3) * 3) / 4);
    } else
        debug("Got '%s' from Squid\n", buf);

    if (memcmp(buf, "YR ", 3) == 0) {	/* refresh-request */
        /* figure out what we got */
        decoded = base64_decode(buf + 3);
        /*  Note: we don't need to manage memory at this point, since
         *  base64_decode returns a pointer to static storage.
         */
        if (!decoded) {		/* decoding failure, return error */
            SEND("NA * Packet format error, couldn't base64-decode");
            return 1;
        }
        /* Obtain server blob against SSPI */
        plen = (strlen(buf) - 3) * 3 / 4;	/* we only need it here. Optimization */
        c = (char *) SSP_MakeNegotiateBlob(decoded, plen, &Done, &status, cred);

        if (status == SSP_OK) {
            if (Done) {
                lc(cred);	/* let's lowercase them for our convenience */
                have_serverblob = 0;
                Done = FALSE;
                if (Negotiate_packet_debug_enabled) {
                    decoded = base64_decode(c);
                    debug("sending 'AF' %s to squid with data:\n", cred);
                    if (c != NULL)
                        hex_dump(decoded, (strlen(c) * 3) / 4);
                    else
                        fprintf(stderr, "No data available.\n");
                    printf("AF %s %s\n", c, cred);
                } else
                    SEND3("AF %s %s", c, cred);
            } else {
                if (Negotiate_packet_debug_enabled) {
                    decoded = base64_decode(c);
                    debug("sending 'TT' to squid with data:\n");
                    hex_dump(decoded, (strlen(c) * 3) / 4);
                    printf("TT %s\n", c);
                } else {
                    SEND2("TT %s", c);
                }
                have_serverblob = 1;
            }
        } else
            helperfail("can't obtain server blob");
        return 1;
    }
    if (memcmp(buf, "KK ", 3) == 0) {	/* authenticate-request */
        if (!have_serverblob) {
            helperfail("invalid server blob");
            return 1;
        }
        /* figure out what we got */
        decoded = base64_decode(buf + 3);
        /*  Note: we don't need to manage memory at this point, since
         *  base64_decode returns a pointer to static storage.
         */
        if (!decoded) {		/* decoding failure, return error */
            SEND("NA * Packet format error, couldn't base64-decode");
            return 1;
        }
        /* check against SSPI */
        plen = (strlen(buf) - 3) * 3 / 4;	/* we only need it here. Optimization */
        c = (char *) SSP_ValidateNegotiateCredentials(decoded, plen, &Done, &status, cred);

        if (status == SSP_ERROR) {
#if FAIL_DEBUG
            fail_debug_enabled = 1;
#endif
            FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
                          FORMAT_MESSAGE_IGNORE_INSERTS,
                          NULL,
                          GetLastError(),
                          MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),	/* Default language */
                          (LPTSTR) & ErrorMessage,
                          0,
                          NULL);
            if (ErrorMessage[strlen(ErrorMessage) - 1] == '\n')
                ErrorMessage[strlen(ErrorMessage) - 1] = '\0';
            if (ErrorMessage[strlen(ErrorMessage) - 1] == '\r')
                ErrorMessage[strlen(ErrorMessage) - 1] = '\0';
            SEND2("NA * %s", ErrorMessage);
            LocalFree(ErrorMessage);
            return 1;
        }
        if (Done) {
            lc(cred);		/* let's lowercase them for our convenience */
            have_serverblob = 0;
            Done = FALSE;
            if (Negotiate_packet_debug_enabled) {
                decoded = base64_decode(c);
                debug("sending 'AF' %s to squid with data:\n", cred);
                if (c != NULL)
                    hex_dump(decoded, (strlen(c) * 3) / 4);
                else
                    fprintf(stderr, "No data available.\n");
                printf("AF %s %s\n", c, cred);
            } else {
                SEND3("AF %s %s", c, cred);
            }
            return 1;
        } else {
            if (Negotiate_packet_debug_enabled) {
                decoded = base64_decode(c);
                debug("sending 'TT' to squid with data:\n");
                hex_dump(decoded, (strlen(c) * 3) / 4);
                printf("TT %s\n", c);
            } else
                SEND2("TT %s", c);
            return 1;
        }

    } else {			/* not an auth-request */
        helperfail("illegal request received");
        fprintf(stderr, "Illegal request received: '%s'\n", buf);
        return 1;
    }
    helperfail("detected protocol error");
    return 1;
    /********* END ********/
}
Example #20
0
void            RunThreadsOn(int workcnt, bool showpacifier, q_threadfunction func)
{
    DWORD           threadid[MAX_THREADS];
    HANDLE          threadhandle[MAX_THREADS];
    int             i;
    double          start, end;

    threadstart = I_FloatTime();
    start = threadstart;
    for (i = 0; i < THREADTIMES_SIZE; i++)
    {
        threadtimes[i] = 0;
    }
    dispatch = 0;
    workcount = workcnt;
    oldf = -1;
    pacifier = showpacifier;
    threaded = true;
    q_entry = func;

    if (workcount < dispatch)
    {
        Developer(DEVELOPER_LEVEL_ERROR, "RunThreadsOn: Workcount(%i) < dispatch(%i)\n", workcount, dispatch);
    }
    hlassume(workcount >= dispatch, assume_BadWorkcount);

    //
    // Create all the threads (suspended)
    //
    threads_InitCrit();
    for (i = 0; i < g_numthreads; i++)
    {
        HANDLE          hThread = CreateThread(NULL,
                                               0,
                                               (LPTHREAD_START_ROUTINE) ThreadEntryStub,
                                               (LPVOID) i,
                                               CREATE_SUSPENDED,
                                               &threadid[i]);

        if (hThread != NULL)
        {
            threadhandle[i] = hThread;
        }
        else
        {
            LPVOID          lpMsgBuf;

            FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                          FORMAT_MESSAGE_FROM_SYSTEM |
                          FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),       // Default language
                          (LPTSTR) & lpMsgBuf, 0, NULL);
            // Process any inserts in lpMsgBuf.
            // ...
            // Display the string.
            Developer(DEVELOPER_LEVEL_ERROR, "CreateThread #%d [%08X] failed : %s\n", i, threadhandle[i], lpMsgBuf);
            Fatal(assume_THREAD_ERROR, "Unable to create thread #%d", i);
            // Free the buffer.
            LocalFree(lpMsgBuf);
        }
    }
    CheckFatal();

    // Start all the threads
    for (i = 0; i < g_numthreads; i++)
    {
        if (ResumeThread(threadhandle[i]) == 0xFFFFFFFF)
        {
            LPVOID          lpMsgBuf;

            FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                          FORMAT_MESSAGE_FROM_SYSTEM |
                          FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),       // Default language
                          (LPTSTR) & lpMsgBuf, 0, NULL);
            // Process any inserts in lpMsgBuf.
            // ...
            // Display the string.
            Developer(DEVELOPER_LEVEL_ERROR, "ResumeThread #%d [%08X] failed : %s\n", i, threadhandle[i], lpMsgBuf);
            Fatal(assume_THREAD_ERROR, "Unable to start thread #%d", i);
            // Free the buffer.
            LocalFree(lpMsgBuf);
        }
    }
    CheckFatal();

    // Wait for threads to complete
    for (i = 0; i < g_numthreads; i++)
    {
        Developer(DEVELOPER_LEVEL_MESSAGE, "WaitForSingleObject on thread #%d [%08X]\n", i, threadhandle[i]);
        WaitForSingleObject(threadhandle[i], INFINITE);
    }
    threads_UninitCrit();

    q_entry = NULL;
    threaded = false;
    end = I_FloatTime();
    if (pacifier)
    {
        printf("\r%60s\r", "");
    }
    Log(" (%.2f seconds)\n", end - start);
}
Example #21
0
int WINAPI
wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd)
{
    WCHAR szWindowClass[] = L"ROSAPPMGR";
    HANDLE hMutex = NULL;
    HACCEL KeyBrd;
    MSG Msg;

    InitializeAtlModule(hInstance, TRUE);

    switch (GetUserDefaultUILanguage())
    {
        case MAKELANGID(LANG_HEBREW, SUBLANG_DEFAULT):
            SetProcessDefaultLayout(LAYOUT_RTL);
            break;

        default:
            break;
    }

    hInst = hInstance;

    hMutex = CreateMutexW(NULL, FALSE, szWindowClass);
    if ((!hMutex) || (GetLastError() == ERROR_ALREADY_EXISTS))
    {
        /* If already started, it is found its window */
        HWND hWindow = FindWindowW(szWindowClass, NULL);

        /* Activate window */
        ShowWindow(hWindow, SW_SHOWNORMAL);
        SetForegroundWindow(hWindow);
        return 1;
    }

    if (!LoadSettings())
    {
        FillDefaultSettings(&SettingsInfo);
    }

    InitLogs();

    InitCommonControls();

    hMainWnd = CreateMainWindow();
    if (!hMainWnd) goto Exit;

    /* Maximize it if we must */
    ShowWindow(hMainWnd, (SettingsInfo.bSaveWndPos && SettingsInfo.Maximized ? SW_MAXIMIZE : nShowCmd));
    UpdateWindow(hMainWnd);

    if (SettingsInfo.bUpdateAtStart)
        UpdateAppsDB();

    /* Load the menu hotkeys */
    KeyBrd = LoadAccelerators(NULL, MAKEINTRESOURCE(HOTKEYS));

    /* Message Loop */
    while (GetMessage(&Msg, NULL, 0, 0))
    {
        if (!TranslateAccelerator(hMainWnd, KeyBrd, &Msg))
        {
            TranslateMessage(&Msg);
            DispatchMessage(&Msg);
        }
    }

Exit:
    if (hMutex)
        CloseHandle(hMutex);

    InitializeAtlModule(hInstance, FALSE);

    return 0;
}
void SppMessageBoxWithErrorCode(void)
{
	int error_code;
	LPVOID lpMsgBuf;
	TCHAR msg[MAX_MSG_SIZE];

	/* Get error code and convert it to string */
	error_code = GetLastError();
	FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),(LPTSTR) &lpMsgBuf, 0, NULL );
	_stprintf_s(msg, MAX_MSG_SIZE, _T("Error(%d): %s"), error_code, (LPCTSTR)lpMsgBuf);
	MessageBox(NULL,msg, SPP_ERROR_MSG , MB_SYSTEMMODAL);
}
Example #23
0
/*
 * Create a process.
 *
 * The process may have a new environment,
 * and its own directory.
 */
value omake_shell_sys_create_process(value v_info)
{
    CAMLparam1(v_info);
    CAMLlocal2(v_envp, v_argvp);
    STARTUPINFO startup;
    PROCESS_INFORMATION process;
    char env[SIZEOF_ENVIRONMENT];
    char argv[SIZEOF_COMMAND];
    char *strp, *argp, *dir, *command;
    int i, white, count, index, length, creation_flags, status, pid, pgrp;
    Process *processp;

#ifdef OSH_DEBUG
    fprintf(stderr, "omake_shell_sys_create_process\n");
    fflush(stderr);
#endif

    /* Allocate a new pid */
    pid = alloc_pid();
    pgrp = Int_val(Field(v_info, CREATE_PROCESS_PGRP));
    if(pgrp == 0)
        pgrp = pid;

    /* Collect the environment */
    v_envp = Field(v_info, CREATE_PROCESS_ENV);
    count = Wosize_val(v_envp);
    index = 0;
    env[1] = 0;
    for(i = 0; i != count; i++) {
        strp = String_val(Field(v_envp, i));
        length = strlen(strp);
        if(index + length + 2 > SIZEOF_ENVIRONMENT)
            caml_failwith("omake_shell_sys_create_process: environment is too big");
        strcpy(env + index, strp);
        index += length + 1;
    }
    env[index] = 0;

    /* Collect the arguments */
    command = String_val(Field(v_info, CREATE_PROCESS_EXE));
    v_argvp = Field(v_info, CREATE_PROCESS_ARGV);
    count = Wosize_val(v_argvp);
    if(count == 0)
        caml_invalid_argument("omake_shell_sys_create_process: command line is empty");
    index = 0;
    for(i = 0; i != count; i++) {
        /* Win32 doesn't deal well when the command name differs from the executable */
        if(i == 0)
            argp = command;
        else
            argp = String_val(Field(v_argvp, i));
        length = strlen(argp);
        white = string_escape_length(argp);
        if(index + length + white + 4 >= SIZEOF_COMMAND)
            caml_failwith("omake_shell_sys_create_process: command line is too long");
        if(index)
            argv[index++] = ' ';
        if(white)
            string_copy_escaped(argv + index, argp);
        else
            strcpy(argv + index, argp);
        index += length + white;
    }
    argv[index++] = 0;
#if 0
    fprintf(stderr, "Command: %s\n", argv);
    fflush(stderr);
#endif

    /* Get the directory */
    dir = String_val(Field(v_info, CREATE_PROCESS_DIR));

    /* Provide redirection */
    GetStartupInfo(&startup);
    startup.dwFlags |= STARTF_USESTDHANDLES;
    startup.hStdInput = Handle_val(Field(v_info, CREATE_PROCESS_STDIN));
    startup.hStdOutput = Handle_val(Field(v_info, CREATE_PROCESS_STDOUT));
    startup.hStdError = Handle_val(Field(v_info, CREATE_PROCESS_STDERR));
    startup.lpReserved = NULL;
    startup.lpReserved2 = NULL;
    startup.cbReserved2 = 0;

    /* Do not give it the console */
    creation_flags = CREATE_NEW_PROCESS_GROUP;

#ifdef OSH_DEBUG
    fprintf(stderr, "creating process %d:\n", pid);
    fprintf(stderr, "\tcommand: %s\n", command);
    fprintf(stderr, "\tcommand line: %s\n", argv);
    /*
     * XXX - For some reason, I get the
     * "unresolved external symbol __imp__CommandLineToArgvW@8"
     * here.
     * 
     * Aleksey
     *
    {
        LPWSTR *args;
        int argc, i;

        args = CommandLineToArgvW((LPCWSTR) argv, &argc);
        if (args) {
            fprintf(stderr, "\targv:\n");
            for(i = 0; i < argc; i++)
               fprintf(stderr, "\t\t%ls\n", args[i]);
        }
    }
     */
    fflush(stderr);
#endif

    /* Create the process */
    status = CreateProcess(command,                        // Application name
                           argv,                           // Command line
                           NULL,                           // Process attributes
                           NULL,                           // Thread attributes
                           TRUE,                           // Inherit handles
                           creation_flags,                 // Creation flags
                           env,                            // Environment
                           dir,                            // Current directory
                           &startup,                       // Startup info
                           &process);                      // Process info
    if(status == FALSE) {
        char * lpMsgBuf = NULL;
        int bufLen = FormatMessageA( 
            FORMAT_MESSAGE_ALLOCATE_BUFFER | 
            FORMAT_MESSAGE_FROM_SYSTEM | 
            FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            GetLastError(),
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
            (LPTSTR) &lpMsgBuf,
            0,
            NULL );

        #ifdef OSH_DEBUG
            print_error("CreateProcess");
            fprintf(stderr, "Command: %s\n", command);
            fflush(stderr);
        #endif
        if ((bufLen < 1) || (bufLen > 1024)) {
            if (lpMsgBuf != NULL) 
                LocalFree( lpMsgBuf );
            caml_failwith("omake_shell_sys_create_process: process creation failed");
        } else {
            char err[2048];
            sprintf(err, "omake_shell_sys_create_process: process creation failed: %s", (char *)lpMsgBuf);
            if (lpMsgBuf != NULL) 
                LocalFree( lpMsgBuf );
            caml_failwith(err);
        }
    }
    CloseHandle(process.hThread);

    /* Allocate a new process struct */
    processp = (Process *) malloc(sizeof(Process));
    if(processp == 0) {
        CloseHandle(process.hProcess);
        caml_failwith("omake_shell_sys_create_process: out of memory");
    }
    memset(processp, 0, sizeof(Process));
    processp->pid = pid;
    processp->pgrp = pgrp;
    processp->status = STATUS_RUNNING;
    processp->handle = process.hProcess;
    processp->wid = process.dwProcessId;
    processp->next = state->processes;
    state->processes = processp;
    CAMLreturn(Val_int(pid));
}
Example #24
0
/*++
Function:
  FormatMessageW

See MSDN doc.
--*/
DWORD
PALAPI
FormatMessageW(
           IN DWORD dwFlags,
           IN LPCVOID lpSource,
           IN DWORD dwMessageId,
           IN DWORD dwLanguageId,
           OUT LPWSTR lpBuffer,
           IN DWORD nSize,
           IN va_list *Arguments)
{
    BOOL bIgnoreInserts = FALSE;
    BOOL bIsVaList = TRUE;
    BOOL bIsLocalAlloced = FALSE;
    LPWSTR lpSourceString = NULL;
    UINT nCount = 0;
    LPWSTR lpReturnString = NULL;
    LPWSTR lpWorkingString = NULL; 
    

    PERF_ENTRY(FormatMessageW);
    ENTRY( "FormatMessageW(dwFlags=%#x, lpSource=%p, dwMessageId=%#x, "
           "dwLanguageId=%#x, lpBuffer=%p, nSize=%u, va_list=%p)\n", 
           dwFlags, lpSource, dwMessageId, dwLanguageId, lpBuffer, nSize,
           Arguments);
    
    /* Sanity checks. */
    if ( dwFlags & FORMAT_MESSAGE_FROM_STRING && !lpSource )
    {
        /* This behavior is different then in Windows.  
           Windows would just crash.*/
        ERROR( "lpSource cannot be NULL.\n" );
        SetLastError( ERROR_INVALID_PARAMETER );
        goto exit;
    }

    if ( !(dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER ) && !lpBuffer )
    {
        /* This behavior is different then in Windows.  
           Windows would just crash.*/
        ERROR( "lpBuffer cannot be NULL, if "
               " FORMAT_MESSAGE_ALLOCATE_BUFFER is not specified.\n" );
        SetLastError( ERROR_INVALID_PARAMETER );
        goto exit;
    }
    
    if ( ( dwFlags & FORMAT_MESSAGE_FROM_STRING ) && 
         ( dwFlags & FORMAT_MESSAGE_FROM_SYSTEM ) )
    {
        ERROR( "These flags cannot co-exist. You can either "
               "specify FORMAT_MESSAGE_FROM_STRING, or "
               "FORMAT_MESSAGE_FROM_SYSTEM.\n" );
        SetLastError( ERROR_INVALID_PARAMETER );
        goto exit;
    }
    
    if ( !( dwFlags & FORMAT_MESSAGE_FROM_STRING ) && 
         ( dwLanguageId != 0
#if ENABLE_DOWNLEVEL_FOR_NLS         
         && dwLanguageId != MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ) 
#endif
         ) )
    {
        ERROR( "Invalid language indentifier.\n" );
        SetLastError( ERROR_RESOURCE_LANG_NOT_FOUND );
        goto exit;
    }

    /* Parameter processing. */
    if ( dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER )
    {
        TRACE( "Allocated %d TCHARs. Don't forget to call LocalFree to "
               "free the memory when done.\n", nSize );
        bIsLocalAlloced = TRUE;
    }
    
    if ( dwFlags & FORMAT_MESSAGE_IGNORE_INSERTS )
    {
        bIgnoreInserts = TRUE;
    }

    if ( dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY )
    {
        if ( !Arguments && !bIgnoreInserts )
        {
            ERROR( "The va_list cannot be NULL.\n" );
            SetLastError( ERROR_INVALID_PARAMETER );
            goto exit;
        }
        else
        {
            bIsVaList = FALSE;
        }
    }
    
    if ( dwFlags & FORMAT_MESSAGE_FROM_STRING )
    {
        lpSourceString = (LPWSTR)lpSource;
    }
    else if ( dwFlags & FORMAT_MESSAGE_FROM_SYSTEM ) 
    {
        if ((dwMessageId & 0xFFFF0000) == 0x80070000)
        {
            // This message has been produced by HRESULT_FROM_WIN32.  Undo its work.
            dwMessageId &= 0xFFFF;
        }

        lpWorkingString = lpReturnString = 
            FMTMSG_GetMessageString( dwMessageId );
        
        if ( !lpWorkingString )
        {
            ERROR( "Unable to find the message %d.\n", dwMessageId );
            SetLastError( ERROR_INTERNAL_ERROR );
            nCount = 0;
            goto exit;
        }

        nCount = PAL_wcslen( lpWorkingString );
        
        if ( !bIsLocalAlloced && nCount > nSize )
        {
            ERROR( "Insufficient buffer.\n" );
            SetLastError( ERROR_INSUFFICIENT_BUFFER );
            lpWorkingString = NULL;
            nCount = 0;
            goto exit;
        }
        if ( !lpWorkingString )
        {
            ERROR( "Invalid error indentifier.\n" );
            SetLastError( ERROR_INVALID_ADDRESS );
        }
        goto exit;
    }
    else
    {
        ERROR( "Unknown flag.\n" );
        SetLastError( ERROR_INVALID_PARAMETER );
        goto exit;
    }

    if ( nSize == 0 && bIsLocalAlloced )
    {
        nSize = 1;
    }

    lpWorkingString = static_cast<WCHAR *>(
        LocalAlloc( LMEM_FIXED, nSize * sizeof( WCHAR ) ) );
    if ( !lpWorkingString )
    {
        ERROR( "Unable to allocate memory for the working string.\n" );
        SetLastError( ERROR_INSUFFICIENT_BUFFER );
        goto exit;
    }


    /* Process the string. */
    lpReturnString = lpWorkingString;
    while ( *lpSourceString )
    {
        if ( *lpSourceString == '%' && !bIgnoreInserts )
        {
            lpSourceString++;
            /* Escape sequences. */
            if ( *lpSourceString == '0' )
            {
                /* Terminates a message without a newline character. */
                *lpWorkingString = '\0';
                goto exit;
            }
            else if ( PAL_iswdigit( *lpSourceString ) )
            {
                /* Get the insert number. */
                WCHAR Number[] = { '\0', '\0', '\0' };
                SIZE_T Index = 0;

                Number[ 0 ] = *lpSourceString;
                lpSourceString++;
                
                if ( PAL_iswdigit( *lpSourceString ) )
                {
                    Number[ 1 ] = *lpSourceString;
                    lpSourceString++;
                    if ( PAL_iswdigit( *lpSourceString ) )
                    {
                        ERROR( "Invalid insert indentifier.\n" );
                        SetLastError( ERROR_INVALID_PARAMETER );
                        lpWorkingString = NULL;
                        nCount = 0;
                        goto exit;
                    }
                }
                Index = FMTMSG__watoi( Number );
                if ( Index == 0 )
                {
                    ERROR( "Invalid insert indentifier.\n" );
                    SetLastError( ERROR_INVALID_PARAMETER );
                    lpWorkingString = NULL;
                    nCount = 0;
                    goto exit;
                }
                if ( *lpSourceString == '!' )
                {
                    LPWSTR lpInsertString = NULL;
                    LPWSTR lpPrintfString = NULL;
                    LPWSTR lpStartOfFormattedString = NULL;
                    UINT nPrintfLength = 0;
                    LPWSTR lpFormattedString = NULL;
                    UINT nFormattedLength = 0;

                    if ( !bIsVaList )
                    {
                        lpInsertString = ((LPWSTR*)Arguments)[ Index - 1 ];
                    }
                    else
                    {
                        va_list TheArgs;
                        
                        va_copy(TheArgs, *Arguments);
                        UINT i = 0;
                        for ( ; i < Index; i++ )
                        {
                            lpInsertString = va_arg( TheArgs, LPWSTR );
                        }
                    }

                    /* Calculate the length, and extract the printf string.*/
                    lpSourceString++;
                    {
                        LPWSTR p = PAL_wcschr( lpSourceString, '!' );

                        if ( NULL == p )
                        {
                            nPrintfLength = 0;
                        }
                        else
                        {
                            nPrintfLength = p - lpSourceString;
                        }
                    }
                                        
                    lpPrintfString = 
                        (LPWSTR)PAL_malloc( ( nPrintfLength + 1 ) * sizeof( WCHAR ) );
                    
                    if ( !lpPrintfString )
                    {
                        ERROR( "Unable to allocate memory.\n" );
                        SetLastError( ERROR_NOT_ENOUGH_MEMORY );
                        lpWorkingString = NULL;
                        nCount = 0;
                        goto exit;
                    }
                    
                    PAL_wcsncpy( lpPrintfString, lpSourceString, nPrintfLength );
                    *( lpPrintfString + nPrintfLength ) = '\0';

                    lpStartOfFormattedString = lpFormattedString = 
                           FMTMSG_ProcessPrintf( *lpPrintfString, 
                                                 lpPrintfString, 
                                                 lpInsertString);

                    if ( !lpFormattedString )
                    {
                        ERROR( "Unable to process the format string.\n" );
                        /* Function will set the error code. */
                        PAL_free( lpPrintfString );
                        lpWorkingString = NULL;
                        goto exit;
                    }
                     

                    nFormattedLength = PAL_wcslen( lpFormattedString );
                    
                    /* Append the processed printf string into the working string */
                    while ( *lpFormattedString )
                    {
                        _CHECKED_ADD_TO_STRING( *lpFormattedString );
                        lpFormattedString++;
                    }
                    
                    lpSourceString += nPrintfLength + 1;
                    PAL_free( lpPrintfString );
                    PAL_free( lpStartOfFormattedString );
                    lpPrintfString = lpFormattedString = NULL;
                }
                else
                {
                    /* The printf format string defaults to 's'.*/
                    LPWSTR lpInsert = NULL;

                    if ( !bIsVaList )
                    {
                        lpInsert = ((LPWSTR*)Arguments)[Index - 1];
                    }
                    else
                    {
                        va_list TheArgs;
                        va_copy(TheArgs, *Arguments);
                        UINT i = 0;
                        for ( ; i < Index; i++ )
                        {
                            lpInsert = va_arg( TheArgs, LPWSTR );
                        }
                    }

                    while ( *lpInsert )
                    {
                        _CHECKED_ADD_TO_STRING( *lpInsert );
                        lpInsert++;
                    }
                }
            }
            /* Format specifiers. */
            else if ( *lpSourceString == '%' )
            {
                _CHECKED_ADD_TO_STRING( '%' );
                lpSourceString++;
            }
            else if ( *lpSourceString == 'n' )
            {
                /* Hard line break. */
                _CHECKED_ADD_TO_STRING( '\n' );
                lpSourceString++;
            }
            else if ( *lpSourceString == '.' )
            {
                _CHECKED_ADD_TO_STRING( '.' );
                lpSourceString++;
            }
            else if ( *lpSourceString == '!' )
            {
                _CHECKED_ADD_TO_STRING( '!' );
                lpSourceString++;
            }
            else if ( !*lpSourceString )
            {
                ERROR( "Invalid parameter.\n" );
                SetLastError( ERROR_INVALID_PARAMETER );
                lpWorkingString = NULL;
                nCount = 0;
                goto exit;
            }
            else /* Append the character. */
            {
                _CHECKED_ADD_TO_STRING( *lpSourceString );
                lpSourceString++;
            }
        }/* END if ( *lpSourceString == '%' ) */
        else
        {
            /* In Windows if FormatMessage is called with ignore inserts,
            then FormatMessage strips %1!s! down to %1, since string is the
            default. */
            if ( bIgnoreInserts && *lpSourceString == '!' && 
                 *( lpSourceString + 1 ) == 's' )
            {
                LPWSTR lpLastBang = PAL_wcschr( lpSourceString + 1, '!' );

                if ( lpLastBang && ( 2 == lpLastBang - lpSourceString ) )
                {
                    lpSourceString = lpLastBang + 1;
                }
                else
                {
                    ERROR( "Mal-formed string\n" );
                    SetLastError( ERROR_INVALID_PARAMETER );
                    lpWorkingString = NULL;
                    nCount = 0;
                    goto exit;
                }
            }
            else
            {
                /* Append to the string. */
                _CHECKED_ADD_TO_STRING( *lpSourceString );
                lpSourceString++;
            }
        }
    }
    
    /* Terminate the message. */
    _CHECKED_ADD_TO_STRING( '\0' );
    /* NULL does not count. */
    nCount--;

exit: /* Function clean-up and exit. */
    if ( lpWorkingString )
    {
        if ( bIsLocalAlloced )
        {
            TRACE( "Assigning the buffer to the pointer.\n" );
            // when FORMAT_MESSAGE_ALLOCATE_BUFFER is specified, nSize
            // does not specify the size of lpBuffer, rather it specifies
            // the minimum size of the string
            // as such we have to blindly assume that lpBuffer has enough space to
            // store PVOID
            // might cause a prefast warning, but there is no good way to suppress it yet
            _ASSERTE(dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER);
            *((LPVOID*)lpBuffer) = (LPVOID)lpReturnString;
        }
        else /* Only delete lpReturnString if the caller has their own buffer.*/
        {
            TRACE( "Copying the string into the buffer.\n" );
            PAL_wcsncpy( lpBuffer, lpReturnString, nCount + 1 );
            LocalFree( lpReturnString );
        }
    }
    else /* Error, something occurred. */
    {
        if ( lpReturnString )
        {
            LocalFree( lpReturnString );
        }
    }
    LOGEXIT( "FormatMessageW returns %d.\n", nCount );
    PERF_EXIT(FormatMessageW);
    return nCount;
}
Example #25
0
BOOL CTortoiseProcApp::InitInstance()
{
	EnableCrashHandler();
	InitializeJumpList();
	CheckUpgrade();
	CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
	CMFCButton::EnableWindowsTheming();

	Gdiplus::GdiplusStartupInput gdiplusStartupInput;
	Gdiplus::GdiplusStartup(&m_gdiplusToken,&gdiplusStartupInput,NULL);

	if(!CheckMsysGitDir())
	{
		UINT ret = CMessageBox::Show(NULL,_T("MSysGit (http://code.google.com/p/msysgit/) not found."),
									_T("TortoiseGit"), 3, IDI_HAND, _T("&Set MSysGit path"), _T("&Goto WebSite"), _T("&Abort"));
		if(ret == 2)
		{
			ShellExecute(NULL, NULL, _T("http://code.google.com/p/msysgit/"), NULL, NULL, SW_SHOW);
		}
		else if(ret == 1)
		{
			// open settings dialog
			CSettings dlg(IDS_PROC_SETTINGS_TITLE);
			dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
			dlg.SetTreeWidth(220);

			dlg.DoModal();
			dlg.HandleRestart();
		}
		return FALSE;
	}

	//set the resource dll for the required language
	CRegDWORD loc = CRegDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033);
	long langId = loc;
	CString langDll;
	CStringA langpath = CStringA(CPathUtils::GetAppParentDirectory());
	langpath += "Languages";
//	bindtextdomain("subversion", (LPCSTR)langpath);
//	bind_textdomain_codeset("subversion", "UTF-8");
	HINSTANCE hInst = NULL;
	do
	{
		langDll.Format(_T("..\\Languages\\TortoiseProc%d.dll"), langId);

		hInst = LoadLibrary(langDll);

		CString sVer = _T(STRPRODUCTVER);
		CString sFileVer = CPathUtils::GetVersionFromFile(langDll);
		if (sFileVer.Compare(sVer)!=0)
		{
			FreeLibrary(hInst);
			hInst = NULL;
		}
		if (hInst != NULL)
		{
			AfxSetResourceHandle(hInst);
		}
		else
		{
			DWORD lid = SUBLANGID(langId);
			lid--;
			if (lid > 0)
			{
				langId = MAKELANGID(PRIMARYLANGID(langId), lid);
			}
			else
				langId = 0;
		}
	} while ((hInst == NULL) && (langId != 0));
	TCHAR buf[6];
	_tcscpy_s(buf, _T("en"));
	langId = loc;
	CString sHelppath;
	sHelppath = this->m_pszHelpFilePath;
	sHelppath = sHelppath.MakeLower();
	// MFC uses a help file with the same name as the application by default,
	// which means we have to change that default to our language specific help files
	sHelppath.Replace(_T("tortoiseproc.chm"), _T("TortoiseGit_en.chm"));
	free((void*)m_pszHelpFilePath);
	m_pszHelpFilePath=_tcsdup(sHelppath);
	sHelppath = CPathUtils::GetAppParentDirectory() + _T("Languages\\TortoiseGit_en.chm");
	do
	{
		CString sLang = _T("_");
		if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf)))
		{
			sLang += buf;
			sHelppath.Replace(_T("_en"), sLang);
			if (PathFileExists(sHelppath))
			{
				free((void*)m_pszHelpFilePath);
				m_pszHelpFilePath=_tcsdup(sHelppath);
				break;
			}
		}
		sHelppath.Replace(sLang, _T("_en"));
		if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf)))
		{
			sLang += _T("_");
			sLang += buf;
			sHelppath.Replace(_T("_en"), sLang);
			if (PathFileExists(sHelppath))
			{
				free((void*)m_pszHelpFilePath);
				m_pszHelpFilePath=_tcsdup(sHelppath);
				break;
			}
		}
		sHelppath.Replace(sLang, _T("_en"));

		DWORD lid = SUBLANGID(langId);
		lid--;
		if (lid > 0)
		{
			langId = MAKELANGID(PRIMARYLANGID(langId), lid);
		}
		else
			langId = 0;
	} while (langId);
	setlocale(LC_ALL, "");

	// 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.

	INITCOMMONCONTROLSEX used = {
		sizeof(INITCOMMONCONTROLSEX),
			ICC_ANIMATE_CLASS | ICC_BAR_CLASSES | ICC_COOL_CLASSES | ICC_DATE_CLASSES |
			ICC_HOTKEY_CLASS | ICC_INTERNET_CLASSES | ICC_LISTVIEW_CLASSES |
			ICC_NATIVEFNTCTL_CLASS | ICC_PAGESCROLLER_CLASS | ICC_PROGRESS_CLASS |
			ICC_TAB_CLASSES | ICC_TREEVIEW_CLASSES | ICC_UPDOWN_CLASS |
			ICC_USEREX_CLASSES | ICC_WIN95_CLASSES
	};
	InitCommonControlsEx(&used);
	AfxOleInit();
	AfxEnableControlContainer();
	AfxInitRichEdit2();
	CWinAppEx::InitInstance();
	SetRegistryKey(_T("TortoiseGit"));

	CCmdLineParser parser(AfxGetApp()->m_lpCmdLine);

	// if HKCU\Software\TortoiseGit\Debug is not 0, show our command line
	// in a message box
	if (CRegDWORD(_T("Software\\TortoiseGit\\Debug"), FALSE)==TRUE)
		AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION);

	if ( parser.HasKey(_T("path")) && parser.HasKey(_T("pathfile")))
	{
		CMessageBox::Show(NULL, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR);
		return FALSE;
	}

	CTGitPath cmdLinePath;
	CTGitPathList pathList;
	if ( parser.HasKey(_T("pathfile")) )
	{

		CString sPathfileArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("pathfile")));

		cmdLinePath.SetFromUnknown(sPathfileArgument);
		if (pathList.LoadFromFile(cmdLinePath)==false)
			return FALSE;		// no path specified!
		if ( parser.HasKey(_T("deletepathfile")) )
		{
			// We can delete the temporary path file, now that we've loaded it
			::DeleteFile(cmdLinePath.GetWinPath());
		}
		// This was a path to a temporary file - it's got no meaning now, and
		// anybody who uses it again is in for a problem...
		cmdLinePath.Reset();

	}
	else
	{

		CString sPathArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("path")));
		int asterisk = sPathArgument.Find('*');
		cmdLinePath.SetFromUnknown(asterisk >= 0 ? sPathArgument.Left(asterisk) : sPathArgument);
		pathList.LoadFromAsteriskSeparatedString(sPathArgument);
	}

	if (pathList.GetCount() == 0) {
		pathList.AddPath(CTGitPath::CTGitPath(g_Git.m_CurrentDir));
	}

	hWndExplorer = NULL;
	CString sVal = parser.GetVal(_T("hwnd"));
	if (!sVal.IsEmpty())
		hWndExplorer = (HWND)_ttoi64(sVal);

	while (GetParent(hWndExplorer)!=NULL)
		hWndExplorer = GetParent(hWndExplorer);
	if (!IsWindow(hWndExplorer))
	{
		hWndExplorer = NULL;
	}

	// Subversion sometimes writes temp files to the current directory!
	// Since TSVN doesn't need a specific CWD anyway, we just set it
	// to the users temp folder: that way, Subversion is guaranteed to
	// have write access to the CWD
	{
		DWORD len = GetCurrentDirectory(0, NULL);
		if (len)
		{
			TCHAR * originalCurrentDirectory = new TCHAR[len];
			if (GetCurrentDirectory(len, originalCurrentDirectory))
			{
				//sOrigCWD = originalCurrentDirectory;
				//sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD);
			}
			delete [] originalCurrentDirectory;
		}
		TCHAR pathbuf[MAX_PATH];
		GetTempPath(MAX_PATH, pathbuf);
		SetCurrentDirectory(pathbuf);
	}

	// check for newer versions
	if (CRegDWORD(_T("Software\\TortoiseGit\\CheckNewer"), TRUE) != FALSE)
	{
		time_t now;
		struct tm ptm;

		time(&now);
		if ((now != 0) && (localtime_s(&ptm, &now)==0))
		{
			int week = 0;
			// we don't calculate the real 'week of the year' here
			// because just to decide if we should check for an update
			// that's not needed.
			week = ptm.tm_yday / 7;

			CRegDWORD oldweek = CRegDWORD(_T("Software\\TortoiseGit\\CheckNewerWeek"), (DWORD)-1);
			if (((DWORD)oldweek) == -1)
				oldweek = week;		// first start of TortoiseProc, no update check needed
			else
			{
				if ((DWORD)week != oldweek)
				{
					oldweek = week;

					TCHAR com[MAX_PATH+100];
					GetModuleFileName(NULL, com, MAX_PATH);
					_tcscat_s(com, MAX_PATH+100, _T(" /command:updatecheck"));

					CAppUtils::LaunchApplication(com, 0, false);
				}
			}
		}
	}

	if (parser.HasVal(_T("configdir")))
	{
		// the user can override the location of the Subversion config directory here
		CString sConfigDir = parser.GetVal(_T("configdir"));
//		g_GitGlobal.SetConfigDir(sConfigDir);
	}
	// to avoid that SASL will look for and load its plugin dlls all around the
	// system, we set the path here.
	// Note that SASL doesn't have to be initialized yet for this to work
//	sasl_set_path(SASL_PATH_TYPE_PLUGIN, (LPSTR)(LPCSTR)CUnicodeUtils::GetUTF8(CPathUtils::GetAppDirectory().TrimRight('\\')));

	HANDLE TSVNMutex = ::CreateMutex(NULL, FALSE, _T("TortoiseGitProc.exe"));
	if(!g_Git.SetCurrentDir(cmdLinePath.GetWinPathString()))
	{
		int i=0;
		for(i=0;i<pathList.GetCount();i++)
			if(g_Git.SetCurrentDir(pathList[i].GetWinPath()))
				break;
	}

	if(!g_Git.m_CurrentDir.IsEmpty())
		SetCurrentDirectory(g_Git.m_CurrentDir);

	{
		CString err;
		try
		{
			// requires CWD to be set
			CGit::m_LogEncode = CAppUtils::GetLogOutputEncode();
		}
		catch (char* msg)
		{
			err = CString(msg);
		}

		if (!err.IsEmpty())
		{
			UINT choice = CMessageBox::Show(hWndExplorer, err, _T("TortoiseGit Error"), 1, IDI_ERROR, _T("&Edit .git/config"), _T("Edit &global .gitconfig"), _T("&Abort"));
			if (choice == 1)
			{
				// open the config file with alternative editor
				CString path = g_Git.m_CurrentDir;
				path += _T("\\.git\\config");
				CAppUtils::LaunchAlternativeEditor(path);
			}
			else if (choice == 2)
			{
				// open the global config file with alternative editor
				TCHAR buf[MAX_PATH];
				ExpandEnvironmentStrings(_T("%HOMEDRIVE%\\%HOMEPATH%\\.gitconfig"), buf, MAX_PATH);
				CAppUtils::LaunchAlternativeEditor(buf);
			}
			return FALSE;
		}
	}

	// execute the requested command
	CommandServer server;
	Command * cmd = server.GetCommand(parser.GetVal(_T("command")));
	if (cmd)
	{
		cmd->SetExplorerHwnd(hWndExplorer);

		cmd->SetParser(parser);
		cmd->SetPaths(pathList, cmdLinePath);

		retSuccess = cmd->Execute();
		delete cmd;
	}

	if (TSVNMutex)
		::CloseHandle(TSVNMutex);

	// Look for temporary files left around by TortoiseSVN and
	// remove them. But only delete 'old' files because some
	// apps might still be needing the recent ones.
	{
		DWORD len = ::GetTempPath(0, NULL);
		TCHAR * path = new TCHAR[len + 100];
		len = ::GetTempPath (len+100, path);
		if (len != 0)
		{
			CSimpleFileFind finder = CSimpleFileFind(path, _T("*svn*.*"));
			FILETIME systime_;
			::GetSystemTimeAsFileTime(&systime_);
			__int64 systime = (((_int64)systime_.dwHighDateTime)<<32) | ((__int64)systime_.dwLowDateTime);
			while (finder.FindNextFileNoDirectories())
			{
				CString filepath = finder.GetFilePath();
				HANDLE hFile = ::CreateFile(filepath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
				if (hFile != INVALID_HANDLE_VALUE)
				{
					FILETIME createtime_;
					if (::GetFileTime(hFile, &createtime_, NULL, NULL))
					{
						::CloseHandle(hFile);
						__int64 createtime = (((_int64)createtime_.dwHighDateTime)<<32) | ((__int64)createtime_.dwLowDateTime);
						if ((createtime + 864000000000) < systime)		//only delete files older than a day
						{
							::SetFileAttributes(filepath, FILE_ATTRIBUTE_NORMAL);
							::DeleteFile(filepath);
						}
					}
					else
						::CloseHandle(hFile);
				}
			}
		}
		delete[] path;
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	// application, rather than start the application's message pump.
	return FALSE;
}
Example #26
0
BOOL CALLBACK EnumLocalesProcA( LPSTR lpLocaleStringA )
{
    struct EnumLocalesParams * params;

    LCID  localeId;
    LPSTR pszEndA;

    WCHAR langCode[ELP_LANGUAGE_FIELD_LENGTH];

    /* convert hex-string to LCID */
    localeId = strtol( lpLocaleStringA, &pszEndA, 16 );

    /* check params received via TLS */
    params = (struct EnumLocalesParams *) TlsGetValue( g_dwTLSLocaleEncId );
    if( NULL == params || '\0' == params->Language[0] )
        return FALSE;

    /*
        get the ISO language code for this locale

        remember: we call the GetLocaleInfoW function
        because the ansi version of this function returns
        an error under WinNT/2000 when called with an
        unicode only lcid
    */
    if( GetLocaleInfo( localeId, LOCALE_SISO639LANGNAME , langCode, ELP_LANGUAGE_FIELD_LENGTH ) )
    {
        WCHAR ctryCode[ELP_COUNTRY_FIELD_LENGTH];

        /* continue if language code does not match */
        if( 0 != wcscmp( langCode, params->Language ) )
            return TRUE;

        /* check if country code is set and equals the current locale */
        if( '\0' != params->Country[0] && GetLocaleInfo( localeId,
                    LOCALE_SISO3166CTRYNAME , ctryCode, ELP_COUNTRY_FIELD_LENGTH ) )
        {
            /* save return value in TLS and break if  found desired locale */
            if( 0 == wcscmp( ctryCode, params->Country ) )
            {
                params->Locale = localeId;
                return FALSE;
            }
        }
        else
        {
            /* fill with default values for that language */
            LANGID langId = LANGIDFROMLCID( localeId );

            /* exchange sublanguage with SUBLANG_NEUTRAL */
            langId = MAKELANGID( PRIMARYLANGID( langId ), SUBLANG_NEUTRAL );

            /* and use default sorting order */
            params->Locale = MAKELCID( langId, SORT_DEFAULT );

            return FALSE;
        }
    }

    /* retry by going on */
    return TRUE;
}
Example #27
0
void init_gettext(const char *path, const std::string &configured_language, int argc, char** argv) {
#else
void init_gettext(const char *path, const std::string &configured_language) {
#endif
#if USE_GETTEXT
	/** first try to set user override environment **/
	if (configured_language.length() != 0) {
#ifndef _WIN32
		/* add user specified locale to environment */
		setenv("LANGUAGE", configured_language.c_str(), 1);

		/* reload locale with changed environment */
		setlocale(LC_ALL, "");
#elif defined(_MSC_VER)
		std::string current_language_var("");
		if (getenv("LANGUAGE") != 0) {
			current_language_var = std::string(getenv("LANGUAGE"));
		}

		char *lang_str = (char*)calloc(10 + configured_language.length(), sizeof(char));
		strcat(lang_str, "LANGUAGE=");
		strcat(lang_str, configured_language.c_str());
		putenv(lang_str);

		SetEnvironmentVariableA("LANGUAGE",configured_language.c_str());

#ifndef SERVER
		//very very dirty workaround to force gettext to see the right environment
		if (current_language_var != configured_language) {
			STARTUPINFO startupinfo;
			PROCESS_INFORMATION processinfo;
			memset(&startupinfo,0,sizeof(startupinfo));
			memset(&processinfo,0,sizeof(processinfo));
			errorstream << "MSVC localization workaround active restating minetest in new environment!" << std::endl;

			std::string parameters = "";

			for (unsigned int i=1;i < argc; i++) {
				if (parameters != "") {
					parameters += " ";
				}
				parameters += argv[i];
			}

			const char* ptr_parameters = 0;

			if (parameters != "") {
				ptr_parameters = parameters.c_str();
			}
			
			/** users may start by short name in commandline without extention **/
			std::string appname = argv[0];
			if (appname.substr(appname.length() -4) != ".exe") {
				appname += ".exe";
			}

			if (!CreateProcess(appname.c_str(),
					(char*) ptr_parameters,
					NULL,
					NULL,
					false,
					DETACHED_PROCESS | CREATE_UNICODE_ENVIRONMENT,
					NULL,
					NULL,
					&startupinfo,
					&processinfo)) {
				char buffer[1024];		
				FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
					NULL,
					GetLastError(),
					MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
					buffer,
					sizeof(buffer)-1,
					NULL);
				errorstream << "*******************************************************" << std::endl;
				errorstream << "CMD: " << appname << std::endl;
				errorstream << "Failed to restart with current locale: " << std::endl;
				errorstream << buffer;
				errorstream << "Expect language to be broken!" << std::endl;
				errorstream << "*******************************************************" << std::endl;
			}
			else {
				exit(0);
			}
#else
			errorstream << "*******************************************************" << std::endl;
			errorstream << "Can't apply locale workaround for server!" << std::endl;
			errorstream << "Expect language to be broken!" << std::endl;
			errorstream << "*******************************************************" << std::endl;

#endif
		}

		setlocale(LC_ALL,configured_language.c_str());
#else // Mingw
		char *lang_str = (char*)calloc(10 + configured_language.length(), sizeof(char));
		strcat(lang_str, "LANGUAGE=");
		strcat(lang_str, configured_language.c_str());
		putenv(lang_str);

		setlocale(LC_ALL, "");
#endif // ifndef _WIN32
	}
	else {
		 /* set current system default locale */
		setlocale(LC_ALL, "");
	}

#if defined(_WIN32)
	if (getenv("LANGUAGE") != 0) {
		setlocale(LC_ALL, getenv("LANGUAGE"));
	}
#ifdef _MSC_VER
	else if (getenv("LANG") != 0) {
		setlocale(LC_ALL, getenv("LANG"));
	}
#endif
#endif

	bindtextdomain(PROJECT_NAME, path);
	textdomain(PROJECT_NAME);

#if defined(_WIN32)
	// Set character encoding for Win32
	char *tdomain = textdomain( (char *) NULL );
	if( tdomain == NULL )
	{
		errorstream << "Warning: domainname parameter is the null pointer" <<
				", default domain is not set" << std::endl;
		tdomain = (char *) "messages";
	}
	/* char *codeset = */bind_textdomain_codeset( tdomain, "UTF-8" );
	//errorstream << "Gettext debug: domainname = " << tdomain << "; codeset = "<< codeset << std::endl;
#endif // defined(_WIN32)

#else
	/* set current system default locale */
	setlocale(LC_ALL, "");
#endif // if USE_GETTEXT

	/* no matter what locale is used we need number format to be "C" */
	/* to ensure formspec parameters are evaluated correct!          */

	setlocale(LC_NUMERIC,"C");
	infostream << "Message locale is now set to: "
			<< setlocale(LC_ALL, 0) << std::endl;
}
Example #28
0
		CMMapIndexInput::CMMapIndexInput(const tchar* filename)
			:m_nPos(0)
			,m_pData(NULL)
		{			

#ifdef WIN32
			m_hMap = NULL;
			m_hFile = CreateFile(filename,GENERIC_READ,FILE_SHARE_READ, 0,OPEN_EXISTING,0,0);
			
			if (m_hFile < 0)
			{
				DWORD err = GetLastError();
				if ( err == ERROR_FILE_NOT_FOUND )
					FIRTEX_THROW3(FILEIO_ERROR, _T("File does not exist"));
				else if ( err == EACCES )
					FIRTEX_THROW3(FILEIO_ERROR,_T("File Access denied"));
				else if ( err == ERROR_TOO_MANY_OPEN_FILES )
					FIRTEX_THROW3(FILEIO_ERROR,_T("Too many open files"));
				else
					FIRTEX_THROW3(FILEIO_ERROR, _T("File IO Error"));
			}

			DWORD nHigh = 0;
			m_length = GetFileSize(m_hFile,&nHigh);
			if(nHigh > 0)
				m_length |= (nHigh<<32);

			if ( m_length > 0 )
			{
				m_hMap = CreateFileMapping(m_hFile,NULL,PAGE_READONLY,0,0,NULL);
				if (m_hMap != NULL )
				{
					void* address = MapViewOfFile(m_hMap,FILE_MAP_READ,0,0,0);
					if ( address != NULL )
					{
						m_pData = (uint8_t*)address;
						return; ///OK!
					}
				}
				CloseHandle(m_hMap);

				tchar* lpMsgBuf = 0;
				DWORD dw = GetLastError(); 

				FormatMessage(
					FORMAT_MESSAGE_ALLOCATE_BUFFER | 
					FORMAT_MESSAGE_FROM_SYSTEM,
					NULL,
					dw,
					MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
					lpMsgBuf,
					0, NULL );

				tchar* errstr = new tchar[_tcslen(lpMsgBuf) + 40];
				_stprintf(errstr, _T("MMapIndexInput::MMapIndexInput failed with error %d: %s"), dw, lpMsgBuf); 
				LocalFree(lpMsgBuf);

				FIRTEX_THROW3(FILEIO_ERROR,errstr);
			}

#else //WIN32

			m_hFile = ::fileOpen(filename, O_BINARY | O_RDONLY | O_RANDOM | O_LARGEFILE, _S_IREAD );

			if (m_hFile < 0)
			{
				int err = errno;
				tstring sFileName = filename;
				if ( err == ENOENT )
					FIRTEX_THROW3(FILEIO_ERROR,"File does not exist: " + sFileName);
				else if ( err == EACCES )
					FIRTEX_THROW3(FILEIO_ERROR,"File Access denied: " + sFileName);
				else if ( err == EMFILE )
					FIRTEX_THROW3(FILEIO_ERROR,"Too many open files: " + sFileName);
			}				
			else 
			{
				m_length = fileSize(m_hFile);			
				void* address = ::mmap(0, m_length, PROT_READ, MAP_SHARED, m_hFile, 0);
				if (address == MAP_FAILED)
				{
					FIRTEX_THROW3(FILEIO_ERROR,_T("Map failed."));
				}
				else
				{
					m_pData = (uint8_t*)address;
				}			
			}
#endif
			m_filename = filename;
		}
Example #29
0
extern "C" LCID WINAPI dllGetThreadLocale(void)
{
  // primary language identifier, sublanguage identifier, sorting identifier
  return MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT);
}
Example #30
0
bool Win32DllLoader::Load()
{
  if (m_dllHandle != NULL)
    return true;

  std::string strFileName = GetFileName();

  std::wstring strDllW;
  g_charsetConverter.utf8ToW(CSpecialProtocol::TranslatePath(strFileName), strDllW, false, false, false);
  m_dllHandle = LoadLibraryExW(strDllW.c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
  if (!m_dllHandle)
  {
    DWORD dw = GetLastError(); 
    wchar_t* lpMsgBuf = NULL;
    DWORD strLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPWSTR)&lpMsgBuf, 0, NULL);
    if (strLen == 0)
      strLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), (LPWSTR)&lpMsgBuf, 0, NULL);

    if (strLen != 0)
    {
      std::string strMessage;
      g_charsetConverter.wToUTF8(std::wstring(lpMsgBuf, strLen), strMessage);
      CLog::Log(LOGERROR, "%s: Failed to load \"%s\" with error %lu: \"%s\"", __FUNCTION__, CSpecialProtocol::TranslatePath(strFileName).c_str(), dw, strMessage.c_str());
    }
    else
      CLog::Log(LOGERROR, "%s: Failed to load \"%s\" with error %lu", __FUNCTION__, CSpecialProtocol::TranslatePath(strFileName).c_str(), dw);
    
    LocalFree(lpMsgBuf);
    return false;
  }

  // handle functions that the dll imports
  if (NeedsHooking(strFileName.c_str()))
    OverrideImports(strFileName);
  else
    bIsSystemDll = true;

  return true;
}