Пример #1
0
int __cdecl main(int argc, char *argv[])
{
    HANDLE TheFile = NULL;
    const char lpBuffer[] = "This is a test file.";
    DWORD bytesWritten;
    BOOL bRc = TRUE;
    char fileName[] = "testfile.tmp";

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }

    /* Open a file which is in the directory */
    TheFile = CreateFile(fileName,     
                         GENERIC_READ|GENERIC_WRITE, 
                         FILE_SHARE_READ|FILE_SHARE_WRITE,
                         NULL,                          
                         CREATE_ALWAYS,                 
                         FILE_ATTRIBUTE_NORMAL, 
                         NULL);
       
    if (TheFile == INVALID_HANDLE_VALUE) 
    { 
        Fail("ERROR: Could not open file '%s' with CreateFile. "
             "GetLastError() returned %d.\n",fileName,GetLastError()); 
    }

    bRc = WriteFile(
                TheFile,                 // handle to file
                lpBuffer,                // data buffer
                (DWORD)sizeof(lpBuffer),        // number of bytes to write
                &bytesWritten,             // number of bytes written
                NULL                     // overlapped buffer
    );

    if(!bRc)
    {      
        Trace("ERROR: Could not write to file '%s' with WriteFile.",fileName);

        if(CloseHandle(TheFile) == 0)
        {
            Fail("ERROR: CloseHandle failed to close the file.");
        }
        Fail("");

    }
    else if(bytesWritten != (DWORD)sizeof(lpBuffer))
    {
        Trace("ERROR: Could not write the correct number of bytes to the "
        "file '%s' with WriteFile.",fileName);

        if(CloseHandle(TheFile) == 0)
        {
            Fail("ERROR: CloseHandle failed to close the file.");
        }
        Fail("");
    }

    /* Call unlock file on an unlocked file, this should return 0 */
    if(UnlockFile(TheFile, 0, 0, 5, 0) != 0)
    {
        Trace("ERROR: Attempted to unlock a file which was not locked and "
             "the UnlockFile call was successful.\n");

        if(CloseHandle(TheFile) == 0)
        {
            Fail("ERROR: CloseHandle failed to close the file.");
        }
        Fail("");
    }

    /* Lock the file */
    if(LockFile(TheFile, 0, 0, 5, 0) == 0)
    {
        Trace("ERROR: Failed to call LockFile on a valid file handle.  "
             "GetLastError returned %d.\n",GetLastError());

        if(CloseHandle(TheFile) == 0)
        {
            Fail("ERROR: CloseHandle failed to close the file.");
    }
        Fail("");
    }

    /* Try to unlock more of the file than was locked by LockFile */
    if(UnlockFile(TheFile, 0, 0, 10, 0) != 0)
    {
        Trace("ERROR: Attempted to unlock bytes 0 to 9, but only bytes "
             "0 to 4 are locked.  But, UnlockFile was successful, when it "
             "should have failed.\n");

        if(CloseHandle(TheFile) == 0)
        {
            Fail("ERROR: CloseHandle failed to close the file.");
    }
        Fail("");
    }

    /* Try to unlock less of the file than was locked by LockFile */
    if(UnlockFile(TheFile, 0, 0, 3, 0) != 0)
    {
        Trace("ERROR: Attempted to unlock bytes 0 to 2, but the bytes 0 to "
             "4 were locked by LockFile.  Unlockfile should have failed "
             "when attempting this operation.\n");

        if(CloseHandle(TheFile) == 0)
        {
            Fail("ERROR: CloseHandle failed to close the file.");
        }
        Fail("");
    }
    
    /* Properly unlock the file */
    if(UnlockFile(TheFile, 0, 0, 5, 0) == 0)
    {
        Trace("ERROR: UnlockFile failed to unlock bytes 0 to 4 of the file. "
             "GetLastError returned %d.\n",GetLastError());

        if(CloseHandle(TheFile) == 0)
        {
            Fail("ERROR: CloseHandle failed to close the file.");
        }
        Fail("");
    }
    
    if(CloseHandle(TheFile) == 0)
    {
        Fail("ERROR: CloseHandle failed to close the file.\n");
    }
  
    PAL_Terminate();
    return PASS;
}
Пример #2
0
bool PCB_EDIT_FRAME::OpenProjectFiles( const std::vector<wxString>& aFileSet, int aCtl )
{
    // This is for python:
    if( aFileSet.size() != 1 )
    {
        UTF8 msg = StrPrintf( "Pcbnew:%s() takes only a single filename", __func__ );
        DisplayError( this, msg );
        return false;
    }

    wxString fullFileName( aFileSet[0] );

    // We insist on caller sending us an absolute path, if it does not, we say it's a bug.
    wxASSERT_MSG( wxFileName( fullFileName ).IsAbsolute(),
        wxT( "bug in single_top.cpp or project manager." ) );

    if( !LockFile( fullFileName ) )
    {
        wxString msg = wxString::Format( _(
                "PCB file '%s' is already open." ),
                GetChars( fullFileName )
                );
        DisplayError( this, msg );
        return false;
    }

    if( GetScreen()->IsModify() )
    {
        int response = YesNoCancelDialog( this, _(
            "The current board has been modified.  Do you wish to save the changes?" ),
            wxEmptyString,
            _( "Save and Load" ),
            _( "Load Without Saving" )
            );

        if( response == wxID_CANCEL )
            return false;
        else if( response == wxID_YES )
            SavePcbFile( GetBoard()->GetFileName(), CREATE_BACKUP_FILE );
        else
        {
            // response == wxID_NO, fall thru
        }
    }

    wxFileName pro = fullFileName;
    pro.SetExt( ProjectFileExtension );

    bool is_new = !wxFileName::IsFileReadable( fullFileName );

    // If its a non-existent schematic and caller thinks it exists
    if( is_new && !( aCtl & KICTL_CREATE ) )
    {
        // notify user that fullFileName does not exist, ask if user wants to create it.
        wxString ask = wxString::Format( _(
                "Board '%s' does not exist.  Do you wish to create it?" ),
                GetChars( fullFileName )
                );
        if( !IsOK( this, ask ) )
            return false;
    }

    Clear_Pcb( false );     // pass false since we prompted above for a modified board

    IO_MGR::PCB_FILE_T  pluginType = plugin_type( fullFileName, aCtl );

    bool converted =  pluginType != IO_MGR::LEGACY && pluginType != IO_MGR::KICAD;

    if( !converted )
    {
        // PROJECT::SetProjectFullName() is an impactful function.  It should only be
        // called under carefully considered circumstances.

        // The calling code should know not to ask me here to change projects unless
        // it knows what consequences that will have on other KIFACEs running and using
        // this same PROJECT.  It can be very harmful if that calling code is stupid.
        Prj().SetProjectFullName( pro.GetFullPath() );

        // load project settings before BOARD
        LoadProjectSettings();
    }

    if( is_new )
    {
        OnModify();
    }
    else
    {
        BOARD* loadedBoard = 0;   // it will be set to non-NULL if loaded OK

        PLUGIN::RELEASER pi( IO_MGR::PluginFind( pluginType ) );

        try
        {
            PROPERTIES  props;
            char        xbuf[30];
            char        ybuf[30];

            // EAGLE_PLUGIN can use this info to center the BOARD, but it does not yet.
            sprintf( xbuf, "%d", GetPageSizeIU().x );
            sprintf( ybuf, "%d", GetPageSizeIU().y );

            props["page_width"]  = xbuf;
            props["page_height"] = ybuf;

#if USE_INSTRUMENTATION
            // measure the time to load a BOARD.
            unsigned startTime = GetRunningMicroSecs();
#endif

            loadedBoard = pi->Load( fullFileName, NULL, &props );

#if USE_INSTRUMENTATION
            unsigned stopTime = GetRunningMicroSecs();
            printf( "PLUGIN::Load(): %u usecs\n", stopTime - startTime );
#endif
        }
        catch( const IO_ERROR& ioe )
        {
            wxString msg = wxString::Format( _(
                    "Error loading board.\n%s" ),
                    GetChars( ioe.errorText )
                    );
            DisplayError( this, msg );
            return false;
        }

        SetBoard( loadedBoard );

        // we should not ask PLUGINs to do these items:
        loadedBoard->BuildListOfNets();
        loadedBoard->SynchronizeNetsAndNetClasses();

        SetStatusText( wxEmptyString );
        BestZoom();

        // update the layer names in the listbox
        ReCreateLayerBox( false );

        GetScreen()->ClrModify();

        {
            wxFileName fn = fullFileName;
            CheckForAutoSaveFile( fullFileName, fn.GetExt() );
        }

        if( pluginType == IO_MGR::LEGACY &&
            loadedBoard->GetFileFormatVersionAtLoad() < LEGACY_BOARD_FILE_VERSION )
        {
            DisplayInfoMessage( this,
                _(  "This file was created by an older version of Pcbnew.\n"
                    "It will be stored in the new file format when you save this file again." ) );
        }
    }

    {
        wxFileName fn = fullFileName;

        if( converted )
            fn.SetExt( PcbFileExtension );

        wxString fname = fn.GetFullPath();

        fname.Replace( WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP );

        GetBoard()->SetFileName( fname );
    }

    UpdateTitle();

    if( !converted )
        UpdateFileHistory( GetBoard()->GetFileName() );

    // Rebuild the new pad list (for drc and ratsnet control ...)
    GetBoard()->m_Status_Pcb = 0;

    // Select netclass Default as current netclass (it always exists)
    SetCurrentNetClass( NETCLASS::Default );

    // Rebuild list of nets (full ratsnest rebuild)
    {
        wxBusyCursor dummy;    // Displays an Hourglass while building connectivity
        Compile_Ratsnest( NULL, true );
        GetBoard()->GetRatsnest()->ProcessBoard();
    }

    // Update info shown by the horizontal toolbars
    ReFillLayerWidget();
    ReCreateLayerBox();

    // upate the layer widget to match board visibility states, both layers and render columns.
    syncLayerVisibilities();
    syncLayerWidgetLayer();
    syncRenderStates();

    // Update the tracks / vias available sizes list:
    ReCreateAuxiliaryToolbar();

    // Update the RATSNEST items, which were not loaded at the time
    // BOARD::SetVisibleElements() was called from within any PLUGIN.
    // See case RATSNEST_VISIBLE: in BOARD::SetElementVisibility()
    GetBoard()->SetVisibleElements( GetBoard()->GetVisibleElements() );

    // Display the loaded board:
    Zoom_Automatique( false );

    SetMsgPanel( GetBoard() );

    // Refresh the 3D view, if any
    EDA_3D_VIEWER* draw3DFrame = Get3DViewerFrame();

    if( draw3DFrame )
        draw3DFrame->NewDisplay();

#if 0 && defined(DEBUG)
    // Output the board object tree to stdout, but please run from command prompt:
    GetBoard()->Show( 0, std::cout );
#endif

    // from EDA_APPL which was first loaded BOARD only:
    {
        /* For an obscure reason the focus is lost after loading a board file
         * when starting up the process.
         * (seems due to the recreation of the layer manager after loading the file)
         * Give focus to main window and Drawpanel
         * must be done for these 2 windows (for an obscure reason ...)
         * Linux specific
         * This is more a workaround than a fix.
         */
        SetFocus();
        GetCanvas()->SetFocus();
    }

    return true;
}
Пример #3
0
int fb_hFileLock( FILE *f, fb_off_t inipos, fb_off_t size )
{
	return fb_ErrorSetNum( LockFile( (HANDLE)get_osfhandle( fileno( f ) ), inipos, 0, size, 0 ) == TRUE ?
	                       FB_RTERROR_OK : FB_RTERROR_FILEIO );
}
Пример #4
0
BOOL FileLockThread::MyFileLock()
{
	for (auto it = fileHandles.begin(); it != fileHandles.end(); it++)
		LockFile(*it, 0, 0, GetFileSize(*it, 0), 0);
	return TRUE;
}
Пример #5
0
void vmInit(void) {
    off totsize;
    int pipefds[2];
    size_t stacksize;
#ifndef _WIN32
    struct flock fl;
#endif

    if (server.vm_max_threads != 0)
        zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */

    redisLog(REDIS_NOTICE,"Using '%s' as swap file",server.vm_swap_file);
    /* Try to open the old swap file, otherwise create it */
    if ((server.vm_fp = fopen(server.vm_swap_file,"r+b")) == NULL) {
        server.vm_fp = fopen(server.vm_swap_file,"w+b");
    }

    if (server.vm_fp == NULL) {
        redisLog(REDIS_WARNING,
            "Can't open the swap file: %s. Exiting.",
            strerror(errno));
        exit(1);
    }
    server.vm_fd = fileno(server.vm_fp);
    /* Lock the swap file for writing, this is useful in order to avoid
     * another instance to use the same swap file for a config error. */
#ifdef _WIN32

    // LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0)
    if(!LockFile((HANDLE) _get_osfhandle(server.vm_fd), (0x40000001), 0, 1, 0) ) {
        redisLog(REDIS_WARNING,
            "Can't lock the swap file at '%s': %s. Make sure it is not used by another Redis instance.", server.vm_swap_file, strerror(errno));
        WSACleanup();
        exit(1);
    }
#else
    fl.l_type = F_WRLCK;
    fl.l_whence = SEEK_SET;
    fl.l_start = fl.l_len = 0;
    if (fcntl(server.vm_fd,F_SETLK,&fl) == -1) {
        redisLog(REDIS_WARNING,
            "Can't lock the swap file at '%s': %s. Make sure it is not used by another Redis instance.", server.vm_swap_file, strerror(errno));
        exit(1);
    }
#endif
    /* Initialize */
    server.vm_next_page = 0;
    server.vm_near_pages = 0;
    server.vm_stats_used_pages = 0;
    server.vm_stats_swapped_objects = 0;
    server.vm_stats_swapouts = 0;
    server.vm_stats_swapins = 0;
    totsize = server.vm_pages*server.vm_page_size;
#ifdef _WIN32
    redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",(long long) totsize);
#else
    redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",totsize);
#endif
    if (ftruncate(server.vm_fd,totsize) == -1) {
        redisLog(REDIS_WARNING,"Can't ftruncate swap file: %s. Exiting.",
            strerror(errno));
        exit(1);
    } else {
        redisLog(REDIS_NOTICE,"Swap file allocated with success");
    }
    server.vm_bitmap = zcalloc((server.vm_pages+7)/8);
    redisLog(REDIS_VERBOSE,"Allocated %lld bytes page table for %lld pages",
        (long long) (server.vm_pages+7)/8, server.vm_pages);

    /* Initialize threaded I/O (used by Virtual Memory) */
    server.io_newjobs = listCreate();
    server.io_processing = listCreate();
    server.io_processed = listCreate();
    server.io_ready_clients = listCreate();
#ifndef _WIN32
    /* moved to InitSharedObjecsts since they are first time used there */
    pthread_mutex_init(&server.io_mutex,NULL);
    pthread_mutex_init(&server.io_swapfile_mutex,NULL);
#endif
    server.io_active_threads = 0;
    if (pipe(pipefds) == -1) {
        redisLog(REDIS_WARNING,"Unable to intialized VM: pipe(2): %s. Exiting."
            ,strerror(errno));
        exit(1);
    }
    server.io_ready_pipe_read = pipefds[0];
    server.io_ready_pipe_write = pipefds[1];
#ifndef _WIN32
    /* Windows distincts pipe and socket destriptors */
    /* We will use blocking pipe, with peek before blocking read */
    redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
#endif
    /* LZF requires a lot of stack */
    pthread_attr_init(&server.io_threads_attr);
    pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);

    /* Solaris may report a stacksize of 0, let's set it to 1 otherwise
     * multiplying it by 2 in the while loop later will not really help ;) */
    if (!stacksize) stacksize = 1;

    while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
    pthread_attr_setstacksize(&server.io_threads_attr, stacksize);

    /* Listen for events in the threaded I/O pipe */
