예제 #1
0
bool ConsolePlan::removeSpot(float angle, Plane2DCoordinate coordinate)
{
    QString str;
    if (m_planeSpots.contains(angle))
    {
        QList<Plane2DCoordinate> coordinates = m_planeSpots.value(angle);
        int i = containSpot(coordinates,coordinate);
        if (i >= 0)
        {
            coordinates.removeAt(i);
            if (coordinates.size() == 0)
            {
                m_planeSpots.remove(angle);
            }else
            {
                m_planeSpots.insert(angle,coordinates);
            }

            str = printLastAction(RemoveSpot) + printLastError(NoError);
            qCDebug(PlanGenerator()) << PlanGenerator().categoryName() << str;
            return true;
        }else
        {
            str = printLastAction(RemoveSpot) + printLastError(ErrorPlaneNoSuchSpot);
            qCDebug(PlanGenerator()) << PlanGenerator().categoryName() << str;
            return false;
        }
    }else
    {
        str = printLastAction(RemoveSpot) + printLastError(ErrorNoSuchPlane);
        qCWarning(PlanGenerator()) << PlanGenerator().categoryName() << str;
        emit error(ErrorNoSuchPlane);
        return false;
    }
}
예제 #2
0
bool ConsolePlan::addSpot(float angle, Plane2DCoordinate coordinate)
{
    QString str;
    if (m_planeSpots.contains(angle))
    {
        QList<Plane2DCoordinate> coordinates = m_planeSpots.value(angle);
        if (containSpot(coordinates,coordinate) >= 0)
        {
            str = printLastAction(AddSpot) + printLastError(ErrorSuchSpotExists);
            qCWarning(PlanGenerator()) << PlanGenerator().categoryName() << str;
            return false;
        }else
        {
            coordinates.append(coordinate);
            m_planeSpots.insert(angle,coordinates);
            str = printLastAction(AddSpot) + printLastError(NoError);
            qCDebug(PlanGenerator()) << PlanGenerator().categoryName() << str;
            return true;
        }
    }else
    {
        str = printLastAction(AddSpot) + printLastError(ErrorNoSuchPlane);
        qCWarning(PlanGenerator()) << PlanGenerator().categoryName() << str;
        emit error(ErrorNoSuchPlane);
        return false;
    }
}
예제 #3
0
bool ConsolePlan::addSpots(float angle, QList<Plane2DCoordinate> coordinates)
{
    QString str;
    if (m_planeSpots.contains(angle))
    {

        QList<Plane2DCoordinate> planeSpots = m_planeSpots.value(angle);
        for (int i = 0;i < coordinates.size();i++)
        {
            if (containSpot(planeSpots,coordinates.at(i)) >= 0)
            {
                str = printLastAction(AddSpot) + printLastError(ErrorSuchSpotExists);
                qCWarning(PlanGenerator()) << PlanGenerator().categoryName() << str;
                return false;
            }
        }
        for (int i = 0;i < coordinates.size();i++)
        {
            addSpot(angle,coordinates.at(i));
        }

        str = printLastAction(AddSpot) + printLastError(NoError);
        qCDebug(PlanGenerator()) << PlanGenerator().categoryName() << str;
        return true;
    }else
    {
        str = printLastAction(AddSpot) + printLastError(ErrorNoSuchPlane);
        qCWarning(PlanGenerator()) << PlanGenerator().categoryName() << str;
        emit error(ErrorNoSuchPlane);
        return false;
    }
}
예제 #4
0
    // バイトコードがメモリにロードされた直後のコールバック。
    // 対応するDLLがあればロードする
    static void cb4dll(const char* hybPath)
    {
        int len = HMD_STRLEN(hybPath);
        char* dllPath = (char*)HMD_ALLOCA(len + sizeof(dll_prefix)+sizeof(dll_ext));
        char* q = dllPath;
        char* q2 = q;

        const unsigned char* p = _mbsrchr((const unsigned char*)hybPath, PATH_DELIM);
        if (p == NULL) {
            p = (const unsigned char*)hybPath;
        } else {
            p += 1;
            size_t lp = p - (const unsigned char*)hybPath;
            memcpy(q, hybPath, lp);
            q += lp;
            q2 = q;
        }
        // pはhybPathのファイル名部分の先頭アドレス
        const unsigned char* p2 = _mbsstr((const unsigned char*)p, (const unsigned char*)".hyb");
        if ((p2 <= p) || (p2 >= (const unsigned char*)hybPath + len)) {
            p2 = (const unsigned char*)hybPath + len;
        }
        // p2は拡張子を抜いたファイル名部分の末尾アドレス

        memcpy(q, dll_prefix, sizeof(dll_prefix));
        q += sizeof(dll_prefix) - 1;
        size_t lp2 = p2 - p;
        memcpy(q, p, lp2);
        q += lp2;
        memcpy(q, dll_ext, sizeof(dll_ext));
        q += sizeof(dll_ext) - 1;
        *q = '\0';

#ifdef VERBOSE_LOAD_DLL
        HMD_PRINTF("try load dll: %s\n", dllPath);
#endif
		HMODULE hmod = LoadLibraryMB(dllPath);    // dllロード
#ifdef VERBOSE_LOAD_DLL
        if (hmod == NULL) printLastError();
#endif        
        if (hmod == NULL && q2 != dllPath) {
            // パス抜きのファイル名だけでロードしてみる
#ifdef VERBOSE_LOAD_DLL
            HMD_PRINTF("try load dll: %s\n", q2);
#endif        
            hmod = LoadLibraryMB(q2);
#ifdef VERBOSE_LOAD_DLL
            if (hmod == NULL) printLastError();
#endif        
        }

        if (hmod != NULL) {
            dllHandleArr.add(hmod);
#ifdef VERBOSE_LOAD_DLL
            HMD_PRINTF("DLL '%s' loaded.\n", q2);
#endif
        }
    }
