static void nlPrepareClose(NLsocket socket) { if(nlIsValidSocket(socket) != NL_TRUE) return; struct Unlocker { NLsocket socket; ~Unlocker() { nlUnlockSocket(socket, NL_BOTH); } Unlocker(NLsocket s) : socket(s) {} }; if(nlLockSocket(socket, NL_BOTH) == NL_FALSE) { return; } Unlocker unlocker(socket); // code copied&modified from sock_Close // The advantage we have here is that we don't lock the whole socket array. // nlClose is doing this, so if we would hang in nlClose, we block the // *whole* HawkNL system (or at least actions like opening new sockets etc.)! nl_socket_t *sock = nlSockets[socket]; struct ip_mreq mreq; if(sock->type == NL_UDP_MULTICAST) { /* leave the multicast group */ mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)&sock->addressout)->sin_addr.s_addr; mreq.imr_interface.s_addr = INADDR_ANY; //bindaddress; (void)setsockopt((SOCKET)sock->realsocket, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&mreq, (int)sizeof(mreq)); } if(sock->type == NL_RELIABLE_PACKETS) { /* check for unsent data */ if(sock->sendlen > 0) { int tries = 200; /* 200 * 50 ms = up to a 10 second delay to allow data to be sent */ while(tries-- > 0 && sock->sendlen > 0) { SDL_Delay(50); } } // oh just f**k it sock->sendlen = 0; } if((sock->type == NL_RELIABLE_PACKETS || sock->type == NL_RELIABLE) && sock->listen == NL_FALSE) { struct linger l = {1, 10}; (void)setsockopt((SOCKET)sock->realsocket, SOL_SOCKET, SO_LINGER, (const char *)&l, (int)sizeof(l)); } (void)closesocket((SOCKET)sock->realsocket); }
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // DeviceRemoved() //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void PlugIn::DeviceRemoved(Device& device) { // Suspend the device device.Unplug(); // Save it's settings if necessary if (DALA::System::IsMaster()) DP::DeviceSettings::SaveToPrefs(device, DP::DeviceSettings::sStandardControlsToSave, DP::DeviceSettings::kStandardNumberControlsToSave); { // Unlock the mutex since CMIOObjectsPublishedAndDied() can callout to property listeners CAMutex::Unlocker unlocker(GetStateMutex()); // Tell the DAL that the device has gone away CMIOObjectID objectID = device.GetObjectID(); OSStatus err = CMIOObjectsPublishedAndDied(GetInterface(), kCMIOObjectSystemObject, 0, 0, 1, &objectID); AssertNoError(err, "CMIO::DP::Sample::PlugIn::Teardown: got an error telling the DAL a device died"); } // Remove it from the device list RemoveDevice(device); // Get rid of the device object device.Teardown(); delete &device; }
void ExiftoolImageWritingWorker::process() { Helpers::AsyncCoordinatorUnlocker unlocker(m_AsyncCoordinator); Q_UNUSED(unlocker); bool success = false; initWorker(); QTemporaryFile jsonFile; if (jsonFile.open()) { LOG_INFO << "Serializing artworks to json" << jsonFile.fileName(); QJsonArray objectsToSave; artworksToJsonArray(m_ItemsToWriteSnapshot, objectsToSave); QJsonDocument document(objectsToSave); jsonFile.write(document.toJson()); jsonFile.flush(); jsonFile.close(); int numberOfItems = (int)m_ItemsToWriteSnapshot.size(); QTemporaryFile argumentsFile; if (argumentsFile.open()) { QStringList exiftoolArguments = createArgumentsList(jsonFile.fileName()); foreach (const QString &line, exiftoolArguments) { argumentsFile.write(line.toUtf8()); #ifdef Q_OS_WIN argumentsFile.write("\r\n"); #else argumentsFile.write("\n"); #endif }
void InitializeDictionariesJobItem::processJob() { LOG_DEBUG << "#"; Helpers::AsyncCoordinatorUnlocker unlocker(m_InitCoordinator); Q_UNUSED(unlocker); doInitializeDictionaries(); }
result_t Event::wait() { if (m_event.isSet()) return 0; v8::Unlocker unlocker(isolate); m_event.wait(); return 0; }
result_t Condition::wait() { if (!m_lockCond->m_lock.owned()) return CHECK_ERROR(CALL_E_INVALID_CALL); v8::Unlocker unlocker(isolate); m_cond.wait(m_lockCond->m_lock); return 0; }
//!\brief Функция возвращает файловый указатель для вывода Trace сообщений. void GetTraceLogFileName( char *logFileName, int *strSizeInChar ) { if ( klTraceInfo==NULL ) return; TraceAutoUnlock unlocker( klTraceCricSec ); *strSizeInChar = klTraceInfo->traceLogFile.length() + 1; if ( logFileName!=NULL ) strcpy( logFileName, klTraceInfo->traceLogFile.c_str() ); }
result_t Semaphore::wait() { if (m_sem.trywait()) return 0; v8::Unlocker unlocker(isolate); m_sem.wait(); return 0; }
bool SkBitmapProcState::lockBaseBitmap() { AutoScaledCacheUnlocker unlocker(&fScaledCacheID); SkPixelRef* pr = fOrigBitmap.pixelRef(); SkASSERT(NULL == fScaledCacheID); if (pr->isLocked() || !pr->implementsDecodeInto()) { // fast-case, no need to look in our cache fScaledBitmap = fOrigBitmap; fScaledBitmap.lockPixels(); if (NULL == fScaledBitmap.getPixels()) { return false; } } else { fScaledCacheID = SkScaledImageCache::FindAndLock(fOrigBitmap, SK_Scalar1, SK_Scalar1, &fScaledBitmap); if (fScaledCacheID) { fScaledBitmap.lockPixels(); if (!fScaledBitmap.getPixels()) { fScaledBitmap.unlockPixels(); // found a purged entry (discardablememory?), release it SkScaledImageCache::Unlock(fScaledCacheID); fScaledCacheID = NULL; // fall through to rebuild } } if (NULL == fScaledCacheID) { if (!get_locked_pixels(fOrigBitmap, 0, &fScaledBitmap)) { return false; } // TODO: if fScaled comes back at a different width/height than fOrig, // we need to update the matrix we are using to sample from this guy. fScaledCacheID = SkScaledImageCache::AddAndLock(fOrigBitmap, SK_Scalar1, SK_Scalar1, fScaledBitmap); if (!fScaledCacheID) { fScaledBitmap.reset(); return false; } } } fBitmap = &fScaledBitmap; unlocker.release(); return true; }
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // DeviceArrived() //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void PlugIn::DeviceArrived(UInt64 guid, const io_string_t registryPath) { try { // Instantiate a new CMIODevice object in the DAL CMIODeviceID deviceID = 0; OSStatus err = CMIOObjectCreate(GetInterface(), kCMIOObjectSystemObject, kCMIODeviceClassID, &deviceID); ThrowIfError(err, CAException(err), "CMIO::DP::Sample::PlugIn::DeviceArrived: couldn't instantiate the CMIODevice object"); // Make a device object Device* device = new Device(*this, deviceID, mAssistantPort, guid, registryPath); try { // Initialize the device device->Initialize(); // Restore its settings if necessary if (DALA::System::IsMaster()) { DP::DeviceSettings::RestoreFromPrefs(*device, DP::DeviceSettings::sStandardControlsToSave, DP::DeviceSettings::kStandardNumberControlsToSave); } // Set the object state mutex Object::SetObjectStateMutexForID(deviceID, device->GetObjectStateMutex()); // Add it to the device list AddDevice(*device); // Unlock the mutex since CMIOObjectsPublishedAndDied() can callout to property listeners CAMutex::Unlocker unlocker(GetStateMutex()); // Tell the DAL about the device err = CMIOObjectsPublishedAndDied(GetInterface(), kCMIOObjectSystemObject, 1, &deviceID, 0, 0); ThrowIfError(err, err, "CMIO::DP::Sample::PlugIn::DeviceArrived: couldn't tell the DAL about a new device"); } catch (...) { // Remove it from the device list (which is always safe to attempt) and delete it RemoveDevice(*device); delete device; } } catch (...) { } }
void *FiberBase::fiber_proc(void *p) { Isolate* isolate = (Isolate*)p; Runtime rt; rt.m_pDateCache = &isolate->m_dc; Runtime::reg(&rt); v8::Locker locker(isolate->m_isolate); v8::Isolate::Scope isolate_scope(isolate->m_isolate); v8::HandleScope handle_scope(isolate->m_isolate); v8::Context::Scope context_scope( v8::Local<v8::Context>::New(isolate->m_isolate, isolate->m_context)); isolate->m_idleFibers --; while (1) { AsyncEvent *ae; if ((ae = (AsyncEvent*)isolate->m_jobs.tryget()) == NULL) { isolate->m_idleFibers ++; if (isolate->m_idleFibers > g_spareFibers) { isolate->m_idleFibers --; break; } { v8::Unlocker unlocker(isolate->m_isolate); ae = (AsyncEvent*)isolate->m_jobs.get(); } isolate->m_idleFibers --; } { v8::HandleScope handle_scope(isolate->m_isolate); ae->js_invoke(); } } isolate->m_currentFibers --; return NULL; }
void *FiberBase::fiber_proc(void *p) { Isolate* isolate = Isolate::now(); v8::Locker locker(isolate->m_isolate); v8::Isolate::Scope isolate_scope(isolate->m_isolate); v8::HandleScope handle_scope(isolate->m_isolate); v8::Context::Scope context_scope( v8::Local<v8::Context>::New(isolate->m_isolate, isolate->m_context)); s_idleFibers --; while (1) { AsyncEvent *ae; if ((ae = g_jobs.tryget()) == NULL) { s_idleFibers ++; if (s_idleFibers > g_spareFibers) { s_idleFibers --; break; } { v8::Unlocker unlocker(isolate->m_isolate); ae = g_jobs.get(); } s_idleFibers --; } { v8::HandleScope handle_scope(isolate->m_isolate); ae->js_invoke(); } } s_fibers --; return NULL; }
bool AutoCompleteWorker::initWorker() { LOG_DEBUG << "#"; Helpers::AsyncCoordinatorUnlocker unlocker(m_InitCoordinator); Q_UNUSED(unlocker); bool success = false; do { if (!m_FaceCompletionEngine.initialize()) { break; } if (!m_PresetsCompletionEngine.initialize()) { break; } success = true; } while(false); return success; }
void *FiberBase::fiber_proc(void *p) { Isolate &isolate = Isolate::now(); v8::Locker locker(isolate.isolate); v8::Isolate::Scope isolate_scope(isolate.isolate); v8::HandleScope handle_scope(isolate.isolate); v8::Context::Scope context_scope( v8::Local<v8::Context>::New(isolate.isolate, isolate.s_context)); while (1) { asyncEvent *ae; if ((ae = g_jobs.tryget()) == NULL) { s_idleFibers ++; if (s_idleFibers > MAX_IDLE) { s_idleFibers --; break; } v8::Unlocker unlocker(isolate.isolate); ae = g_jobs.get(); s_idleFibers --; } { v8::HandleScope handle_scope(isolate.isolate); ae->js_callback(); } } s_fibers --; return NULL; }
bool SpellCheckWorker::initWorker() { LOG_INFO << "Dicts root:" << m_DictsRoot; Helpers::AsyncCoordinatorUnlocker unlocker(m_InitCoordinator); Q_UNUSED(unlocker); QDir resourcesDir(m_DictsRoot); QString affPath = resourcesDir.absoluteFilePath(EN_HUNSPELL_AFF); QString dicPath = resourcesDir.absoluteFilePath(EN_HUNSPELL_DIC); bool initResult = false; if (QFileInfo(affPath).exists() && QFileInfo(dicPath).exists()) { #ifdef Q_OS_WIN // specific Hunspell handling of UTF-8 encoded pathes affPath = "\\\\?\\" + QDir::toNativeSeparators(affPath); dicPath = "\\\\?\\" + QDir::toNativeSeparators(dicPath); #endif try { m_Hunspell = new Hunspell(affPath.toUtf8().constData(), dicPath.toUtf8().constData()); LOG_DEBUG << "Hunspell initialized with AFF" << affPath << "and DIC" << dicPath; initResult = true; m_Encoding = QString::fromLatin1(m_Hunspell->get_dic_encoding()); m_Codec = QTextCodec::codecForName(m_Encoding.toLatin1().constData()); } catch (...) { LOG_DEBUG << "Error in Hunspell with AFF" << affPath << "and DIC" << dicPath; m_Hunspell = NULL; } } else { LOG_WARNING << "DIC or AFF file not found." << dicPath << "||" << affPath; } return initResult; }
result_t coroutine_base::sleep(int32_t ms) { v8::Unlocker unlocker(isolate); exlib::Fiber::sleep(ms); return 0; }
// modified sock_Write of sock.c from HawkNL // returns true if socket is connected and data could be send static bool nlUpdateState(NLsocket socket) { if(nlIsValidSocket(socket) != NL_TRUE) return false; struct Unlocker { NLsocket socket; ~Unlocker() { nlUnlockSocket(socket, NL_BOTH); } Unlocker(NLsocket s) : socket(s) {} }; if(nlLockSocket(socket, NL_BOTH) == NL_FALSE) { return false; } Unlocker unlocker(socket); nl_socket_t *sock = nlSockets[socket]; NLint count = 0; if((sock->type == NL_RELIABLE) || (sock->type == NL_RELIABLE_PACKETS)) /* TCP */ { if(sock->connecting == NL_TRUE) { fd_set fdset; struct timeval t = {0,0}; int serrval = -1; socklen_t serrsize = (socklen_t)sizeof(serrval); FD_ZERO(&fdset); FD_SET((SOCKET)sock->realsocket, &fdset); if(select(sock->realsocket + 1, NULL, &fdset, NULL, &t) == 1) { /* Check the socket status */ (void)getsockopt( sock->realsocket, SOL_SOCKET, SO_ERROR, (char *)&serrval, &serrsize ); if(serrval != 0) { if(serrval == ECONNREFUSED) { nlSetError(NL_CON_REFUSED); } else if(serrval == EINPROGRESS || serrval == EWOULDBLOCK) { nlSetError(NL_CON_PENDING); } return false; } /* the connect has completed */ sock->connected = NL_TRUE; sock->connecting = NL_FALSE; } else { /* check for a failed connect */ FD_ZERO(&fdset); FD_SET((SOCKET)sock->realsocket, &fdset); if(select(sock->realsocket + 1, NULL, NULL, &fdset, &t) == 1) { nlSetError(NL_CON_REFUSED); } else { nlSetError(NL_CON_PENDING); } return false; } } /* check for reliable packets */ if(sock->type == NL_RELIABLE_PACKETS) { return true; } return true; } else /* unconnected UDP */ { /* check for a non-blocking connection pending */ if(sock->connecting == NL_TRUE) { nlSetError(NL_CON_PENDING); return false; } /* check for a connection error */ if(sock->conerror == NL_TRUE) { nlSetError(NL_CON_REFUSED); return false; } if(sock->type == NL_BROADCAST) { ((struct sockaddr_in *)&sock->addressin)->sin_addr.s_addr = INADDR_BROADCAST; } if(sock->type == NL_UDP_MULTICAST) { return true; } else if(sock->connected == NL_TRUE) { return true; } else { return true; } } if(count == SOCKET_ERROR) { return false; } return false; }
bool SkBitmapProcState::possiblyScaleImage() { AutoScaledCacheUnlocker unlocker(&fScaledCacheID); SkASSERT(NULL == fBitmap); SkASSERT(NULL == fScaledCacheID); if (fFilterLevel <= SkPaint::kLow_FilterLevel) { return false; } // Check to see if the transformation matrix is simple, and if we're // doing high quality scaling. If so, do the bitmap scale here and // remove the scaling component from the matrix. if (SkPaint::kHigh_FilterLevel == fFilterLevel && fInvMatrix.getType() <= (SkMatrix::kScale_Mask | SkMatrix::kTranslate_Mask) && kN32_SkColorType == fOrigBitmap.colorType() && cache_size_okay(fOrigBitmap, fInvMatrix)) { SkScalar invScaleX = fInvMatrix.getScaleX(); SkScalar invScaleY = fInvMatrix.getScaleY(); fScaledCacheID = SkScaledImageCache::FindAndLock(fOrigBitmap, invScaleX, invScaleY, &fScaledBitmap); if (fScaledCacheID) { fScaledBitmap.lockPixels(); if (!fScaledBitmap.getPixels()) { fScaledBitmap.unlockPixels(); // found a purged entry (discardablememory?), release it SkScaledImageCache::Unlock(fScaledCacheID); fScaledCacheID = NULL; // fall through to rebuild } } if (NULL == fScaledCacheID) { float dest_width = fOrigBitmap.width() / invScaleX; float dest_height = fOrigBitmap.height() / invScaleY; // All the criteria are met; let's make a new bitmap. if (!SkBitmapScaler::Resize(&fScaledBitmap, fOrigBitmap, SkBitmapScaler::RESIZE_BEST, dest_width, dest_height, SkScaledImageCache::GetAllocator())) { // we failed to create fScaledBitmap, so just return and let // the scanline proc handle it. return false; } SkASSERT(NULL != fScaledBitmap.getPixels()); fScaledCacheID = SkScaledImageCache::AddAndLock(fOrigBitmap, invScaleX, invScaleY, fScaledBitmap); if (!fScaledCacheID) { fScaledBitmap.reset(); return false; } SkASSERT(NULL != fScaledBitmap.getPixels()); } SkASSERT(NULL != fScaledBitmap.getPixels()); fBitmap = &fScaledBitmap; // set the inv matrix type to translate-only; fInvMatrix.setTranslate(fInvMatrix.getTranslateX() / fInvMatrix.getScaleX(), fInvMatrix.getTranslateY() / fInvMatrix.getScaleY()); // no need for any further filtering; we just did it! fFilterLevel = SkPaint::kNone_FilterLevel; unlocker.release(); return true; } /* * If High, then our special-case for scale-only did not take, and so we * have to make a choice: * 1. fall back on mipmaps + bilerp * 2. fall back on scanline bicubic filter * For now, we compute the "scale" value from the matrix, and have a * threshold to decide when bicubic is better, and when mips are better. * No doubt a fancier decision tree could be used uere. * * If Medium, then we just try to build a mipmap and select a level, * setting the filter-level to kLow to signal that we just need bilerp * to process the selected level. */ SkScalar scaleSqd = effective_matrix_scale_sqrd(fInvMatrix); if (SkPaint::kHigh_FilterLevel == fFilterLevel) { // Set the limit at 0.25 for the CTM... if the CTM is scaling smaller // than this, then the mipmaps quality may be greater (certainly faster) // so we only keep High quality if the scale is greater than this. // // Since we're dealing with the inverse, we compare against its inverse. const SkScalar bicubicLimit = 4.0f; const SkScalar bicubicLimitSqd = bicubicLimit * bicubicLimit; if (scaleSqd < bicubicLimitSqd) { // use bicubic scanline return false; } // else set the filter-level to Medium, since we're scaling down and // want to reqeust mipmaps fFilterLevel = SkPaint::kMedium_FilterLevel; } SkASSERT(SkPaint::kMedium_FilterLevel == fFilterLevel); /** * Medium quality means use a mipmap for down-scaling, and just bilper * for upscaling. Since we're examining the inverse matrix, we look for * a scale > 1 to indicate down scaling by the CTM. */ if (scaleSqd > SK_Scalar1) { const SkMipMap* mip = NULL; SkASSERT(NULL == fScaledCacheID); fScaledCacheID = SkScaledImageCache::FindAndLockMip(fOrigBitmap, &mip); if (!fScaledCacheID) { SkASSERT(NULL == mip); mip = SkMipMap::Build(fOrigBitmap); if (mip) { fScaledCacheID = SkScaledImageCache::AddAndLockMip(fOrigBitmap, mip); SkASSERT(mip->getRefCnt() > 1); mip->unref(); // the cache took a ref SkASSERT(fScaledCacheID); } } else { SkASSERT(mip); } if (mip) { SkScalar levelScale = SkScalarInvert(SkScalarSqrt(scaleSqd)); SkMipMap::Level level; if (mip->extractLevel(levelScale, &level)) { SkScalar invScaleFixup = level.fScale; fInvMatrix.postScale(invScaleFixup, invScaleFixup); SkImageInfo info = fOrigBitmap.info(); info.fWidth = level.fWidth; info.fHeight = level.fHeight; fScaledBitmap.installPixels(info, level.fPixels, level.fRowBytes); fBitmap = &fScaledBitmap; fFilterLevel = SkPaint::kLow_FilterLevel; unlocker.release(); return true; } } } return false; }
void CDownloadQueue::Process() { // send src requests to local server ProcessLocalRequests(); { wxMutexLocker lock(m_mutex); uint32 downspeed = 0; if (thePrefs::GetMaxDownload() != UNLIMITED && m_datarate > 1500) { downspeed = (((uint32)thePrefs::GetMaxDownload())*1024*100)/(m_datarate+1); if (downspeed < 50) { downspeed = 50; } else if (downspeed > 200) { downspeed = 200; } } m_datarate = 0; m_udcounter++; uint32 cur_datarate = 0; uint32 cur_udcounter = m_udcounter; std::list<int> m_sourcecountlist; bool mustPreventSleep = false; for ( uint16 i = 0; i < m_filelist.size(); i++ ) { CPartFile* file = m_filelist[i]; CMutexUnlocker unlocker(m_mutex); uint8 status = file->GetStatus(); mustPreventSleep |= !(status == PS_ERROR || status == PS_INSUFFICIENT || status == PS_PAUSED || status == PS_COMPLETE); if (status == PS_READY || status == PS_EMPTY ){ cur_datarate += file->Process( downspeed, cur_udcounter ); } else { //This will make sure we don't keep old sources to paused and stoped files.. file->StopPausedFile(); } if (!file->IsPaused() && !file->IsStopped()) { m_sourcecountlist.push_back(file->GetSourceCount()); } } if (thePrefs::GetPreventSleepWhileDownloading()) { if ((mustPreventSleep == false) && (theStats::GetSessionSentBytes() < theStats::GetSessionReceivedBytes())) { // I can see right through your clever plan. mustPreventSleep = true; } if (mustPreventSleep) { PlatformSpecific::PreventSleepMode(); } else { PlatformSpecific::AllowSleepMode(); } } else { // Just in case the value changes while we're preventing. Calls to this function are totally inexpensive anwyay PlatformSpecific::AllowSleepMode(); } // Set the source rarity thresholds int nSourceGroups = m_sourcecountlist.size(); if (nSourceGroups) { m_sourcecountlist.sort(); if (nSourceGroups == 1) { // High anyway. m_rareFileThreshold = m_sourcecountlist.front() + 1; m_commonFileThreshold = m_rareFileThreshold + 1; } else if (nSourceGroups == 2) { // One high, one low (unless they're both 0, then both high) m_rareFileThreshold = (m_sourcecountlist.back() > 0) ? (m_sourcecountlist.back() - 1) : 1; m_commonFileThreshold = m_rareFileThreshold + 1; } else { // More than two, time to do some math. // Lower 25% with the current #define values. int rarecutpoint = (nSourceGroups / RARITY_FACTOR); for (int i = 0; i < rarecutpoint; ++ i) { m_sourcecountlist.pop_front(); } m_rareFileThreshold = (m_sourcecountlist.front() > 0) ? (m_sourcecountlist.front() - 1) : 1; // 50% of the non-rare ones, with the curent #define values. int commoncutpoint = (nSourceGroups - rarecutpoint) / NORMALITY_FACTOR; for (int i = 0; i < commoncutpoint; ++ i) { m_sourcecountlist.pop_front(); } m_commonFileThreshold = (m_sourcecountlist.front() > 0) ? (m_sourcecountlist.front() - 1) : 1; } } else { m_rareFileThreshold = RARE_FILE; m_commonFileThreshold = 100; } m_datarate += cur_datarate; if (m_udcounter == 5) { if (theApp->serverconnect->IsUDPSocketAvailable()) { if( (::GetTickCount() - m_lastudpstattime) > UDPSERVERSTATTIME) { m_lastudpstattime = ::GetTickCount(); CMutexUnlocker unlocker(m_mutex); theApp->serverlist->ServerStats(); } } } if (m_udcounter == 10) { m_udcounter = 0; if (theApp->serverconnect->IsUDPSocketAvailable()) { if ( (::GetTickCount() - m_lastudpsearchtime) > UDPSERVERREASKTIME) { SendNextUDPPacket(); } } } if ( (::GetTickCount() - m_lastsorttime) > 10000 ) { DoSortByPriority(); } // Check if any paused files can be resumed CheckDiskspace(thePrefs::GetTempDir()); } // Check for new links once per second. if ((::GetTickCount() - m_nLastED2KLinkCheck) >= 1000) { theApp->AddLinksFromFile(); m_nLastED2KLinkCheck = ::GetTickCount(); } }
void CDownloadQueue::Process() { // send src requests to local server ProcessLocalRequests(); { wxMutexLocker lock(m_mutex); uint32 downspeed = 0; if (thePrefs::GetMaxDownload() != UNLIMITED && m_datarate > 1500) { downspeed = (((uint32)thePrefs::GetMaxDownload())*1024*100)/(m_datarate+1); if (downspeed < 50) { downspeed = 50; } else if (downspeed > 200) { downspeed = 200; } } m_datarate = 0; m_udcounter++; uint32 cur_datarate = 0; uint32 cur_udcounter = m_udcounter; for ( uint16 i = 0; i < m_filelist.size(); i++ ) { CPartFile* file = m_filelist[i]; CMutexUnlocker unlocker(m_mutex); if ( file->GetStatus() == PS_READY || file->GetStatus() == PS_EMPTY ){ cur_datarate += file->Process( downspeed, cur_udcounter ); } else { //This will make sure we don't keep old sources to paused and stoped files.. file->StopPausedFile(); } } m_datarate += cur_datarate; if (m_udcounter == 5) { if (theApp->serverconnect->IsUDPSocketAvailable()) { if( (::GetTickCount() - m_lastudpstattime) > UDPSERVERSTATTIME) { m_lastudpstattime = ::GetTickCount(); CMutexUnlocker unlocker(m_mutex); theApp->serverlist->ServerStats(); } } } if (m_udcounter == 10) { m_udcounter = 0; if (theApp->serverconnect->IsUDPSocketAvailable()) { if ( (::GetTickCount() - m_lastudpsearchtime) > UDPSERVERREASKTIME) { SendNextUDPPacket(); } } } if ( (::GetTickCount() - m_lastsorttime) > 10000 ) { DoSortByPriority(); } // Check if any paused files can be resumed CheckDiskspace(thePrefs::GetTempDir()); } // Check for new links once per second. if ((::GetTickCount() - m_nLastED2KLinkCheck) >= 1000) { theApp->AddLinksFromFile(); m_nLastED2KLinkCheck = ::GetTickCount(); } }
nsresult nsProfileLock::Lock(nsIFile* aProfileDir, nsIProfileUnlocker* *aUnlocker) { #if defined (XP_MACOSX) NS_NAMED_LITERAL_STRING(LOCKFILE_NAME, ".parentlock"); NS_NAMED_LITERAL_STRING(OLD_LOCKFILE_NAME, "parent.lock"); #elif defined (XP_UNIX) NS_NAMED_LITERAL_STRING(OLD_LOCKFILE_NAME, "lock"); NS_NAMED_LITERAL_STRING(LOCKFILE_NAME, ".parentlock"); #else NS_NAMED_LITERAL_STRING(LOCKFILE_NAME, "parent.lock"); #endif nsresult rv; if (aUnlocker) *aUnlocker = nullptr; NS_ENSURE_STATE(!mHaveLock); bool isDir; rv = aProfileDir->IsDirectory(&isDir); if (NS_FAILED(rv)) return rv; if (!isDir) return NS_ERROR_FILE_NOT_DIRECTORY; nsCOMPtr<nsIFile> lockFile; rv = aProfileDir->Clone(getter_AddRefs(lockFile)); if (NS_FAILED(rv)) return rv; rv = lockFile->Append(LOCKFILE_NAME); if (NS_FAILED(rv)) return rv; #if defined(XP_MACOSX) // First, try locking using fcntl. It is more reliable on // a local machine, but may not be supported by an NFS server. rv = LockWithFcntl(lockFile); if (NS_FAILED(rv) && (rv != NS_ERROR_FILE_ACCESS_DENIED)) { // If that failed for any reason other than NS_ERROR_FILE_ACCESS_DENIED, // assume we tried an NFS that does not support it. Now, try with symlink. rv = LockWithSymlink(lockFile, false); } if (NS_SUCCEEDED(rv)) { // Check for the old-style lock used by pre-mozilla 1.3 builds. // Those builds used an earlier check to prevent the application // from launching if another instance was already running. Because // of that, we don't need to create an old-style lock as well. struct LockProcessInfo { ProcessSerialNumber psn; unsigned long launchDate; }; PRFileDesc *fd = nullptr; int32_t ioBytes; ProcessInfoRec processInfo; LockProcessInfo lockProcessInfo; rv = lockFile->SetLeafName(OLD_LOCKFILE_NAME); if (NS_FAILED(rv)) return rv; rv = lockFile->OpenNSPRFileDesc(PR_RDONLY, 0, &fd); if (NS_SUCCEEDED(rv)) { ioBytes = PR_Read(fd, &lockProcessInfo, sizeof(LockProcessInfo)); PR_Close(fd); if (ioBytes == sizeof(LockProcessInfo)) { #ifdef __LP64__ processInfo.processAppRef = nullptr; #else processInfo.processAppSpec = nullptr; #endif processInfo.processName = nullptr; processInfo.processInfoLength = sizeof(ProcessInfoRec); if (::GetProcessInformation(&lockProcessInfo.psn, &processInfo) == noErr && processInfo.processLaunchDate == lockProcessInfo.launchDate) { return NS_ERROR_FILE_ACCESS_DENIED; } } else { NS_WARNING("Could not read lock file - ignoring lock"); } } rv = NS_OK; // Don't propagate error from OpenNSPRFileDesc. } #elif defined(XP_UNIX) // Get the old lockfile name nsCOMPtr<nsIFile> oldLockFile; rv = aProfileDir->Clone(getter_AddRefs(oldLockFile)); if (NS_FAILED(rv)) return rv; rv = oldLockFile->Append(OLD_LOCKFILE_NAME); if (NS_FAILED(rv)) return rv; // First, try locking using fcntl. It is more reliable on // a local machine, but may not be supported by an NFS server. rv = LockWithFcntl(lockFile); if (NS_SUCCEEDED(rv)) { // Check to see whether there is a symlink lock held by an older // Firefox build, and also place our own symlink lock --- but // mark it "obsolete" so that other newer builds can break the lock // if they obtain the fcntl lock rv = LockWithSymlink(oldLockFile, true); // If the symlink failed for some reason other than it already // exists, then something went wrong e.g. the file system // doesn't support symlinks, or we don't have permission to // create a symlink there. In such cases we should just // continue because it's unlikely there is an old build // running with a symlink there and we've already successfully // placed a fcntl lock. if (rv != NS_ERROR_FILE_ACCESS_DENIED) rv = NS_OK; } else if (rv != NS_ERROR_FILE_ACCESS_DENIED) { // If that failed for any reason other than NS_ERROR_FILE_ACCESS_DENIED, // assume we tried an NFS that does not support it. Now, try with symlink // using the old symlink path rv = LockWithSymlink(oldLockFile, false); } #elif defined(XP_WIN) nsAutoString filePath; rv = lockFile->GetPath(filePath); if (NS_FAILED(rv)) return rv; lockFile->GetLastModifiedTime(&mReplacedLockTime); // always create the profile lock and never delete it so we can use its // modification timestamp to detect startup crashes mLockFileHandle = CreateFileW(filePath.get(), GENERIC_READ | GENERIC_WRITE, 0, // no sharing - of course nullptr, CREATE_ALWAYS, 0, nullptr); if (mLockFileHandle == INVALID_HANDLE_VALUE) { if (aUnlocker) { RefPtr<mozilla::ProfileUnlockerWin> unlocker( new mozilla::ProfileUnlockerWin(filePath)); if (NS_SUCCEEDED(unlocker->Init())) { nsCOMPtr<nsIProfileUnlocker> unlockerInterface( do_QueryObject(unlocker)); unlockerInterface.forget(aUnlocker); } } return NS_ERROR_FILE_ACCESS_DENIED; } #elif defined(XP_OS2) nsAutoCString filePath; rv = lockFile->GetNativePath(filePath); if (NS_FAILED(rv)) return rv; lockFile->GetLastModifiedTime(&mReplacedLockTime); ULONG ulAction = 0; APIRET rc; rc = DosOpen(filePath.get(), &mLockFileHandle, &ulAction, 0, FILE_NORMAL, OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS, OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYREADWRITE | OPEN_FLAGS_NOINHERIT, 0 ); if (rc != NO_ERROR) { mLockFileHandle = -1; return NS_ERROR_FILE_ACCESS_DENIED; } #elif defined(VMS) nsAutoCString filePath; rv = lockFile->GetNativePath(filePath); if (NS_FAILED(rv)) return rv; lockFile->GetLastModifiedTime(&mReplacedLockTime); mLockFileDesc = open_noshr(filePath.get(), O_CREAT, 0666); if (mLockFileDesc == -1) { if ((errno == EVMSERR) && (vaxc$errno == RMS$_FLK)) { return NS_ERROR_FILE_ACCESS_DENIED; } else { NS_ERROR("Failed to open lock file."); return NS_ERROR_FAILURE; } } #endif mHaveLock = true; return rv; }