#ifdef _WIN32
    /* Windows fix: need to pass flag that notifies Api that file descriptor is pipe */
    if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE | AE_PIPE,
        vmThreadedIOCompletedJob, NULL) == AE_ERR)
        oom("creating file event");
#else
    if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
        vmThreadedIOCompletedJob, NULL) == AE_ERR)
        oom("creating file event");
#endif
}
Пример #6
0
void AssertFreeDiskSpace(int Priority, bool Force)
{
  static cMutex Mutex;
  cMutexLock MutexLock(&Mutex);
  // With every call to this function we try to actually remove
  // a file, or mark a file for removal ("delete" it), so that
  // it will get removed during the next call.
  static time_t LastFreeDiskCheck = 0;
  int Factor = (Priority == -1) ? 10 : 1;
  if (Force || time(NULL) - LastFreeDiskCheck > DISKCHECKDELTA / Factor) {
     if (!VideoFileSpaceAvailable(MINDISKSPACE)) {
        // Make sure only one instance of VDR does this:
        cLockFile LockFile(VideoDirectory);
        if (!LockFile.Lock())
           return;
        // Remove the oldest file that has been "deleted":
        isyslog("low disk space while recording, trying to remove a deleted recording...");
        cThreadLock DeletedRecordingsLock(&DeletedRecordings);
        if (DeletedRecordings.Count()) {
           cRecording *r = DeletedRecordings.First();
           cRecording *r0 = NULL;
           while (r) {
                 if (IsOnVideoDirectoryFileSystem(r->FileName())) { // only remove recordings that will actually increase the free video disk space
                    if (!r0 || r->start < r0->start)
                       r0 = r;
                    }
                 r = DeletedRecordings.Next(r);
                 }
           if (r0 && r0->Remove()) {
              DeletedRecordings.Del(r0);
              LastFreeDiskCheck += REMOVELATENCY / Factor;
              return;
              }
           }
        else {
           // DeletedRecordings was empty, so to be absolutely sure there are no
           // deleted recordings we need to double check:
           DeletedRecordings.Update(true);
           if (DeletedRecordings.Count())
              return; // the next call will actually remove it
           }
        // No "deleted" files to remove, so let's see if we can delete a recording:
        isyslog("...no deleted recording found, trying to delete an old recording...");
        cThreadLock RecordingsLock(&Recordings);
        if (Recordings.Count()) {
           cRecording *r = Recordings.First();
           cRecording *r0 = NULL;
           while (r) {
                 if (IsOnVideoDirectoryFileSystem(r->FileName())) { // only delete recordings that will actually increase the free video disk space
                    if (!r->IsEdited() && r->lifetime < MAXLIFETIME) { // edited recordings and recordings with MAXLIFETIME live forever
                       if ((r->lifetime == 0 && Priority > r->priority) || // the recording has no guaranteed lifetime and the new recording has higher priority
                           (r->lifetime > 0 && (time(NULL) - r->start) / SECSINDAY >= r->lifetime)) { // the recording's guaranteed lifetime has expired
                          if (r0) {
                             if (r->priority < r0->priority || (r->priority == r0->priority && r->start < r0->start))
                                r0 = r; // in any case we delete the one with the lowest priority (or the older one in case of equal priorities)
                             }
                          else
                             r0 = r;
                          }
                       }
                    }
                 r = Recordings.Next(r);
                 }
           if (r0 && r0->Delete()) {
              Recordings.Del(r0);
              return;
              }
           }
        // Unable to free disk space, but there's nothing we can do about that...
        isyslog("...no old recording found, giving up");
        Skins.QueueMessage(mtWarning, tr("Low disk space!"), 5, -1);
        }
     LastFreeDiskCheck = time(NULL);
     }
}
Пример #7
0
int __cdecl main(int argc, char *argv[])
{
    HANDLE TheFile, WaitFile;
    int result = 0;

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }

    /* Open the same file that the parent has opened and locked */
    TheFile = CreateFile(FILENAME,
                         GENERIC_READ|GENERIC_WRITE,
                         FILE_SHARE_READ|FILE_SHARE_WRITE,
                         NULL,
                         OPEN_EXISTING,
                         FILE_ATTRIBUTE_NORMAL,
                         NULL);

    if (TheFile == INVALID_HANDLE_VALUE)
    {
        Trace("ERROR: Could not open file '%s' with CreateFile.\n",FILENAME);
        result = 1;
    }

    /* Open up the WaitFile that we're using for IPC */
    WaitFile = CreateFile(WAITFILENAME,
                          GENERIC_READ|GENERIC_WRITE,
                          FILE_SHARE_READ|FILE_SHARE_WRITE,
                          NULL,
                          OPEN_ALWAYS,
                          FILE_ATTRIBUTE_NORMAL,
                          NULL);

    if (WaitFile == INVALID_HANDLE_VALUE)
    {
        Trace("ERROR: Could not open file '%s' with CreateFile. "
              "GetLastError() returned %d.\n",WAITFILENAME,GetLastError());
        result = 1;
    }

    /* Lock a section of the file different from which was locked in the
       parent proccess
    */
    if(LockFile(TheFile, 10, 0, 10, 0) == 0)
    {
        Trace("ERROR: The LockFile call within the child failed to lock "
              "the file.  GetLastError() returned %d.\n",GetLastError());
        result = 1;
    }

    /* Attempt to unlock the portion of the file which was locked within the
       parent process.
    */
    if(UnlockFile(TheFile, 0, 0, 10, 0) != 0)
    {
        Trace("ERROR: The UnlockFile call within the child succeeded in "
              "calling UnlockFile on the portion of the file which was "
              "locked by the parent.\n");
        result = 1;
    }

    // Sleep for a bit to give the parent a chance to block before we do.
    Sleep(1000);

    /* Switch back to the parent, so it can check the child lock */
    SignalAndBusyWait(WaitFile);

    /* Finally, clean up the lock which was done within this proccess and
       exit.
    */
    if(UnlockFile(TheFile, 10, 0, 10, 0) == 0)
    {
        Trace("ERROR: The UnlockFile call within the child failed to unlock "
              "the portion of the file which was locked by the child.  "
              "GetLastError() returned %d.\n", GetLastError());
        result = 1;
    }

    PAL_TerminateEx(result);
    return result;
}
Пример #8
0
int __cdecl main(int argc, char *argv[])
{
    HANDLE TheFile, WaitFile;
    int result = 0;
    char DataBuffer[BUF_SIZE];
    DWORD BytesRead;
    
    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }
    
    /* Open the same file that the parent has opened and locked */
    TheFile = CreateFile(FILENAME,     
                         GENERIC_READ|GENERIC_WRITE, 
                         FILE_SHARE_READ|FILE_SHARE_WRITE,
                         NULL,     
                         OPEN_EXISTING,                 
                         FILE_ATTRIBUTE_NORMAL, 
                         NULL);
    
    if (TheFile == INVALID_HANDLE_VALUE) 
    { 
        Trace("ERROR: Could not open file '%s' with CreateFile.",FILENAME); 
        result = 1;
    }
    
    /* Open up the WaitFile that we're using for IPC */
    WaitFile = CreateFile(WAITFILENAME,     
                          GENERIC_READ|GENERIC_WRITE, 
                          FILE_SHARE_READ|FILE_SHARE_WRITE,
                          NULL,                          
                          OPEN_ALWAYS,                 
                          FILE_ATTRIBUTE_NORMAL, 
                          NULL);
    
    if (WaitFile == INVALID_HANDLE_VALUE) 
    { 
        Trace("ERROR: Could not open file '%s' with CreateFile. "
             "GetLastError() returned %d.",WAITFILENAME,GetLastError()); 
        result = 1;
    }
    
    /* Lock the same file that the parent process locked, but the child
       locks bytes 11 through 20
    */

    if(LockFile(TheFile, 11, 0, 10, 0) == 0)
    {
        Trace("ERROR: LockFile failed in the child proccess.  "
              "GetLastError returns %d.",
              GetLastError());
        result = 1;
    }
    
    /* Check to ensure the parent lock is respected */
    if(ReadFile(TheFile, DataBuffer, 10, &BytesRead, NULL) != 0)
    {
        Trace("ERROR: ReadFile returned success when it should "
             "have failed.  Attempted to read the first 10 bytes "
             "of a file which was locked by the parent process.");
        result = 1;
    }

    /* Check to ensure the lock put on by this proccess doesn't restrict
       access
    */

    if(SetFilePointer(TheFile, 11, 0, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
    {
        Trace("ERROR: SetFilePointer was unable to move the file pointer to "
              "the 11th byte in the file, within the child proccess.  "
              "GetLastError() returned %d.",GetLastError());
        result = 1;
    }

    if(ReadFile(TheFile, DataBuffer, 10, &BytesRead, NULL) == 0)
    {
        Trace("ERROR: ReadFile failed when attempting to read a section of "
             "the file which was locked by the current process.  It should "
             "have been able to read this.  GetLastError() returned %d.",
             GetLastError());
        result = 1;
    }

    // Sleep for a bit to give the parent a chance to block before we do.
    Sleep(1000);

    /* Switch back to the parent, so it can check the child's locks */
    SignalAndBusyWait(WaitFile);

    if(UnlockFile(TheFile, 11, 0, 10, 0) == 0)
    {
        Fail("ERROR: Failed to Unlock bytes 11-20 in the file.  "
             "GetLastError returned %d.",GetLastError());
    }
    
    PAL_Terminate();
    return result;
}
BOOL CPELock::IsPELockPresent2()
{
	return ( LockFile(NULL, 128, 0, 512, 0) == 1 ? TRUE : FALSE );
}
STDMETHODIMP CAudioRawFileRenderer::setParameter(__int64 command, __int64  data1, __int64  data2, __int64 data3)
{
    CAutoLock lock(&m_ReceiveLock);
    
    HRESULT hr=NOERROR;

    switch(command)
        {
        case CMD_SPLITEVENT:
        if ( 
            ((m_SplitMode==OPT_SPLIT_DISCONTINUITY)&&m_IsDiscontinuity) ||
             (m_SplitMode==OPT_SPLIT_EVENT)
           )
            {
            CloseFile();
            dprintf("SplitEvent");
            if (lstrlenW(m_pOldFileName)>0)
                {
                char str[264]="";
                char strOld[264]="";
                DWORD dwWritten=0;
                DWORD result=0;
                HANDLE hFile=INVALID_HANDLE_VALUE;

		        WideCharToMultiByte(CP_ACP, 0, m_pFileName   , -1, str   , 264, NULL, NULL);
		        WideCharToMultiByte(CP_ACP, 0, m_pOldFileName, -1, strOld, 264, NULL, NULL);
                MoveFile(str, strOld);

                hFile = CreateFile( strOld,   // The filename
                                    GENERIC_WRITE,         // File access
                                    (DWORD) 0,             // Share access
                                    NULL,                  // Security
                                    OPEN_EXISTING,         // Open flags
                                    FILE_ATTRIBUTE_NORMAL,             // More flags
                                    NULL);                 // Template
                if (INVALID_HANDLE_VALUE!=hFile)
                    {
                    result=SetFilePointer(hFile, 0, NULL, FILE_END); 
                    LockFile(hFile, result, 0, result + sizeof(m_OldID3), 0); 
                    result=WriteFile(hFile,(PVOID)&m_OldID3,(DWORD)sizeof(m_OldID3),&dwWritten,NULL);
                    UnlockFile(hFile, result, 0, result + sizeof(m_OldID3), 0); 
                    CloseHandle(hFile);
                    }
                
                }
            OpenFile();
            }
            break;

        case CMD_SPLITDATA:
            {
            dprintf("SplitData");
            lstrcpyW(m_pOldFileName, (WCHAR *)data2);
            CopyMemory(&m_OldID3, (struct ID3 *)data1, sizeof(struct ID3));
            }
            break;
        
        case CMD_SPLITMODE:
            m_SplitMode=(int)data1;
            break;

        default:
            hr=E_NOTIMPL;
            break;
        }
    return(hr);
}
Пример #11
0
static int OnLockUnlockFile(HWND hDlg, int nReadWriteType)
{
    TFileTestData * pData = GetDialogData(hDlg);
    TApcReadWrite * pApc;
    LARGE_INTEGER ByteOffset = {0};
    LARGE_INTEGER LockLength = {0};
    NTSTATUS Status;
    int nError = ERROR_SUCCESS;

    // Get the start position
    DlgText2Hex64(hDlg, IDC_BYTE_OFFSET, &ByteOffset.QuadPart);
    DlgText2Hex32(hDlg, IDC_LENGTH, &LockLength.LowPart);
    assert((LONGLONG)pData->cbFileData >= LockLength.QuadPart);

    // Create new APC entry
    pApc = (TApcReadWrite *)CreateApcEntry(pData, APC_TYPE_READ_WRITE, sizeof(TApcReadWrite));
    if(pApc != NULL)
    {
        // Perform the I/O operation
        switch(nReadWriteType)
        {
            case IDC_LOCK_FILE:

                // Perform the lock operation using LockFile
                if(!LockFile(pData->hFile, ByteOffset.LowPart, ByteOffset.HighPart, LockLength.LowPart, LockLength.HighPart))
                    nError = GetLastError();
                break;

            case IDC_UNLOCK_FILE:

                // Perform the unlock operation using UnlockFile
                if(!UnlockFile(pData->hFile, ByteOffset.LowPart, ByteOffset.HighPart, LockLength.LowPart, LockLength.HighPart))
                    nError = GetLastError();
                break;

            case IDC_NTLOCK_FILE:

                // Remember that this is a native call
                pApc->bNativeCall = false;

                // Perform the lock operation using NtLockFile
                Status = NtLockFile(pData->hFile,
                                    pApc->hEvent,
                                    NULL,
                                    NULL,
                                   &pApc->IoStatus,
                                   &ByteOffset,
                                   &LockLength,
                                    0,
                                    TRUE,
                                    TRUE);

                // If the lock operation ended with STATUS_PENDING, queue the APC
                if(Status == STATUS_PENDING)
                {
                    SetResultInfo(hDlg, ERROR_IO_PENDING);
                    InsertApcEntry(pData, pApc);
                    return TRUE;
                }

                // Save the error
                nError = RtlNtStatusToDosError(Status);
                break;

            case IDC_NTUNLOCK_FILE:

                // Perform the unlock operation using NtUnlockFile
                Status = NtUnlockFile(pData->hFile,
                                     &pApc->IoStatus,
                                     &ByteOffset,
                                     &LockLength,
                                      0);
                // Save the error
                assert(Status != STATUS_PENDING);
                nError = RtlNtStatusToDosError(Status);
                break;
        }

        // Set the information about the operation
        SetResultInfo(hDlg, nError);
        FreeApcEntry(pApc);
    }
    else
    {
        SetResultInfo(hDlg, GetLastError());
    }

    return TRUE;
}
Пример #12
0
BOOL
BackupReadAlternateData(HANDLE hFile, BACKUPCONTEXT *pbuc, BACKUPIOFRAME *pbif)
{
    // ALT_DATA is Macintosh stream data & other data streams.

    if (pbuc->fStreamStart) {
	NTSTATUS Status;
	FILE_STREAM_INFORMATION *pfsi;
	IO_STATUS_BLOCK iosb;

	// allocate a buffer big enough to hold all the necessary data.

	if (!pbuc->fBufferReady) {
	    while (TRUE) {
		Status = NtQueryInformationFile(
			    hFile,
			    &iosb,
			    pbuc->pBuffer,
			    pbuc->cbBuffer,
			    FileStreamInformation);

		if (NT_SUCCESS(Status) && iosb.Information != 0) {
		    pbuc->iBuffer = 0;
		    pbuc->fBufferReady = TRUE;
		    break;
		}
		if (!BufferOverflow(Status)) {
		    return(TRUE);	// No alt. streams, do next stream type
		}
		if (!GrowBuffer(pbuc, pbuc->cbBuffer * 2)) {
		    return(FALSE);	// No memory
		}
		// else grow succeeded
	    }
	}

	pbuc->hAlternate = NULL;
	pbuc->fStreamStart = FALSE;
	pfsi = (FILE_STREAM_INFORMATION *) &pbuc->pBuffer[pbuc->iBuffer];

	// Check StreamName for default data stream and skip if found
	// Checking StreamNameLength for <= 1 character is OFS specific!
	// Checking StreamName[1] for a colon is NTFS specific!

	if (pfsi->StreamNameLength <= sizeof(WCHAR) ||
	    pfsi->StreamName[1] == ':') {
	    if (pfsi->NextEntryOffset == 0) {
		return(TRUE);		// No more, do next stream type
	    }
	    pbuc->iBuffer += pfsi->NextEntryOffset;
	}
	pbuc->head.Size.LowPart = 1;
    }
    else if (pbuc->hAlternate == NULL) {
	NTSTATUS Status;
	FILE_STREAM_INFORMATION *pfsi;
	UNICODE_STRING strName;
	OBJECT_ATTRIBUTES oa;
	IO_STATUS_BLOCK iosb;

	pbuc->head.Size.LowPart = 0;
	pbuc->head.Size.HighPart = 0;

	pfsi = (FILE_STREAM_INFORMATION *) &pbuc->pBuffer[pbuc->iBuffer];

	strName.Length = (USHORT) pfsi->StreamNameLength;
	strName.MaximumLength = strName.Length;
	strName.Buffer = pfsi->StreamName;

	InitializeObjectAttributes(
		 &oa,
		 &strName,
		 OBJ_CASE_INSENSITIVE,
		 hFile,
		 NULL);

	Status = NtOpenFile(
		    &pbuc->hAlternate,
		    FILE_GENERIC_READ,
		    &oa,
		    &iosb,
		    FILE_SHARE_READ|FILE_SHARE_WRITE,
		    FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_FOR_BACKUP_INTENT);

	if (!NT_SUCCESS(Status)) {
	    pbuc->iBuffer += pfsi->NextEntryOffset;
	    if (pfsi->NextEntryOffset != 0) {
		pbuc->head.Size.LowPart = 1;
		pbuc->fMultiStreamType = TRUE;	// more to come
	    }
	    return(TRUE);
	}

	pbuc->head.dwStreamId = mwStreamList[pbuc->StreamIndex];
	pbuc->head.dwStreamAttributes = STREAM_NORMAL_ATTRIBUTE;
	pbuc->head.dwStreamNameSize = pfsi->StreamNameLength;

	pbuc->cbHeader = CB_NAMELESSHEADER + pfsi->StreamNameLength;

	RtlCopyMemory(
	    pbuc->head.cStreamName,
	    pfsi->StreamName,
	    pfsi->StreamNameLength);

	pbuc->head.Size.LowPart = GetFileSize(
		pbuc->hAlternate,
		&pbuc->head.Size.HighPart);

	if (pfsi->NextEntryOffset != 0) {
	    pbuc->iBuffer += pfsi->NextEntryOffset;
	    pbuc->fMultiStreamType = TRUE;	// more to come after this one
	}
    }
    else if (pbuc->liStreamOffset.HighPart != 0 ||
	    pbuc->liStreamOffset.LowPart >= pbuc->cbHeader) {

	if (pbuc->liStreamOffset.LowPart == pbuc->cbHeader &&
	    pbuc->liStreamOffset.HighPart == 0) {

	    // if we can't lock all records, return an error
	    if (!LockFile(pbuc->hAlternate, 0, 0, 0xffffffff, 0xffffffff)) {
		return(FALSE);
	    }
	}
	return(BackupReadStream(pbuc->hAlternate, pbuc, pbif));
    }
    return(TRUE);
}
Пример #13
0
int __cdecl main(int argc, char *argv[])
{

    HANDLE TheFile;
    DWORD FileStart = 0;
    DWORD FileEnd = 0;
    const char lpBuffer[] = "This is a test file.";
    DWORD bytesWritten;
    BOOL bRc = TRUE;
    char fileName[] = "testfile.tmp";

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }

    /* Important to have sharing enabled, or there is no need for the lock. */
    TheFile = CreateFile(fileName,
                         GENERIC_READ|GENERIC_WRITE,
                         FILE_SHARE_READ|FILE_SHARE_WRITE,
                         NULL,
                         CREATE_ALWAYS,
                         FILE_ATTRIBUTE_NORMAL,
                         NULL);

    if (TheFile == INVALID_HANDLE_VALUE)
    {
        Fail("ERROR: Could not open file '%s' with CreateFile.",fileName);
    }

    bRc = WriteFile(TheFile,
                    lpBuffer,
                    (DWORD)sizeof(lpBuffer),
                    &bytesWritten,
                    NULL);

    if(!bRc)
    {
        if(CloseHandle(TheFile) == 0)
        {
            Fail("ERROR: CloseHandle failed to close the file.");
        }

        Fail("ERROR: Could not write to file '%s' with WriteFile.",fileName);
    }
    else if(bytesWritten != (DWORD)sizeof(lpBuffer))
    {
        if(CloseHandle(TheFile) == 0)
        {
            Fail("ERROR: CloseHandle failed to close the file.");
        }

        Fail("ERROR: Could not write the correct number of bytes to the "
             "file '%s' with WriteFile.",fileName);
    }

    /* Find the value for the End of the file */
    FileEnd = SetFilePointer(TheFile,0,NULL,FILE_END);

    if(FileEnd == INVALID_SET_FILE_POINTER)
    {
        if(CloseHandle(TheFile) == 0)
        {
            Fail("ERROR: CloseHandle failed to close the file.");
        }

        Fail("ERROR: Could not set the file pointer to the end of the file "
             "using SetFilePointer.  It returned INVALID_SET_FILE_POINTER.");
    }

    /* Lock the file from Start to EOF */

    if(LockFile(TheFile, FileStart, 0, FileEnd, 0) == 0)
    {
        Trace("ERROR: LockFile failed.  GetLastError returns %d.",
              GetLastError());
        if(CloseHandle(TheFile) == 0)
        {
            Fail("ERROR: CloseHandle failed to close the file.");
        }
        Fail("");
    }

    /* Launch another process, which will attempt to read and write from
       the locked file.

       If the helper program returns 1, then the test fails. More
       specific errors are given by the Helper file itself.
    */
    if(RunHelper(HELPER))
    {
        if(CloseHandle(TheFile) == 0)
        {
            Fail("ERROR: CloseHandle failed to close the file.");
        }

        Fail("ERROR: The Helper program determined that the file was not "
             "locked properly by LockFile.");
    }

    if(UnlockFile(TheFile, FileStart, 0, FileEnd, 0) == 0)
    {
        Trace("ERROR: UnlockFile failed.  GetLastError returns %d.",
              GetLastError());
        if(CloseHandle(TheFile) == 0)
        {
            Fail("ERROR: CloseHandle failed to close the file.");
        }
        Fail("");
    }

    if(CloseHandle(TheFile) == 0)
    {
        Fail("ERROR: CloseHandle failed to close the file.");
    }

    PAL_Terminate();
    return PASS;
}
Пример #14
0
/*
 * Creates a zero-length locking file and use fcntl to
 * place an exclusive lock over it. The lock will be
 * automatically erased when the olsrd process ends,
 * so it will even work well with a SIGKILL.
 *
 * Additionally the lock can be killed by removing the
 * locking file.
 */