예제 #5
0
/*********************************************************************************
 * Name        : writeFileSignature                                              *
 * Developer   : Kuzmenko_AN                                                     *
 * Description : write up information about finding files at temp                *
 * @param      : TEMP FILE HANDLE           ( HANDLE )                           *
 * @param      : POINTER TO WIN32_FIND_DATA ( LPWIN32_FIND_DATA )                *
 * @return     : -1 invalid parameters or 0 - success                            *
 *********************************************************************************/
int writeFileSignatureAtFile( HANDLE tmpHndl , LPWIN32_FIND_DATA lpwin32FD ){
    DWORD  dwWrittenBytes , dwReadBytes;
    UINT32 u32FileDigestSignature;
    TCHAR  digSigBiffer[_BUFFER_SIZE_] = L"<FILE> : ";

    if( tmpHndl == INVALID_HANDLE_VALUE || lpwin32FD == nullptr ){
        return -1;
    }

    // get a digest for file and create a record into temp file
    u32FileDigestSignature = getFileDigestSignature( lpwin32FD );
    
    // some conversion from int to wchar_t
    std::wstringstream wss;
    std::wstring wcs;
    wss << u32FileDigestSignature;
    wss >> wcs;
    LPCTSTR result = wcs.c_str();
    
    //std::wcout << u32FileDigestSignature << std::endl;

    digestSignatureMap.insert(std::pair<std::wstring , UINT32>(lpwin32FD->cFileName ,u32FileDigestSignature));
     
    wcsncat( digSigBiffer , result  , sizeof(u32FileDigestSignature)*sizeof(UINT32) );
    wcsncat( digSigBiffer , L" : " , wcslen(L" : ")*sizeof(wchar_t) );
    wcsncat( digSigBiffer , lpwin32FD->cFileName , wcslen(lpwin32FD->cFileName)*sizeof(wchar_t) );

    if( !WriteFile( tmpHndl , digSigBiffer , wcslen(digSigBiffer)*sizeof(wchar_t) , &dwWrittenBytes , NULL ) ){
        printLastError( _T("Cannot write at file") );
        return -1;
    }
    WriteFile( tmpHndl , L"\r\n" , sizeof(wchar_t) * 2 , &dwWrittenBytes , NULL );
    return 0;
}
예제 #6
0
int asyncFileClose(AsyncFile *f) {
  /* Close the given asynchronous file. */

  AsyncFileState *state;

  if (!asyncFileValid(f)) return 0;  /* already closed */
  state = (AsyncFileState*) f->state;
  if(!CloseHandle(state->hFile)) {
    printLastError(TEXT("AsyncFileClose failed"));
    success(false);
  }
  state->hFile = INVALID_HANDLE_VALUE;
  SetEvent(state->hEvent);
  WaitForSingleObject(state->hThread, 5000);
  if(state->hThread) {
    warnPrintf(TEXT("Terminating async thread"));
    TerminateThread(state->hThread,0);
  }
  CloseHandle(state->hEvent);
  if (state->bufferPtr != NULL) asyncFree(state->bufferPtr);
  free((void *) f->state);
  f->state = NULL;
  f->sessionID = 0;
  return 1;
}
예제 #7
0
jint
transport_receivePacket(jdwpPacket *packet)
{
    jdwpTransportError err;

    err = (*transport)->ReadPacket(transport, packet);
    if (err != JDWPTRANSPORT_ERROR_NONE) {
        /*
         * If transport has been closed return EOF
         */
        if (!(*transport)->IsOpen(transport)) {
            packet->type.cmd.len = 0;
            return 0;
        }

        printLastError(transport, err);

        /*
         * Users of transport_receivePacket expect 0 for success,
         * non-0 otherwise.
         */
        return (jint)-1;
    }
    return 0;
}
예제 #8
0
/*********************************************************************************
 * Name        : initDigestSignatureMap                                          *
 * Developer   : Kuzmenko_AN                                                     *
 * Description : init a digest signature for each file                           *
 * @param      : SEARCH HANDLE              ( HANDLE )                           *
 * @param      : TEMP FILE HANDLE           ( HANDLE )                           *
 * @param      : POINTER TO WIN32_FIND_DATA ( LPWIN32_FIND_DATA )                *
 * @param      : pattern for search         ( LPCTSTR )                          *
 * @return     : VOID                                                            *
 *********************************************************************************/
 void initDigestSignatureMap( HANDLE sHndl , HANDLE tmpHndl , LPWIN32_FIND_DATA lpwin32FD , LPCTSTR searchPattern ){
    static short unsigned int tabs = 0;     // tabs for formatting console output
    
    sHndl = FindFirstFile( searchPattern , lpwin32FD );
    do{
        if( wcscmp( lpwin32FD->cFileName , L"." ) == 0  || 
            wcscmp( lpwin32FD->cFileName , L".." ) == 0 || 
            wcscmp( lpwin32FD->cFileName , _FILE_INFO_ ) ==0   ) continue;

        if( lpwin32FD->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ){
            //std::wcout << _T("<DIRECTORY> : ") << lpwin32FD->cFileName << std::endl;
            SetCurrentDirectory( lpwin32FD->cFileName ); 
            tabs = tabs + 5;
            initDigestSignatureMap( sHndl , tmpHndl , lpwin32FD , searchPattern );
            tabs = tabs - 5;
            SetCurrentDirectory( _T("..") );
        }
        else{
            //std::wcout << std::setw(tabs) << " " << _T("<FILE> : ") << lpwin32FD->cFileName << std::endl;
            if( -1 == writeFileSignatureAtFile( tmpHndl , lpwin32FD ) ){
                printLastError( _T("Writing Operations is fault") );
                return;
            }
        }
    }while( FindNextFile( sHndl , lpwin32FD ) );
 }
