static void ConnectThread( void *arg ) { PRStatus rv; PRFileDesc *clientSock; PRNetAddr serverAddress; clientSock = PR_NewTCPSocket(); PR_ASSERT(clientSock); if ( resume ) { if ( debug ) printf("pausing 3 seconds before connect\n"); PR_Sleep( PR_SecondsToInterval(3)); } memset(&serverAddress, 0, sizeof(serverAddress)); rv = PR_InitializeNetAddr(PR_IpAddrLoopback, BASE_PORT, &serverAddress); PR_ASSERT( PR_SUCCESS == rv ); rv = PR_Connect( clientSock, &serverAddress, PR_SecondsToInterval(1)); PR_ASSERT( PR_SUCCESS == rv ); /* that's all we do. ... Wait for the acceptread() to timeout */ while( state != AllDone ) PR_Sleep( PR_SecondsToInterval(1)); return; } /* end ConnectThread() */
static PRIntervalTime Alarms2(PRUint32 loops) { PRStatus rv; PRAlarm *alarm; PRIntervalTime overhead, timein = PR_IntervalNow(); AlarmData ad; PRIntervalTime duration = PR_SecondsToInterval(30); PRLock *ml = PR_NewLock(); PRCondVar *cv = PR_NewCondVar(ml); ad.ml = ml; ad.cv = cv; ad.rate = 1; ad.times = loops; ad.late = ad.times = 0; ad.duration = duration; ad.timein = PR_IntervalNow(); ad.period = PR_SecondsToInterval(1); alarm = PR_CreateAlarm(); (void)PR_SetAlarm( alarm, ad.period, ad.rate, AlarmFn2, &ad); overhead = PR_IntervalNow() - timein; PR_Lock(ml); while ((PRIntervalTime)(PR_IntervalNow() - ad.timein) < duration) PR_WaitCondVar(cv, PR_INTERVAL_NO_TIMEOUT); PR_Unlock(ml); timein = PR_IntervalNow(); rv = PR_DestroyAlarm(alarm); if (rv != PR_SUCCESS) { if (!debug_mode) failed_already=1; else printf("***Destroying alarm status: FAIL\n"); } PR_DestroyCondVar(cv); PR_DestroyLock(ml); overhead += (PR_IntervalNow() - timein); return duration + overhead; } /* Alarms2 */
/* * If the read would block we return -1 and set 'wouldblock' to TRUE. * Otherwise we return the amount of data read. Other errors should return -1 * and set 'wouldblock' to FALSE. */ ssize_t Curl_nss_recv(struct connectdata * conn, /* connection data */ int num, /* socketindex */ char *buf, /* store read data here */ size_t buffersize, /* max amount to read */ bool * wouldblock) { ssize_t nread; struct SessionHandle *data = conn->data; PRInt32 timeout; if(data->set.timeout) timeout = PR_SecondsToInterval((PRUint32)data->set.timeout); else timeout = PR_MillisecondsToInterval(DEFAULT_CONNECT_TIMEOUT); nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0, timeout); *wouldblock = FALSE; if(nread < 0) { /* failed SSL read */ PRInt32 err = PR_GetError(); if(err == PR_WOULD_BLOCK_ERROR) { *wouldblock = TRUE; return -1; /* basically EWOULDBLOCK */ } if(err == PR_IO_TIMEOUT_ERROR) { failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } failf(conn->data, "SSL read: errno %d", err); return -1; } return nread; }
int main(int argc, char **argv) { if (test_common_init(&argc, &argv) != 0) return -1; nsresult rv; #if defined(PR_LOGGING) gTestLog = PR_NewLogModule("Test"); #endif rv = NS_InitXPCOM2(nullptr, nullptr, nullptr); if (NS_FAILED(rv)) return rv; rv = RunTest(); if (NS_FAILED(rv)) LOG(("RunTest failed [rv=%x]\n", rv)); LOG(("sleeping main thread for 2 seconds...\n")); PR_Sleep(PR_SecondsToInterval(2)); NS_ShutdownXPCOM(nullptr); return 0; }
/* * FUNCTION: PKIX_PL_Date_Create_CurrentOffBySeconds * (see comments in pkix_pl_pki.h) */ PKIX_Error * PKIX_PL_Date_Create_CurrentOffBySeconds( PKIX_Int32 secondsOffset, PKIX_PL_Date **pDate, void *plContext) { PKIX_PL_Date *date = NULL; PRTime time; PKIX_ENTER(DATE, "PKIX_PL_Date_Create_CurrentOffBySeconds"); PKIX_NULLCHECK_ONE(pDate); time = PR_Now() + PR_SecondsToInterval(secondsOffset); /* create a PKIX_PL_Date object */ PKIX_CHECK(PKIX_PL_Object_Alloc (PKIX_DATE_TYPE, sizeof (PKIX_PL_Date), (PKIX_PL_Object **)&date, plContext), PKIX_COULDNOTCREATEOBJECT); /* populate the nssTime field */ date->nssTime = time; *pDate = date; cleanup: PKIX_RETURN(DATE); }
static void AcceptThread(void *arg) { PRIntn bytesRead; char dataBuf[ACCEPT_READ_BUFSIZE]; PRFileDesc *arSock; PRNetAddr *arAddr; bytesRead = PR_AcceptRead( listenSock, &arSock, &arAddr, dataBuf, ACCEPT_READ_DATASIZE, PR_SecondsToInterval(1)); if ( bytesRead == -1 && PR_GetError() == PR_IO_TIMEOUT_ERROR ) if ( debug ) printf("AcceptRead timed out\n"); else if ( debug ) printf("Oops! read: %d, error: %d\n", bytesRead, PR_GetError()); while( state != AllDone ) { PR_Lock( ml ); while( state != RunAcceptRead ) PR_WaitCondVar( cv, PR_INTERVAL_NO_TIMEOUT ); if ( ++iCounter >= jitter ) state = AllDone; else state = RunJitter; if ( verbose ) printf("."); PR_NotifyCondVar( cv ); PR_Unlock( ml ); PR_Write( file1, ".", 1 ); } return; } /* end AcceptThread() */
/** * create transport, open streams, and close */ static nsresult RunCloseTest(nsISocketTransportService *sts, const char *host, int port, uint32_t inFlags, uint32_t outFlags) { nsresult rv; LOG(("RunCloseTest\n")); nsCOMPtr<nsISocketTransport> transport; rv = sts->CreateTransport(nullptr, 0, nsDependentCString(host), port, nullptr, getter_AddRefs(transport)); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIInputStream> in; rv = transport->OpenInputStream(inFlags, 0, 0, getter_AddRefs(in)); nsCOMPtr<nsIAsyncInputStream> asyncIn = do_QueryInterface(in, &rv); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIOutputStream> out; rv = transport->OpenOutputStream(outFlags, 0, 0, getter_AddRefs(out)); nsCOMPtr<nsIAsyncOutputStream> asyncOut = do_QueryInterface(out, &rv); if (NS_FAILED(rv)) return rv; LOG(("waiting 1 second before closing transport and streams...\n")); PR_Sleep(PR_SecondsToInterval(1)); // let nsCOMPtr destructors close everything... return NS_OK; }
/* * snmp_collator_sem_wait() * * A wrapper used to get the semaphore. We don't want to block, * but we want to retry a specified number of times in case the * semaphore is help by the sub-agent. */ static void snmp_collator_sem_wait() { int i = 0; int got_sem = 0; if (SEM_FAILED == stats_sem) { LDAPDebug1Arg(LDAP_DEBUG_ANY, "semaphore for stats file (%s) is not available.\n", szStatsFile); return; } for (i=0; i < SNMP_NUM_SEM_WAITS; i++) { if (sem_trywait(stats_sem) == 0) { got_sem = 1; break; } PR_Sleep(PR_SecondsToInterval(1)); } if (!got_sem) { /* If we've been unable to get the semaphore, there's * something wrong (likely the sub-agent went out to * lunch). We remove the old semaphore and recreate * a new one to avoid hanging up the server. */ sem_close(stats_sem); sem_unlink(stats_sem_name); snmp_collator_create_semaphore(); } }
/* * linger * The linger time, in seconds. */ JNIEXPORT void JNICALL Java_org_mozilla_jss_ssl_SSLSocket_setSoLinger(JNIEnv *env, jobject self, jboolean on, jint linger) { PRSocketOptionData sockOptions; PRStatus status; JSSL_SocketData *sock = NULL; if( JSSL_getSockData(env, self, &sock) != PR_SUCCESS ) { goto finish; } sockOptions.option = PR_SockOpt_Linger; sockOptions.value.linger.polarity = on; if(on) { sockOptions.value.linger.linger = PR_SecondsToInterval(linger); } status = PR_SetSocketOption(sock->fd, &sockOptions); if( status != PR_SUCCESS ) { JSSL_throwSSLSocketException(env, "PR_SetSocketOption failed"); goto finish; } finish: EXCEPTION_CHECK(env, sock) return; }
static PRIntervalTime ReentrantMonitor(PRUint32 loops) { PRStatus status; PRThread *thread; PRMonitor *ml = PR_NewMonitor(); if (debug_mode) printf("\nMonitor created for reentrant test\n"); PR_EnterMonitor(ml); PR_EnterMonitor(ml); if (debug_mode) printf("Monitor acquired twice\n"); thread = PR_CreateThread( PR_USER_THREAD, TryEntry, ml, PR_PRIORITY_LOW, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); PR_ASSERT(thread != NULL); PR_Sleep(PR_SecondsToInterval(1)); PR_ExitMonitor(ml); if (debug_mode) printf("Monitor released first time\n"); PR_ExitMonitor(ml); if (debug_mode) printf("Monitor released second time\n"); status = PR_JoinThread(thread); if (debug_mode) printf( "Reentrant thread joined %s\n", (status == PR_SUCCESS) ? "successfully" : "in error"); PR_DestroyMonitor(ml); return 0; } /* ReentrantMonitor */
nsresult nsWifiMonitor::DoScan() { nsCOMArray<nsWifiAccessPoint> accessPoints; mozilla::nsWifiScannerDBus wifiScanner(&accessPoints); nsCOMArray<nsWifiAccessPoint> lastAccessPoints; while (mKeepGoing) { accessPoints.Clear(); nsresult rv = wifiScanner.Scan(); NS_ENSURE_SUCCESS(rv, rv); bool accessPointsChanged = !AccessPointsEqual(accessPoints, lastAccessPoints); ReplaceArray(lastAccessPoints, accessPoints); rv = CallWifiListeners(lastAccessPoints, accessPointsChanged); NS_ENSURE_SUCCESS(rv, rv); LOG(("waiting on monitor\n")); mozilla::ReentrantMonitorAutoEnter mon(mReentrantMonitor); mon.Wait(PR_SecondsToInterval(kDefaultWifiScanInterval)); } return NS_OK; }
/* * Serve_Client * Thread, started by the server, for serving a client connection. * Reads data from socket and writes it back, unmodified, and * closes the socket */ static void PR_CALLBACK Serve_Client(void *arg) { Serve_Client_Param *scp = (Serve_Client_Param *) arg; buffer *in_buf; Session *sp; PRJob *jobp; sp = PR_NEW(Session); sp->iod = scp->iod; in_buf = PR_NEW(buffer); if (in_buf == NULL) { fprintf(stderr,"%s: failed to alloc buffer struct\n",program_name); failed_already=1; return; } sp->in_buf = in_buf; sp->bytes = scp->datalen; sp->msg_num = 0; sp->bytes_read = 0; sp->tp = scp->tp; sp->exit_mon = scp->exit_mon; sp->job_counterp = scp->job_counterp; sp->iod.timeout = PR_SecondsToInterval(60); jobp = PR_QueueJob_Read(sp->tp, &sp->iod, serve_client_read, sp, PR_FALSE); PR_ASSERT(NULL != jobp); PR_DELETE(scp); }
static void PR_CALLBACK forked(void *arg) { PRIntn i; PRLock *ml; PRCondVar *cv; PR_LogPrint("%s logging creating mutex\n", (const char*)arg); ml = PR_NewLock(); PR_LogPrint("%s logging creating condition variable\n", (const char*)arg); cv = PR_NewCondVar(ml); PR_LogPrint("%s waiting on condition timeout 10 times\n", (const char*)arg); for (i = 0; i < 10; ++i) { PR_Lock(ml); PR_WaitCondVar(cv, PR_SecondsToInterval(1)); PR_Unlock(ml); } PR_LogPrint("%s logging destroying condition variable\n", (const char*)arg); PR_DestroyCondVar(cv); PR_LogPrint("%s logging destroying mutex\n", (const char*)arg); PR_DestroyLock(ml); PR_LogPrint("%s forked thread exiting\n", (const char*)arg); }
static void TestIntervals(void) { PRStatus rv; PRUint32 delta; PRInt32 seconds; PRUint64 elapsed, thousand; PRTime timein, timeout; PRLock *ml = PR_NewLock(); PRCondVar *cv = PR_NewCondVar(ml); for (seconds = 0; seconds < 10; ++seconds) { PRIntervalTime ticks = PR_SecondsToInterval(seconds); PR_Lock(ml); timein = PR_Now(); rv = PR_WaitCondVar(cv, ticks); timeout = PR_Now(); PR_Unlock(ml); LL_SUB(elapsed, timeout, timein); LL_I2L(thousand, 1000); LL_DIV(elapsed, elapsed, thousand); LL_L2UI(delta, elapsed); if (debug_mode) PR_fprintf(output, "TestIntervals: %swaiting %ld seconds took %ld msecs\n", ((rv == PR_SUCCESS) ? "" : "FAILED "), seconds, delta); } PR_DestroyCondVar(cv); PR_DestroyLock(ml); if (debug_mode) PR_fprintf(output, "\n"); } /* TestIntervals */
/* periodically generate a csn and dump it to the error log */ static void _csngen_gen_tester_main (void *data) { CSNGen *gen = (CSNGen*)data; CSN *csn = NULL; char buff [CSN_STRSIZE]; int rc; PR_ASSERT (gen); while (!s_must_exit) { rc = csngen_new_csn (gen, &csn, PR_FALSE); if (rc != CSN_SUCCESS) { slapi_log_err(SLAPI_LOG_ERR, "_csngen_gen_tester_main", "failed to generate csn; csn error - %d\n", rc); } else { slapi_log_err(SLAPI_LOG_INFO, "_csngen_gen_tester_main", "generate csn %s\n", csn_as_string(csn, PR_FALSE, buff)); } csn_free(&csn); /* sleep for 30 seconds */ DS_Sleep (PR_SecondsToInterval(10)); } PR_AtomicDecrement (&s_thread_count); }
static void Client(const char *server_name) { PRStatus rv; PRHostEnt host; char buffer[PR_NETDB_BUF_SIZE]; PRIntervalTime dally = PR_SecondsToInterval(60); PR_fprintf(err, "Translating the name %s\n", server_name); rv = PR_GetHostByName(server_name, buffer, sizeof(buffer), &host); if (PR_FAILURE == rv) PL_FPrintError(err, "PR_GetHostByName"); else { if (PR_EnumerateHostEnt( 0, &host, PORT_NUMBER, &shared->server_address) < 0) PL_FPrintError(err, "PR_EnumerateHostEnt"); else { do { shared->threads += 1; (void)PR_CreateThread( PR_USER_THREAD, Clientel, shared, PR_PRIORITY_NORMAL, thread_scope, PR_UNJOINABLE_THREAD, 8 * 1024); if (shared->threads == initial_streams) { PR_Sleep(dally); initial_streams += 1; } } while (PR_TRUE); } } }
static void eq_loop(void *arg) { while (eq_running) { PRIntervalTime timeout; int until; PR_Lock(eq->eq_lock); while (!WORK_AVAILABLE) { if (!eq_running) { PR_Unlock(eq->eq_lock); goto bye; } /* Compute new timeout */ if (NULL != eq->eq_queue) { until = eq->eq_queue->ec_when - current_time(); timeout = PR_SecondsToInterval(until); } else { timeout = PR_INTERVAL_NO_TIMEOUT; } PR_WaitCondVar(eq->eq_cv, timeout); } /* There is some work to do */ PR_Unlock(eq->eq_lock); eq_call_all(); } bye: eq_stopped = 1; PR_Lock(ss_lock); PR_NotifyAllCondVar(ss_cv); PR_Unlock(ss_lock); }
PRIntervalTime nsSocketTransportService::PollTimeout() { if (mActiveCount == 0) return NS_SOCKET_POLL_TIMEOUT; // compute minimum time before any socket timeout expires. uint32_t minR = UINT16_MAX; for (uint32_t i=0; i<mActiveCount; ++i) { const SocketContext &s = mActiveList[i]; // mPollTimeout could be less than mElapsedTime if setTimeout // was called with a value smaller than mElapsedTime. uint32_t r = (s.mElapsedTime < s.mHandler->mPollTimeout) ? s.mHandler->mPollTimeout - s.mElapsedTime : 0; if (r < minR) minR = r; } // nsASocketHandler defines UINT16_MAX as do not timeout if (minR == UINT16_MAX) { SOCKET_LOG(("poll timeout: none\n")); return NS_SOCKET_POLL_TIMEOUT; } SOCKET_LOG(("poll timeout: %lu\n", minR)); return PR_SecondsToInterval(minR); }
int main(int argc, char** argv) { nsresult rv; if (argc < 2) { fprintf(stderr, "usage: %s <url> [<poll-interval>]\n", argv[0]); return 1; } rv = NS_InitXPCOM2(nsnull, nsnull, nsnull); if (NS_FAILED(rv)) { fprintf(stderr, "NS_InitXPCOM2 failed\n"); return 1; } // Create a stream data source and initialize it on argv[1], which // is hopefully a "file:" URL. (Actually, we can do _any_ kind of // URL, but only a "file:" URL will be written back to disk.) nsCOMPtr<nsIRDFDataSource> ds = do_CreateInstance(kRDFXMLDataSourceCID, &rv); if (NS_FAILED(rv)) { NS_ERROR("unable to create RDF/XML data source"); return rv; } nsCOMPtr<nsIRDFRemoteDataSource> remote = do_QueryInterface(ds); if (! remote) return NS_ERROR_UNEXPECTED; rv = remote->Init(argv[1]); NS_ASSERTION(NS_SUCCEEDED(rv), "unable to initialize data source"); if (NS_FAILED(rv)) return rv; // The do_QI() on the pointer is a hack to make sure that the new // object gets AddRef()-ed. nsCOMPtr<nsIRDFObserver> observer = do_QueryInterface(new Observer); if (! observer) return NS_ERROR_OUT_OF_MEMORY; rv = ds->AddObserver(observer); if (NS_FAILED(rv)) return rv; while (1) { // Okay, this should load the XML file... rv = remote->Refresh(PR_TRUE); NS_ASSERTION(NS_SUCCEEDED(rv), "unable to open datasource"); if (NS_FAILED(rv)) return rv; if (argc <= 2) break; PRInt32 pollinterval = atol(argv[2]); if (! pollinterval) break; PR_Sleep(PR_SecondsToInterval(pollinterval)); } return NS_OK; }
int main(int argc, char** argv) { PR_AR_Init(PR_SecondsToInterval(12)); //test_reverse(NULL); PRThread* threads[THREAD_MAX]; PRInt32 i; for (i=0;i<THREAD_MAX;i++) { threads[i] = PR_CreateThread(PR_SYSTEM_THREAD, test_reverse, 0, PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); } for (i=0;i<THREAD_MAX;i++) { PR_JoinThread(threads[i]); } return 0; }
int main(int argc, char **argv) { if (test_common_init(&argc, &argv) != 0) return -1; int sleepLen = 10; // default: 10 seconds if (argc == 1) { printf("usage: TestDNS [-N] hostname1 [hostname2 ...]\n"); return -1; } { nsCOMPtr<nsIServiceManager> servMan; NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr); nsCOMPtr<nsPIDNSService> dns = do_GetService(NS_DNSSERVICE_CONTRACTID); if (!dns) return -1; if (argv[1][0] == '-') { sleepLen = atoi(argv[1]+1); argv++; argc--; } for (int j=0; j<2; ++j) { for (int i=1; i<argc; ++i) { // assume non-ASCII input is given in the native charset nsAutoCString hostBuf; if (IsAscii(argv[i])) hostBuf.Assign(argv[i]); else hostBuf = NS_ConvertUTF16toUTF8(NS_ConvertASCIItoUTF16(argv[i])); nsCOMPtr<nsIDNSListener> listener = new myDNSListener(argv[i], i); nsCOMPtr<nsICancelable> req; nsresult rv = dns->AsyncResolve(hostBuf, nsIDNSService::RESOLVE_CANONICAL_NAME, listener, nullptr, getter_AddRefs(req)); if (NS_FAILED(rv)) printf("### AsyncResolve failed [rv=%x]\n", static_cast<uint32_t>(rv)); } printf("main thread sleeping for %d seconds...\n", sleepLen); PR_Sleep(PR_SecondsToInterval(sleepLen)); } printf("shutting down main thread...\n"); dns->Shutdown(); } NS_ShutdownXPCOM(nullptr); return 0; }
/* * FUNCTION: pkix_pl_AiaMgr_FindLDAPClient * DESCRIPTION: * * This function checks the collection of LDAPClient connections held by the * AIAMgr pointed to by "aiaMgr" for one matching the domain name given by * "domainName". The string may include a port number: e.g., "betty.nist.gov" * or "nss.red.iplanet.com:1389". If a match is found, that LDAPClient is * stored at "pClient". Otherwise, an LDAPClient is created and added to the * collection, and then stored at "pClient". * * PARAMETERS: * "aiaMgr" * The AIAMgr whose LDAPClient connected are to be managed. Must be * non-NULL. * "domainName" * Address of a string pointing to a server name. Must be non-NULL. * "pClient" * Address at which the returned LDAPClient is stored. Must be non-NULL. * "plContext" * Platform-specific context pointer. * THREAD SAFETY: * Thread Safe (see Thread Safety Definitions in Programmer's Guide) * RETURNS: * Returns NULL if the function succeeds. * Returns an AIAMgr Error if the function fails in a non-fatal way * Returns a Fatal Error if the function fails in an unrecoverable way. */ static PKIX_Error * pkix_pl_AiaMgr_FindLDAPClient( PKIX_PL_AIAMgr *aiaMgr, char *domainName, PKIX_PL_LdapClient **pClient, void *plContext) { PKIX_PL_String *domainString = NULL; PKIX_PL_LdapDefaultClient *client = NULL; PKIX_ENTER(AIAMGR, "pkix_pl_AiaMgr_FindLDAPClient"); PKIX_NULLCHECK_THREE(aiaMgr, domainName, pClient); /* create PKIX_PL_String from domain name */ PKIX_CHECK(PKIX_PL_String_Create (PKIX_ESCASCII, domainName, 0, &domainString, plContext), PKIX_STRINGCREATEFAILED); /* Is this domainName already in cache? */ PKIX_CHECK(PKIX_PL_HashTable_Lookup (aiaConnectionCache, (PKIX_PL_Object *)domainString, (PKIX_PL_Object **)&client, plContext), PKIX_HASHTABLELOOKUPFAILED); if (client == NULL) { /* No, create a connection (and cache it) */ PKIX_CHECK(PKIX_PL_LdapDefaultClient_CreateByName (domainName, /* Do not use NBIO until we verify, that * it is working. For now use 1 min timeout. */ PR_SecondsToInterval( ((PKIX_PL_NssContext*)plContext)->timeoutSeconds), NULL, &client, plContext), PKIX_LDAPDEFAULTCLIENTCREATEBYNAMEFAILED); PKIX_CHECK(PKIX_PL_HashTable_Add (aiaConnectionCache, (PKIX_PL_Object *)domainString, (PKIX_PL_Object *)client, plContext), PKIX_HASHTABLEADDFAILED); } *pClient = (PKIX_PL_LdapClient *)client; cleanup: PKIX_DECREF(domainString); PKIX_RETURN(AIAMGR); }
static PRIntervalTime OCSPFetchingTypeToTimeoutTime(NSSCertDBTrustDomain::OCSPFetching ocspFetching) { switch (ocspFetching) { case NSSCertDBTrustDomain::FetchOCSPForDVSoftFail: return PR_SecondsToInterval(2); case NSSCertDBTrustDomain::FetchOCSPForEV: case NSSCertDBTrustDomain::FetchOCSPForDVHardFail: return PR_SecondsToInterval(10); // The rest of these are error cases. Assert in debug builds, but return // the default value corresponding to 2 seconds in release builds. case NSSCertDBTrustDomain::NeverFetchOCSP: case NSSCertDBTrustDomain::LocalOnlyOCSPForEV: PR_NOT_REACHED("we should never see this OCSPFetching type here"); default: PR_NOT_REACHED("we're not handling every OCSPFetching type"); } return PR_SecondsToInterval(2); }
static void _csngen_stop_test_threads(void) { s_must_exit = 1; while (s_thread_count > 0) { /* sleep for 30 seconds */ DS_Sleep (PR_SecondsToInterval(20)); } }
static void serve_client_read(void *arg) { Session *sp = (Session *) arg; int rem; int bytes; int offset; PRFileDesc *sockfd; char *buf; PRJob *jobp; PRIntervalTime timeout = PR_INTERVAL_NO_TIMEOUT; sockfd = sp->iod.socket; buf = sp->in_buf->data; PR_ASSERT(sp->msg_num < num_tcp_mesgs_per_connection); PR_ASSERT(sp->bytes_read < sp->bytes); offset = sp->bytes_read; rem = sp->bytes - offset; bytes = PR_Recv(sockfd, buf + offset, rem, 0, timeout); if (bytes < 0) { return; } sp->bytes_read += bytes; sp->iod.timeout = PR_SecondsToInterval(60); if (sp->bytes_read < sp->bytes) { jobp = PR_QueueJob_Read(sp->tp, &sp->iod, serve_client_read, sp, PR_FALSE); PR_ASSERT(NULL != jobp); return; } PR_ASSERT(sp->bytes_read == sp->bytes); DPRINTF(("serve_client: read complete, msg(%d) \n", sp->msg_num)); sp->iod.timeout = PR_SecondsToInterval(60); jobp = PR_QueueJob_Write(sp->tp, &sp->iod, serve_client_write, sp, PR_FALSE); PR_ASSERT(NULL != jobp); return; }
static void WaitForCompletion(PRIntn execution) { while (execution > 0) { PRIntn dally = (execution > 30) ? 30 : execution; PR_Sleep(PR_SecondsToInterval(dally)); if (pthread_stats) PT_FPrintStats(debug_out, "\nPThread Statistics\n"); execution -= dally; } } /* WaitForCompletion */
int main(int argc, char* argv[]) { if (test_common_init(&argc, &argv) != 0) return -1; nsresult rv; if (argc < 4) { printf("usage: %s <file-to-read> <start-offset> <read-length>\n", argv[0]); return -1; } char* fileName = argv[1]; int64_t offset, length; int err = PR_sscanf(argv[2], "%lld", &offset); if (err == -1) { printf("Start offset must be an integer!\n"); return 1; } err = PR_sscanf(argv[3], "%lld", &length); if (err == -1) { printf("Length must be an integer!\n"); return 1; } { nsCOMPtr<nsIServiceManager> servMan; NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr); nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan); NS_ASSERTION(registrar, "Null nsIComponentRegistrar"); if (registrar) registrar->AutoRegister(nullptr); #if defined(PR_LOGGING) gTestLog = PR_NewLogModule("Test"); #endif nsCOMPtr<nsIFile> file; rv = NS_NewNativeLocalFile(nsDependentCString(fileName), false, getter_AddRefs(file)); if (NS_FAILED(rv)) return rv; rv = RunTest(file, offset, length); NS_ASSERTION(NS_SUCCEEDED(rv), "RunTest failed"); // give background threads a chance to finish whatever work they may // be doing. PR_Sleep(PR_SecondsToInterval(1)); } // this scopes the nsCOMPtrs // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM rv = NS_ShutdownXPCOM(nullptr); NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed"); return NS_OK; }
static PRIntervalTime Alarms1(PRUint32 loops) { PRAlarm *alarm; AlarmData ad; PRIntervalTime overhead, timein = PR_IntervalNow(); PRIntervalTime duration = PR_SecondsToInterval(3); PRLock *ml = PR_NewLock(); PRCondVar *cv = PR_NewCondVar(ml); ad.ml = ml; ad.cv = cv; ad.rate = 1; ad.times = loops; ad.late = ad.times = 0; ad.duration = duration; ad.timein = PR_IntervalNow(); ad.period = PR_SecondsToInterval(1); alarm = PR_CreateAlarm(); (void)PR_SetAlarm( alarm, ad.period, ad.rate, AlarmFn1, &ad); overhead = PR_IntervalNow() - timein; PR_Lock(ml); while ((PRIntervalTime)(PR_IntervalNow() - ad.timein) < duration) PR_WaitCondVar(cv, PR_INTERVAL_NO_TIMEOUT); PR_Unlock(ml); timein = PR_IntervalNow(); (void)PR_DestroyAlarm(alarm); PR_DestroyCondVar(cv); PR_DestroyLock(ml); overhead += (PR_IntervalNow() - timein); return duration + overhead; } /* Alarms1 */
void doReadThread (void* arg) { PRInt32 last; Arg_t *args = (Arg_t*)arg; PRInt32 aWorkDelay = args->a, aWaitDelay = args->b; PR_Sleep(0); while (1) { // -- enter read lock PR_EnterMonitor (gMonitor); if (0 < gWriteWaiting) // give up the monitor to waiting writes { PRIntervalTime fiveSecs = PR_SecondsToInterval(5); gReadWaiting++; if (gReadWaiting > gMaxReadWaits) // stats gMaxReadWaits = gReadWaiting; while (0 < gWriteWaiting) PR_Wait (gMonitor, fiveSecs); gReadWaiting--; } gReading++; gReads++; // stats if (gReading > gMaxReads) // stats gMaxReads = gReading; PR_ExitMonitor (gMonitor); // -- read lock entered last = gCounter; spin (aWorkDelay); PR_ASSERT (gCounter == last); // test invariance // -- exit read lock PR_EnterMonitor (gMonitor); // read unlock gReading--; // if ((0 == gReading) && (0 < gWriteWaiting)) // notify waiting writes (do it anyway to show off the CondWait bug) PR_NotifyAll (gMonitor); PR_ExitMonitor (gMonitor); // -- read lock exited spin (aWaitDelay); } }
int pseudoMain (int argc, char** argv, char *pad) { PRInt32 lastWriteCount = gCounter; PRInt32 lastReadCount = gReads; Arg_t a1 = {500, 250}; Arg_t a2 = {500, 500}; Arg_t a3 = {250, 500}; Arg_t a4 = {750, 250}; Arg_t a5 = {100, 750}; Arg_t a6 = {100, 500}; Arg_t a7 = {100, 750}; gMonitor = PR_NewMonitor (); fireThread ("R1", doReadThread, &a1); fireThread ("R2", doReadThread, &a2); fireThread ("R3", doReadThread, &a3); fireThread ("R4", doReadThread, &a4); fireThread ("W1", doWriteThread, &a5); fireThread ("W2", doWriteThread, &a6); fireThread ("W3", doWriteThread, &a7); fireThread ("R5", doReadThread, &a1); fireThread ("R6", doReadThread, &a2); fireThread ("R7", doReadThread, &a3); fireThread ("R8", doReadThread, &a4); fireThread ("W4", doWriteThread, &a5); fireThread ("W5", doWriteThread, &a6); fireThread ("W6", doWriteThread, &a7); while (1) { PRInt32 writeCount, readCount; PRIntervalTime fiveSecs = PR_SecondsToInterval(5); PR_Sleep (fiveSecs); // get out of the way // print some stats, not threadsafe, informative only writeCount = gCounter; readCount = gReads; printf ("\ntick %d writes (+%d), %d reads (+%d) [max %d, %d, %d]", writeCount, writeCount - lastWriteCount, readCount, readCount - lastReadCount, gMaxReads, gMaxWriteWaits, gMaxReadWaits); lastWriteCount = writeCount; lastReadCount = readCount; gMaxReads = gMaxWriteWaits = gMaxReadWaits = 0; } return 0; }