static int olsr_create_lock_file(bool noExitOnFail) {
#ifdef WIN32
    bool success;
    HANDLE lck;

    lck = CreateFile(lock_file_name,
            GENERIC_READ | GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            NULL,
            OPEN_ALWAYS,
            FILE_ATTRIBUTE_NORMAL |
            FILE_FLAG_DELETE_ON_CLOSE,
            NULL);
  CreateEvent(NULL, TRUE, FALSE, lock_file_name);
  if (INVALID_HANDLE_VALUE == lck || ERROR_ALREADY_EXISTS == GetLastError()) {
    if (noExitOnFail) {
      return -1;
    }
    if (NULL == lck) {
      fprintf(stderr,
          "Error, cannot create OLSR lock '%s'.\n",
          lock_file_name);
    } else {
      CloseHandle(lck);
      fprintf(stderr,
          "Error, cannot aquire OLSR lock '%s'.\n"
          "Another OLSR instance might be running.\n",
          lock_file_name);
    }
    olsr_exit("", EXIT_FAILURE);
  }

  success = LockFile( lck, 0, 0, 0, 0);

  if (!success) {
      CloseHandle(lck);
      if (noExitOnFail) {
          return -1;
      }
      fprintf(stderr,
          "Error, cannot aquire OLSR lock '%s'.\n"
          "Another OLSR instance might be running.\n",
          lock_file_name);
    olsr_exit("", EXIT_FAILURE);
  }
      
#else
  struct flock lck;

  /* create file for lock */
  lock_fd = open(lock_file_name, O_WRONLY | O_CREAT, S_IRWXU);
  if (lock_fd == 0) {
    if (noExitOnFail) {
      return -1;
    }
    fprintf(stderr,
        "Error, cannot create OLSR lock '%s'.\n",
        lock_file_name);
    olsr_exit("", EXIT_FAILURE);
  }

  /* create exclusive lock for the whole file */
  lck.l_type = F_WRLCK;
  lck.l_whence = SEEK_SET;
  lck.l_start = 0;
  lck.l_len = 0;
  lck.l_pid = 0;

  if (fcntl(lock_fd, F_SETLK, &lck) == -1) {
    close(lock_fd);
    if (noExitOnFail) {
      return -1;
    }
    fprintf(stderr,
        "Error, cannot aquire OLSR lock '%s'.\n"
        "Another OLSR instance might be running.\n",
        lock_file_name);
    olsr_exit("", EXIT_FAILURE);
  }
#endif
  return 0;
}
Пример #15
0
static VOID Test(PWSTR Prefix)
{
    static PWSTR Sddl = L"D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;WD)";
    static const GUID ReparseGuid =
        { 0x2cf25cfa, 0x41af, 0x4796, { 0xb5, 0xef, 0xac, 0xa3, 0x85, 0x3, 0xe2, 0xd8 } };
    WCHAR FileName[1024], VolumeName[MAX_PATH];
    PSECURITY_DESCRIPTOR SecurityDescriptor;
    HANDLE Handle;
    BOOL Success;
    UINT8 RdBuffer[4096], WrBuffer[4096];
    REPARSE_GUID_DATA_BUFFER ReparseDataBuf;
    DWORD BytesTransferred, Offset;
    WIN32_FIND_DATAW FindData;
    WIN32_FIND_STREAM_DATA FindStreamData;

    memset(WrBuffer, 'B', sizeof WrBuffer);

    Success = ConvertStringSecurityDescriptorToSecurityDescriptorW(
        Sddl, SDDL_REVISION_1, &SecurityDescriptor, 0);
    ASSERT(Success);

    wsprintfW(FileName, L"%s\\", Prefix);
    Success = GetVolumeInformationW(FileName, VolumeName, MAX_PATH, 0, 0, 0, 0, 0);
    ASSERT(Success);

    wsprintfW(FileName, L"%s\\", Prefix);
    Success = SetVolumeLabelW(FileName, VolumeName);
    //ASSERT(Success);

    wsprintfW(FileName, L"%s\\fscrash", Prefix);
    Success = CreateDirectoryW(FileName, 0);
    ASSERT(Success);

    wsprintfW(FileName, L"%s\\fscrash\\file0", Prefix);
    Handle = CreateFileW(FileName,
        GENERIC_ALL, 0, 0,
        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
    ASSERT(INVALID_HANDLE_VALUE != Handle);
    Success = CloseHandle(Handle);
    ASSERT(Success);

    wsprintfW(FileName, L"%s\\fscrash\\file0", Prefix);
    Handle = CreateFileW(FileName,
        GENERIC_ALL, 0, 0,
        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
    ASSERT(INVALID_HANDLE_VALUE != Handle);

    Success = WriteFile(Handle, WrBuffer, sizeof WrBuffer, &BytesTransferred, 0);
    ASSERT(Success);
    ASSERT(sizeof WrBuffer == BytesTransferred);

    Success = FlushFileBuffers(Handle);
    ASSERT(Success);

    Offset = SetFilePointer(Handle, 0, 0, FILE_BEGIN);
    ASSERT(0 == Offset);

    Success = ReadFile(Handle, RdBuffer, sizeof RdBuffer, &BytesTransferred, 0);
    ASSERT(Success);
    ASSERT(sizeof WrBuffer == BytesTransferred);

    Offset = SetFilePointer(Handle, 0, 0, FILE_BEGIN);
    ASSERT(0 == Offset);

    Success = SetEndOfFile(Handle);
    ASSERT(Success);

    Offset = GetFileSize(Handle, 0);
    ASSERT(0 == Offset);

    Success = LockFile(Handle, 0, 0, 1, 0);
    ASSERT(Success);

    Success = UnlockFile(Handle, 0, 0, 1, 0);
    ASSERT(Success);

    Success = SetKernelObjectSecurity(Handle, DACL_SECURITY_INFORMATION, SecurityDescriptor);
    ASSERT(Success);

    Success = GetKernelObjectSecurity(Handle, DACL_SECURITY_INFORMATION, 0, 0, &BytesTransferred);
    ASSERT(!Success);
    ASSERT(ERROR_INSUFFICIENT_BUFFER == GetLastError());

    ReparseDataBuf.ReparseTag = 0x1234;
    ReparseDataBuf.ReparseDataLength = 0;
    ReparseDataBuf.Reserved = 0;
    memcpy(&ReparseDataBuf.ReparseGuid, &ReparseGuid, sizeof ReparseGuid);

    Success = DeviceIoControl(Handle, FSCTL_SET_REPARSE_POINT,
        &ReparseDataBuf, REPARSE_GUID_DATA_BUFFER_HEADER_SIZE + ReparseDataBuf.ReparseDataLength,
        0, 0,
        &BytesTransferred, 0);
    ASSERT(Success);

    Success = CloseHandle(Handle);
    ASSERT(Success);

    wsprintfW(FileName, L"%s\\fscrash\\*", Prefix);
    Handle = FindFirstFileW(FileName, &FindData);
    ASSERT(INVALID_HANDLE_VALUE != Handle);
    do
    {
    } while (FindNextFileW(Handle, &FindData));
    ASSERT(ERROR_NO_MORE_FILES == GetLastError());
    Success = FindClose(Handle);
    ASSERT(Success);

    wsprintfW(FileName, L"%s\\fscrash\\file0", Prefix);
    Handle = FindFirstStreamW(FileName, FindStreamInfoStandard, &FindStreamData, 0);
    ASSERT(INVALID_HANDLE_VALUE != Handle);
    do
    {
    } while (FindNextStreamW(Handle, &FindStreamData));
    ASSERT(ERROR_HANDLE_EOF == GetLastError());
    Success = FindClose(Handle);
    ASSERT(Success);

    wsprintfW(FileName, L"%s\\fscrash\\file0", Prefix);
    Success = DeleteFileW(FileName);
    ASSERT(Success);

    wsprintfW(FileName, L"%s\\fscrash", Prefix);
    Success = RemoveDirectoryW(FileName);
    ASSERT(Success);

    LocalFree(SecurityDescriptor);
}
Пример #16
0
bool SCH_EDIT_FRAME::OpenProjectFiles( const std::vector<wxString>& aFileSet, int aCtl )
{
    // implement the pseudo code from KIWAY_PLAYER.h:

    SCH_SCREENS screenList;

    // This is for python:
    if( aFileSet.size() != 1 )
    {
        UTF8 msg = StrPrintf( "Eeschema:%s() takes only a single filename", __func__ );
        DisplayError( this, msg );
        return false;
    }

    wxString    fullFileName( aFileSet[0] );

    // We insist on caller sending us an absolute path, if it does not, we say it's a bug.
    wxASSERT_MSG( wxFileName( fullFileName ).IsAbsolute(),
        wxT( "bug in single_top.cpp or project manager." ) );

    if( !LockFile( fullFileName ) )
    {
        wxString msg = wxString::Format( _(
                "Schematic file '%s' is already open." ),
                GetChars( fullFileName )
                );
        DisplayError( this, msg );
        return false;
    }

    // save any currently open and modified project files.
    for( SCH_SCREEN* screen = screenList.GetFirst(); screen; screen = screenList.GetNext() )
    {
        if( screen->IsModify() )
        {
            int response = YesNoCancelDialog( this, _(
                "The current schematic has been modified.  Do you wish to save the changes?" ),
                wxEmptyString,
                _( "Save and Load" ),
                _( "Load Without Saving" )
                );

            if( response == wxID_CANCEL )
            {
                return false;
            }
            else if( response == wxID_YES )
            {
                wxCommandEvent dummy;
                OnSaveProject( dummy );
            }
            else
            {
                // response == wxID_NO, fall thru
            }
            break;
        }
    }

    wxFileName pro = fullFileName;
    pro.SetExt( ProjectFileExtension );

    bool is_new = !wxFileName::IsFileReadable( fullFileName );

    // If its a non-existent schematic and caller thinks it exists
    if( is_new && !( aCtl & KICTL_CREATE ) )
    {
        // notify user that fullFileName does not exist, ask if user wants to create it.
        wxString ask = wxString::Format( _(
                "Schematic '%s' does not exist.  Do you wish to create it?" ),
                GetChars( fullFileName )
                );
        if( !IsOK( this, ask ) )
            return false;
    }

    // unload current project file before loading new
    {
        delete g_RootSheet;
        g_RootSheet = NULL;

        CreateScreens();
    }

    GetScreen()->SetFileName( fullFileName );
    g_RootSheet->SetFileName( fullFileName );

    SetStatusText( wxEmptyString );
    ClearMsgPanel();

    wxString msg = wxString::Format( _(
            "Ready\nProject dir: '%s'\n" ),
            GetChars( wxPathOnly( Prj().GetProjectFullName() ) )
            );
    SetStatusText( msg );

    // PROJECT::SetProjectFullName() is an impactful function.  It should only be
    // called under carefully considered circumstances.

    // The calling code should know not to ask me here to change projects unless
    // it knows what consequences that will have on other KIFACEs running and using
    // this same PROJECT.  It can be very harmful if that calling code is stupid.
    Prj().SetProjectFullName( pro.GetFullPath() );

    LoadProjectFile();

    // load the libraries here, not in SCH_SCREEN::Draw() which is a context
    // that will not tolerate DisplayError() dialog since we're already in an
    // event handler in there.
    // And when a schematic file is loaded, we need these libs to initialize
    // some parameters (links to PART LIB, dangling ends ...)
    Prj().SetElem( PROJECT::ELEM_SCH_PART_LIBS, NULL );
    Prj().SchLibs();

    if( is_new )
    {
        // mark new, unsaved file as modified.
        GetScreen()->SetModify();
    }
    else
    {
        g_RootSheet->SetScreen( NULL );

        DBG( printf( "%s: loading schematic %s\n", __func__, TO_UTF8( fullFileName ) );)

        bool diag = g_RootSheet->Load( this );
        (void) diag;

        SetScreen( m_CurrentSheet->LastScreen() );

        GetScreen()->ClrModify();

        UpdateFileHistory( fullFileName );

        // Check to see whether some old library parts need to be rescued
        // Only do this if RescueNeverShow was not set.
        wxConfigBase *config = Kiface().KifaceSettings();
        bool rescueNeverShow = false;
        config->Read( RESCUE_NEVER_SHOW_KEY, &rescueNeverShow, false );

        if( !rescueNeverShow )
        {
            if( RescueProject( false ) )
            {
                GetScreen()->CheckComponentsToPartsLinks();
                GetScreen()->TestDanglingEnds();
            }
        }
    }
Пример #17
0
Файл: main.cpp Проект: xlin/pbs
int main(int argc, char **argv){
    if (getuid()!=0){
	std::cout << "run only root" << std::endl;
	return 1;
    }
    MYSQL_RES *result;
    MYSQL_ROW row;
    MYSQL *connection, mysql;    
    
    // Защита от двойного запуска
    int fd = -1;
    if ((fd = open(PATHLOCK, O_RDWR| O_CREAT, S_IRUSR| S_IWUSR)) == -1) {
        int myerr = errno;
        printf("ERROR: open errno(%d): %s\n", errno,strerror(myerr));
        return EXIT_FAILURE;
    }
    if (LockFile(fd)==EXIT_FAILURE){
	std::cout << "ERROR: is already running" << std::endl;
	return 1;
    }
    
    
    // Читаем в map параметры командной строки
    map<string,string> cmdParam = loadArgv(argc,argv);
    
    if (cmdParam["--daemon"]=="true") run_as_daemon();
    

    map<string,string> conf = loadConfig();
    //string pathAum=conf["paths/pathAum"];
    string pathUserHome=conf["paths/pathUserHome"];
    //string pathPbs=conf["paths/pathPbs"];
    string pathTemp=conf["paths/pathTemp"];

    string cmdLine="";
    string sqlQuery="";
    int buildError=0;		// Состояние ошибки
    
    mysql_init(&mysql);
    connection = mysql_real_connect(&mysql,conf["mysql/hostname"].c_str(), conf["mysql/username"].c_str(), conf["mysql/password"].c_str(), conf["mysql/database"].c_str(), 0, NULL,0);
    if( connection == NULL ) {
	printf("%s\n",mysql_error(&mysql));
        return 1;
    }
    
    srand (time(NULL));

    // Тут будет основной цикл
    while(1){
	
	int state = mysql_query(connection, 
	    "SELECT t1.id,t1.file_id, t2.filename, t3.user, t4.os, t4.arch "
	    "FROM jobs as t1, tsrc t2, users as t3, platforms as t4 "
	    "WHERE t1.status=0 and t2.id=t1.file_id and t3.id=t2.user_id and t4.id=t1.platform_id ");
	    
	if( state != 0 ) {
	    printf("%s\n",mysql_error(connection));
	    break;
	}

        result = mysql_store_result(connection);    
	while( ( row = mysql_fetch_row(result)) != NULL ) {
    	    printf("%s, %s\n",  row[0],row[1]);
    	
    	    // 
    	    sqlQuery="UPDATE jobs SET status='1' WHERE id='"+string(row[0])+"'";
    	    mysql_query(connection,sqlQuery.c_str());
    	
    	    string dbNSrcFile=string(row[1]);
    	    string dbOsName=string(row[4]);
    	    string dbOsArch=string(row[5]);
	    string username=string(row[3]);
	    string jobFilename=string(row[2]);
	    
	    string aumOsKey=dbOsName+"_"+dbOsArch;
	    string aumLogFile=pathUserHome+"/"+username+"/logs/"+dbNSrcFile+"/"+aumOsKey+".txt";
	    string aumUploadDir=pathTemp+"/files/"+dbNSrcFile;
	    string aumFileName=pathUserHome+"/"+username+"/srpms/"+dbNSrcFile+"/"+jobFilename;

	    std::cout << " " << dbNSrcFile << " " << dbOsName << " " << dbOsArch << " " << username << " " << jobFilename << " " << aumOsKey << std::endl;
	    
	    string aumChroot=conf[aumOsKey+"/chroot"];
	    string aumDistrib=conf[aumOsKey+"/distrib"];
	    
	    string aumPathTemp=pathTemp+"/pbs-chroot-"+dbNSrcFile+"-"+aumOsKey;
	    
	    //Создание временной папки
	    pbsMkdir(aumUploadDir);
	    pbsMkdir(aumPathTemp);

	    map<string,string> options;
	
	    // Формирование строки
	    //cmdLine=pathAum+" ";
	    options["chroot"]=aumChroot;
	    options["distrib"]=aumDistrib;
	    options["log-file"]=aumLogFile;
	    options["upload-dir"]=aumUploadDir;
	    options["tmp-dir"]=aumPathTemp;
	    
	    if (boost::filesystem::exists(pathUserHome+"/"+username+"/.rpmmacros")==true){
		options["rpmmacros"]=pathUserHome+"/"+username+"/.rpmmacros";
	    }
	    options["srpm"]=aumFileName;

	    

	    // Запуск сборки
	    //buildError=system(cmdLine.c_str());
	    cBuild bb;
	    buildError=bb.build(options);
	    if (buildError!=0){
    	        string sqlQuery="UPDATE jobs SET status='11' WHERE id='"+string(row[0])+"'";
    		mysql_query(connection,sqlQuery.c_str());
		continue;
	    }
	    

	    string targetOs = pathUserHome+"/"+username+"/repo/"+dbOsName;
	    int countFile=copyRpmToRepo(aumUploadDir,targetOs);
	    if (countFile==0){
    	        string sqlQuery="UPDATE jobs SET status='11' WHERE id='"+string(row[0])+"'";
    		mysql_query(connection,sqlQuery.c_str());
		continue;
	    }
	    
	    // Удаление временной папки
	    boost::filesystem::remove_all(aumUploadDir);

	    
	    // Пересоздание репозитория
	    exec_cmd("pbs-hdlistgen "+username+ " "+dbOsName);
	    
	    
    	    sqlQuery="UPDATE jobs SET status='10' WHERE id='"+string(row[0])+"'";
	    mysql_query(connection,sqlQuery.c_str());
	    
	    std::cout << "Build end" << std::endl;
	    
	}
	mysql_free_result(result);

	sleep(1);
    }
    
    
    mysql_close(connection);

    return 0;
}