예제 #9
0
static void JNICALL
acceptThread(jvmtiEnv* jvmti_env, JNIEnv* jni_env, void* arg)
{
    TransportInfo *info;
    jdwpTransportEnv *t;
    jdwpTransportError rc;

    LOG_MISC(("Begin accept thread"));

    info = (TransportInfo*)(void*)arg;
    t = info->transport;

    rc = (*t)->Accept(t, info->timeout, 0);

    /* System property no longer needed */
    setTransportProperty(jni_env, NULL);

    if (rc != JDWPTRANSPORT_ERROR_NONE) {
        /*
         * If accept fails it probably means a timeout, or another fatal error
         * We thus exit the VM after stopping the listener.
         */
        printLastError(t, rc);
        (*t)->StopListening(t);
        EXIT_ERROR(JVMTI_ERROR_NONE, "could not connect, timeout or fatal error");
    } else {
        (*t)->StopListening(t);
        connectionInitiated(t);
    }

    LOG_MISC(("End accept thread"));
}
예제 #10
0
jint
transport_sendPacket(jdwpPacket *packet)
{
    jdwpTransportError err = JDWPTRANSPORT_ERROR_NONE;
    jint rc = 0;

    if (transport != NULL) {
        if ( (*transport)->IsOpen(transport) ) {
            debugMonitorEnter(sendLock);
            err = (*transport)->WritePacket(transport, packet);
            debugMonitorExit(sendLock);
        }
        if (err != JDWPTRANSPORT_ERROR_NONE) {
            if ((*transport)->IsOpen(transport)) {
                printLastError(transport, err);
            }

            /*
             * The users of transport_sendPacket except 0 for
             * success; non-0 otherwise.
             */
            rc = (jint)-1;
        }

    } /* else, bit bucket */

    return rc;
}
예제 #11
0
bool InstallCommand::installService()
{
	bool installed = false;

	if (createService(*serviceParameters))
	{
		// successful installation, output result information

		const char* startType = serviceParameters->isAutoStart() ? "automatic" : "manual";

		if (serviceParameters->getDependency() == NULL)
		{
			cout << "The " << getServiceName() << " " << startType << " service was successfully installed" << endl;
		}
		else
		{
			cout << "The " << getServiceName() << " " << startType << " service was successfully installed, depends on "
				 << serviceParameters->getDependency() << " service." << endl;
		}

		installed = true;
	}
	else
	{
		cerr << "Error attempting to install the " << getServiceName() << " service" << endl;
		printLastError();
	}


	return installed;

}
예제 #12
0
bool ConsolePlan::removePlane(float angle)
{
    QString str;
    if (m_planeSpots.contains(angle))
    {
        m_planeSpots.remove(angle);
        str = printLastAction(RemovePlane) + printLastError(NoError);
        qCDebug(PlanGenerator()) << PlanGenerator().categoryName() << str;
        return true;
    }else
    {
        emit error(ErrorNoSuchPlane);
        str = printLastAction(RemovePlane) + printLastError(ErrorNoSuchPlane);
        qCWarning(PlanGenerator()) << PlanGenerator().categoryName() << str;
        return false;
    }
}
예제 #13
0
bool ConsolePlan::addPlane(float angle, QList<Plane2DCoordinate> coordinates)
{
    QString str;
    if (m_planeSpots.contains(angle))
    {
        //  overwrite the existed plane
        m_planeSpots.insert(angle,coordinates);
        str = printLastAction(AddPlane) + printLastError(ErrorOverwriteExistingPlane);
        qCWarning(PlanGenerator()) << PlanGenerator().categoryName() << str;
        return false;
    }else
    {
        m_planeSpots.insert(angle,coordinates);
        str = printLastAction(AddPlane) + printLastError(NoError);
        qCDebug(PlanGenerator()) << PlanGenerator().categoryName() << str;
        return true;
    }
}
예제 #14
0
/*
 *----------------------------------------------------------------------
 *
 * OS_Accept --
 *
 *  Accepts a new FastCGI connection.  This routine knows whether
 *  we're dealing with TCP based sockets or NT Named Pipes for IPC.
 *
 *  fail_on_intr is ignored in the Win lib.
 *
 * Results:
 *      -1 if the operation fails, otherwise this is a valid IPC fd.
 *
 *----------------------------------------------------------------------
 */
int OS_Accept(int listen_sock, int fail_on_intr, const char *webServerAddrs)
{
    int ipcFd = -1;

    // Touch args to prevent warnings
    listen_sock = 0; fail_on_intr = 0;

    // @todo Muliple listen sockets and sockets other than 0 are not
    // supported due to the use of globals.

    if (shutdownPending) 
    {
        OS_LibShutdown();
        return -1;
    }

    // The mutex is to keep other processes (and threads, when supported)
    // from going into the accept cycle.  The accept cycle needs to
    // periodically break out to check the state of the shutdown flag
    // and there's no point to having more than one thread do that.
    
    if (acceptMutex != INVALID_HANDLE_VALUE) 
    {
        if (WaitForSingleObject(acceptMutex, INFINITE) == WAIT_FAILED) 
		
        {
            printLastError("WaitForSingleObject() failed");
            return -1;
        }
    }
    
    if (shutdownPending) 
    {
        OS_LibShutdown();
    }
    else if (listenType == FD_PIPE_SYNC) 
    {
        ipcFd = acceptNamedPipe();
    }
    else if (listenType == FD_SOCKET_SYNC)
    {
        ipcFd = acceptSocket(webServerAddrs);
    }
    else
    {
        fprintf(stderr, "unknown listenType (%d)\n", listenType);
    }
	    
    if (acceptMutex != INVALID_HANDLE_VALUE) 
    {
        ReleaseMutex(acceptMutex);
    }

    return ipcFd;
}
예제 #15
0
/*
 * Execute the 'install service' command
 */
int InstallCommand::execute()
{

	int commandStatus = COMMAND_FAILURE;
	bool lookupError = true;

	if (!parametersValid)
	{
		cerr << "JavaService install command parameters not valid, or incomplete";
	}
	else if (isServiceInstalled(lookupError) && !lookupError)
	{
		cerr << "The " << getServiceName() << " service is already installed";
	}
	else if (lookupError)
	{
		cerr << "Error while checking to see if " << getServiceName() << " service is installed" << endl;
		printLastError();
	}
	else
	{
		bool installed = installService();

		if (installed)
		{
			commandStatus = COMMAND_SUCCESS; // success, even if saving config fails

			if (!saveServiceConfig())
			{
				cerr << "Error saving " << getServiceName() << "  service configuration (service installed)" << endl;
				printLastError();
			}
		}
		else
		{
			cerr << "Error attempting to install " << getServiceName() << "  service" << endl;
			printLastError();
		}
	}

	return commandStatus;
}
int
ioNewOSSemaphore(sqOSSemaphore *sem)
{
	*sem = CreateSemaphore(	0, /* don't need no stinkin' security */
							0, /* initial signal count */
							LONG_MAX, /* sky's the limit */
							0 /* don't need no stinkin' name */);
	if (!*sem)
		printLastError("ioNewOSSemaphore CreateSemaphore");
	return *sem ? 0 : GetLastError();
}
예제 #17
0
static int acceptNamedPipe()
{
    int ipcFd = -1;

#ifdef DEBUG_CGI
	
	FILE *dbg = fopen("c:\\libcgi1.log", "w");
	int i=0;
#endif
#ifdef DEBUG_CGI
	fprintf(dbg,"%d\n",hListen);
	fclose(dbg);		
#endif
	
    if (! ConnectNamedPipe(hListen, NULL))
    {
        switch (GetLastError())
        {
            case ERROR_PIPE_CONNECTED:

                // A client connected after CreateNamedPipe but
                // before ConnectNamedPipe. Its a good connection.

                break;
        
            case ERROR_IO_PENDING:

                // The NamedPipe was opened with an Overlapped structure
                // and there is a pending io operation.  mod_fastcgi 
                // did this in 2.2.12 (fcgi_pm.c v1.52).

            case ERROR_PIPE_LISTENING:

                // The pipe handle is in nonblocking mode.

            case ERROR_NO_DATA:

                // The previous client closed its handle (and we failed
                // to call DisconnectNamedPipe)

            default:

                printLastError("unexpected ConnectNamedPipe() error");
        }
    }

    ipcFd = Win32NewDescriptor(FD_PIPE_SYNC, (int) hListen, -1);
	if (ipcFd == -1) 
    {
        DisconnectNamedPipe(hListen);
    }

    return ipcFd;
}
/* Write count bytes from the given byte array to the given serial port's
   output buffer. Return the number of bytes written. This implementation is
   asynchronous: it may return before the entire packet has been sent. */
int serialPortWriteFrom(int portNum, int count, void *startPtr)
{ DWORD cbReallyWritten;

  if(!isValidComm(portNum)) return 0;
  if(!WriteFile(serialPorts[portNum-1],startPtr,count,&cbReallyWritten,NULL))
    {
      printLastError(TEXT("WriteComm failed"));
      success(false);
      return 0;
    }
  return cbReallyWritten;
}
/* Read up to count bytes from the given serial port into the given byte array.
   Read only up to the number of bytes in the port's input buffer; if fewer bytes
   than count have been received, do not wait for additional data to arrive.
   Return zero if no data is available. */
int serialPortReadInto(int portNum, int count, void *startPtr)
{ DWORD cbReallyRead;

  if(!isValidComm(portNum)) return 0;

  if(!ReadFile(serialPorts[portNum-1],startPtr,count,&cbReallyRead,NULL))
    {
      printLastError(TEXT("ReadComm failed"));
      success(false);
      return 0;
    }
  return cbReallyRead;
}
static void
initThreadLocalThreadIndices(void)
{
	if (tlthIndex == (DWORD)-1) {
		tlthIndex = TlsAlloc();
		tltiIndex = TlsAlloc();
		if (tlthIndex == TLS_OUT_OF_INDEXES
		 || tltiIndex == TLS_OUT_OF_INDEXES) { /* illiterate swine! */
			printLastError(TEXT("ThreadLocalThreadIndices TlsAlloc failed"));
			exit(1);
		}
	}
}
예제 #21
0
void _agpu_device::setWindowPixelFormat(agpu_pointer window)
{
    auto hwnd = (HWND)window;
    auto dc = GetDC(hwnd);

    UINT numFormats;
    int pixelAttributes[] = {
        WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
        WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
        WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
        WGL_RED_BITS_ARB, 8,
        WGL_GREEN_BITS_ARB, 8,
        WGL_BLUE_BITS_ARB, 8,
        WGL_ALPHA_BITS_ARB, 8,
        WGL_DEPTH_BITS_ARB, 0,
        0
    };

    PIXELFORMATDESCRIPTOR pixelFormatDescriptor =
    {
        sizeof(PIXELFORMATDESCRIPTOR),
        1,
        PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,    //Flags
        PFD_TYPE_RGBA,            //The kind of framebuffer. RGBA or palette.
        32,                        //Colordepth of the framebuffer.
        0, 0, 0, 0, 0, 0,
        0,
        0,
        0,
        0, 0, 0, 0,
        0,                        //Number of bits for the depthbuffer
        0,                        //Number of bits for the stencilbuffer
        0,                        //Number of Aux buffers in the framebuffer.
        PFD_MAIN_PLANE,
        0,
        0, 0, 0
    };

    int pixelFormat= 0;
    mainContext->wglChoosePixelFormatARB(dc, &pixelAttributes[0], nullptr, 1, &pixelFormat, &numFormats);

    auto res = SetPixelFormat(dc, pixelFormat, &pixelFormatDescriptor);
    if (res == FALSE)
    {
        if (!printLastError())
            printError("Failed to set window pixel format.\n");

    }
}
예제 #22
0
bool OpenGLContext::makeCurrentWithWindow(agpu_pointer window)
{
    auto windowDC = GetDC((HWND)window);
    auto res = wglMakeCurrent(windowDC, context) == TRUE;
    if (res)
    {
        currentGLContext = this;
    }
    else
    {
        if (!printLastError())
            printError("Failed to set context with window.\n");
    }
    return res;
}
/*****************************************************************************
 Squeak Serial Port functions
 *****************************************************************************/
int serialPortClose(int portNum)
{ HANDLE port;
  /* Allow ports that aren't open to be closed		20nov98 jfb */
  if(portNum <= 0 || portNum > MAX_SERIAL_PORTS)
    { /* port number out of range */
      success(false);
      return 0;
    }
  if ((port = serialPorts[portNum-1]) != INVALID_HANDLE_VALUE)
    { PurgeComm( port, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR |  
                       PURGE_RXCLEAR ) ;
      if(!CloseHandle(port))
         printLastError(TEXT("CloseHandle failed"));
      serialPorts[portNum-1] = INVALID_HANDLE_VALUE;
    }
  return 1;
}
예제 #24
0
int _tmain(int argc, _TCHAR* argv[])
{
    // variables for filesystem routine operations
    HANDLE hndlTmpFile = INVALID_HANDLE_VALUE;
    HANDLE hndlFile = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATA win32FileInfo;

    // set digest file for information about files at directory and subdirectories with their fletcher's checksum
    hndlTmpFile = CreateFile( _FILE_INFO_ , FILE_APPEND_DATA , 0 , NULL , CREATE_ALWAYS , FILE_ATTRIBUTE_NORMAL , NULL );
    if( hndlTmpFile == INVALID_HANDLE_VALUE ){
        printLastError( _T("Tempory file was not created, fault!") );
        FindClose( hndlFile );
        CloseHandle( hndlTmpFile );
        std::wcin.get();
	    return 0;  
    }
    
    std::wcout << L"This program calculates the signature files in a directory and subdirectories in which it is located." << std::endl;
    std::wcout << L"The program checks the signature every " << _SLEEP_TIME_ 
                  << "  seconds, if the signatures do not match, it displays a list of files and the number of iteration." << std::endl; 

    std::wcout << std::endl << std::endl;

    // init catalog and files
    initDigestSignatureMap( hndlFile , hndlTmpFile , &win32FileInfo , L"*.*" );

    // check sigature map
    unsigned long iterate(0);
    do{
        std::wcout << L"Current iterate is " << ++iterate << std::endl;
        if( 1 == checkFilesDigestSignature( hndlFile , &win32FileInfo , L"*.*" ) ){
            std::wcout << "Files was not changed : all digest is valid" << std::endl;
        }
        Sleep(_SLEEP_TIME_);
        std::wcout << std::endl;
    }while(iterate <= MAXLONG32 );
    
    std::wcout << L"May Be long is not too kong?" << std::endl;

    std::wcin.get();

    FindClose( hndlFile );
    CloseHandle( hndlTmpFile );
	return 0;
}
예제 #25
0
static int acceptNamedPipe()
{
    int ipcFd = -1;

    if (! ConnectNamedPipe(hListen, NULL))
    {
        switch (GetLastError())
        {
            case ERROR_PIPE_CONNECTED:

                // A client connected after CreateNamedPipe but
                // before ConnectNamedPipe. Its a good connection.

                break;
        
            case ERROR_IO_PENDING:

                // The NamedPipe was opened with an Overlapped structure
                // and there is a pending io operation.  mod_fastcgi 
                // did this in 2.2.12 (fcgi_pm.c v1.52).

            case ERROR_PIPE_LISTENING:

                // The pipe handle is in nonblocking mode.

            case ERROR_NO_DATA:

                // The previous client closed its handle (and we failed
                // to call DisconnectNamedPipe)

            default:

                printLastError("unexpected ConnectNamedPipe() error");
        }
    }

    ASSERT(INT_MIN <= (intptr_t)hListen && (intptr_t)hListen <= INT_MAX);
    ipcFd = Win32NewDescriptor(FD_PIPE_SYNC, (int)(intptr_t)hListen, -1);
	if (ipcFd == -1) 
    {
        DisconnectNamedPipe(hListen);
    }

    return ipcFd;
}
static DWORD
duplicateAndSetThreadHandleForCurrentThread(void)
{
	HANDLE threadHandle;
	DWORD lastError;

	if (DuplicateHandle(GetCurrentProcess(), // source process handle
						GetCurrentThread(),  // source handle (N.B. pseudo)
						GetCurrentProcess(), // target process handle
						&threadHandle,		 // out param
						0,// desired access, ignored if DUPLICATE_SAME_ACCESS
						TRUE,				 // handle is inheritable
						DUPLICATE_SAME_ACCESS)) { // options
		assert(threadHandle);
		TlsSetValue(tlthIndex,threadHandle);
		return 0;
	}
	lastError = GetLastError();
	printLastError("DuplicateHandle");
	return lastError;
}
예제 #27
0
LPCSTR getFunctionName(SIZE_T programCounter, DWORD64& displacement64,
	SYMBOL_INFO* functionInfo)
{
	// Initialize structures passed to the symbol handler.
	functionInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
	functionInfo->MaxNameLen = 256;

	// Try to get the name of the function containing this program
	// counter address.
	displacement64 = 0;
	LPCSTR functionName;
	HANDLE hProcess = GetCurrentProcess();
	if (SymFromAddr(hProcess, programCounter, &displacement64, functionInfo)) {
		functionName = functionInfo->Name;
	}
	else {
		printLastError();
		// GetFormattedMessage( GetLastError() );
		sprintf_s(functionInfo->Name, (size_t)256, "0x%x", programCounter);
		functionName = functionInfo->Name;
		displacement64 = 0;
	}
	return functionName;
}
/* ioShowDisplayOnWindow: similar to ioShowDisplay but adds the int windowIndex
 * Return true if ok, false if not, but not currently checked */
sqInt ioShowDisplayOnWindow(unsigned char* dispBits, sqInt width, 
			    sqInt height, sqInt depth, sqInt affectedL, 
			    sqInt affectedR, sqInt affectedT, sqInt affectedB, 
			    sqInt windowIndex) {
  HWND hwnd = (windowIndex == 1 ? stWindow : ((HWND)windowIndex));
  HDC dc;
  BITMAPINFO *bmi;
  int lines;
  int lsbDisplay;

  if(!IsWindow(hwnd))
    return 0;

  if(affectedR < affectedL || affectedT > affectedB)
    return 1;

  /* Careful here:
     After resizing the main window the affected area can
     be larger than the area covered by the display bits ... */
  if (affectedR > width) affectedR= width-1;
  if (affectedB > height) affectedB= height-1;
  /* ... and don't forget left and top - else reverse_image_* will crash */
  if (affectedL > width) affectedL= width-1;
  if (affectedT > height) affectedT= height-1;

  /* Don't draw empty areas */
  if(affectedL == affectedR || affectedT == affectedB) return 1;
  /* reload the update rectangle */
  updateRect.left = affectedL;
  updateRect.top = affectedT;
  updateRect.right = affectedR;
  updateRect.bottom = affectedB;
  /* ----- EXPERIMENTAL ----- */
  lsbDisplay = depth < 0;
  if(lsbDisplay) depth = -depth;

  bmi = BmiForDepth(depth);
  if(!bmi)
    {
  	return 0;
    }

  /* reverse the image bits if necessary */

  if( !lsbDisplay && depth < 32 )
    if(depth == 16)
      reverse_image_words((unsigned int*) dispBits, (unsigned int*) dispBits,
			  depth, width, &updateRect);
    else
      reverse_image_bytes((unsigned int*) dispBits, (unsigned int*) dispBits,
			  depth, width, &updateRect);

  bmi->bmiHeader.biWidth = width;
  bmi->bmiHeader.biHeight = -height;
  bmi->bmiHeader.biSizeImage = 0;

  dc = GetDC(hwnd);
  if(!dc) {
    printLastError(TEXT("ioShowDisplayBits: GetDC() failed"));
    return 0;
  }



  lines = SetDIBitsToDevice(dc,
  	    0, /* dst_x */
  	    0, /* dst_y */
  	    width,  /* dst_w */
  	    height, /* dst_h */
  	    0, /* src_x */
  	    0, /* src_y */
  	    0, /* start scan line in DIB */
  	    height, /* num scan lines in DIB */
	    (void*) dispBits,  /* bits */
	    bmi,
	    DIB_RGB_COLORS);

  if(lines == 0) {
    /* Note: the above is at least five times faster than what follows.
       Unfortunately, it also requires quite a bit of resources to
       be available. These are almost always available except in a
       few extreme conditions - but to compensate for those the
       following is provided. */
    int pitch, start, end, nPix, line, left;
    int bitsPtr;

    /* compute pitch of form */
    pitch = ((width * depth) + 31 & ~31) / 8;
    /* compute first word of update region */
    start = ((updateRect.left * depth) & ~31) / 8;
    /* compute last word of update region */
    end   = ((updateRect.right * depth) + 31 & ~31) / 8;
    /* compute #of bits covered in update region */
    nPix = ((end - start) * 8) / depth;
    left = (start * 8) / depth;
    bmi->bmiHeader.biWidth = nPix;
    bmi->bmiHeader.biHeight = 1;
    bmi->bmiHeader.biSizeImage = 0;
    bitsPtr = dispBits + start + (updateRect.top * pitch);
    for(line = updateRect.top; line < updateRect.bottom; line++) {
      lines = SetDIBitsToDevice(dc, left, line, nPix, 1, 0, 0, 0, 1,
				(void*) bitsPtr, bmi, DIB_RGB_COLORS);
      bitsPtr += pitch;
    }
  }

  ReleaseDC(hwnd,dc);

  if(lines == 0) {
    printLastError(TEXT("SetDIBitsToDevice failed"));
    warnPrintf(TEXT("width=%d,height=%d,bits=%X,dc=%X\n"),
	       width, height, dispBits,dc);
  }
  /* reverse the image bits if necessary */

  if( !lsbDisplay && depth < 32 )
    if(depth == 16)
      reverse_image_words((unsigned int*) dispBits, (unsigned int*) dispBits,
			  depth, width, &updateRect);
    else
      reverse_image_bytes((unsigned int*) dispBits, (unsigned int*) dispBits,
			  depth, width, &updateRect);

  return 1;
}
예제 #29
0
jdwpError
transport_startTransport(jboolean isServer, char *name, char *address,
                         long timeout)
{
    jvmtiStartFunction func;
    jdwpTransportEnv *trans;
    char threadName[MAXPATHLEN + 100];
    jint err;
    jdwpError serror;

    /*
     * If the transport is already loaded then use it
     * Note: We're assuming here that we don't support multiple
     * transports - when we do then we need to handle the case
     * where the transport library only supports a single environment.
     * That probably means we have a bag a transport environments
     * to correspond to the transports bag.
     */
    if (transport != NULL) {
        trans = transport;
    } else {
        serror = loadTransport(name, &trans);
        if (serror != JDWP_ERROR(NONE)) {
            return serror;
        }
    }

    if (isServer) {

        char *retAddress;
        char *launchCommand;
        TransportInfo *info;
        jvmtiError error;
        int len;
        char* prop_value;

        info = jvmtiAllocate(sizeof(*info));
        if (info == NULL) {
            return JDWP_ERROR(OUT_OF_MEMORY);
        }
        info->name = jvmtiAllocate((int)strlen(name)+1);
        (void)strcpy(info->name, name);
        info->address = NULL;
        info->timeout = timeout;
        if (info->name == NULL) {
            serror = JDWP_ERROR(OUT_OF_MEMORY);
            goto handleError;
        }
        if (address != NULL) {
            info->address = jvmtiAllocate((int)strlen(address)+1);
            (void)strcpy(info->address, address);
            if (info->address == NULL) {
                serror = JDWP_ERROR(OUT_OF_MEMORY);
                goto handleError;
            }
        }

        info->transport = trans;

        err = (*trans)->StartListening(trans, address, &retAddress);
        if (err != JDWPTRANSPORT_ERROR_NONE) {
            printLastError(trans, err);
            serror = JDWP_ERROR(TRANSPORT_INIT);
            goto handleError;
        }

        /*
         * Record listener address in a system property
         */
        len = (int)strlen(name) + (int)strlen(retAddress) + 2; /* ':' and '\0' */
        prop_value = (char*)jvmtiAllocate(len);
        strcpy(prop_value, name);
        strcat(prop_value, ":");
        strcat(prop_value, retAddress);
        setTransportProperty(getEnv(), prop_value);
        jvmtiDeallocate(prop_value);


        (void)strcpy(threadName, "JDWP Transport Listener: ");
        (void)strcat(threadName, name);

        func = &acceptThread;
        error = spawnNewThread(func, (void*)info, threadName);
        if (error != JVMTI_ERROR_NONE) {
            serror = map2jdwpError(error);
            goto handleError;
        }

        launchCommand = debugInit_launchOnInit();
        if (launchCommand != NULL) {
            serror = launch(launchCommand, name, retAddress);
            if (serror != JDWP_ERROR(NONE)) {
                goto handleError;
            }
        } else {
            if ( ! gdata->quiet ) {
                TTY_MESSAGE(("Listening for transport %s at address: %s",
                    name, retAddress));
            }
        }
        return JDWP_ERROR(NONE);

handleError:
        jvmtiDeallocate(info->name);
        jvmtiDeallocate(info->address);
        jvmtiDeallocate(info);
    } else {
        /*
         * Note that we don't attempt to do a launch here. Launching
         * is currently supported only in server mode.
         */

        /*
         * If we're connecting to another process, there shouldn't be
         * any concurrent listens, so its ok if we block here in this
         * thread, waiting for the attach to finish.
         */
         err = (*trans)->Attach(trans, address, timeout, 0);
         if (err != JDWPTRANSPORT_ERROR_NONE) {
             printLastError(trans, err);
             serror = JDWP_ERROR(TRANSPORT_INIT);
             return serror;
         }

         /*
          * Start the transport loop in a separate thread
          */
         (void)strcpy(threadName, "JDWP Transport Listener: ");
         (void)strcat(threadName, name);

         func = &attachThread;
         err = spawnNewThread(func, (void*)trans, threadName);
         serror = map2jdwpError(err);
    }
    return serror;
}
예제 #30
0
agpu_device *_agpu_device::open(agpu_device_open_info* openInfo)
{
    // Create the device.
    std::unique_ptr<agpu_device> device(new agpu_device);
    bool failure = false;

    // Perform the main context creation in
    device->mainContextJobQueue.start();
    AsyncJob contextCreationJob([&] {
        std::unique_ptr<OpenGLContext> contextWrapper(new OpenGLContext());

        // Window for context creation.
        HINSTANCE hInstance = GetModuleHandle(nullptr);
        WNDCLASSW wc;
        memset(&wc, 0, sizeof(wc));
        wc.lpfnWndProc = dummyWindowProc;
        wc.hInstance = hInstance;
        wc.lpszClassName = L"agpuDummyOGLWindow";
        wc.style = CS_OWNDC;
        if (!RegisterClassW(&wc))
        {
            failure = true;
            return;
        }

        HWND dummyWindow = CreateWindowW(wc.lpszClassName, L"agpuDummyOGLWindow", WS_OVERLAPPEDWINDOW, 0, 0, 16, 16, 0, 0, hInstance, 0);

        // Need to create a dummy context first.
        PIXELFORMATDESCRIPTOR pixelFormatDescriptor =
        {
            sizeof(PIXELFORMATDESCRIPTOR),
            1,
            PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,    //Flags
            PFD_TYPE_RGBA,            //The kind of framebuffer. RGBA or palette.
            32,                        //Colordepth of the framebuffer.
            0, 0, 0, 0, 0, 0,
            0,
            0,
            0,
            0, 0, 0, 0,
            24,                        //Number of bits for the depthbuffer
            8,                        //Number of bits for the stencilbuffer
            0,                        //Number of Aux buffers in the framebuffer.
            PFD_MAIN_PLANE,
            0,
            0, 0, 0
        };

        // Set the pixel format.
        auto dummyDC = GetDC(dummyWindow);
        int dummyPixelFormat = ChoosePixelFormat(dummyDC, &pixelFormatDescriptor);
        auto pfRes = SetPixelFormat(dummyDC, dummyPixelFormat, &pixelFormatDescriptor);;
        if (pfRes == FALSE)
        {
            if (!printLastError())
                printError("Failed to set window pixel format.\n");

        }

        // Create the context.
        auto dummyContext = wglCreateContext(dummyDC);
        if (!dummyContext)
        {
            DestroyWindow(dummyWindow);
            failure = true;
            return;
        }

        // Use the context.
        if (!wglMakeCurrent(dummyDC, dummyContext))
        {
            wglDeleteContext(dummyContext);
            DestroyWindow(dummyWindow);
            failure = true;
            return;
        }

        // Create the context window.
        HWND contextWindow = CreateWindowW(wc.lpszClassName, L"agpuOGLWindow", WS_OVERLAPPEDWINDOW, 0, 0, 16, 16, 0, 0, hInstance, 0);
        auto contextDC = GetDC(contextWindow);

        // Choose a proper pixel format
        contextWrapper->wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
        if (contextWrapper->wglChoosePixelFormatARB)
        {
            int pixelFormat;
            UINT numFormats;
            int pixelAttributes[] = {
                WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
                WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
                WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
                WGL_RED_BITS_ARB, 8,
                WGL_GREEN_BITS_ARB, 8,
                WGL_BLUE_BITS_ARB, 8,
                WGL_ALPHA_BITS_ARB, 8,
                WGL_DEPTH_BITS_ARB, 0,
                0
            };

            contextWrapper->wglChoosePixelFormatARB(contextDC, &pixelAttributes[0], nullptr, 1, &pixelFormat, &numFormats);
            auto res = SetPixelFormat(contextDC, pixelFormat, &pixelFormatDescriptor);
            if (res == FALSE)
            {
                printError("Failed to set the pixel format.\n");
                failure = true;
                return;
            }
        }
        else
        {
            printError("Missing a required extension.\n");
            failure = true;
            return;
        }

        // Now create the actual context.
        contextWrapper->wglCreateContextAttribsARB = (wglCreateContextAttribsARBProc)wglGetProcAddress("wglCreateContextAttribsARB");
        if (contextWrapper->wglCreateContextAttribsARB)
        {
            int contextAttributes[] =
            {
                WGL_CONTEXT_MAJOR_VERSION_ARB, 0,
                WGL_CONTEXT_MINOR_VERSION_ARB, 0,
                //GLX_CONTEXT_FLAGS_ARB        , GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
                0
            };

            for (int versionIndex = 0; GLContextVersionPriorities[versionIndex] != OpenGLVersion::Invalid; ++versionIndex)
            {
                auto version = (int)GLContextVersionPriorities[versionIndex];

                // GLX_CONTEXT_MAJOR_VERSION_ARB
                contextAttributes[1] = version / 10;
                // GLX_CONTEXT_MINOR_VERSION_ARB
                contextAttributes[3] = version % 10;

                contextWrapper->context = contextWrapper->wglCreateContextAttribsARB(contextDC, NULL, contextAttributes);//glXCreateContextAttribsARB(display, framebufferConfig, 0, True, contextAttributes);

                // Check for success.
                if (contextWrapper->context)
                {
                    contextWrapper->version = OpenGLVersion(version);
                    break;
                }
            }
        }
        else
        {
            contextWrapper->context = wglCreateContext(contextDC);
        }

        // Destroy the dummy context
        wglMakeCurrent(dummyDC, NULL);
        wglDeleteContext(dummyContext);
        DestroyWindow(dummyWindow);

        // Set the current context.
        if (!contextWrapper->context || !wglMakeCurrent(contextDC, contextWrapper->context))
        {
            failure = true;
            return;
        }

        // Create the device and load the extensions.
        contextWrapper->window = contextWindow;
        contextWrapper->hDC = contextDC;
        contextWrapper->makeCurrent();
        device->mainContext = contextWrapper.release();
        device->mainContext->device = device.get();
        device->initializeObjects();
    });

    device->mainContextJobQueue.addJob(&contextCreationJob);
    contextCreationJob.wait();
    if (failure)
        return nullptr;

    return device.release();
}