diff options
Diffstat (limited to 'nsprpub/pr/tests')
161 files changed, 13557 insertions, 11620 deletions
diff --git a/nsprpub/pr/tests/Makefile.in b/nsprpub/pr/tests/Makefile.in index f1cfba9cc..8a87ad094 100644 --- a/nsprpub/pr/tests/Makefile.in +++ b/nsprpub/pr/tests/Makefile.in @@ -150,8 +150,6 @@ CSRCS = \ sockping.c \ sockpong.c \ sprintf.c \ - sproc_ch.c \ - sproc_p.c \ stack.c \ stdio.c \ str2addr.c \ @@ -237,49 +235,6 @@ ABSOLUTE_LIB_DIR = $(PWD)/$(dist_libdir) endif endif -ifeq ($(OS_ARCH), IRIX) - ifeq ($(USE_CPLUS), 1) - CC = CC - endif - LDOPTS += -rpath $(ABSOLUTE_LIB_DIR) - ifdef NS_USE_GCC - LDOPTS += -Wl,-rdata_shared - else - LDOPTS += -rdata_shared - endif -# For 6.x machines, include this flag - ifeq ($(basename $(OS_RELEASE)),6) - ifndef NS_USE_GCC - ifeq ($(USE_N32),1) - LDOPTS += -n32 - else - LDOPTS += -32 - endif - - ifeq ($(USE_PTHREADS), 1) - ifeq ($(OS_RELEASE), 6.2) - LDOPTS += -Wl,-woff,85 - endif - endif - endif - endif -endif - -ifeq ($(OS_ARCH), OSF1) - ifeq ($(USE_CPLUS), 1) - CC = cxx - endif -# I haven't figured out how to pass -rpath to cc on OSF1 V3.2, so -# we do static linking. - ifeq (,$(filter-out V2.0 V3.2,$(OS_RELEASE))) - LIBNSPR = $(dist_libdir)/libnspr$(MOD_MAJOR_VERSION).a - LIBPLC = $(dist_libdir)/libplc$(MOD_MAJOR_VERSION).a - EXTRA_LIBS = -lc_r - else - LDOPTS += -rpath $(ABSOLUTE_LIB_DIR) - endif -endif - ifeq ($(OS_ARCH), HP-UX) LDOPTS += -z -Wl,+s,+b,$(ABSOLUTE_LIB_DIR) ifeq ($(USE_64),1) diff --git a/nsprpub/pr/tests/README.TXT b/nsprpub/pr/tests/README.TXT index 94349fa2b..ebae6cdce 100644 --- a/nsprpub/pr/tests/README.TXT +++ b/nsprpub/pr/tests/README.TXT @@ -317,12 +317,6 @@ sockopt.c sprintf.c Tests sprintf. -sproc_ch.c - Obsolete. Tests IRIX sproc-based threads. - -sproc_p.c - Obsolete. Tests IRIX sproc-based threads. - stack.c Test atomic stack operations. diff --git a/nsprpub/pr/tests/abstract.c b/nsprpub/pr/tests/abstract.c index 6be5610c0..3d255c1c2 100644 --- a/nsprpub/pr/tests/abstract.c +++ b/nsprpub/pr/tests/abstract.c @@ -15,143 +15,143 @@ static const char abstractSocketName[] = "\0testsocket"; static void ClientThread(void* aArg) { - PRFileDesc* socket; - PRNetAddr addr; - PRUint8 buf[1024]; - PRInt32 len; - PRInt32 total; - - addr.local.family = PR_AF_LOCAL; - memcpy(addr.local.path, abstractSocketName, sizeof(abstractSocketName)); - - socket = PR_OpenTCPSocket(addr.raw.family); - if (!socket) { - fprintf(stderr, "PR_OpenTCPSokcet failed\n"); - exit(1); - } - - if (PR_Connect(socket, &addr, PR_INTERVAL_NO_TIMEOUT) == PR_FAILURE) { - fprintf(stderr, "PR_Connect failed\n"); - exit(1); - } - - total = 0; - while (total < sizeof(buf)) { - len = PR_Recv(socket, buf + total, sizeof(buf) - total, 0, - PR_INTERVAL_NO_TIMEOUT); - if (len < 1) { - fprintf(stderr, "PR_Recv failed\n"); - exit(1); + PRFileDesc* socket; + PRNetAddr addr; + PRUint8 buf[1024]; + PRInt32 len; + PRInt32 total; + + addr.local.family = PR_AF_LOCAL; + memcpy(addr.local.path, abstractSocketName, sizeof(abstractSocketName)); + + socket = PR_OpenTCPSocket(addr.raw.family); + if (!socket) { + fprintf(stderr, "PR_OpenTCPSokcet failed\n"); + exit(1); } - total += len; - } - - total = 0; - while (total < sizeof(buf)) { - len = PR_Send(socket, buf + total, sizeof(buf) - total, 0, - PR_INTERVAL_NO_TIMEOUT); - if (len < 1) { - fprintf(stderr, "PR_Send failed\n"); - exit(1); + + if (PR_Connect(socket, &addr, PR_INTERVAL_NO_TIMEOUT) == PR_FAILURE) { + fprintf(stderr, "PR_Connect failed\n"); + exit(1); + } + + total = 0; + while (total < sizeof(buf)) { + len = PR_Recv(socket, buf + total, sizeof(buf) - total, 0, + PR_INTERVAL_NO_TIMEOUT); + if (len < 1) { + fprintf(stderr, "PR_Recv failed\n"); + exit(1); + } + total += len; } - total += len; - } - if (PR_Close(socket) == PR_FAILURE) { - fprintf(stderr, "PR_Close failed\n"); - exit(1); - } + total = 0; + while (total < sizeof(buf)) { + len = PR_Send(socket, buf + total, sizeof(buf) - total, 0, + PR_INTERVAL_NO_TIMEOUT); + if (len < 1) { + fprintf(stderr, "PR_Send failed\n"); + exit(1); + } + total += len; + } + + if (PR_Close(socket) == PR_FAILURE) { + fprintf(stderr, "PR_Close failed\n"); + exit(1); + } } int main() { - PRFileDesc* socket; - PRFileDesc* acceptSocket; - PRThread* thread; - PRNetAddr addr; - PRUint8 buf[1024]; - PRInt32 len; - PRInt32 total; - - addr.local.family = PR_AF_LOCAL; - memcpy(addr.local.path, abstractSocketName, sizeof(abstractSocketName)); - - socket = PR_OpenTCPSocket(addr.raw.family); - if (!socket) { - fprintf(stderr, "PR_OpenTCPSocket failed\n"); - exit(1); - } - if (PR_Bind(socket, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_Bind failed\n"); - exit(1); - } - - if (PR_Listen(socket, 5) == PR_FAILURE) { - fprintf(stderr, "PR_Listen failed\n"); - exit(1); - } - - thread = PR_CreateThread(PR_USER_THREAD, ClientThread, 0, PR_PRIORITY_NORMAL, - PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); - if (!thread) { - fprintf(stderr, "PR_CreateThread failed"); - exit(1); - } - - acceptSocket = PR_Accept(socket, NULL, PR_INTERVAL_NO_TIMEOUT); - if (!acceptSocket) { - fprintf(stderr, "PR_Accept failed\n"); - exit(1); - } - - memset(buf, 'A', sizeof(buf)); - - total = 0; - while (total < sizeof(buf)) { - len = PR_Send(acceptSocket, buf + total, sizeof(buf) - total, 0, - PR_INTERVAL_NO_TIMEOUT); - if (len < 1) { - fprintf(stderr, "PR_Send failed\n"); - exit(1); + PRFileDesc* socket; + PRFileDesc* acceptSocket; + PRThread* thread; + PRNetAddr addr; + PRUint8 buf[1024]; + PRInt32 len; + PRInt32 total; + + addr.local.family = PR_AF_LOCAL; + memcpy(addr.local.path, abstractSocketName, sizeof(abstractSocketName)); + + socket = PR_OpenTCPSocket(addr.raw.family); + if (!socket) { + fprintf(stderr, "PR_OpenTCPSocket failed\n"); + exit(1); + } + if (PR_Bind(socket, &addr) == PR_FAILURE) { + fprintf(stderr, "PR_Bind failed\n"); + exit(1); + } + + if (PR_Listen(socket, 5) == PR_FAILURE) { + fprintf(stderr, "PR_Listen failed\n"); + exit(1); + } + + thread = PR_CreateThread(PR_USER_THREAD, ClientThread, 0, PR_PRIORITY_NORMAL, + PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); + if (!thread) { + fprintf(stderr, "PR_CreateThread failed"); + exit(1); } - total += len; - } - - total = 0; - while (total < sizeof(buf)) { - len = PR_Recv(acceptSocket, buf + total, sizeof(buf) - total, 0, - PR_INTERVAL_NO_TIMEOUT); - if (len < 1) { - fprintf(stderr, "PR_Recv failed\n"); - exit(1); + + acceptSocket = PR_Accept(socket, NULL, PR_INTERVAL_NO_TIMEOUT); + if (!acceptSocket) { + fprintf(stderr, "PR_Accept failed\n"); + exit(1); + } + + memset(buf, 'A', sizeof(buf)); + + total = 0; + while (total < sizeof(buf)) { + len = PR_Send(acceptSocket, buf + total, sizeof(buf) - total, 0, + PR_INTERVAL_NO_TIMEOUT); + if (len < 1) { + fprintf(stderr, "PR_Send failed\n"); + exit(1); + } + total += len; + } + + total = 0; + while (total < sizeof(buf)) { + len = PR_Recv(acceptSocket, buf + total, sizeof(buf) - total, 0, + PR_INTERVAL_NO_TIMEOUT); + if (len < 1) { + fprintf(stderr, "PR_Recv failed\n"); + exit(1); + } + total += len; + } + + if (PR_Close(acceptSocket) == PR_FAILURE) { + fprintf(stderr, "PR_Close failed\n"); + exit(1); + } + + if (PR_JoinThread(thread) == PR_FAILURE) { + fprintf(stderr, "PR_JoinThread failed\n"); + exit(1); + } + + if (PR_Close(socket) == PR_FAILURE) { + fprintf(stderr, "PR_Close failed\n"); + exit(1); } - total += len; - } - - if (PR_Close(acceptSocket) == PR_FAILURE) { - fprintf(stderr, "PR_Close failed\n"); - exit(1); - } - - if (PR_JoinThread(thread) == PR_FAILURE) { - fprintf(stderr, "PR_JoinThread failed\n"); - exit(1); - } - - if (PR_Close(socket) == PR_FAILURE) { - fprintf(stderr, "PR_Close failed\n"); - exit(1); - } - printf("PASS\n"); - return 0; + printf("PASS\n"); + return 0; } #else int main() { - prinf("PASS\n"); - return 0; + printf("PASS\n"); + return 0; } #endif diff --git a/nsprpub/pr/tests/accept.c b/nsprpub/pr/tests/accept.c index b327eb211..3e3850b69 100644 --- a/nsprpub/pr/tests/accept.c +++ b/nsprpub/pr/tests/accept.c @@ -12,7 +12,7 @@ ** ** Modification History: ** 04-Jun-97 AGarcia - Reconvert test file to return a 0 for PASS and a 1 for FAIL -** 13-May-97 AGarcia- Converted the test to accomodate the debug_mode +** 13-May-97 AGarcia- Converted the test to accomodate the debug_mode ** The debug mode will print all of the printfs associated with this test. ** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements @@ -51,7 +51,7 @@ #define SERVER_MAX_BIND_COUNT 100 -#if defined(XP_OS2) || defined(SYMBIAN) +#if defined(XP_OS2) #define TIMEOUTSECS 10 #else #define TIMEOUTSECS 2 @@ -96,8 +96,9 @@ void Test_Assert(const char *msg, const char *file, PRIntn line) void timeout_callback(void *magic) { TEST_ASSERT(magic == (void *)CALLBACK_MAGIC); - if (debug_mode) + if (debug_mode) { PR_fprintf(output, "timeout callback called okay\n"); + } } #endif @@ -120,37 +121,40 @@ ClientThread(void *_action) memset(buf, 0xaf, sizeof(buf)); /* initialize with arbitrary data */ sock = PR_NewTCPSocket(); if (!sock) { - if (!debug_mode) + if (!debug_mode) { failed_already=1; - else + } + else { PR_fprintf(output, "client: unable to create socket\n"); + } return; } if (action != CLIENT_TIMEOUT_ACCEPT) { if ((rv = PR_Connect(sock, &serverAddr, - timeoutTime)) < 0) { - if (!debug_mode) + timeoutTime)) < 0) { + if (!debug_mode) { failed_already=1; - else - PR_fprintf(output, - "client: unable to connect to server (%ld, %ld, %ld, %ld)\n", - iterations, rv, PR_GetError(), PR_GetOSError()); + } + else + PR_fprintf(output, + "client: unable to connect to server (%ld, %ld, %ld, %ld)\n", + iterations, rv, PR_GetError(), PR_GetOSError()); goto ErrorExit; } if (action != CLIENT_TIMEOUT_SEND) { if ((rv = PR_Send(sock, buf, CLIENT_DATA, - 0, timeoutTime))< 0) { + 0, timeoutTime))< 0) { if (!debug_mode) { failed_already=1; } else { PR_fprintf(output, - "client: unable to send to server (%d, %ld, %ld)\n", - CLIENT_DATA, rv, PR_GetError()); + "client: unable to send to server (%d, %ld, %ld)\n", + CLIENT_DATA, rv, PR_GetError()); } - goto ErrorExit; + goto ErrorExit; } } else { PR_Sleep(PR_SecondsToInterval(TIMEOUTSECS + 1)); @@ -158,34 +162,38 @@ ClientThread(void *_action) } else { PR_Sleep(PR_SecondsToInterval(TIMEOUTSECS + 1)); } - if (debug_mode) + if (debug_mode) { PR_fprintf(output, "."); + } PR_Close(sock); - sock = NULL; + sock = NULL; } - if (debug_mode) + if (debug_mode) { PR_fprintf(output, "\n"); + } ErrorExit: - if (sock != NULL) + if (sock != NULL) { PR_Close(sock); + } } -static void +static void RunTest(PRInt32 acceptType, PRInt32 clientAction) { -int i; + int i; /* First bind to the socket */ listenSock = PR_NewTCPSocket(); if (!listenSock) { failed_already=1; - if (debug_mode) + if (debug_mode) { PR_fprintf(output, "unable to create listen socket\n"); + } return; } - memset(&listenAddr, 0 , sizeof(listenAddr)); + memset(&listenAddr, 0, sizeof(listenAddr)); listenAddr.inet.family = PR_AF_INET; listenAddr.inet.port = PR_htons(BASE_PORT); listenAddr.inet.ip = PR_htonl(PR_INADDR_ANY); @@ -197,148 +205,153 @@ int i; while (PR_Bind(listenSock, &listenAddr) == PR_FAILURE) { if (PR_GetError() == PR_ADDRESS_IN_USE_ERROR) { listenAddr.inet.port += 2; - if (i++ < SERVER_MAX_BIND_COUNT) + if (i++ < SERVER_MAX_BIND_COUNT) { continue; + } } failed_already=1; if (debug_mode) { - PR_fprintf(output,"accept: ERROR - PR_Bind failed\n"); + PR_fprintf(output,"accept: ERROR - PR_Bind failed\n"); } - return; + return; } rv = PR_Listen(listenSock, 100); if (rv == PR_FAILURE) { failed_already=1; - if (debug_mode) + if (debug_mode) { PR_fprintf(output, "unable to listen\n"); + } return; } clientCommand = clientAction; clientThread = PR_CreateThread(PR_USER_THREAD, ClientThread, - (void *)&clientCommand, PR_PRIORITY_NORMAL, thread_scope, - PR_JOINABLE_THREAD, 0); + (void *)&clientCommand, PR_PRIORITY_NORMAL, thread_scope, + PR_JOINABLE_THREAD, 0); if (!clientThread) { failed_already=1; - if (debug_mode) + if (debug_mode) { PR_fprintf(output, "error creating client thread\n"); + } return; } iterations = count; - for (;iterations--;) { + for (; iterations--;) { switch (acceptType) { - case ACCEPT_NORMAL: - clientSock = PR_Accept(listenSock, &clientAddr, - timeoutTime); - switch(clientAction) { - case CLIENT_TIMEOUT_ACCEPT: - TEST_ASSERT(clientSock == 0); - TEST_ASSERT(PR_GetError() == PR_IO_TIMEOUT_ERROR); - break; - case CLIENT_NORMAL: - TEST_ASSERT(clientSock); - bytesRead = PR_Recv(clientSock, - buf, CLIENT_DATA, 0, timeoutTime); - TEST_ASSERT(bytesRead == CLIENT_DATA); - break; - case CLIENT_TIMEOUT_SEND: - TEST_ASSERT(clientSock); - bytesRead = PR_Recv(clientSock, - buf, CLIENT_DATA, 0, timeoutTime); - TEST_ASSERT(bytesRead == -1); - TEST_ASSERT(PR_GetError() == PR_IO_TIMEOUT_ERROR); - break; - } - break; - case ACCEPT_READ: - status = PR_AcceptRead(listenSock, &clientSock, - &raddr, buf, CLIENT_DATA, timeoutTime); - switch(clientAction) { - case CLIENT_TIMEOUT_ACCEPT: - /* Invalid test case */ - TEST_ASSERT(0); - break; - case CLIENT_NORMAL: - TEST_ASSERT(clientSock); - TEST_ASSERT(status == CLIENT_DATA); + case ACCEPT_NORMAL: + clientSock = PR_Accept(listenSock, &clientAddr, + timeoutTime); + switch(clientAction) { + case CLIENT_TIMEOUT_ACCEPT: + TEST_ASSERT(clientSock == 0); + TEST_ASSERT(PR_GetError() == PR_IO_TIMEOUT_ERROR); + break; + case CLIENT_NORMAL: + TEST_ASSERT(clientSock); + bytesRead = PR_Recv(clientSock, + buf, CLIENT_DATA, 0, timeoutTime); + TEST_ASSERT(bytesRead == CLIENT_DATA); + break; + case CLIENT_TIMEOUT_SEND: + TEST_ASSERT(clientSock); + bytesRead = PR_Recv(clientSock, + buf, CLIENT_DATA, 0, timeoutTime); + TEST_ASSERT(bytesRead == -1); + TEST_ASSERT(PR_GetError() == PR_IO_TIMEOUT_ERROR); + break; + } break; - case CLIENT_TIMEOUT_SEND: - TEST_ASSERT(status == -1); - TEST_ASSERT(PR_GetError() == PR_IO_TIMEOUT_ERROR); + case ACCEPT_READ: + status = PR_AcceptRead(listenSock, &clientSock, + &raddr, buf, CLIENT_DATA, timeoutTime); + switch(clientAction) { + case CLIENT_TIMEOUT_ACCEPT: + /* Invalid test case */ + TEST_ASSERT(0); + break; + case CLIENT_NORMAL: + TEST_ASSERT(clientSock); + TEST_ASSERT(status == CLIENT_DATA); + break; + case CLIENT_TIMEOUT_SEND: + TEST_ASSERT(status == -1); + TEST_ASSERT(PR_GetError() == PR_IO_TIMEOUT_ERROR); + break; + } break; - } - break; #ifdef WINNT - case ACCEPT_FAST: - clientSock = PR_NTFast_Accept(listenSock, - &clientAddr, timeoutTime); - switch(clientAction) { - case CLIENT_TIMEOUT_ACCEPT: - TEST_ASSERT(clientSock == 0); - if (debug_mode) - PR_fprintf(output, "PR_GetError is %ld\n", PR_GetError()); - TEST_ASSERT(PR_GetError() == PR_IO_TIMEOUT_ERROR); - break; - case CLIENT_NORMAL: - TEST_ASSERT(clientSock); - bytesRead = PR_Recv(clientSock, - buf, CLIENT_DATA, 0, timeoutTime); - TEST_ASSERT(bytesRead == CLIENT_DATA); - break; - case CLIENT_TIMEOUT_SEND: - TEST_ASSERT(clientSock); - bytesRead = PR_Recv(clientSock, - buf, CLIENT_DATA, 0, timeoutTime); - TEST_ASSERT(bytesRead == -1); - TEST_ASSERT(PR_GetError() == PR_IO_TIMEOUT_ERROR); - break; - } - break; - break; - case ACCEPT_READ_FAST: - status = PR_NTFast_AcceptRead(listenSock, - &clientSock, &raddr, buf, 4096, timeoutTime); - switch(clientAction) { - case CLIENT_TIMEOUT_ACCEPT: - /* Invalid test case */ - TEST_ASSERT(0); - break; - case CLIENT_NORMAL: - TEST_ASSERT(clientSock); - TEST_ASSERT(status == CLIENT_DATA); - break; - case CLIENT_TIMEOUT_SEND: - TEST_ASSERT(clientSock == NULL); - TEST_ASSERT(status == -1); - TEST_ASSERT(PR_GetError() == PR_IO_TIMEOUT_ERROR); + case ACCEPT_FAST: + clientSock = PR_NTFast_Accept(listenSock, + &clientAddr, timeoutTime); + switch(clientAction) { + case CLIENT_TIMEOUT_ACCEPT: + TEST_ASSERT(clientSock == 0); + if (debug_mode) { + PR_fprintf(output, "PR_GetError is %ld\n", PR_GetError()); + } + TEST_ASSERT(PR_GetError() == PR_IO_TIMEOUT_ERROR); + break; + case CLIENT_NORMAL: + TEST_ASSERT(clientSock); + bytesRead = PR_Recv(clientSock, + buf, CLIENT_DATA, 0, timeoutTime); + TEST_ASSERT(bytesRead == CLIENT_DATA); + break; + case CLIENT_TIMEOUT_SEND: + TEST_ASSERT(clientSock); + bytesRead = PR_Recv(clientSock, + buf, CLIENT_DATA, 0, timeoutTime); + TEST_ASSERT(bytesRead == -1); + TEST_ASSERT(PR_GetError() == PR_IO_TIMEOUT_ERROR); + break; + } break; - } - break; - case ACCEPT_READ_FAST_CB: - status = PR_NTFast_AcceptRead_WithTimeoutCallback( - listenSock, &clientSock, &raddr, buf, 4096, - timeoutTime, timeout_callback, (void *)CALLBACK_MAGIC); - switch(clientAction) { - case CLIENT_TIMEOUT_ACCEPT: - /* Invalid test case */ - TEST_ASSERT(0); break; - case CLIENT_NORMAL: - TEST_ASSERT(clientSock); - TEST_ASSERT(status == CLIENT_DATA); + case ACCEPT_READ_FAST: + status = PR_NTFast_AcceptRead(listenSock, + &clientSock, &raddr, buf, 4096, timeoutTime); + switch(clientAction) { + case CLIENT_TIMEOUT_ACCEPT: + /* Invalid test case */ + TEST_ASSERT(0); + break; + case CLIENT_NORMAL: + TEST_ASSERT(clientSock); + TEST_ASSERT(status == CLIENT_DATA); + break; + case CLIENT_TIMEOUT_SEND: + TEST_ASSERT(clientSock == NULL); + TEST_ASSERT(status == -1); + TEST_ASSERT(PR_GetError() == PR_IO_TIMEOUT_ERROR); + break; + } break; - case CLIENT_TIMEOUT_SEND: - if (debug_mode) - PR_fprintf(output, "clientSock = 0x%8.8lx\n", clientSock); - TEST_ASSERT(clientSock == NULL); - TEST_ASSERT(status == -1); - TEST_ASSERT(PR_GetError() == PR_IO_TIMEOUT_ERROR); + case ACCEPT_READ_FAST_CB: + status = PR_NTFast_AcceptRead_WithTimeoutCallback( + listenSock, &clientSock, &raddr, buf, 4096, + timeoutTime, timeout_callback, (void *)CALLBACK_MAGIC); + switch(clientAction) { + case CLIENT_TIMEOUT_ACCEPT: + /* Invalid test case */ + TEST_ASSERT(0); + break; + case CLIENT_NORMAL: + TEST_ASSERT(clientSock); + TEST_ASSERT(status == CLIENT_DATA); + break; + case CLIENT_TIMEOUT_SEND: + if (debug_mode) { + PR_fprintf(output, "clientSock = 0x%8.8lx\n", clientSock); + } + TEST_ASSERT(clientSock == NULL); + TEST_ASSERT(status == -1); + TEST_ASSERT(PR_GetError() == PR_IO_TIMEOUT_ERROR); + break; + } break; - } - break; #endif } if (clientSock != NULL) { @@ -353,58 +366,58 @@ int i; void AcceptUpdatedTest(void) -{ - RunTest(ACCEPT_NORMAL, CLIENT_NORMAL); +{ + RunTest(ACCEPT_NORMAL, CLIENT_NORMAL); } void AcceptNotUpdatedTest(void) -{ - RunTest(ACCEPT_FAST, CLIENT_NORMAL); +{ + RunTest(ACCEPT_FAST, CLIENT_NORMAL); } void AcceptReadTest(void) -{ - RunTest(ACCEPT_READ, CLIENT_NORMAL); +{ + RunTest(ACCEPT_READ, CLIENT_NORMAL); } void AcceptReadNotUpdatedTest(void) -{ - RunTest(ACCEPT_READ_FAST, CLIENT_NORMAL); +{ + RunTest(ACCEPT_READ_FAST, CLIENT_NORMAL); } void AcceptReadCallbackTest(void) -{ - RunTest(ACCEPT_READ_FAST_CB, CLIENT_NORMAL); +{ + RunTest(ACCEPT_READ_FAST_CB, CLIENT_NORMAL); } void TimeoutAcceptUpdatedTest(void) -{ - RunTest(ACCEPT_NORMAL, CLIENT_TIMEOUT_ACCEPT); +{ + RunTest(ACCEPT_NORMAL, CLIENT_TIMEOUT_ACCEPT); } void TimeoutAcceptNotUpdatedTest(void) -{ - RunTest(ACCEPT_FAST, CLIENT_TIMEOUT_ACCEPT); +{ + RunTest(ACCEPT_FAST, CLIENT_TIMEOUT_ACCEPT); } void TimeoutAcceptReadCallbackTest(void) -{ - RunTest(ACCEPT_READ_FAST_CB, CLIENT_TIMEOUT_ACCEPT); +{ + RunTest(ACCEPT_READ_FAST_CB, CLIENT_TIMEOUT_ACCEPT); } void TimeoutReadUpdatedTest(void) -{ - RunTest(ACCEPT_NORMAL, CLIENT_TIMEOUT_SEND); +{ + RunTest(ACCEPT_NORMAL, CLIENT_TIMEOUT_SEND); } void TimeoutReadNotUpdatedTest(void) -{ - RunTest(ACCEPT_FAST, CLIENT_TIMEOUT_SEND); +{ + RunTest(ACCEPT_FAST, CLIENT_TIMEOUT_SEND); } void TimeoutReadReadTest(void) -{ - RunTest(ACCEPT_READ, CLIENT_TIMEOUT_SEND); +{ + RunTest(ACCEPT_READ, CLIENT_TIMEOUT_SEND); } void TimeoutReadReadNotUpdatedTest(void) -{ - RunTest(ACCEPT_READ_FAST, CLIENT_TIMEOUT_SEND); +{ + RunTest(ACCEPT_READ_FAST, CLIENT_TIMEOUT_SEND); } void TimeoutReadReadCallbackTest(void) -{ - RunTest(ACCEPT_READ_FAST_CB, CLIENT_TIMEOUT_SEND); +{ + RunTest(ACCEPT_READ_FAST_CB, CLIENT_TIMEOUT_SEND); } /************************************************************************/ @@ -419,8 +432,9 @@ static void Measure(void (*func)(void), const char *msg) stop = PR_IntervalNow(); d = (double)PR_IntervalToMicroseconds(stop - start); - if (debug_mode) + if (debug_mode) { PR_fprintf(output, "%40s: %6.2f usec\n", msg, d / count); + } } @@ -437,20 +451,22 @@ int main(int argc, char **argv) PLOptState *opt = PL_CreateOptState(argc, argv, "Gdc:"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'G': /* global threads */ - thread_scope = PR_GLOBAL_THREAD; - break; - case 'd': /* debug mode */ - debug_mode = 1; - break; - case 'c': /* loop counter */ - count = atoi(opt->value); - break; - default: - break; + case 'G': /* global threads */ + thread_scope = PR_GLOBAL_THREAD; + break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + case 'c': /* loop counter */ + count = atoi(opt->value); + break; + default: + break; } } PL_DestroyOptState(opt); @@ -460,8 +476,9 @@ int main(int argc, char **argv) PR_STDIO_INIT(); timeoutTime = PR_SecondsToInterval(TIMEOUTSECS); - if (debug_mode) + if (debug_mode) { PR_fprintf(output, "\nRun accept() sucessful connection tests\n"); + } Measure(AcceptUpdatedTest, "PR_Accept()"); Measure(AcceptReadTest, "PR_AcceptRead()"); @@ -470,14 +487,16 @@ int main(int argc, char **argv) Measure(AcceptReadNotUpdatedTest, "PR_NTFast_AcceptRead()"); Measure(AcceptReadCallbackTest, "PR_NTFast_AcceptRead_WithTimeoutCallback()"); #endif - if (debug_mode) + if (debug_mode) { PR_fprintf(output, "\nRun accept() timeout in the accept tests\n"); + } #ifdef WINNT Measure(TimeoutReadReadCallbackTest, "PR_NTFast_AcceptRead_WithTimeoutCallback()"); #endif Measure(TimeoutReadUpdatedTest, "PR_Accept()"); - if (debug_mode) + if (debug_mode) { PR_fprintf(output, "\nRun accept() timeout in the read tests\n"); + } Measure(TimeoutReadReadTest, "PR_AcceptRead()"); #ifdef WINNT Measure(TimeoutReadNotUpdatedTest, "PR_NTFast_Accept()"); diff --git a/nsprpub/pr/tests/acceptread.c b/nsprpub/pr/tests/acceptread.c index 184cfcbba..d7fe079c4 100644 --- a/nsprpub/pr/tests/acceptread.c +++ b/nsprpub/pr/tests/acceptread.c @@ -23,21 +23,19 @@ static PRStatus PrintAddress(const PRNetAddr* address) { char buffer[100]; PRStatus rv = PR_NetAddrToString(address, buffer, sizeof(buffer)); - if (PR_FAILURE == rv) PL_FPrintError(err_out, "PR_NetAddrToString"); + if (PR_FAILURE == rv) { + PL_FPrintError(err_out, "PR_NetAddrToString"); + } else PR_fprintf( - std_out, "Accepted connection from (0x%p)%s:%d\n", - address, buffer, address->inet.port); + std_out, "Accepted connection from (0x%p)%s:%d\n", + address, buffer, address->inet.port); return rv; } /* PrintAddress */ static void ConnectingThread(void *arg) { PRInt32 nbytes; -#ifdef SYMBIAN - char buf[256]; -#else char buf[1024]; -#endif PRFileDesc *sock; PRNetAddr peer_addr, *addr; @@ -70,10 +68,14 @@ static void ConnectingThread(void *arg) PR_Sleep(write_dally); nbytes = PR_Send(sock, GET, sizeof(GET), 0, PR_INTERVAL_NO_TIMEOUT); - if (nbytes == -1) PL_FPrintError(err_out, "PR_Send (client) failed"); + if (nbytes == -1) { + PL_FPrintError(err_out, "PR_Send (client) failed"); + } nbytes = PR_Recv(sock, buf, sizeof(buf), 0, PR_INTERVAL_NO_TIMEOUT); - if (nbytes == -1) PL_FPrintError(err_out, "PR_Recv (client) failed"); + if (nbytes == -1) { + PL_FPrintError(err_out, "PR_Recv (client) failed"); + } else { PR_fprintf(std_out, "PR_Recv (client) succeeded: %d bytes\n", nbytes); @@ -81,11 +83,13 @@ static void ConnectingThread(void *arg) PR_fprintf(std_out, "%s\n", buf); } - if (PR_FAILURE == PR_Shutdown(sock, PR_SHUTDOWN_BOTH)) + if (PR_FAILURE == PR_Shutdown(sock, PR_SHUTDOWN_BOTH)) { PL_FPrintError(err_out, "PR_Shutdown (client) failed"); + } - if (PR_FAILURE == PR_Close(sock)) + if (PR_FAILURE == PR_Close(sock)) { PL_FPrintError(err_out, "PR_Close (client) failed"); + } return; } /* ConnectingThread */ @@ -104,7 +108,7 @@ static void AcceptingThread(void *arg) if (NULL == listen_sock) { PL_FPrintError(err_out, "PR_NewTCPSocket (server) failed"); - PR_ProcessExit(1); + PR_ProcessExit(1); } sock_opt.option = PR_SockOpt_Reuseaddr; sock_opt.value.reuse_addr = PR_TRUE; @@ -112,24 +116,26 @@ static void AcceptingThread(void *arg) if (PR_FAILURE == rv) { PL_FPrintError(err_out, "PR_SetSocketOption (server) failed"); - PR_ProcessExit(1); + PR_ProcessExit(1); } rv = PR_Bind(listen_sock, listen_addr); if (PR_FAILURE == rv) { PL_FPrintError(err_out, "PR_Bind (server) failed"); - PR_ProcessExit(1); + PR_ProcessExit(1); } rv = PR_Listen(listen_sock, 10); if (PR_FAILURE == rv) { PL_FPrintError(err_out, "PR_Listen (server) failed"); - PR_ProcessExit(1); + PR_ProcessExit(1); } bytes = PR_AcceptRead( - listen_sock, &accept_sock, &accept_addr, buf, buf_size, accept_timeout); + listen_sock, &accept_sock, &accept_addr, buf, buf_size, accept_timeout); - if (-1 == bytes) PL_FPrintError(err_out, "PR_AcceptRead (server) failed"); + if (-1 == bytes) { + PL_FPrintError(err_out, "PR_AcceptRead (server) failed"); + } else { PrintAddress(accept_addr); @@ -138,20 +144,23 @@ static void AcceptingThread(void *arg) buf, &buf[BUF_SIZE], buf); bytes = PR_Write(accept_sock, buf, bytes); rv = PR_Shutdown(accept_sock, PR_SHUTDOWN_BOTH); - if (PR_FAILURE == rv) + if (PR_FAILURE == rv) { PL_FPrintError(err_out, "PR_Shutdown (server) failed"); + } } if (-1 != bytes) { rv = PR_Close(accept_sock); - if (PR_FAILURE == rv) + if (PR_FAILURE == rv) { PL_FPrintError(err_out, "PR_Close (server) failed"); + } } rv = PR_Close(listen_sock); - if (PR_FAILURE == rv) + if (PR_FAILURE == rv) { PL_FPrintError(err_out, "PR_Close (server) failed"); + } } /* AcceptingThread */ int main(int argc, char **argv) @@ -169,8 +178,12 @@ int main(int argc, char **argv) std_out = PR_STDOUT; accept_timeout = PR_SecondsToInterval(2); - if (argc != 2 && argc != 3) port_number = DEFAULT_PORT; - else port_number = (PRUint16)atoi(argv[(argc == 2) ? 1 : 2]); + if (argc != 2 && argc != 3) { + port_number = DEFAULT_PORT; + } + else { + port_number = (PRUint16)atoi(argv[(argc == 2) ? 1 : 2]); + } status = PR_InitializeNetAddr(PR_IpAddrAny, port_number, &server_addr); if (PR_SUCCESS != status) @@ -181,7 +194,7 @@ int main(int argc, char **argv) if (argc < 3) { status = PR_InitializeNetAddr( - PR_IpAddrLoopback, port_number, &client_addr); + PR_IpAddrLoopback, port_number, &client_addr); if (PR_SUCCESS != status) { PL_FPrintError(err_out, "PR_InitializeNetAddr failed"); @@ -191,7 +204,7 @@ int main(int argc, char **argv) else { status = PR_GetHostByName( - argv[1], netdb_buf, sizeof(netdb_buf), &he); + argv[1], netdb_buf, sizeof(netdb_buf), &he); if (status == PR_FAILURE) { PL_FPrintError(err_out, "PR_GetHostByName failed"); @@ -214,8 +227,8 @@ int main(int argc, char **argv) std_out, "Testing w/ write_dally = %d msec\n", PR_IntervalToMilliseconds(write_dally)); server_thread = PR_CreateThread( - PR_USER_THREAD, AcceptingThread, &server_addr, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, AcceptingThread, &server_addr, + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); if (server_thread == NULL) { PL_FPrintError(err_out, "PR_CreateThread (server) failed"); @@ -225,19 +238,21 @@ int main(int argc, char **argv) PR_Sleep(delta); /* let the server pot thicken */ client_thread = PR_CreateThread( - PR_USER_THREAD, ConnectingThread, &client_addr, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, ConnectingThread, &client_addr, + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); if (client_thread == NULL) { PL_FPrintError(err_out, "PR_CreateThread (client) failed"); PR_ProcessExit(1); } - if (PR_JoinThread(client_thread) == PR_FAILURE) + if (PR_JoinThread(client_thread) == PR_FAILURE) { PL_FPrintError(err_out, "PR_JoinThread (client) failed"); + } - if (PR_JoinThread(server_thread) == PR_FAILURE) + if (PR_JoinThread(server_thread) == PR_FAILURE) { PL_FPrintError(err_out, "PR_JoinThread (server) failed"); + } } return 0; diff --git a/nsprpub/pr/tests/acceptreademu.c b/nsprpub/pr/tests/acceptreademu.c index 981cebadd..75140c02f 100644 --- a/nsprpub/pr/tests/acceptreademu.c +++ b/nsprpub/pr/tests/acceptreademu.c @@ -29,7 +29,7 @@ static PRIOMethods emu_layer_methods; /* the acceptread method in emu_layer_methods */ static PRInt32 PR_CALLBACK emu_AcceptRead(PRFileDesc *sd, PRFileDesc **nd, - PRNetAddr **raddr, void *buf, PRInt32 amount, PRIntervalTime timeout) + PRNetAddr **raddr, void *buf, PRInt32 amount, PRIntervalTime timeout) { return PR_EmulateAcceptRead(sd, nd, raddr, buf, amount, timeout); } @@ -38,21 +38,19 @@ static PRStatus PrintAddress(const PRNetAddr* address) { char buffer[100]; PRStatus rv = PR_NetAddrToString(address, buffer, sizeof(buffer)); - if (PR_FAILURE == rv) PL_FPrintError(err_out, "PR_NetAddrToString"); + if (PR_FAILURE == rv) { + PL_FPrintError(err_out, "PR_NetAddrToString"); + } else PR_fprintf( - std_out, "Accepted connection from (0x%p)%s:%d\n", - address, buffer, address->inet.port); + std_out, "Accepted connection from (0x%p)%s:%d\n", + address, buffer, address->inet.port); return rv; } /* PrintAddress */ static void ConnectingThread(void *arg) { PRInt32 nbytes; -#ifdef SYMBIAN - char buf[256]; -#else char buf[1024]; -#endif PRFileDesc *sock; PRNetAddr peer_addr, *addr; @@ -85,10 +83,14 @@ static void ConnectingThread(void *arg) PR_Sleep(write_dally); nbytes = PR_Send(sock, GET, sizeof(GET), 0, PR_INTERVAL_NO_TIMEOUT); - if (nbytes == -1) PL_FPrintError(err_out, "PR_Send (client) failed"); + if (nbytes == -1) { + PL_FPrintError(err_out, "PR_Send (client) failed"); + } nbytes = PR_Recv(sock, buf, sizeof(buf), 0, PR_INTERVAL_NO_TIMEOUT); - if (nbytes == -1) PL_FPrintError(err_out, "PR_Recv (client) failed"); + if (nbytes == -1) { + PL_FPrintError(err_out, "PR_Recv (client) failed"); + } else { PR_fprintf(std_out, "PR_Recv (client) succeeded: %d bytes\n", nbytes); @@ -96,11 +98,13 @@ static void ConnectingThread(void *arg) PR_fprintf(std_out, "%s\n", buf); } - if (PR_FAILURE == PR_Shutdown(sock, PR_SHUTDOWN_BOTH)) + if (PR_FAILURE == PR_Shutdown(sock, PR_SHUTDOWN_BOTH)) { PL_FPrintError(err_out, "PR_Shutdown (client) failed"); + } - if (PR_FAILURE == PR_Close(sock)) + if (PR_FAILURE == PR_Close(sock)) { PL_FPrintError(err_out, "PR_Close (client) failed"); + } return; } /* ConnectingThread */ @@ -120,18 +124,18 @@ static void AcceptingThread(void *arg) if (NULL == listen_sock) { PL_FPrintError(err_out, "PR_NewTCPSocket (server) failed"); - PR_ProcessExit(1); + PR_ProcessExit(1); } layer = PR_CreateIOLayerStub(emu_layer_ident, &emu_layer_methods); if (NULL == layer) { PL_FPrintError(err_out, "PR_CreateIOLayerStub (server) failed"); - PR_ProcessExit(1); + PR_ProcessExit(1); } if (PR_PushIOLayer(listen_sock, PR_TOP_IO_LAYER, layer) == PR_FAILURE) { PL_FPrintError(err_out, "PR_PushIOLayer (server) failed"); - PR_ProcessExit(1); + PR_ProcessExit(1); } sock_opt.option = PR_SockOpt_Reuseaddr; sock_opt.value.reuse_addr = PR_TRUE; @@ -139,24 +143,26 @@ static void AcceptingThread(void *arg) if (PR_FAILURE == rv) { PL_FPrintError(err_out, "PR_SetSocketOption (server) failed"); - PR_ProcessExit(1); + PR_ProcessExit(1); } rv = PR_Bind(listen_sock, listen_addr); if (PR_FAILURE == rv) { PL_FPrintError(err_out, "PR_Bind (server) failed"); - PR_ProcessExit(1); + PR_ProcessExit(1); } rv = PR_Listen(listen_sock, 10); if (PR_FAILURE == rv) { PL_FPrintError(err_out, "PR_Listen (server) failed"); - PR_ProcessExit(1); + PR_ProcessExit(1); } bytes = PR_AcceptRead( - listen_sock, &accept_sock, &accept_addr, buf, buf_size, accept_timeout); + listen_sock, &accept_sock, &accept_addr, buf, buf_size, accept_timeout); - if (-1 == bytes) PL_FPrintError(err_out, "PR_AcceptRead (server) failed"); + if (-1 == bytes) { + PL_FPrintError(err_out, "PR_AcceptRead (server) failed"); + } else { PrintAddress(accept_addr); @@ -165,20 +171,23 @@ static void AcceptingThread(void *arg) buf, &buf[BUF_SIZE], buf); bytes = PR_Write(accept_sock, buf, bytes); rv = PR_Shutdown(accept_sock, PR_SHUTDOWN_BOTH); - if (PR_FAILURE == rv) + if (PR_FAILURE == rv) { PL_FPrintError(err_out, "PR_Shutdown (server) failed"); + } } if (-1 != bytes) { rv = PR_Close(accept_sock); - if (PR_FAILURE == rv) + if (PR_FAILURE == rv) { PL_FPrintError(err_out, "PR_Close (server) failed"); + } } rv = PR_Close(listen_sock); - if (PR_FAILURE == rv) + if (PR_FAILURE == rv) { PL_FPrintError(err_out, "PR_Close (server) failed"); + } } /* AcceptingThread */ int main(int argc, char **argv) @@ -199,8 +208,12 @@ int main(int argc, char **argv) emu_layer_methods = *PR_GetDefaultIOMethods(); emu_layer_methods.acceptread = emu_AcceptRead; - if (argc != 2 && argc != 3) port_number = DEFAULT_PORT; - else port_number = (PRUint16)atoi(argv[(argc == 2) ? 1 : 2]); + if (argc != 2 && argc != 3) { + port_number = DEFAULT_PORT; + } + else { + port_number = (PRUint16)atoi(argv[(argc == 2) ? 1 : 2]); + } status = PR_InitializeNetAddr(PR_IpAddrAny, port_number, &server_addr); if (PR_SUCCESS != status) @@ -211,7 +224,7 @@ int main(int argc, char **argv) if (argc < 3) { status = PR_InitializeNetAddr( - PR_IpAddrLoopback, port_number, &client_addr); + PR_IpAddrLoopback, port_number, &client_addr); if (PR_SUCCESS != status) { PL_FPrintError(err_out, "PR_InitializeNetAddr failed"); @@ -221,7 +234,7 @@ int main(int argc, char **argv) else { status = PR_GetHostByName( - argv[1], netdb_buf, sizeof(netdb_buf), &he); + argv[1], netdb_buf, sizeof(netdb_buf), &he); if (status == PR_FAILURE) { PL_FPrintError(err_out, "PR_GetHostByName failed"); @@ -244,8 +257,8 @@ int main(int argc, char **argv) std_out, "Testing w/ write_dally = %d msec\n", PR_IntervalToMilliseconds(write_dally)); server_thread = PR_CreateThread( - PR_USER_THREAD, AcceptingThread, &server_addr, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, AcceptingThread, &server_addr, + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); if (server_thread == NULL) { PL_FPrintError(err_out, "PR_CreateThread (server) failed"); @@ -255,19 +268,21 @@ int main(int argc, char **argv) PR_Sleep(delta); /* let the server pot thicken */ client_thread = PR_CreateThread( - PR_USER_THREAD, ConnectingThread, &client_addr, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, ConnectingThread, &client_addr, + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); if (client_thread == NULL) { PL_FPrintError(err_out, "PR_CreateThread (client) failed"); PR_ProcessExit(1); } - if (PR_JoinThread(client_thread) == PR_FAILURE) + if (PR_JoinThread(client_thread) == PR_FAILURE) { PL_FPrintError(err_out, "PR_JoinThread (client) failed"); + } - if (PR_JoinThread(server_thread) == PR_FAILURE) + if (PR_JoinThread(server_thread) == PR_FAILURE) { PL_FPrintError(err_out, "PR_JoinThread (server) failed"); + } } return 0; diff --git a/nsprpub/pr/tests/addrstr.c b/nsprpub/pr/tests/addrstr.c index 4e830a718..b6736a74b 100644 --- a/nsprpub/pr/tests/addrstr.c +++ b/nsprpub/pr/tests/addrstr.c @@ -19,12 +19,12 @@ const char *testaddrs[] = { "::FFFE:9504:3501", "::fffe:9504:3501", "0:0:1:0:35c:0:0:0", "0:0:1:0:35c::", "0:0:3f4c:0:0:4552:0:0", "::3f4c:0:0:4552:0:0", - "0:0:1245:0:0:0:0567:0", "0:0:1245::567:0", - "0:1:2:3:4:5:6:7", "0:1:2:3:4:5:6:7", - "1:2:3:0:4:5:6:7", "1:2:3:0:4:5:6:7", - "1:2:3:4:5:6:7:0", "1:2:3:4:5:6:7:0", - "1:2:3:4:5:6:7:8", "1:2:3:4:5:6:7:8", - "1:2:3:4:5:6::7", "1:2:3:4:5:6:0:7", + "0:0:1245:0:0:0:0567:0", "0:0:1245::567:0", + "0:1:2:3:4:5:6:7", "0:1:2:3:4:5:6:7", + "1:2:3:0:4:5:6:7", "1:2:3:0:4:5:6:7", + "1:2:3:4:5:6:7:0", "1:2:3:4:5:6:7:0", + "1:2:3:4:5:6:7:8", "1:2:3:4:5:6:7:8", + "1:2:3:4:5:6::7", "1:2:3:4:5:6:0:7", 0 }; @@ -49,23 +49,23 @@ int main(int argc, char **argv) PRStatus rv; while ((in = *nexttestaddr++) != 0) { - expected_out = *nexttestaddr++; - rv = PR_StringToNetAddr(in, &addr); - if (rv) { - printf("cannot convert %s to addr: %d\n", in, rv); + expected_out = *nexttestaddr++; + rv = PR_StringToNetAddr(in, &addr); + if (rv) { + printf("cannot convert %s to addr: %d\n", in, rv); failed_already = 1; - continue; - } - rv = PR_NetAddrToString(&addr, buf, sizeof(buf)); - if (rv) { - printf("cannot convert %s back to string: %d\n", in, rv); + continue; + } + rv = PR_NetAddrToString(&addr, buf, sizeof(buf)); + if (rv) { + printf("cannot convert %s back to string: %d\n", in, rv); failed_already = 1; - continue; - } - if (strcmp(buf, expected_out)) { + continue; + } + if (strcmp(buf, expected_out)) { /* This is not necessarily an error */ - printf("%s expected %s got %s\n", in, expected_out, buf); - } + printf("%s expected %s got %s\n", in, expected_out, buf); + } } while ((in = *nextbadaddr++) != 0) { if (PR_StringToNetAddr(in, &addr) == PR_SUCCESS) { diff --git a/nsprpub/pr/tests/affinity.c b/nsprpub/pr/tests/affinity.c index 4bdbaf723..14d08efc1 100644 --- a/nsprpub/pr/tests/affinity.c +++ b/nsprpub/pr/tests/affinity.c @@ -11,82 +11,74 @@ #include <stdlib.h> #include <string.h> -#ifndef XP_BEOS /* * Test PR_GetThreadAffinityMask - * The function is called by each of local, global and global bound threads - * The test should be run on both single and multi-cpu systems + * The function is called by each of local, global and global bound threads + * The test should be run on both single and multi-cpu systems */ static void PR_CALLBACK thread_start(void *arg) { -PRUint32 mask = 0; + PRUint32 mask = 0; - if (PR_GetThreadAffinityMask(PR_GetCurrentThread(), &mask)) - printf("\tthread_start: PR_GetCurrentThreadAffinityMask failed\n"); - else - printf("\tthread_start: AffinityMask = 0x%x\n",mask); + if (PR_GetThreadAffinityMask(PR_GetCurrentThread(), &mask)) { + printf("\tthread_start: PR_GetCurrentThreadAffinityMask failed\n"); + } + else { + printf("\tthread_start: AffinityMask = 0x%x\n",mask); + } } int main(int argc, char **argv) { - PRThread *t; - - printf("main: creating local thread\n"); - - t = PR_CreateThread(PR_USER_THREAD, - thread_start, 0, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_JOINABLE_THREAD, - 0); - - if (NULL == t) { - printf("main: cannot create local thread\n"); - exit(1); - } - - PR_JoinThread(t); - - printf("main: creating global thread\n"); - t = PR_CreateThread(PR_USER_THREAD, - thread_start, 0, - PR_PRIORITY_NORMAL, - PR_GLOBAL_THREAD, - PR_JOINABLE_THREAD, - 0); - - if (NULL == t) { - printf("main: cannot create global thread\n"); - exit(1); - } - - PR_JoinThread(t); - - printf("main: creating global bound thread\n"); - t = PR_CreateThread(PR_USER_THREAD, - thread_start, 0, - PR_PRIORITY_NORMAL, - PR_GLOBAL_BOUND_THREAD, - PR_JOINABLE_THREAD, - 0); - - if (NULL == t) { - printf("main: cannot create global bound thread\n"); - exit(1); - } - - PR_JoinThread(t); + PRThread *t; + + printf("main: creating local thread\n"); + + t = PR_CreateThread(PR_USER_THREAD, + thread_start, 0, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_JOINABLE_THREAD, + 0); + + if (NULL == t) { + printf("main: cannot create local thread\n"); + exit(1); + } + + PR_JoinThread(t); + + printf("main: creating global thread\n"); + t = PR_CreateThread(PR_USER_THREAD, + thread_start, 0, + PR_PRIORITY_NORMAL, + PR_GLOBAL_THREAD, + PR_JOINABLE_THREAD, + 0); + + if (NULL == t) { + printf("main: cannot create global thread\n"); + exit(1); + } + + PR_JoinThread(t); + + printf("main: creating global bound thread\n"); + t = PR_CreateThread(PR_USER_THREAD, + thread_start, 0, + PR_PRIORITY_NORMAL, + PR_GLOBAL_BOUND_THREAD, + PR_JOINABLE_THREAD, + 0); + + if (NULL == t) { + printf("main: cannot create global bound thread\n"); + exit(1); + } + + PR_JoinThread(t); return 0; } - -#else /* !XP_BEOS */ - -int main() -{ - printf( "This test is not supported on the BeOS\n" ); - return 0; -} -#endif /* !XP_BEOS */ diff --git a/nsprpub/pr/tests/alarm.c b/nsprpub/pr/tests/alarm.c index e3dedb67f..10a148e44 100644 --- a/nsprpub/pr/tests/alarm.c +++ b/nsprpub/pr/tests/alarm.c @@ -12,12 +12,12 @@ ** ** Modification History: ** 13-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** @@ -60,8 +60,9 @@ static void Notifier(void *arg) PR_Lock(notifyData->ml); while (notifyData->counter > 0) { - while (!notifyData->pending) + while (!notifyData->pending) { PR_WaitCondVar(notifyData->child, PR_INTERVAL_NO_TIMEOUT); + } notifyData->counter -= 1; notifyData->pending = PR_FALSE; PR_NotifyCondVar(notifyData->parent); @@ -71,17 +72,17 @@ static void Notifier(void *arg) /*********************************************************************** ** PRIVATE FUNCTION: ConditionNotify ** DESCRIPTION: -** +** ** INPUTS: loops ** OUTPUTS: None ** RETURN: overhead ** SIDE EFFECTS: -** +** ** RESTRICTIONS: ** None ** MEMORY: NA ** ALGORITHM: -** +** ***********************************************************************/ @@ -90,7 +91,7 @@ static PRIntervalTime ConditionNotify(PRUint32 loops) PRThread *thread; NotifyData notifyData; PRIntervalTime timein, overhead; - + timein = PR_IntervalNow(); notifyData.counter = loops; @@ -98,9 +99,9 @@ static PRIntervalTime ConditionNotify(PRUint32 loops) notifyData.child = PR_NewCondVar(notifyData.ml); notifyData.parent = PR_NewCondVar(notifyData.ml); thread = PR_CreateThread( - PR_USER_THREAD, Notifier, ¬ifyData, - PR_GetThreadPriority(PR_GetCurrentThread()), - thread_scope, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, Notifier, ¬ifyData, + PR_GetThreadPriority(PR_GetCurrentThread()), + thread_scope, PR_JOINABLE_THREAD, 0); overhead = PR_IntervalNow() - timein; /* elapsed so far */ @@ -109,8 +110,9 @@ static PRIntervalTime ConditionNotify(PRUint32 loops) { notifyData.pending = PR_TRUE; PR_NotifyCondVar(notifyData.child); - while (notifyData.pending) + while (notifyData.pending) { PR_WaitCondVar(notifyData.parent, PR_INTERVAL_NO_TIMEOUT); + } } PR_Unlock(notifyData.ml); @@ -120,7 +122,7 @@ static PRIntervalTime ConditionNotify(PRUint32 loops) PR_DestroyCondVar(notifyData.child); PR_DestroyCondVar(notifyData.parent); PR_DestroyLock(notifyData.ml); - + overhead += (PR_IntervalNow() - timein); /* more overhead */ return overhead; @@ -171,38 +173,44 @@ static PRBool AlarmFn1(PRAlarmID *id, void *clientData, PRUint32 late) ad->late += late; ad->times += 1; keepGoing = ((PRIntervalTime)(now - ad->timein) < ad->duration) ? - PR_TRUE : PR_FALSE; - if (!keepGoing) + PR_TRUE : PR_FALSE; + if (!keepGoing) { rv = PR_NotifyCondVar(ad->cv); + } resetAlarm = ((ad->times % 31) == 0) ? PR_TRUE : PR_FALSE; - + interval = (ad->period + ad->rate - 1) / ad->rate; if (!late && (interval > 10)) { interval &= (now & 0x03) + 1; PR_WaitCondVar(ad->cv, interval); } - + PR_Unlock(ad->ml); if (rv != PR_SUCCESS) { - if (!debug_mode) failed_already=1; - else - printf("AlarmFn: notify status: FAIL\n"); - - } + if (!debug_mode) { + failed_already=1; + } + else { + printf("AlarmFn: notify status: FAIL\n"); + } + + } if (resetAlarm) - { + { ad->rate += 3; ad->late = ad->times = 0; if (PR_ResetAlarm(id, ad->period, ad->rate) != PR_SUCCESS) { - if (!debug_mode) - failed_already=1; - else - printf("AlarmFn: Resetting alarm status: FAIL\n"); + if (!debug_mode) { + failed_already=1; + } + else { + printf("AlarmFn: Resetting alarm status: FAIL\n"); + } keepGoing = PR_FALSE; } @@ -235,12 +243,13 @@ static PRIntervalTime Alarms1(PRUint32 loops) (void)PR_SetAlarm( alarm, ad.period, ad.rate, AlarmFn1, &ad); - + overhead = PR_IntervalNow() - timein; PR_Lock(ml); - while ((PRIntervalTime)(PR_IntervalNow() - ad.timein) < duration) + while ((PRIntervalTime)(PR_IntervalNow() - ad.timein) < duration) { PR_WaitCondVar(cv, PR_INTERVAL_NO_TIMEOUT); + } PR_Unlock(ml); timein = PR_IntervalNow(); @@ -248,7 +257,7 @@ static PRIntervalTime Alarms1(PRUint32 loops) PR_DestroyCondVar(cv); PR_DestroyLock(ml); overhead += (PR_IntervalNow() - timein); - + return duration + overhead; } /* Alarms1 */ @@ -262,7 +271,7 @@ static PRBool AlarmFn2(PRAlarmID *id, void *clientData, PRUint32 late) PR_Lock(ad->ml); ad->times += 1; keepGoing = ((PRIntervalTime)(now - ad->timein) < ad->duration) ? - PR_TRUE : PR_FALSE; + PR_TRUE : PR_FALSE; interval = (ad->period + ad->rate - 1) / ad->rate; if (!late && (interval > 10)) @@ -271,13 +280,16 @@ static PRBool AlarmFn2(PRAlarmID *id, void *clientData, PRUint32 late) PR_WaitCondVar(ad->cv, interval); } - if (!keepGoing) rv = PR_NotifyCondVar(ad->cv); + if (!keepGoing) { + rv = PR_NotifyCondVar(ad->cv); + } PR_Unlock(ad->ml); - if (rv != PR_SUCCESS) - failed_already=1;; + if (rv != PR_SUCCESS) { + failed_already=1; + }; return keepGoing; } /* AlarmFn2 */ @@ -306,31 +318,34 @@ static PRIntervalTime Alarms2(PRUint32 loops) (void)PR_SetAlarm( alarm, ad.period, ad.rate, AlarmFn2, &ad); - + overhead = PR_IntervalNow() - timein; PR_Lock(ml); - while ((PRIntervalTime)(PR_IntervalNow() - ad.timein) < duration) + 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"); + 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 */ @@ -370,35 +385,38 @@ static PRIntervalTime Alarms3(PRUint32 loops) alarm, ad[i].period, ad[i].rate, AlarmFn2, &ad[i]); } - + overhead = PR_IntervalNow() - timein; PR_Lock(ml); for (i = 0; i < 3; ++i) { - while ((PRIntervalTime)(PR_IntervalNow() - ad[i].timein) < duration) + while ((PRIntervalTime)(PR_IntervalNow() - ad[i].timein) < duration) { PR_WaitCondVar(cv, PR_INTERVAL_NO_TIMEOUT); + } } PR_Unlock(ml); timein = PR_IntervalNow(); - if (debug_mode) - printf + if (debug_mode) + printf ("Alarms3 finished at %u, %u, %u\n", - ad[0].timein, ad[1].timein, ad[2].timein); - + ad[0].timein, ad[1].timein, ad[2].timein); + rv = PR_DestroyAlarm(alarm); if (rv != PR_SUCCESS) { - if (!debug_mode) - failed_already=1; - else - printf("***Destroying alarm status: FAIL\n"); - } + if (!debug_mode) { + failed_already=1; + } + else { + printf("***Destroying alarm status: FAIL\n"); + } + } PR_DestroyCondVar(cv); PR_DestroyLock(ml); - + overhead += (duration / 3); overhead += (PR_IntervalNow() - timein); @@ -411,15 +429,17 @@ static PRUint32 TimeThis( PRUint32 overhead, usecs; PRIntervalTime predicted, timein, timeout, ticks; - if (debug_mode) - printf("Testing %s ...", msg); + if (debug_mode) { + printf("Testing %s ...", msg); + } timein = PR_IntervalNow(); predicted = func(loops); timeout = PR_IntervalNow(); - if (debug_mode) - printf(" done\n"); + if (debug_mode) { + printf(" done\n"); + } ticks = timeout - timein; usecs = PR_IntervalToMicroseconds(ticks); @@ -427,18 +447,18 @@ static PRUint32 TimeThis( if(ticks < predicted) { - if (debug_mode) { - printf("\tFinished in negative time\n"); - printf("\tpredicted overhead was %d usecs\n", overhead); - printf("\ttest completed in %d usecs\n\n", usecs); - } + if (debug_mode) { + printf("\tFinished in negative time\n"); + printf("\tpredicted overhead was %d usecs\n", overhead); + printf("\ttest completed in %d usecs\n\n", usecs); + } } else { - if (debug_mode) - printf( - "\ttotal: %d usecs\n\toverhead: %d usecs\n\tcost: %6.3f usecs\n\n", - usecs, overhead, ((double)(usecs - overhead) / (double)loops)); + if (debug_mode) + printf( + "\ttotal: %d usecs\n\toverhead: %d usecs\n\tcost: %6.3f usecs\n\n", + usecs, overhead, ((double)(usecs - overhead) / (double)loops)); } return overhead; @@ -448,70 +468,83 @@ int prmain(int argc, char** argv) { PRUint32 cpu, cpus = 0, loops = 0; - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name [-d] - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "Gdl:c:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name [-d] + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "Gdl:c:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'G': /* GLOBAL threads */ - thread_scope = PR_GLOBAL_THREAD; - break; - case 'd': /* debug mode */ - debug_mode = 1; - break; - case 'l': /* loop count */ - loops = atoi(opt->value); - break; - case 'c': /* concurrency limit */ - cpus = atoi(opt->value); - break; - default: - break; + case 'G': /* GLOBAL threads */ + thread_scope = PR_GLOBAL_THREAD; + break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + case 'l': /* loop count */ + loops = atoi(opt->value); + break; + case 'c': /* concurrency limit */ + cpus = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); - if (cpus == 0) cpus = 1; - if (loops == 0) loops = 4; + if (cpus == 0) { + cpus = 1; + } + if (loops == 0) { + loops = 4; + } - if (debug_mode) - printf("Alarm: Using %d loops\n", loops); + if (debug_mode) { + printf("Alarm: Using %d loops\n", loops); + } - if (debug_mode) + if (debug_mode) { printf("Alarm: Using %d cpu(s)\n", cpus); + } for (cpu = 1; cpu <= cpus; ++cpu) { - if (debug_mode) - printf("\nAlarm: Using %d CPU(s)\n", cpu); + if (debug_mode) { + printf("\nAlarm: Using %d CPU(s)\n", cpu); + } - PR_SetConcurrency(cpu); + PR_SetConcurrency(cpu); - /* some basic time test */ - (void)TimeThis("ConditionNotify", ConditionNotify, loops); - (void)TimeThis("ConditionTimeout", ConditionTimeout, loops); - (void)TimeThis("Alarms1", Alarms1, loops); - (void)TimeThis("Alarms2", Alarms2, loops); - (void)TimeThis("Alarms3", Alarms3, loops); + /* some basic time test */ + (void)TimeThis("ConditionNotify", ConditionNotify, loops); + (void)TimeThis("ConditionTimeout", ConditionTimeout, loops); + (void)TimeThis("Alarms1", Alarms1, loops); + (void)TimeThis("Alarms2", Alarms2, loops); + (void)TimeThis("Alarms3", Alarms3, loops); } return 0; } int main(int argc, char** argv) { - PR_Initialize(prmain, argc, argv, 0); - PR_STDIO_INIT(); - if (failed_already) return 1; - else return 0; + PR_Initialize(prmain, argc, argv, 0); + PR_STDIO_INIT(); + if (failed_already) { + return 1; + } + else { + return 0; + } } /* main */ diff --git a/nsprpub/pr/tests/anonfm.c b/nsprpub/pr/tests/anonfm.c index 85e290243..529be6fae 100644 --- a/nsprpub/pr/tests/anonfm.c +++ b/nsprpub/pr/tests/anonfm.c @@ -5,7 +5,7 @@ /* ** File: anonfm.c -** Description: Test anonymous file map +** Description: Test anonymous file map ** ** Synopsis: anonfm [options] [dirName] ** @@ -13,7 +13,7 @@ ** -d enable debug mode ** -h display a help message ** -s <n> size of the anonymous memory map, in KBytes. default: 100KBytes. -** -C 1 Operate this process as ClientOne() +** -C 1 Operate this process as ClientOne() ** -C 2 Operate this process as ClientTwo() ** ** anonfn.c contains two tests, corresponding to the two protocols for @@ -28,8 +28,8 @@ ** PRProcessAttr structure. ** */ -#include <plgetopt.h> -#include <nspr.h> +#include <plgetopt.h> +#include <nspr.h> #include <private/primpl.h> #include <stdio.h> #include <stdlib.h> @@ -73,37 +73,37 @@ static void ClientOne( void ) PRStatus rc; PR_LOG(lm, msgLevel, - ("ClientOne() starting")); - + ("ClientOne() starting")); + fmString = PR_GetEnv( fmEnvName ); if ( NULL == fmString ) { - failed_already = 1; + failed_already = 1; PR_LOG(lm, msgLevel, - ("ClientOne(): PR_Getenv() failed")); + ("ClientOne(): PR_Getenv() failed")); return; } PR_LOG(lm, msgLevel, - ("ClientOne(): PR_Getenv(): found: %s", fmString)); + ("ClientOne(): PR_Getenv(): found: %s", fmString)); fm = PR_ImportFileMapFromString( fmString ); if ( NULL == fm ) { - failed_already = 1; + failed_already = 1; PR_LOG(lm, msgLevel, - ("ClientOne(): PR_ImportFileMapFromString() failed")); + ("ClientOne(): PR_ImportFileMapFromString() failed")); return; } PR_LOG(lm, msgLevel, - ("ClientOne(): PR_ImportFileMapFromString(): fm: %p", fm )); + ("ClientOne(): PR_ImportFileMapFromString(): fm: %p", fm )); addr = PR_MemMap( fm, LL_ZERO, fmSize ); if ( NULL == addr ) { - failed_already = 1; + failed_already = 1; PR_LOG(lm, msgLevel, - ("ClientOne(): PR_MemMap() failed, OSError: %d", PR_GetOSError() )); + ("ClientOne(): PR_MemMap() failed, OSError: %d", PR_GetOSError() )); return; } PR_LOG(lm, msgLevel, - ("ClientOne(): PR_MemMap(): addr: %p", addr )); + ("ClientOne(): PR_MemMap(): addr: %p", addr )); /* write to memory map to release server */ *addr = 1; @@ -111,17 +111,17 @@ static void ClientOne( void ) rc = PR_MemUnmap( addr, fmSize ); PR_ASSERT( rc == PR_SUCCESS ); PR_LOG(lm, msgLevel, - ("ClientOne(): PR_MemUnap(): success" )); + ("ClientOne(): PR_MemUnap(): success" )); rc = PR_CloseFileMap( fm ); if ( PR_FAILURE == rc ) { - failed_already = 1; + failed_already = 1; PR_LOG(lm, msgLevel, - ("ClientOne(): PR_MemUnap() failed, OSError: %d", PR_GetOSError() )); + ("ClientOne(): PR_MemUnap() failed, OSError: %d", PR_GetOSError() )); return; } PR_LOG(lm, msgLevel, - ("ClientOne(): PR_CloseFileMap(): success" )); + ("ClientOne(): PR_CloseFileMap(): success" )); return; } /* end ClientOne() */ @@ -150,23 +150,23 @@ static void ServerOne( void ) PRInt32 exit_status; PR_LOG(lm, msgLevel, - ("ServerOne() starting")); - + ("ServerOne() starting")); + fm = PR_OpenAnonFileMap( dirName, fmSize, fmProt ); if ( NULL == fm ) { - failed_already = 1; + failed_already = 1; PR_LOG(lm, msgLevel, - ("PR_OpenAnonFileMap() failed")); + ("PR_OpenAnonFileMap() failed")); return; } PR_LOG(lm, msgLevel, - ("ServerOne(): FileMap: %p", fm )); - + ("ServerOne(): FileMap: %p", fm )); + rc = PR_ExportFileMapAsString( fm, sizeof(fmString), fmString ); if ( PR_FAILURE == rc ) { - failed_already = 1; + failed_already = 1; PR_LOG(lm, msgLevel, - ("PR_ExportFileMap() failed")); + ("PR_ExportFileMap() failed")); return; } @@ -175,22 +175,23 @@ static void ServerOne( void ) */ PR_snprintf( envBuf, sizeof(envBuf), "%s=%s", fmEnvName, fmString); putenv( envBuf ); - + addr = PR_MemMap( fm, LL_ZERO, fmSize ); if ( NULL == addr ) { - failed_already = 1; + failed_already = 1; PR_LOG(lm, msgLevel, - ("PR_MemMap() failed")); + ("PR_MemMap() failed")); return; } /* set initial value for client */ - for (i = 0; i < (PRIntn)fmSize ; i++ ) - *(addr+i) = 0x00; + for (i = 0; i < (PRIntn)fmSize ; i++ ) { + *(addr+i) = 0x00; + } PR_LOG(lm, msgLevel, - ("ServerOne(): PR_MemMap(): addr: %p", addr )); - + ("ServerOne(): PR_MemMap(): addr: %p", addr )); + /* ** set arguments for child process */ @@ -202,45 +203,47 @@ static void ServerOne( void ) proc = PR_CreateProcess(child_argv[0], child_argv, NULL, NULL); PR_ASSERT( proc ); PR_LOG(lm, msgLevel, - ("ServerOne(): PR_CreateProcess(): proc: %x", proc )); + ("ServerOne(): PR_CreateProcess(): proc: %x", proc )); /* ** ClientOne() will set the memory to 1 */ PR_LOG(lm, msgLevel, - ("ServerOne(): waiting on Client, *addr: %x", *addr )); + ("ServerOne(): waiting on Client, *addr: %x", *addr )); while( *addr == 0x00 ) { - if ( debug ) + if ( debug ) { fprintf(stderr, "."); + } PR_Sleep(PR_MillisecondsToInterval(300)); } - if ( debug ) + if ( debug ) { fprintf(stderr, "\n"); + } PR_LOG(lm, msgLevel, - ("ServerOne(): Client responded" )); + ("ServerOne(): Client responded" )); rc = PR_WaitProcess( proc, &exit_status ); PR_ASSERT( PR_FAILURE != rc ); rc = PR_MemUnmap( addr, fmSize); if ( PR_FAILURE == rc ) { - failed_already = 1; + failed_already = 1; PR_LOG(lm, msgLevel, - ("PR_MemUnmap() failed")); + ("PR_MemUnmap() failed")); return; } PR_LOG(lm, msgLevel, - ("ServerOne(): PR_MemUnmap(): success" )); + ("ServerOne(): PR_MemUnmap(): success" )); rc = PR_CloseFileMap(fm); if ( PR_FAILURE == rc ) { - failed_already = 1; + failed_already = 1; PR_LOG(lm, msgLevel, - ("PR_CloseFileMap() failed")); + ("PR_CloseFileMap() failed")); return; } PR_LOG(lm, msgLevel, - ("ServerOne(): PR_CloseFileMap() success" )); + ("ServerOne(): PR_CloseFileMap() success" )); return; } /* end ServerOne() */ @@ -251,7 +254,7 @@ static void ServerOne( void ) static void ServerTwo( void ) { PR_LOG(lm, msgLevel, - ("ServerTwo(): Not implemented yet" )); + ("ServerTwo(): Not implemented yet" )); } /* end ServerTwo() */ @@ -264,30 +267,32 @@ int main(int argc, char **argv) PLOptStatus os; PLOptState *opt = PL_CreateOptState(argc, argv, "hdC:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'C': /* Client style */ - client = atol(opt->value); - break; - case 's': /* file size */ - fmSize = atol( opt->value ) * 1024; - break; - case 'd': /* debug */ - debug = 1; - msgLevel = PR_LOG_DEBUG; - break; - case 'h': /* help message */ - Help(); - break; - default: - strcpy(dirName, opt->value); - break; + case 'C': /* Client style */ + client = atol(opt->value); + break; + case 's': /* file size */ + fmSize = atol( opt->value ) * 1024; + break; + case 'd': /* debug */ + debug = 1; + msgLevel = PR_LOG_DEBUG; + break; + case 'h': /* help message */ + Help(); + break; + default: + strcpy(dirName, opt->value); + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); } lm = PR_NewLogModule("Test"); /* Initialize logging */ @@ -298,13 +303,16 @@ int main(int argc, char **argv) ClientTwo(); } else { ServerOne(); - if ( failed_already ) goto Finished; + if ( failed_already ) { + goto Finished; + } ServerTwo(); } Finished: - if ( debug ) + if ( debug ) { printf("%s\n", (failed_already)? "FAIL" : "PASS"); + } return( (failed_already == PR_TRUE )? 1 : 0 ); } /* main() */ /* end anonfm.c */ diff --git a/nsprpub/pr/tests/append.c b/nsprpub/pr/tests/append.c index 53439d5f0..9d688a4f8 100644 --- a/nsprpub/pr/tests/append.c +++ b/nsprpub/pr/tests/append.c @@ -42,27 +42,31 @@ int main(int argc, char **argv) PLOptStatus os; PLOptState *opt = PL_CreateOptState(argc, argv, "vd"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug */ - debug = 1; - break; - case 'v': /* verbose */ - verbose = 1; - break; - default: - break; + case 'd': /* debug */ + debug = 1; + break; + case 'v': /* verbose */ + verbose = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); } /* end block "Get command line options" */ -/* ---------------------------------------------------------------------- */ + /* ---------------------------------------------------------------------- */ fd = PR_Open( "/tmp/nsprAppend", (PR_APPEND | PR_CREATE_FILE | PR_TRUNCATE | PR_WRONLY), 0666 ); if ( NULL == fd ) { - if (debug) printf("PR_Open() failed for writing: %d\n", PR_GetError()); + if (debug) { + printf("PR_Open() failed for writing: %d\n", PR_GetError()); + } failedAlready = PR_TRUE; goto Finished; } @@ -70,27 +74,35 @@ int main(int argc, char **argv) for ( i = 0; i < addedBytes ; i++ ) { rv = PR_Write( fd, &buf, sizeof(buf)); if ( sizeof(buf) != rv ) { - if (debug) printf("PR_Write() failed: %d\n", PR_GetError()); + if (debug) { + printf("PR_Write() failed: %d\n", PR_GetError()); + } failedAlready = PR_TRUE; goto Finished; } - rv = PR_Seek( fd, 0 , PR_SEEK_SET ); + rv = PR_Seek( fd, 0, PR_SEEK_SET ); if ( -1 == rv ) { - if (debug) printf("PR_Seek() failed: %d\n", PR_GetError()); + if (debug) { + printf("PR_Seek() failed: %d\n", PR_GetError()); + } failedAlready = PR_TRUE; goto Finished; } } rc = PR_Close( fd ); if ( PR_FAILURE == rc ) { - if (debug) printf("PR_Close() failed after writing: %d\n", PR_GetError()); + if (debug) { + printf("PR_Close() failed after writing: %d\n", PR_GetError()); + } failedAlready = PR_TRUE; goto Finished; } -/* ---------------------------------------------------------------------- */ + /* ---------------------------------------------------------------------- */ fd = PR_Open( "/tmp/nsprAppend", PR_RDONLY, 0 ); if ( NULL == fd ) { - if (debug) printf("PR_Open() failed for reading: %d\n", PR_GetError()); + if (debug) { + printf("PR_Open() failed for reading: %d\n", PR_GetError()); + } failedAlready = PR_TRUE; goto Finished; } @@ -98,7 +110,9 @@ int main(int argc, char **argv) for ( i = 0; i < addedBytes ; i++ ) { rv = PR_Read( fd, &inBuf, sizeof(inBuf)); if ( sizeof(inBuf) != rv) { - if (debug) printf("PR_Write() failed: %d\n", PR_GetError()); + if (debug) { + printf("PR_Write() failed: %d\n", PR_GetError()); + } failedAlready = PR_TRUE; goto Finished; } @@ -107,19 +121,25 @@ int main(int argc, char **argv) rc = PR_Close( fd ); if ( PR_FAILURE == rc ) { - if (debug) printf("PR_Close() failed after reading: %d\n", PR_GetError()); + if (debug) { + printf("PR_Close() failed after reading: %d\n", PR_GetError()); + } failedAlready = PR_TRUE; goto Finished; } if ( sum != addedBytes ) { - if (debug) printf("Uh Oh! addedBytes: %d. Sum: %d\n", addedBytes, sum); + if (debug) { + printf("Uh Oh! addedBytes: %d. Sum: %d\n", addedBytes, sum); + } failedAlready = PR_TRUE; goto Finished; } -/* ---------------------------------------------------------------------- */ + /* ---------------------------------------------------------------------- */ Finished: - if (debug || verbose) printf("%s\n", (failedAlready)? "FAILED" : "PASSED" ); + if (debug || verbose) { + printf("%s\n", (failedAlready)? "FAILED" : "PASSED" ); + } return( (failedAlready)? 1 : 0 ); } /* main() */ diff --git a/nsprpub/pr/tests/atomic.c b/nsprpub/pr/tests/atomic.c index eb9df9495..42d25da8d 100644 --- a/nsprpub/pr/tests/atomic.c +++ b/nsprpub/pr/tests/atomic.c @@ -2,7 +2,7 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - + #include "prio.h" #include "prprf.h" #include "pratom.h" diff --git a/nsprpub/pr/tests/attach.c b/nsprpub/pr/tests/attach.c index a1493b8ec..2c1ac9979 100644 --- a/nsprpub/pr/tests/attach.c +++ b/nsprpub/pr/tests/attach.c @@ -14,12 +14,12 @@ ** ** Modification History: ** 13-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ** 12-June-97 Revert to return code 0 and 1. ***********************************************************************/ @@ -40,11 +40,6 @@ #elif defined(_PR_PTHREADS) #include <pthread.h> #include "md/_pth.h" -#elif defined(IRIX) -#include <sys/types.h> -#include <sys/prctl.h> -#include <sys/wait.h> -#include <errno.h> #elif defined(SOLARIS) #include <thread.h> #elif defined(OS2) @@ -52,8 +47,6 @@ #define INCL_ERRORS #include <os2.h> #include <process.h> -#elif defined(XP_BEOS) -#include <kernel/OS.h> #endif #define DEFAULT_COUNT 1000 @@ -64,22 +57,22 @@ PRIntn debug_mode; int count; -static void +static void AttachDetach(void) { PRThread *me; PRInt32 index; - for (index=0;index<count; index++) { - me = PR_AttachThread(PR_USER_THREAD, + for (index=0; index<count; index++) { + me = PR_AttachThread(PR_USER_THREAD, PR_PRIORITY_NORMAL, NULL); - + if (!me) { fprintf(stderr, "Error attaching thread %d: PR_AttachThread failed\n", - count); - failed_already = 1; - return; + count); + failed_already = 1; + return; } PR_DetachThread(); } @@ -97,25 +90,20 @@ static void Measure(void (*func)(void), const char *msg) stop = PR_IntervalNow(); d = (double)PR_IntervalToMicroseconds(stop - start); - if (debug_mode) - printf("%40s: %6.2f usec\n", msg, d / count); + if (debug_mode) { + printf("%40s: %6.2f usec\n", msg, d / count); + } } #ifdef WIN32 static unsigned __stdcall threadStartFunc(void *arg) -#elif defined(IRIX) && !defined(_PR_PTHREADS) -static void threadStartFunc(void *arg) -#elif defined(XP_BEOS) -static int32 threadStartFunc(void *arg) #else static void * threadStartFunc(void *arg) #endif { Measure(AttachDetach, "Attach/Detach"); -#ifndef IRIX return 0; -#endif } int main(int argc, char **argv) @@ -131,49 +119,46 @@ int main(int argc, char **argv) DWORD rv; unsigned threadID; HANDLE hThread; -#elif defined(IRIX) - int rv; - int threadID; #elif defined(OS2) int rv; TID threadID; -#elif defined(XP_BEOS) - thread_id threadID; - int32 threadRV; - status_t waitRV; #endif - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name [-d] [-c n] - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "dc:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name [-d] [-c n] + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "dc:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - case 'c': /* loop count */ - count = atoi(opt->value); - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + case 'c': /* loop count */ + count = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); #if defined(WIN16) printf("attach: This test is not valid for Win16\n"); goto exit_now; #endif - if(0 == count) count = DEFAULT_COUNT; + if(0 == count) { + count = DEFAULT_COUNT; + } /* * To force the implicit initialization of nspr20 @@ -190,106 +175,96 @@ int main(int argc, char **argv) #ifdef _PR_PTHREADS rv = _PT_PTHREAD_ATTR_INIT(&attr); - if (debug_mode) PR_ASSERT(0 == rv); - else if (0 != rv) { - failed_already=1; - goto exit_now; - } - + if (debug_mode) { + PR_ASSERT(0 == rv); + } + else if (0 != rv) { + failed_already=1; + goto exit_now; + } + rv = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); - if (debug_mode) PR_ASSERT(0 == rv); - else if (0 != rv) { - failed_already=1; - goto exit_now; - } + if (debug_mode) { + PR_ASSERT(0 == rv); + } + else if (0 != rv) { + failed_already=1; + goto exit_now; + } rv = _PT_PTHREAD_CREATE(&threadID, attr, threadStartFunc, NULL); if (rv != 0) { - fprintf(stderr, "thread creation failed: error code %d\n", rv); - failed_already=1; - goto exit_now; - } - else { - if (debug_mode) - printf ("thread creation succeeded \n"); - - } + fprintf(stderr, "thread creation failed: error code %d\n", rv); + failed_already=1; + goto exit_now; + } + else { + if (debug_mode) { + printf ("thread creation succeeded \n"); + } + + } rv = _PT_PTHREAD_ATTR_DESTROY(&attr); - if (debug_mode) PR_ASSERT(0 == rv); - else if (0 != rv) { - failed_already=1; - goto exit_now; - } + if (debug_mode) { + PR_ASSERT(0 == rv); + } + else if (0 != rv) { + failed_already=1; + goto exit_now; + } rv = pthread_join(threadID, NULL); - if (debug_mode) PR_ASSERT(0 == rv); - else if (0 != rv) { - failed_already=1; - goto exit_now; - } + if (debug_mode) { + PR_ASSERT(0 == rv); + } + else if (0 != rv) { + failed_already=1; + goto exit_now; + } #elif defined(SOLARIS) rv = thr_create(NULL, 0, threadStartFunc, NULL, 0, &threadID); if (rv != 0) { - if(!debug_mode) { - failed_already=1; - goto exit_now; - } else - fprintf(stderr, "thread creation failed: error code %d\n", rv); + if(!debug_mode) { + failed_already=1; + goto exit_now; + } else { + fprintf(stderr, "thread creation failed: error code %d\n", rv); + } } rv = thr_join(threadID, NULL, NULL); - if (debug_mode) PR_ASSERT(0 == rv); - else if (0 != rv) - { - failed_already=1; - goto exit_now; - } + if (debug_mode) { + PR_ASSERT(0 == rv); + } + else if (0 != rv) + { + failed_already=1; + goto exit_now; + } #elif defined(WIN32) hThread = (HANDLE) _beginthreadex(NULL, 0, threadStartFunc, NULL, - STACK_SIZE_PARAM_IS_A_RESERVATION, &threadID); + STACK_SIZE_PARAM_IS_A_RESERVATION, &threadID); if (hThread == 0) { fprintf(stderr, "thread creation failed: error code %d\n", GetLastError()); - failed_already=1; - goto exit_now; + failed_already=1; + goto exit_now; } rv = WaitForSingleObject(hThread, INFINITE); - if (debug_mode)PR_ASSERT(rv != WAIT_FAILED); - else if (rv == WAIT_FAILED) { - failed_already=1; - goto exit_now; - } - -#elif defined(IRIX) - - threadID = sproc(threadStartFunc, PR_SALL, NULL); - if (threadID == -1) { - - fprintf(stderr, "thread creation failed: error code %d\n", - errno); - failed_already=1; - goto exit_now; - - } - else { - if (debug_mode) - printf ("thread creation succeeded \n"); - sleep(3); - goto exit_now; - } - rv = waitpid(threadID, NULL, 0); - if (debug_mode) PR_ASSERT(rv != -1); - else if (rv != -1) { - failed_already=1; - goto exit_now; - } + if (debug_mode) { + PR_ASSERT(rv != WAIT_FAILED); + } + else if (rv == WAIT_FAILED) { + failed_already=1; + goto exit_now; + } #elif defined(OS2) threadID = (TID) _beginthread((void *)threadStartFunc, NULL, - 32768, NULL); + 32768, NULL); if (threadID == -1) { fprintf(stderr, "thread creation failed: error code %d\n", errno); failed_already=1; @@ -303,41 +278,22 @@ int main(int argc, char **argv) goto exit_now; } -#elif defined(XP_BEOS) - - threadID = spawn_thread(threadStartFunc, NULL, B_NORMAL_PRIORITY, NULL); - if (threadID <= B_ERROR) { - fprintf(stderr, "thread creation failed: error code %08lx\n", threadID); - failed_already = 1; - goto exit_now; - } - if (resume_thread(threadID) != B_OK) { - fprintf(stderr, "failed starting thread: error code %08lx\n", threadID); - failed_already = 1; - goto exit_now; - } - - waitRV = wait_for_thread(threadID, &threadRV); - if (debug_mode) - PR_ASSERT(waitRV == B_OK); - else if (waitRV != B_OK) { - failed_already = 1; - goto exit_now; - } - #else - if (!debug_mode) - failed_already=1; - else - printf("The attach test does not apply to this platform because\n" - "either this platform does not have native threads or the\n" - "test needs to be written for this platform.\n"); - goto exit_now; + if (!debug_mode) { + failed_already=1; + } + else + printf("The attach test does not apply to this platform because\n" + "either this platform does not have native threads or the\n" + "test needs to be written for this platform.\n"); + goto exit_now; #endif exit_now: - if(failed_already) - return 1; - else - return 0; + if(failed_already) { + return 1; + } + else { + return 0; + } } diff --git a/nsprpub/pr/tests/bigfile.c b/nsprpub/pr/tests/bigfile.c index 199f57b5f..e17a767e6 100644 --- a/nsprpub/pr/tests/bigfile.c +++ b/nsprpub/pr/tests/bigfile.c @@ -48,11 +48,16 @@ static PRStatus DeleteIfFound(const char *filename) { VERBOSE(v_shout, "Deleting existing file"); rv = PR_Delete(filename); - if (PR_FAILURE == rv) VERBOSE(v_shout, "Cannot delete big file"); + if (PR_FAILURE == rv) { + VERBOSE(v_shout, "Cannot delete big file"); + } } - else if (PR_FILE_NOT_FOUND_ERROR != PR_GetError()) + else if (PR_FILE_NOT_FOUND_ERROR != PR_GetError()) { VERBOSE(v_shout, "Cannot access big file"); - else rv = PR_SUCCESS; + } + else { + rv = PR_SUCCESS; + } return rv; } /* DeleteIfFound */ @@ -61,19 +66,26 @@ static PRIntn Error(const char *msg, const char *filename) PRInt32 error = PR_GetError(); if (NULL != msg) { - if (0 == error) PR_fprintf(output, msg); - else PL_FPrintError(output, msg); + if (0 == error) { + PR_fprintf(output, msg); + } + else { + PL_FPrintError(output, msg); + } } (void)DeleteIfFound(filename); - if (v_shout == verbose) PR_Abort(); + if (v_shout == verbose) { + PR_Abort(); + } return 1; } /* Error */ static void Verbose( Verbosity level, const char *msg, const char *file, PRIntn line) { - if (level <= verbose) + if (level <= verbose) { PR_fprintf(output, "[%s : %d]: %s\n", file, line, msg); + } } /* Verbose */ static void PrintInfo(PRFileInfo64 *info, const char *filename) @@ -119,48 +131,58 @@ int main(int argc, char **argv) while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 0: - filename = opt->value; - break; - case 'd': /* debug mode */ - verbose = v_shout; - break; - case 'k': /* keep file */ - keep = PR_TRUE; - break; - case 'v': /* verbosity */ - if (v_shout > verbose) verbose += 1; - break; - case 'c': /* loop counter */ - count = atoi(opt->value); - break; - case 's': /* filesize */ - filesize = atoi(opt->value); - break; - case 'h': /* confused */ - default: - return Usage(); + case 0: + filename = opt->value; + break; + case 'd': /* debug mode */ + verbose = v_shout; + break; + case 'k': /* keep file */ + keep = PR_TRUE; + break; + case 'v': /* verbosity */ + if (v_shout > verbose) { + verbose += 1; + } + break; + case 'c': /* loop counter */ + count = atoi(opt->value); + break; + case 's': /* filesize */ + filesize = atoi(opt->value); + break; + case 'h': /* confused */ + default: + return Usage(); } } PL_DestroyOptState(opt); - if (0 == count) count = DEFAULT_COUNT; - if (0 == filesize) filesize = DEFAULT_FILESIZE; + if (0 == count) { + count = DEFAULT_COUNT; + } + if (0 == filesize) { + filesize = DEFAULT_FILESIZE; + } if (NULL == filename) { -#ifdef SYMBIAN -#define FILE_NAME "c:\\data\\bigfile.dat" -#else #define FILE_NAME "bigfile.dat" -#endif - if (DEFAULT_FILESIZE != filesize) return Usage(); - else filename = FILE_NAME; + if (DEFAULT_FILESIZE != filesize) { + return Usage(); + } + else { + filename = FILE_NAME; + } } - if (PR_FAILURE == DeleteIfFound(filename)) return 1; + if (PR_FAILURE == DeleteIfFound(filename)) { + return 1; + } test_result = 0; @@ -169,35 +191,51 @@ int main(int argc, char **argv) LL_I2L(filesize64, filesize); buffer = (char*)PR_MALLOC(BUFFER_SIZE); LL_I2L(big_fragment, BUFFER_SIZE); - LL_MUL(filesize64, filesize64, one_meg); + LL_MUL(filesize64, filesize64, one_meg); - for (loop = 0; loop < BUFFER_SIZE; ++loop) buffer[loop] = (char)loop; + for (loop = 0; loop < BUFFER_SIZE; ++loop) { + buffer[loop] = (char)loop; + } VERBOSE(v_whisper, "Creating big file"); file = PR_Open(filename, PR_CREATE_FILE | PR_WRONLY, 0666); - if (NULL == file) return Error("PR_Open()", filename); - + if (NULL == file) { + return Error("PR_Open()", filename); + } + VERBOSE(v_whisper, "Testing available space in empty file"); big_answer = file->methods->available64(file); - if (!LL_IS_ZERO(big_answer)) return Error("empty available64()", filename); + if (!LL_IS_ZERO(big_answer)) { + return Error("empty available64()", filename); + } - LL_SUB(big_size, filesize64, one_meg); + LL_SUB(big_size, filesize64, one_meg); VERBOSE(v_whisper, "Creating sparse big file by seeking to end"); - big_answer = file->methods->seek64(file, big_size, PR_SEEK_SET); - if (!LL_EQ(big_answer, big_size)) return Error("seek", filename); + big_answer = file->methods->seek64(file, big_size, PR_SEEK_SET); + if (!LL_EQ(big_answer, big_size)) { + return Error("seek", filename); + } VERBOSE(v_whisper, "Writing block at end of sparse file"); - bytes = file->methods->write(file, buffer, BUFFER_SIZE); - if (bytes != BUFFER_SIZE) return Error("write", filename); + bytes = file->methods->write(file, buffer, BUFFER_SIZE); + if (bytes != BUFFER_SIZE) { + return Error("write", filename); + } VERBOSE(v_whisper, "Testing available space at end of sparse file"); big_answer = file->methods->available64(file); - if (!LL_IS_ZERO(big_answer)) return Error("eof available64()", filename); + if (!LL_IS_ZERO(big_answer)) { + return Error("eof available64()", filename); + } VERBOSE(v_whisper, "Getting big info on sparse big file"); rv = file->methods->fileInfo64(file, &big_info); - if (PR_FAILURE == rv) return Error("fileInfo64()", filename); - if (v_shout <= verbose) PrintInfo(&big_info, filename); + if (PR_FAILURE == rv) { + return Error("fileInfo64()", filename); + } + if (v_shout <= verbose) { + PrintInfo(&big_info, filename); + } VERBOSE(v_whisper, "Getting small info on sparse big file"); rv = file->methods->fileInfo(file, &small_info); @@ -214,75 +252,104 @@ int main(int argc, char **argv) VERBOSE(v_whisper, "Rewinding big file"); big_answer = file->methods->seek64(file, zero_meg, PR_SEEK_SET); - if (!LL_IS_ZERO(big_answer)) return Error("rewind seek64()", filename); + if (!LL_IS_ZERO(big_answer)) { + return Error("rewind seek64()", filename); + } VERBOSE(v_whisper, "Establishing available space in rewound file"); big_answer = file->methods->available64(file); - if (LL_NE(filesize64, big_answer)) + if (LL_NE(filesize64, big_answer)) { return Error("bof available64()", filename); + } VERBOSE(v_whisper, "Closing big file"); rv = file->methods->close(file); - if (PR_FAILURE == rv) return Error("close()", filename); + if (PR_FAILURE == rv) { + return Error("close()", filename); + } VERBOSE(v_whisper, "Reopening big file"); file = PR_Open(filename, PR_RDWR, 0666); - if (NULL == file) return Error("open failed", filename); + if (NULL == file) { + return Error("open failed", filename); + } VERBOSE(v_whisper, "Checking available data in reopened file"); big_answer = file->methods->available64(file); - if (LL_NE(filesize64, big_answer)) + if (LL_NE(filesize64, big_answer)) { return Error("reopened available64()", filename); + } big_answer = zero_meg; VERBOSE(v_whisper, "Rewriting every byte of big file data"); do { bytes = file->methods->write(file, buffer, BUFFER_SIZE); - if (bytes != BUFFER_SIZE) + if (bytes != BUFFER_SIZE) { return Error("write", filename); + } LL_ADD(big_answer, big_answer, big_fragment); } while (LL_CMP(big_answer, <, filesize64)); VERBOSE(v_whisper, "Checking position at eof"); big_answer = file->methods->seek64(file, zero_meg, PR_SEEK_CUR); - if (LL_NE(big_answer, filesize64)) + if (LL_NE(big_answer, filesize64)) { return Error("file size error", filename); + } VERBOSE(v_whisper, "Testing available space at eof"); big_answer = file->methods->available64(file); - if (!LL_IS_ZERO(big_answer)) + if (!LL_IS_ZERO(big_answer)) { return Error("eof available64()", filename); + } VERBOSE(v_whisper, "Rewinding full file"); big_answer = file->methods->seek64(file, zero_meg, PR_SEEK_SET); - if (!LL_IS_ZERO(big_answer)) return Error("bof seek64()", filename); + if (!LL_IS_ZERO(big_answer)) { + return Error("bof seek64()", filename); + } VERBOSE(v_whisper, "Testing available space in rewound file"); big_answer = file->methods->available64(file); - if (LL_NE(big_answer, filesize64)) return Error("bof available64()", filename); + if (LL_NE(big_answer, filesize64)) { + return Error("bof available64()", filename); + } VERBOSE(v_whisper, "Seeking to end of big file"); big_answer = file->methods->seek64(file, filesize64, PR_SEEK_SET); - if (LL_NE(big_answer, filesize64)) return Error("eof seek64()", filename); + if (LL_NE(big_answer, filesize64)) { + return Error("eof seek64()", filename); + } VERBOSE(v_whisper, "Getting info on big file while it's open"); rv = file->methods->fileInfo64(file, &big_info); - if (PR_FAILURE == rv) return Error("fileInfo64()", filename); - if (v_shout <= verbose) PrintInfo(&big_info, filename); + if (PR_FAILURE == rv) { + return Error("fileInfo64()", filename); + } + if (v_shout <= verbose) { + PrintInfo(&big_info, filename); + } VERBOSE(v_whisper, "Closing big file"); rv = file->methods->close(file); - if (PR_FAILURE == rv) return Error("close()", filename); + if (PR_FAILURE == rv) { + return Error("close()", filename); + } VERBOSE(v_whisper, "Getting info on big file after it's closed"); rv = PR_GetFileInfo64(filename, &big_info); - if (PR_FAILURE == rv) return Error("fileInfo64()", filename); - if (v_shout <= verbose) PrintInfo(&big_info, filename); + if (PR_FAILURE == rv) { + return Error("fileInfo64()", filename); + } + if (v_shout <= verbose) { + PrintInfo(&big_info, filename); + } VERBOSE(v_whisper, "Deleting big file"); rv = PR_Delete(filename); - if (PR_FAILURE == rv) return Error("PR_Delete()", filename); + if (PR_FAILURE == rv) { + return Error("PR_Delete()", filename); + } PR_DELETE(buffer); return test_result; diff --git a/nsprpub/pr/tests/bigfile2.c b/nsprpub/pr/tests/bigfile2.c index a41841c5d..1a7d45b0f 100644 --- a/nsprpub/pr/tests/bigfile2.c +++ b/nsprpub/pr/tests/bigfile2.c @@ -37,7 +37,7 @@ int main(int argc, char **argv) LL_SHL(offset, offset, 32); fd = PR_Open(TEST_FILE_NAME, - PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 0666); + PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 0666); if (fd == NULL) { fprintf(stderr, "PR_Open failed\n"); exit(1); @@ -63,7 +63,7 @@ int main(int argc, char **argv) #ifdef _WIN32 hFile = CreateFile(TEST_FILE_NAME_FOR_CREATEFILE, GENERIC_READ, 0, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { fprintf(stderr, "CreateFile failed\n"); exit(1); diff --git a/nsprpub/pr/tests/bigfile3.c b/nsprpub/pr/tests/bigfile3.c index 6afbfc93f..aeb4d65e4 100644 --- a/nsprpub/pr/tests/bigfile3.c +++ b/nsprpub/pr/tests/bigfile3.c @@ -38,7 +38,7 @@ int main(int argc, char **argv) #ifdef _WIN32 hFile = CreateFile(TEST_FILE_NAME_FOR_CREATEFILE, GENERIC_WRITE, 0, NULL, - CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { fprintf(stderr, "CreateFile failed\n"); exit(1); diff --git a/nsprpub/pr/tests/bug1test.c b/nsprpub/pr/tests/bug1test.c index a8df97f70..62ca90d4a 100644 --- a/nsprpub/pr/tests/bug1test.c +++ b/nsprpub/pr/tests/bug1test.c @@ -17,7 +17,7 @@ before leaving the critical section in _PR_CondWait in hwmon.c). typedef struct Arg_s { - PRInt32 a, b; + PRInt32 a, b; } Arg_t; PRMonitor* gMonitor; // the monitor @@ -27,7 +27,7 @@ PRInt32 gReadWaiting; // number of threads waiting for read lock PRInt32 gCounter; // a counter - // stats +// stats PRInt32 gReads; // number of successful reads PRInt32 gMaxReads; // max number of simultaneous reads PRInt32 gMaxWriteWaits; // max number of writes that waited for read @@ -36,189 +36,194 @@ PRInt32 gMaxReadWaits; // max number of reads that waited for write wait void spin (PRInt32 aDelay) { - PRInt32 index; - PRInt32 delay = aDelay * 1000; + PRInt32 index; + PRInt32 delay = aDelay * 1000; - PR_Sleep(0); + PR_Sleep(0); - // randomize delay a bit - delay = (delay / 2) + (PRInt32)((float)delay * - ((float)rand () / (float)RAND_MAX)); + // randomize delay a bit + delay = (delay / 2) + (PRInt32)((float)delay * + ((float)rand () / (float)RAND_MAX)); - for (index = 0; index < delay * 10; index++) - // consume a bunch of cpu cycles - ; - PR_Sleep(0); + for (index = 0; index < delay * 10; index++) + // consume a bunch of cpu cycles + ; + PR_Sleep(0); } void doWriteThread (void* arg) { - PRInt32 last; - Arg_t *args = (Arg_t*)arg; - PRInt32 aWorkDelay = args->a, aWaitDelay = args->b; - PR_Sleep(0); + PRInt32 last; + Arg_t *args = (Arg_t*)arg; + PRInt32 aWorkDelay = args->a, aWaitDelay = args->b; + PR_Sleep(0); - while (1) - { - // -- enter write lock - PR_EnterMonitor (gMonitor); - - if (0 < gReading) // wait for read locks to go away + while (1) { - PRIntervalTime fiveSecs = PR_SecondsToInterval(5); - - gWriteWaiting++; - if (gWriteWaiting > gMaxWriteWaits) // stats - gMaxWriteWaits = gWriteWaiting; - while (0 < gReading) - PR_Wait (gMonitor, fiveSecs); - gWriteWaiting--; - } - // -- write lock entered + // -- enter write lock + PR_EnterMonitor (gMonitor); + + if (0 < gReading) // wait for read locks to go away + { + PRIntervalTime fiveSecs = PR_SecondsToInterval(5); - last = gCounter; - gCounter++; + gWriteWaiting++; + if (gWriteWaiting > gMaxWriteWaits) { // stats + gMaxWriteWaits = gWriteWaiting; + } + while (0 < gReading) { + PR_Wait (gMonitor, fiveSecs); + } + gWriteWaiting--; + } + // -- write lock entered - spin (aWorkDelay); + last = gCounter; + gCounter++; - PR_ASSERT (gCounter == (last + 1)); // test invariance + spin (aWorkDelay); - // -- exit write lock + PR_ASSERT (gCounter == (last + 1)); // test invariance + + // -- exit write lock // if (0 < gReadWaiting) // notify waiting reads (do it anyway to show off the CondWait bug) - PR_NotifyAll (gMonitor); + PR_NotifyAll (gMonitor); - PR_ExitMonitor (gMonitor); - // -- write lock exited + PR_ExitMonitor (gMonitor); + // -- write lock exited - spin (aWaitDelay); - } + spin (aWaitDelay); + } } 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); + PRInt32 last; + Arg_t *args = (Arg_t*)arg; + PRInt32 aWorkDelay = args->a, aWaitDelay = args->b; + PR_Sleep(0); - if (0 < gWriteWaiting) // give up the monitor to waiting writes + while (1) { - PRIntervalTime fiveSecs = PR_SecondsToInterval(5); - - gReadWaiting++; - if (gReadWaiting > gMaxReadWaits) // stats - gMaxReadWaits = gReadWaiting; - while (0 < gWriteWaiting) - PR_Wait (gMonitor, fiveSecs); - gReadWaiting--; - } + // -- 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++; + gReading++; - gReads++; // stats - if (gReading > gMaxReads) // stats - gMaxReads = gReading; + gReads++; // stats + if (gReading > gMaxReads) { // stats + gMaxReads = gReading; + } - PR_ExitMonitor (gMonitor); - // -- read lock entered + PR_ExitMonitor (gMonitor); + // -- read lock entered - last = gCounter; + last = gCounter; - spin (aWorkDelay); + spin (aWorkDelay); - PR_ASSERT (gCounter == last); // test invariance + PR_ASSERT (gCounter == last); // test invariance - // -- exit read lock - PR_EnterMonitor (gMonitor); // read unlock - gReading--; + // -- 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 + PR_NotifyAll (gMonitor); + PR_ExitMonitor (gMonitor); + // -- read lock exited - spin (aWaitDelay); - } + spin (aWaitDelay); + } } void fireThread ( char* aName, void (*aProc)(void *arg), Arg_t *aArg) { - PRThread *thread = PR_CreateThread( - PR_USER_THREAD, aProc, aArg, PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, PR_UNJOINABLE_THREAD, 0); + PRThread *thread = PR_CreateThread( + PR_USER_THREAD, aProc, aArg, PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, PR_UNJOINABLE_THREAD, 0); } 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; + 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; } static void padStack (int argc, char** argv) { - char pad[512]; /* Work around bug in nspr on windoze */ - pseudoMain (argc, argv, pad); + char pad[512]; /* Work around bug in nspr on windoze */ + pseudoMain (argc, argv, pad); } int main(int argc, char **argv) { - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); - PR_STDIO_INIT(); - padStack (argc, argv); + PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); + PR_STDIO_INIT(); + padStack (argc, argv); } diff --git a/nsprpub/pr/tests/cleanup.c b/nsprpub/pr/tests/cleanup.c index 4079aae18..679fe59c9 100644 --- a/nsprpub/pr/tests/cleanup.c +++ b/nsprpub/pr/tests/cleanup.c @@ -36,7 +36,7 @@ int main(int argc, char **argv) { PLOptStatus os; PRBool cleanup = PR_FALSE; - PRThreadScope type = PR_LOCAL_THREAD; + PRThreadScope type = PR_LOCAL_THREAD; PRFileDesc *err = PR_GetSpecialFD(PR_StandardError); PLOptState *opt = PL_CreateOptState(argc, argv, "Ghs:S:t:cC:"); PRIntn concurrency = 1, child_sleep = 10, main_sleep = 5, threads = 1; @@ -44,55 +44,59 @@ int main(int argc, char **argv) PR_STDIO_INIT(); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'c': /* call PR_Cleanup() before exiting */ - cleanup = PR_TRUE; - break; - case 'G': /* local vs global threads */ - type = PR_GLOBAL_THREAD; - break; - case 's': /* time to sleep */ - child_sleep = atoi(opt->value); - break; - case 'S': /* time to sleep */ - main_sleep = atoi(opt->value); - break; - case 'C': /* number of cpus to create */ - concurrency = atoi(opt->value); - break; - case 't': /* number of threads to create */ - threads = atoi(opt->value); - break; - case 'h': /* user wants some guidance */ - Help(); /* so give him an earful */ - return 2; /* but not a lot else */ - break; - default: - break; + case 'c': /* call PR_Cleanup() before exiting */ + cleanup = PR_TRUE; + break; + case 'G': /* local vs global threads */ + type = PR_GLOBAL_THREAD; + break; + case 's': /* time to sleep */ + child_sleep = atoi(opt->value); + break; + case 'S': /* time to sleep */ + main_sleep = atoi(opt->value); + break; + case 'C': /* number of cpus to create */ + concurrency = atoi(opt->value); + break; + case 't': /* number of threads to create */ + threads = atoi(opt->value); + break; + case 'h': /* user wants some guidance */ + Help(); /* so give him an earful */ + return 2; /* but not a lot else */ + break; + default: + break; } } PL_DestroyOptState(opt); PR_fprintf(err, "Cleanup settings\n"); PR_fprintf(err, "\tThread type: %s\n", - (PR_LOCAL_THREAD == type) ? "LOCAL" : "GLOBAL"); + (PR_LOCAL_THREAD == type) ? "LOCAL" : "GLOBAL"); PR_fprintf(err, "\tConcurrency: %d\n", concurrency); PR_fprintf(err, "\tNumber of threads: %d\n", threads); PR_fprintf(err, "\tThread sleep: %d\n", child_sleep); - PR_fprintf(err, "\tMain sleep: %d\n", main_sleep); - PR_fprintf(err, "\tCleanup will %sbe called\n\n", (cleanup) ? "" : "NOT "); + PR_fprintf(err, "\tMain sleep: %d\n", main_sleep); + PR_fprintf(err, "\tCleanup will %sbe called\n\n", (cleanup) ? "" : "NOT "); PR_SetConcurrency(concurrency); - while (threads-- > 0) - (void)PR_CreateThread( - PR_USER_THREAD, Thread, (void*)child_sleep, PR_PRIORITY_NORMAL, - type, PR_UNJOINABLE_THREAD, 0); + while (threads-- > 0) + (void)PR_CreateThread( + PR_USER_THREAD, Thread, (void*)child_sleep, PR_PRIORITY_NORMAL, + type, PR_UNJOINABLE_THREAD, 0); PR_Sleep(PR_SecondsToInterval(main_sleep)); - if (cleanup) PR_Cleanup(); + if (cleanup) { + PR_Cleanup(); + } PR_fprintf(err, "main() exiting\n"); return 0; diff --git a/nsprpub/pr/tests/cltsrv.c b/nsprpub/pr/tests/cltsrv.c index 1941687eb..caf1ad4d6 100644 --- a/nsprpub/pr/tests/cltsrv.c +++ b/nsprpub/pr/tests/cltsrv.c @@ -23,7 +23,7 @@ * The debug mode will print all of the printfs associated with this test. * The regress mode will be the default mode. Since the regress tool limits * the output to a one line status:PASS or FAIL,all of the printf statements - * have been handled with an if (debug_mode) statement. + * have been handled with an if (debug_mode) statement. */ #include "prclist.h" @@ -182,7 +182,7 @@ static void _MY_Assert(const char *s, const char *file, PRIntn ln) static PRBool Aborted(PRStatus rv) { return ((PR_FAILURE == rv) && (PR_PENDING_INTERRUPT_ERROR == PR_GetError())) ? - PR_TRUE : PR_FALSE; + PR_TRUE : PR_FALSE; } static void TimeOfDayMessage(const char *msg, PRThread* me) @@ -211,8 +211,9 @@ static void PR_CALLBACK Client(void *arg) PRIntervalTime timeout = PR_MillisecondsToInterval(DEFAULT_CLIENT_TIMEOUT); - for (index = 0; index < sizeof(buffer); ++index) + for (index = 0; index < sizeof(buffer); ++index) { buffer[index] = (char)index; + } client->started = PR_IntervalNow(); @@ -228,8 +229,8 @@ static void PR_CALLBACK Client(void *arg) PRInt32 bytes, descbytes, filebytes, netbytes; (void)PR_NetAddrToString(&client->serverAddress, buffer, sizeof(buffer)); - TEST_LOG(cltsrv_log_file, TEST_LOG_INFO, - ("\tClient(0x%p): connecting to server at %s\n", me, buffer)); + TEST_LOG(cltsrv_log_file, TEST_LOG_INFO, + ("\tClient(0x%p): connecting to server at %s\n", me, buffer)); fd = PR_Socket(domain, SOCK_STREAM, protocol); TEST_ASSERT(NULL != fd); @@ -239,7 +240,7 @@ static void PR_CALLBACK Client(void *arg) TEST_LOG( cltsrv_log_file, TEST_LOG_ERROR, ("\tClient(0x%p): conection failed (%d, %d)\n", - me, PR_GetError(), PR_GetOSError())); + me, PR_GetError(), PR_GetOSError())); goto aborted; } @@ -252,10 +253,12 @@ static void PR_CALLBACK Client(void *arg) cltsrv_log_file, TEST_LOG_VERBOSE, ("\tClient(0x%p): sending descriptor for %u bytes\n", me, descbytes)); bytes = PR_Send( - fd, descriptor, sizeof(*descriptor), SEND_FLAGS, timeout); + fd, descriptor, sizeof(*descriptor), SEND_FLAGS, timeout); if (sizeof(CSDescriptor_t) != bytes) { - if (Aborted(PR_FAILURE)) goto aborted; + if (Aborted(PR_FAILURE)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( @@ -270,15 +273,18 @@ static void PR_CALLBACK Client(void *arg) while (netbytes < descbytes) { filebytes = sizeof(buffer); - if ((descbytes - netbytes) < filebytes) + if ((descbytes - netbytes) < filebytes) { filebytes = descbytes - netbytes; + } TEST_LOG( cltsrv_log_file, TEST_LOG_VERBOSE, ("\tClient(0x%p): sending %d bytes\n", me, filebytes)); bytes = PR_Send(fd, buffer, filebytes, SEND_FLAGS, timeout); if (filebytes != bytes) { - if (Aborted(PR_FAILURE)) goto aborted; + if (Aborted(PR_FAILURE)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( @@ -294,8 +300,9 @@ static void PR_CALLBACK Client(void *arg) while (filebytes < descbytes) { netbytes = sizeof(buffer); - if ((descbytes - filebytes) < netbytes) + if ((descbytes - filebytes) < netbytes) { netbytes = descbytes - filebytes; + } TEST_LOG( cltsrv_log_file, TEST_LOG_VERBOSE, ("\tClient(0x%p): receiving %d bytes\n", me, netbytes)); @@ -313,26 +320,28 @@ static void PR_CALLBACK Client(void *arg) TEST_LOG( cltsrv_log_file, TEST_LOG_ERROR, ("\tClient(0x%p): receive data timeout\n", me)); - else + else TEST_LOG( cltsrv_log_file, TEST_LOG_ERROR, ("\tClient(0x%p): receive error (%d, %d)\n", - me, PR_GetError(), PR_GetOSError())); + me, PR_GetError(), PR_GetOSError())); goto retry; - } + } if (0 == bytes) { TEST_LOG( cltsrv_log_file, TEST_LOG_ERROR, ("\t\tClient(0x%p): unexpected end of stream\n", - PR_GetCurrentThread())); + PR_GetCurrentThread())); break; } filebytes += bytes; } rv = PR_Shutdown(fd, PR_SHUTDOWN_BOTH); - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } TEST_ASSERT(PR_SUCCESS == rv); retry: (void)PR_Close(fd); fd = NULL; @@ -345,14 +354,18 @@ retry: client->bytesTransferred += 2 * descbytes; rv = PR_WaitCondVar(client->stateChange, rand() % clipping); PR_Unlock(client->ml); - if (Aborted(rv)) break; + if (Aborted(rv)) { + break; + } } aborted: client->stopped = PR_IntervalNow(); PR_ClearInterrupt(); - if (NULL != fd) rv = PR_Close(fd); + if (NULL != fd) { + rv = PR_Close(fd); + } PR_Lock(client->ml); client->state = cs_exit; @@ -362,7 +375,7 @@ aborted: TEST_LOG( cltsrv_log_file, TEST_LOG_ALWAYS, ("\tClient(0x%p): stopped after %u operations and %u bytes\n", - PR_GetCurrentThread(), client->operations, client->bytesTransferred)); + PR_GetCurrentThread(), client->operations, client->bytesTransferred)); } /* Client */ @@ -380,11 +393,13 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) cltsrv_log_file, TEST_LOG_VERBOSE, ("\tProcessRequest(0x%p): receiving desciptor\n", me)); bytes = PR_Recv( - fd, descriptor, sizeof(*descriptor), RECV_FLAGS, timeout); + fd, descriptor, sizeof(*descriptor), RECV_FLAGS, timeout); if (-1 == bytes) { rv = PR_FAILURE; - if (Aborted(rv)) goto exit; + if (Aborted(rv)) { + goto exit; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( @@ -405,16 +420,18 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) TEST_ASSERT(sizeof(*descriptor) == bytes); TEST_LOG( - cltsrv_log_file, TEST_LOG_VERBOSE, + cltsrv_log_file, TEST_LOG_VERBOSE, ("\t\tProcessRequest(0x%p): read descriptor {%d, %s}\n", - me, descbytes, descriptor->filename)); + me, descbytes, descriptor->filename)); file = PR_Open( - descriptor->filename, (PR_CREATE_FILE | PR_WRONLY), 0666); + descriptor->filename, (PR_CREATE_FILE | PR_WRONLY), 0666); if (NULL == file) { rv = PR_FAILURE; - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( @@ -429,8 +446,9 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) while (filebytes < descbytes) { netbytes = sizeof(buffer); - if ((descbytes - filebytes) < netbytes) + if ((descbytes - filebytes) < netbytes) { netbytes = descbytes - filebytes; + } TEST_LOG( cltsrv_log_file, TEST_LOG_VERBOSE, ("\tProcessRequest(0x%p): receive %d bytes\n", me, netbytes)); @@ -438,7 +456,9 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) if (-1 == bytes) { rv = PR_FAILURE; - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( @@ -454,7 +474,7 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) TEST_LOG( cltsrv_log_file, TEST_LOG_WARNING, ("\t\tProcessRequest(0x%p): unexpected error (%d, %d)\n", - me, PR_GetError(), PR_GetOSError())); + me, PR_GetError(), PR_GetOSError())); goto aborted; } if(0 == bytes) @@ -476,7 +496,9 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) if (netbytes != bytes) { rv = PR_FAILURE; - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( @@ -494,7 +516,9 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) PR_Unlock(server->ml); rv = PR_Close(file); - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } TEST_ASSERT(PR_SUCCESS == rv); file = NULL; @@ -505,19 +529,21 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) if (NULL == file) { rv = PR_FAILURE; - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( cltsrv_log_file, TEST_LOG_ERROR, ("\t\tProcessRequest(0x%p): open file timeout\n", - PR_GetCurrentThread())); + PR_GetCurrentThread())); goto aborted; } TEST_LOG( cltsrv_log_file, TEST_LOG_ERROR, ("\t\tProcessRequest(0x%p): other file open error (%u, %u)\n", - me, PR_GetError(), PR_GetOSError())); + me, PR_GetError(), PR_GetOSError())); goto aborted; } TEST_ASSERT(NULL != file); @@ -526,8 +552,9 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) while (netbytes < descbytes) { filebytes = sizeof(buffer); - if ((descbytes - netbytes) < filebytes) + if ((descbytes - netbytes) < filebytes) { filebytes = descbytes - netbytes; + } TEST_LOG( cltsrv_log_file, TEST_LOG_VERBOSE, ("\tProcessRequest(0x%p): read %d bytes from file\n", me, filebytes)); @@ -535,7 +562,9 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) if (filebytes != bytes) { rv = PR_FAILURE; - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) TEST_LOG( cltsrv_log_file, TEST_LOG_ERROR, @@ -544,7 +573,7 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) TEST_LOG( cltsrv_log_file, TEST_LOG_ERROR, ("\t\tProcessRequest(0x%p): other file error (%d, %d)\n", - me, PR_GetError(), PR_GetOSError())); + me, PR_GetError(), PR_GetOSError())); goto aborted; } TEST_ASSERT(bytes > 0); @@ -557,7 +586,9 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) if (filebytes != bytes) { rv = PR_FAILURE; - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( @@ -567,24 +598,30 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) } break; } - TEST_ASSERT(bytes > 0); + TEST_ASSERT(bytes > 0); } - + PR_Lock(server->ml); server->bytesTransferred += filebytes; PR_Unlock(server->ml); rv = PR_Shutdown(fd, PR_SHUTDOWN_BOTH); - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } rv = PR_Close(file); - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } TEST_ASSERT(PR_SUCCESS == rv); file = NULL; aborted: PR_ClearInterrupt(); - if (NULL != file) PR_Close(file); + if (NULL != file) { + PR_Close(file); + } drv = PR_Delete(descriptor->filename); TEST_ASSERT(PR_SUCCESS == drv); exit: @@ -606,18 +643,18 @@ static PRStatus CreateWorker(CSServer_t *server, CSPool_t *pool) worker->server = server; PR_INIT_CLIST(&worker->element); worker->thread = PR_CreateThread( - PR_USER_THREAD, Worker, worker, - DEFAULT_SERVER_PRIORITY, thread_scope, - PR_UNJOINABLE_THREAD, 0); + PR_USER_THREAD, Worker, worker, + DEFAULT_SERVER_PRIORITY, thread_scope, + PR_UNJOINABLE_THREAD, 0); if (NULL == worker->thread) { PR_DELETE(worker); return PR_FAILURE; } - TEST_LOG(cltsrv_log_file, TEST_LOG_STATUS, - ("\tCreateWorker(0x%p): create new worker (0x%p)\n", - PR_GetCurrentThread(), worker->thread)); + TEST_LOG(cltsrv_log_file, TEST_LOG_STATUS, + ("\tCreateWorker(0x%p): create new worker (0x%p)\n", + PR_GetCurrentThread(), worker->thread)); return PR_SUCCESS; } /* CreateWorker */ @@ -647,17 +684,17 @@ static void PR_CALLBACK Worker(void *arg) TEST_LOG( cltsrv_log_file, TEST_LOG_VERBOSE, ("\t\tWorker(0x%p): waiting for accept slot[%d]\n", - me, pool->accepting)); + me, pool->accepting)); rv = PR_WaitCondVar(pool->acceptComplete, PR_INTERVAL_NO_TIMEOUT); if (Aborted(rv) || (cs_run != server->state)) { TEST_LOG( cltsrv_log_file, TEST_LOG_NOTICE, ("\tWorker(0x%p): has been %s\n", - me, (Aborted(rv) ? "interrupted" : "stopped"))); + me, (Aborted(rv) ? "interrupted" : "stopped"))); goto exit; } - } + } pool->accepting += 1; /* how many are really in accept */ PR_Unlock(server->ml); @@ -666,7 +703,7 @@ static void PR_CALLBACK Worker(void *arg) ("\t\tWorker(0x%p): calling accept\n", me)); fd = PR_Accept(server->listener, &from, PR_INTERVAL_NO_TIMEOUT); - PR_Lock(server->ml); + PR_Lock(server->ml); pool->accepting -= 1; PR_NotifyCondVar(pool->acceptComplete); @@ -692,13 +729,15 @@ static void PR_CALLBACK Worker(void *arg) */ PRBool another = ((pool->workers < server->workers.minimum) || - ((0 == pool->accepting) - && (pool->workers < server->workers.maximum))) ? - PR_TRUE : PR_FALSE; + ((0 == pool->accepting) + && (pool->workers < server->workers.maximum))) ? + PR_TRUE : PR_FALSE; pool->active += 1; PR_Unlock(server->ml); - if (another) (void)CreateWorker(server, pool); + if (another) { + (void)CreateWorker(server, pool); + } rv = ProcessRequest(fd, server); if (PR_SUCCESS != rv) @@ -713,7 +752,7 @@ static void PR_CALLBACK Worker(void *arg) } exit: - PR_ClearInterrupt(); + PR_ClearInterrupt(); PR_Unlock(server->ml); if (NULL != fd) @@ -752,11 +791,12 @@ static void PR_CALLBACK Server(void *arg) TEST_ASSERT(PR_SUCCESS == rv); memset(&serverAddress, 0, sizeof(serverAddress)); - if (PR_AF_INET6 != domain) - rv = PR_InitializeNetAddr(PR_IpAddrAny, DEFAULT_PORT, &serverAddress); - else - rv = PR_SetNetAddr(PR_IpAddrAny, PR_AF_INET6, DEFAULT_PORT, - &serverAddress); + if (PR_AF_INET6 != domain) { + rv = PR_InitializeNetAddr(PR_IpAddrAny, DEFAULT_PORT, &serverAddress); + } + else + rv = PR_SetNetAddr(PR_IpAddrAny, PR_AF_INET6, DEFAULT_PORT, + &serverAddress); rv = PR_Bind(server->listener, &serverAddress); TEST_ASSERT(PR_SUCCESS == rv); @@ -827,7 +867,7 @@ static void PR_CALLBACK Server(void *arg) TEST_LOG( cltsrv_log_file, TEST_LOG_NOTICE, ("\tServer(0x%p): waiting for %u workers to exit\n", - me, server->pool.workers)); + me, server->pool.workers)); (void)PR_WaitCondVar(server->pool.exiting, PR_INTERVAL_NO_TIMEOUT); } @@ -838,9 +878,11 @@ static void PR_CALLBACK Server(void *arg) TEST_LOG( cltsrv_log_file, TEST_LOG_ALWAYS, ("\tServer(0x%p): stopped after %u operations and %u bytes\n", - me, server->operations, server->bytesTransferred)); + me, server->operations, server->bytesTransferred)); - if (NULL != server->listener) PR_Close(server->listener); + if (NULL != server->listener) { + PR_Close(server->listener); + } server->stopped = PR_IntervalNow(); } /* Server */ @@ -848,10 +890,12 @@ static void PR_CALLBACK Server(void *arg) 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"); + if (pthread_stats) { + PT_FPrintStats(debug_out, "\nPThread Statistics\n"); + } execution -= dally; } } /* WaitForCompletion */ @@ -922,70 +966,86 @@ int main(int argc, char** argv) while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'G': /* use global threads */ - thread_scope = PR_GLOBAL_THREAD; - break; - case 'X': /* use XTP as transport */ - protocol = 36; - break; - case '6': /* Use IPv6 */ - domain = PR_AF_INET6; - break; - case 'a': /* the value for accepting */ - accepting = atoi(opt->value); - break; - case 'b': /* the value for backlock */ - backlog = atoi(opt->value); - break; - case 'c': /* number of client threads */ - clients = atoi(opt->value); - break; - case 'f': /* low water fd cache */ - low = atoi(opt->value); - break; - case 'F': /* low water fd cache */ - high = atoi(opt->value); - break; - case 'w': /* minimum server worker threads */ - workersMin = atoi(opt->value); - break; - case 'W': /* maximum server worker threads */ - workersMax = atoi(opt->value); - break; - case 'e': /* program execution time in seconds */ - execution = atoi(opt->value); - break; - case 's': /* server's address */ - serverName = opt->value; - break; - case 'v': /* verbosity */ - verbosity = IncrementVerbosity(); - break; - case 'd': /* debug mode */ - debug_mode = PR_TRUE; - break; - case 'p': /* pthread mode */ - pthread_stats = PR_TRUE; - break; - case 'h': - default: - Help(); - return 2; + case 'G': /* use global threads */ + thread_scope = PR_GLOBAL_THREAD; + break; + case 'X': /* use XTP as transport */ + protocol = 36; + break; + case '6': /* Use IPv6 */ + domain = PR_AF_INET6; + break; + case 'a': /* the value for accepting */ + accepting = atoi(opt->value); + break; + case 'b': /* the value for backlock */ + backlog = atoi(opt->value); + break; + case 'c': /* number of client threads */ + clients = atoi(opt->value); + break; + case 'f': /* low water fd cache */ + low = atoi(opt->value); + break; + case 'F': /* low water fd cache */ + high = atoi(opt->value); + break; + case 'w': /* minimum server worker threads */ + workersMin = atoi(opt->value); + break; + case 'W': /* maximum server worker threads */ + workersMax = atoi(opt->value); + break; + case 'e': /* program execution time in seconds */ + execution = atoi(opt->value); + break; + case 's': /* server's address */ + serverName = opt->value; + break; + case 'v': /* verbosity */ + verbosity = IncrementVerbosity(); + break; + case 'd': /* debug mode */ + debug_mode = PR_TRUE; + break; + case 'p': /* pthread mode */ + pthread_stats = PR_TRUE; + break; + case 'h': + default: + Help(); + return 2; } } PL_DestroyOptState(opt); - if (0 != PL_strcmp(serverName, DEFAULT_SERVER)) serverIsLocal = PR_FALSE; - if (0 == execution) execution = DEFAULT_EXECUTION_TIME; - if (0 == workersMax) workersMax = DEFAULT_WORKERS_MAX; - if (0 == workersMin) workersMin = DEFAULT_WORKERS_MIN; - if (0 == accepting) accepting = ALLOWED_IN_ACCEPT; - if (0 == backlog) backlog = DEFAULT_BACKLOG; + if (0 != PL_strcmp(serverName, DEFAULT_SERVER)) { + serverIsLocal = PR_FALSE; + } + if (0 == execution) { + execution = DEFAULT_EXECUTION_TIME; + } + if (0 == workersMax) { + workersMax = DEFAULT_WORKERS_MAX; + } + if (0 == workersMin) { + workersMin = DEFAULT_WORKERS_MIN; + } + if (0 == accepting) { + accepting = ALLOWED_IN_ACCEPT; + } + if (0 == backlog) { + backlog = DEFAULT_BACKLOG; + } - if (workersMin > accepting) accepting = workersMin; + if (workersMin > accepting) { + accepting = workersMin; + } PR_STDIO_INIT(); TimeOfDayMessage("Client/Server started at", PR_GetCurrentThread()); @@ -1023,8 +1083,8 @@ int main(int argc, char** argv) ("main(0x%p): creating server thread\n", PR_GetCurrentThread())); server->thread = PR_CreateThread( - PR_USER_THREAD, Server, server, PR_PRIORITY_HIGH, - thread_scope, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, Server, server, PR_PRIORITY_HIGH, + thread_scope, PR_JOINABLE_THREAD, 0); TEST_ASSERT(NULL != server->thread); TEST_LOG( @@ -1032,14 +1092,15 @@ int main(int argc, char** argv) ("main(0x%p): waiting for server init\n", PR_GetCurrentThread())); PR_Lock(server->ml); - while (server->state == cs_init) + while (server->state == cs_init) { PR_WaitCondVar(server->stateChange, PR_INTERVAL_NO_TIMEOUT); + } PR_Unlock(server->ml); TEST_LOG( cltsrv_log_file, TEST_LOG_VERBOSE, ("main(0x%p): server init complete (port #%d)\n", - PR_GetCurrentThread(), server->port)); + PR_GetCurrentThread(), server->port)); } if (clients != 0) @@ -1052,8 +1113,8 @@ int main(int argc, char** argv) TEST_LOG( cltsrv_log_file, TEST_LOG_VERBOSE, ("main(0x%p): creating %d client threads\n", - PR_GetCurrentThread(), clients)); - + PR_GetCurrentThread(), clients)); + if (!serverIsLocal) { rv = PR_GetHostByName(serverName, buffer, BUFFER_SIZE, &host); @@ -1070,13 +1131,13 @@ int main(int argc, char** argv) client[index].ml = PR_NewLock(); if (serverIsLocal) { - if (PR_AF_INET6 != domain) - (void)PR_InitializeNetAddr( - PR_IpAddrLoopback, DEFAULT_PORT, - &client[index].serverAddress); - else - rv = PR_SetNetAddr(PR_IpAddrLoopback, PR_AF_INET6, - DEFAULT_PORT, &client[index].serverAddress); + if (PR_AF_INET6 != domain) + (void)PR_InitializeNetAddr( + PR_IpAddrLoopback, DEFAULT_PORT, + &client[index].serverAddress); + else + rv = PR_SetNetAddr(PR_IpAddrLoopback, PR_AF_INET6, + DEFAULT_PORT, &client[index].serverAddress); } else { @@ -1088,12 +1149,13 @@ int main(int argc, char** argv) cltsrv_log_file, TEST_LOG_INFO, ("main(0x%p): creating client threads\n", PR_GetCurrentThread())); client[index].thread = PR_CreateThread( - PR_USER_THREAD, Client, &client[index], PR_PRIORITY_NORMAL, - thread_scope, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, Client, &client[index], PR_PRIORITY_NORMAL, + thread_scope, PR_JOINABLE_THREAD, 0); TEST_ASSERT(NULL != client[index].thread); PR_Lock(client[index].ml); - while (cs_init == client[index].state) + while (cs_init == client[index].state) { PR_WaitCondVar(client[index].stateChange, PR_INTERVAL_NO_TIMEOUT); + } PR_Unlock(client[index].ml); } } @@ -1102,7 +1164,7 @@ int main(int argc, char** argv) TEST_LOG( cltsrv_log_file, TEST_LOG_ALWAYS, ("main(0x%p): waiting for execution interval (%d seconds)\n", - PR_GetCurrentThread(), execution)); + PR_GetCurrentThread(), execution)); WaitForCompletion(execution); @@ -1112,9 +1174,9 @@ int main(int argc, char** argv) { for (index = 0; index < clients; ++index) { - TEST_LOG(cltsrv_log_file, TEST_LOG_STATUS, - ("main(0x%p): notifying client(0x%p) to stop\n", - PR_GetCurrentThread(), client[index].thread)); + TEST_LOG(cltsrv_log_file, TEST_LOG_STATUS, + ("main(0x%p): notifying client(0x%p) to stop\n", + PR_GetCurrentThread(), client[index].thread)); PR_Lock(client[index].ml); if (cs_run == client[index].state) @@ -1127,12 +1189,12 @@ int main(int argc, char** argv) } PR_Unlock(client[index].ml); - TEST_LOG(cltsrv_log_file, TEST_LOG_VERBOSE, - ("main(0x%p): joining client(0x%p)\n", - PR_GetCurrentThread(), client[index].thread)); + TEST_LOG(cltsrv_log_file, TEST_LOG_VERBOSE, + ("main(0x%p): joining client(0x%p)\n", + PR_GetCurrentThread(), client[index].thread)); - joinStatus = PR_JoinThread(client[index].thread); - TEST_ASSERT(PR_SUCCESS == joinStatus); + joinStatus = PR_JoinThread(client[index].thread); + TEST_ASSERT(PR_SUCCESS == joinStatus); PR_DestroyCondVar(client[index].stateChange); PR_DestroyLock(client[index].ml); } @@ -1143,21 +1205,22 @@ int main(int argc, char** argv) { /* All clients joined - retrieve the server */ TEST_LOG( - cltsrv_log_file, TEST_LOG_NOTICE, + cltsrv_log_file, TEST_LOG_NOTICE, ("main(0x%p): notifying server(0x%p) to stop\n", - PR_GetCurrentThread(), server->thread)); + PR_GetCurrentThread(), server->thread)); PR_Lock(server->ml); server->state = cs_stop; PR_Interrupt(server->thread); - while (cs_exit != server->state) + while (cs_exit != server->state) { PR_WaitCondVar(server->stateChange, PR_INTERVAL_NO_TIMEOUT); + } PR_Unlock(server->ml); TEST_LOG( - cltsrv_log_file, TEST_LOG_NOTICE, + cltsrv_log_file, TEST_LOG_NOTICE, ("main(0x%p): joining server(0x%p)\n", - PR_GetCurrentThread(), server->thread)); + PR_GetCurrentThread(), server->thread)); joinStatus = PR_JoinThread(server->thread); TEST_ASSERT(PR_SUCCESS == joinStatus); @@ -1169,7 +1232,7 @@ int main(int argc, char** argv) } TEST_LOG( - cltsrv_log_file, TEST_LOG_ALWAYS, + cltsrv_log_file, TEST_LOG_ALWAYS, ("main(0x%p): test complete\n", PR_GetCurrentThread())); PT_FPrintStats(debug_out, "\nPThread Statistics\n"); diff --git a/nsprpub/pr/tests/concur.c b/nsprpub/pr/tests/concur.c index 108f90668..594029021 100644 --- a/nsprpub/pr/tests/concur.c +++ b/nsprpub/pr/tests/concur.c @@ -4,7 +4,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* -** File: concur.c +** File: concur.c ** Description: test of adding and removing concurrency options */ @@ -46,8 +46,9 @@ static void PR_CALLBACK Dull(void *arg) Context *context = (Context*)arg; PR_Lock(context->ml); context->have += 1; - while (context->want >= context->have) + while (context->want >= context->have) { PR_WaitCondVar(context->cv, PR_INTERVAL_NO_TIMEOUT); + } context->have -= 1; PR_Unlock(context->ml); } /* Dull */ @@ -55,40 +56,46 @@ static void PR_CALLBACK Dull(void *arg) PRIntn PR_CALLBACK Concur(PRIntn argc, char **argv) { PRUintn cpus; - PLOptStatus os; - PRThread **threads; + PLOptStatus os; + PRThread **threads; PRBool debug = PR_FALSE; PRUintn range = DEFAULT_RANGE; - PRStatus rc; + PRStatus rc; PRUintn cnt; PRUintn loops = DEFAULT_LOOPS; - PRIntervalTime hundredMills = PR_MillisecondsToInterval(100); - PLOptState *opt = PL_CreateOptState(argc, argv, "Gdl:r:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + PRIntervalTime hundredMills = PR_MillisecondsToInterval(100); + PLOptState *opt = PL_CreateOptState(argc, argv, "Gdl:r:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'G': /* GLOBAL threads */ - thread_scope = PR_GLOBAL_THREAD; - break; - case 'd': /* debug mode */ - debug = PR_TRUE; - break; - case 'r': /* range limit */ - range = atoi(opt->value); - break; - case 'l': /* loop counter */ - loops = atoi(opt->value); - break; - default: - break; + case 'G': /* GLOBAL threads */ + thread_scope = PR_GLOBAL_THREAD; + break; + case 'd': /* debug mode */ + debug = PR_TRUE; + break; + case 'r': /* range limit */ + range = atoi(opt->value); + break; + case 'l': /* loop counter */ + loops = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); - if (0 == range) range = DEFAULT_RANGE; - if (0 == loops) loops = DEFAULT_LOOPS; + if (0 == range) { + range = DEFAULT_RANGE; + } + if (0 == loops) { + loops = DEFAULT_LOOPS; + } context.ml = PR_NewLock(); context.cv = PR_NewCondVar(context.ml); @@ -97,7 +104,7 @@ PRIntn PR_CALLBACK Concur(PRIntn argc, char **argv) PR_fprintf( PR_STDERR, "Testing with %d CPUs and %d interations\n", range, loops); - threads = (PRThread**) PR_CALLOC(sizeof(PRThread*) * range); + threads = (PRThread**) PR_CALLOC(sizeof(PRThread*) * range); while (--loops > 0) { for (cpus = 1; cpus <= range; ++cpus) @@ -106,8 +113,8 @@ PRIntn PR_CALLBACK Concur(PRIntn argc, char **argv) context.want = cpus; threads[cpus - 1] = PR_CreateThread( - PR_USER_THREAD, Dull, &context, PR_PRIORITY_NORMAL, - thread_scope, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, Dull, &context, PR_PRIORITY_NORMAL, + thread_scope, PR_JOINABLE_THREAD, 0); } PR_Sleep(hundredMills); @@ -121,18 +128,20 @@ PRIntn PR_CALLBACK Concur(PRIntn argc, char **argv) PR_NotifyCondVar(context.cv); PR_Unlock(context.ml); } - for(cnt = 0; cnt < range; cnt++) { - rc = PR_JoinThread(threads[cnt]); - PR_ASSERT(rc == PR_SUCCESS); - } + for(cnt = 0; cnt < range; cnt++) { + rc = PR_JoinThread(threads[cnt]); + PR_ASSERT(rc == PR_SUCCESS); + } } - + if (debug) PR_fprintf( PR_STDERR, "Waiting for %d thread(s) to exit\n", context.have); - while (context.have > 0) PR_Sleep(hundredMills); + while (context.have > 0) { + PR_Sleep(hundredMills); + } if (debug) PR_fprintf( diff --git a/nsprpub/pr/tests/cvar.c b/nsprpub/pr/tests/cvar.c index e2be526e8..4dc891d3f 100644 --- a/nsprpub/pr/tests/cvar.c +++ b/nsprpub/pr/tests/cvar.c @@ -8,16 +8,16 @@ ** ** Name: cvar.c ** -** Description: Tests Condition Variable Operations +** Description: Tests Condition Variable Operations ** ** Modification History: ** 13-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ** 12-June-97 Revert to return code 0 and 1. ***********************************************************************/ @@ -39,15 +39,15 @@ PRMonitor *mon; PRInt32 count = 0; PRIntn debug_mode; -#define kQSIZE 1 +#define kQSIZE 1 typedef struct { - PRLock *bufLock; - int startIdx; - int numFull; - PRCondVar *notFull; - PRCondVar *notEmpty; - void *data[kQSIZE]; + PRLock *bufLock; + int startIdx; + int numFull; + PRCondVar *notFull; + PRCondVar *notEmpty; + void *data[kQSIZE]; } CircBuf; static PRBool failed = PR_FALSE; @@ -57,19 +57,20 @@ static PRBool failed = PR_FALSE; */ static CircBuf* NewCB(void) { - CircBuf *cbp; - - cbp = PR_NEW(CircBuf); - if (cbp == NULL) - return (NULL); - - cbp->bufLock = PR_NewLock(); - cbp->startIdx = 0; - cbp->numFull = 0; - cbp->notFull = PR_NewCondVar(cbp->bufLock); - cbp->notEmpty = PR_NewCondVar(cbp->bufLock); - - return (cbp); + CircBuf *cbp; + + cbp = PR_NEW(CircBuf); + if (cbp == NULL) { + return (NULL); + } + + cbp->bufLock = PR_NewLock(); + cbp->startIdx = 0; + cbp->numFull = 0; + cbp->notFull = PR_NewCondVar(cbp->bufLock); + cbp->notEmpty = PR_NewCondVar(cbp->bufLock); + + return (cbp); } /* @@ -77,54 +78,56 @@ static CircBuf* NewCB(void) */ static void DeleteCB(CircBuf *cbp) { - PR_DestroyLock(cbp->bufLock); - PR_DestroyCondVar(cbp->notFull); - PR_DestroyCondVar(cbp->notEmpty); - PR_DELETE(cbp); + PR_DestroyLock(cbp->bufLock); + PR_DestroyCondVar(cbp->notFull); + PR_DestroyCondVar(cbp->notEmpty); + PR_DELETE(cbp); } /* -** PutCBData puts new data on the queue. If the queue is full, it waits +** PutCBData puts new data on the queue. If the queue is full, it waits ** until there is room. */ static void PutCBData(CircBuf *cbp, void *data) { - PR_Lock(cbp->bufLock); - /* wait while the buffer is full */ - while (cbp->numFull == kQSIZE) - PR_WaitCondVar(cbp->notFull,PR_INTERVAL_NO_TIMEOUT); - cbp->data[(cbp->startIdx + cbp->numFull) % kQSIZE] = data; - cbp->numFull += 1; - - /* let a waiting reader know that there is data */ - PR_NotifyCondVar(cbp->notEmpty); - PR_Unlock(cbp->bufLock); + PR_Lock(cbp->bufLock); + /* wait while the buffer is full */ + while (cbp->numFull == kQSIZE) { + PR_WaitCondVar(cbp->notFull,PR_INTERVAL_NO_TIMEOUT); + } + cbp->data[(cbp->startIdx + cbp->numFull) % kQSIZE] = data; + cbp->numFull += 1; + + /* let a waiting reader know that there is data */ + PR_NotifyCondVar(cbp->notEmpty); + PR_Unlock(cbp->bufLock); } /* -** GetCBData gets the oldest data on the queue. If the queue is empty, it waits +** GetCBData gets the oldest data on the queue. If the queue is empty, it waits ** until new data appears. */ static void* GetCBData(CircBuf *cbp) { - void *data; - - PR_Lock(cbp->bufLock); - /* wait while the buffer is empty */ - while (cbp->numFull == 0) - PR_WaitCondVar(cbp->notEmpty,PR_INTERVAL_NO_TIMEOUT); - data = cbp->data[cbp->startIdx]; - cbp->startIdx =(cbp->startIdx + 1) % kQSIZE; - cbp->numFull -= 1; - - /* let a waiting writer know that there is room */ - PR_NotifyCondVar(cbp->notFull); - PR_Unlock(cbp->bufLock); - - return (data); + void *data; + + PR_Lock(cbp->bufLock); + /* wait while the buffer is empty */ + while (cbp->numFull == 0) { + PR_WaitCondVar(cbp->notEmpty,PR_INTERVAL_NO_TIMEOUT); + } + data = cbp->data[cbp->startIdx]; + cbp->startIdx =(cbp->startIdx + 1) % kQSIZE; + cbp->numFull -= 1; + + /* let a waiting writer know that there is room */ + PR_NotifyCondVar(cbp->notFull); + PR_Unlock(cbp->bufLock); + + return (data); } @@ -134,17 +137,19 @@ static int alive; static void PR_CALLBACK CXReader(void *arg) { - CircBuf *cbp = (CircBuf *)arg; + CircBuf *cbp = (CircBuf *)arg; PRInt32 i, n; void *data; n = count / 2; for (i = 0; i < n; i++) { - data = GetCBData(cbp); - if ((int)data != i) - if (debug_mode) printf("data mismatch at for i = %d usec\n", i); + data = GetCBData(cbp); + if ((int)data != i) + if (debug_mode) { + printf("data mismatch at for i = %d usec\n", i); + } } - + PR_EnterMonitor(mon); --alive; PR_Notify(mon); @@ -153,12 +158,13 @@ static void PR_CALLBACK CXReader(void *arg) static void PR_CALLBACK CXWriter(void *arg) { - CircBuf *cbp = (CircBuf *)arg; + CircBuf *cbp = (CircBuf *)arg; PRInt32 i, n; n = count / 2; - for (i = 0; i < n; i++) - PutCBData(cbp, (void *)i); + for (i = 0; i < n; i++) { + PutCBData(cbp, (void *)i); + } PR_EnterMonitor(mon); --alive; @@ -169,35 +175,35 @@ static void PR_CALLBACK CXWriter(void *arg) static void CondWaitContextSwitch(PRThreadScope scope1, PRThreadScope scope2) { PRThread *t1, *t2; - CircBuf *cbp; + CircBuf *cbp; PR_EnterMonitor(mon); alive = 2; - cbp = NewCB(); - - t1 = PR_CreateThread(PR_USER_THREAD, - CXReader, cbp, - PR_PRIORITY_NORMAL, - scope1, - PR_UNJOINABLE_THREAD, - 0); - PR_ASSERT(t1); - t2 = PR_CreateThread(PR_USER_THREAD, - CXWriter, cbp, - PR_PRIORITY_NORMAL, - scope2, - PR_UNJOINABLE_THREAD, - 0); - PR_ASSERT(t2); + cbp = NewCB(); + + t1 = PR_CreateThread(PR_USER_THREAD, + CXReader, cbp, + PR_PRIORITY_NORMAL, + scope1, + PR_UNJOINABLE_THREAD, + 0); + PR_ASSERT(t1); + t2 = PR_CreateThread(PR_USER_THREAD, + CXWriter, cbp, + PR_PRIORITY_NORMAL, + scope2, + PR_UNJOINABLE_THREAD, + 0); + PR_ASSERT(t2); /* Wait for both of the threads to exit */ while (alive) { - PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT); + PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT); } - DeleteCB(cbp); + DeleteCB(cbp); PR_ExitMonitor(mon); } @@ -230,39 +236,47 @@ static void Measure(void (*func)(void), const char *msg) d = (double)PR_IntervalToMicroseconds(stop - start); - if (debug_mode) printf("%40s: %6.2f usec\n", msg, d / count); + if (debug_mode) { + printf("%40s: %6.2f usec\n", msg, d / count); + } - if (0 == d) failed = PR_TRUE; + if (0 == d) { + failed = PR_TRUE; + } } static PRIntn PR_CALLBACK RealMain(int argc, char **argv) { - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name [-d] [-c n] - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "dc:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name [-d] [-c n] + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "dc:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - case 'c': /* loop count */ - count = atoi(opt->value); - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + case 'c': /* loop count */ + count = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); - if (0 == count) count = DEFAULT_COUNT; + if (0 == count) { + count = DEFAULT_COUNT; + } mon = PR_NewMonitor(); @@ -270,21 +284,25 @@ static PRIntn PR_CALLBACK RealMain(int argc, char **argv) Measure(CondWaitContextSwitchUK, "cond var wait context switch- user/kernel"); Measure(CondWaitContextSwitchKK, "cond var wait context switch- kernel/kernel"); - PR_DestroyMonitor(mon); + PR_DestroyMonitor(mon); - if (debug_mode) printf("%s\n", (failed) ? "FAILED" : "PASSED"); + if (debug_mode) { + printf("%s\n", (failed) ? "FAILED" : "PASSED"); + } - if(failed) - return 1; - else - return 0; + if(failed) { + return 1; + } + else { + return 0; + } } int main(int argc, char *argv[]) { PRIntn rv; - + PR_STDIO_INIT(); rv = PR_Initialize(RealMain, argc, argv, 0); return rv; diff --git a/nsprpub/pr/tests/cvar2.c b/nsprpub/pr/tests/cvar2.c index c61405e27..c9f57d5cc 100644 --- a/nsprpub/pr/tests/cvar2.c +++ b/nsprpub/pr/tests/cvar2.c @@ -11,14 +11,14 @@ ** Description: Simple test creates several local and global threads; ** half use a single,shared condvar, and the ** other half have their own condvar. The main thread then loops -** notifying them to wakeup. +** notifying them to wakeup. ** ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ***********************************************************************/ #include "nspr.h" @@ -67,8 +67,9 @@ SharedCondVarThread(void *_info) for (index=0; index<info->loops; index++) { PR_Lock(info->lock); - if (*info->tcount == 0) + if (*info->tcount == 0) { PR_WaitCondVar(info->cvar, info->timeout); + } #if 0 printf("shared thread %ld notified in loop %ld\n", info->id, index); #endif @@ -95,10 +96,10 @@ PrivateCondVarThread(void *_info) for (index=0; index<info->loops; index++) { PR_Lock(info->lock); if (*info->tcount == 0) { - DPRINTF(("PrivateCondVarThread: thread 0x%lx waiting on cvar = 0x%lx\n", - PR_GetCurrentThread(), info->cvar)); + DPRINTF(("PrivateCondVarThread: thread 0x%lx waiting on cvar = 0x%lx\n", + PR_GetCurrentThread(), info->cvar)); PR_WaitCondVar(info->cvar, info->timeout); - } + } #if 0 printf("solo thread %ld notified in loop %ld\n", info->id, index); #endif @@ -108,8 +109,8 @@ PrivateCondVarThread(void *_info) PR_Lock(info->exitlock); (*info->exitcount)++; PR_NotifyCondVar(info->exitcvar); -DPRINTF(("PrivateCondVarThread: thread 0x%lx notified exitcvar = 0x%lx cnt = %ld\n", - PR_GetCurrentThread(), info->exitcvar,(*info->exitcount))); + DPRINTF(("PrivateCondVarThread: thread 0x%lx notified exitcvar = 0x%lx cnt = %ld\n", + PR_GetCurrentThread(), info->exitcvar,(*info->exitcount))); PR_Unlock(info->exitlock); } #if 0 @@ -117,8 +118,8 @@ DPRINTF(("PrivateCondVarThread: thread 0x%lx notified exitcvar = 0x%lx cnt = %ld #endif } -void -CreateTestThread(threadinfo *info, +void +CreateTestThread(threadinfo *info, PRInt32 id, PRLock *lock, PRCondVar *cvar, @@ -128,7 +129,7 @@ CreateTestThread(threadinfo *info, PRLock *exitlock, PRCondVar *exitcvar, PRInt32 *exitcount, - PRBool shared, + PRBool shared, PRThreadScope scope) { info->id = id; @@ -142,19 +143,20 @@ CreateTestThread(threadinfo *info, info->exitcvar = exitcvar; info->exitcount = exitcount; info->thread = PR_CreateThread( - PR_USER_THREAD, - shared?SharedCondVarThread:PrivateCondVarThread, - info, - PR_PRIORITY_NORMAL, - scope, - PR_JOINABLE_THREAD, - 0); - if (!info->thread) + PR_USER_THREAD, + shared?SharedCondVarThread:PrivateCondVarThread, + info, + PR_PRIORITY_NORMAL, + scope, + PR_JOINABLE_THREAD, + 0); + if (!info->thread) { PL_PrintError("error creating thread\n"); + } } -void +void CondVarTestSUU(void *_arg) { PRInt32 arg = (PRInt32)_arg; @@ -164,7 +166,7 @@ CondVarTestSUU(void *_arg) PRCondVar *sharedcvar; PRLock *exitlock; PRCondVar *exitcvar; - + exitcount=0; tcount=0; list = (threadinfo *)PR_MALLOC(sizeof(threadinfo) * (arg * 4)); @@ -189,7 +191,7 @@ CondVarTestSUU(void *_arg) PR_TRUE, PR_LOCAL_THREAD); index++; - DPRINTF(("CondVarTestSUU: created thread 0x%lx\n",list[index].thread)); + DPRINTF(("CondVarTestSUU: created thread 0x%lx\n",list[index].thread)); } for (loops = 0; loops < count; loops++) { @@ -199,22 +201,24 @@ CondVarTestSUU(void *_arg) (*list[index].tcount)++; PR_NotifyCondVar(list[index].cvar); PR_Unlock(list[index].lock); - DPRINTF(("PrivateCondVarThread: thread 0x%lx notified cvar = 0x%lx\n", - PR_GetCurrentThread(), list[index].cvar)); + DPRINTF(("PrivateCondVarThread: thread 0x%lx notified cvar = 0x%lx\n", + PR_GetCurrentThread(), list[index].cvar)); } /* Wait for threads to finish */ PR_Lock(exitlock); - while(exitcount < arg) + while(exitcount < arg) { PR_WaitCondVar(exitcvar, PR_SecondsToInterval(60)); + } PR_ASSERT(exitcount >= arg); exitcount -= arg; PR_Unlock(exitlock); } /* Join all the threads */ - for(index=0; index<(arg); index++) + for(index=0; index<(arg); index++) { PR_JoinThread(list[index].thread); + } PR_DestroyCondVar(sharedcvar); PR_DestroyLock(sharedlock); @@ -224,7 +228,7 @@ CondVarTestSUU(void *_arg) PR_DELETE(list); } -void +void CondVarTestSUK(void *_arg) { PRInt32 arg = (PRInt32)_arg; @@ -276,8 +280,9 @@ CondVarTestSUK(void *_arg) #endif /* Wait for threads to finish */ PR_Lock(exitlock); - while(exitcount < arg) + while(exitcount < arg) { PR_WaitCondVar(exitcvar, PR_SecondsToInterval(60)); + } PR_ASSERT(exitcount >= arg); exitcount -= arg; PR_Unlock(exitlock); @@ -287,8 +292,9 @@ CondVarTestSUK(void *_arg) } /* Join all the threads */ - for(index=0; index<(arg); index++) + for(index=0; index<(arg); index++) { PR_JoinThread(list[index].thread); + } PR_DestroyCondVar(sharedcvar); PR_DestroyLock(sharedlock); @@ -298,7 +304,7 @@ CondVarTestSUK(void *_arg) PR_DELETE(list); } -void +void CondVarTestPUU(void *_arg) { PRInt32 arg = (PRInt32)_arg; @@ -336,9 +342,9 @@ CondVarTestPUU(void *_arg) PR_FALSE, PR_LOCAL_THREAD); - DPRINTF(("CondVarTestPUU: created thread 0x%lx\n",list[index].thread)); + DPRINTF(("CondVarTestPUU: created thread 0x%lx\n",list[index].thread)); index++; - tcount++; + tcount++; } for (loops = 0; loops < count; loops++) { @@ -351,13 +357,13 @@ CondVarTestPUU(void *_arg) PR_Unlock(list[index].lock); } - PR_Lock(exitlock); + PR_Lock(exitlock); /* Wait for threads to finish */ while(exitcount < arg) { -DPRINTF(("CondVarTestPUU: thread 0x%lx waiting on exitcvar = 0x%lx cnt = %ld\n", - PR_GetCurrentThread(), exitcvar, exitcount)); - PR_WaitCondVar(exitcvar, PR_SecondsToInterval(60)); - } + DPRINTF(("CondVarTestPUU: thread 0x%lx waiting on exitcvar = 0x%lx cnt = %ld\n", + PR_GetCurrentThread(), exitcvar, exitcount)); + PR_WaitCondVar(exitcvar, PR_SecondsToInterval(60)); + } PR_ASSERT(exitcount >= arg); exitcount -= arg; PR_Unlock(exitlock); @@ -365,7 +371,7 @@ DPRINTF(("CondVarTestPUU: thread 0x%lx waiting on exitcvar = 0x%lx cnt = %ld\n", /* Join all the threads */ for(index=0; index<(arg); index++) { - DPRINTF(("CondVarTestPUU: joining thread 0x%lx\n",list[index].thread)); + DPRINTF(("CondVarTestPUU: joining thread 0x%lx\n",list[index].thread)); PR_JoinThread(list[index].thread); if (list[index].internal) { PR_Lock(list[index].lock); @@ -384,7 +390,7 @@ DPRINTF(("CondVarTestPUU: thread 0x%lx waiting on exitcvar = 0x%lx cnt = %ld\n", PR_DELETE(saved_tcount); } -void +void CondVarTestPUK(void *_arg) { PRInt32 arg = (PRInt32)_arg; @@ -438,8 +444,9 @@ CondVarTestPUK(void *_arg) /* Wait for threads to finish */ PR_Lock(exitlock); - while(exitcount < arg) + while(exitcount < arg) { PR_WaitCondVar(exitcvar, PR_SecondsToInterval(60)); + } PR_ASSERT(exitcount >= arg); exitcount -= arg; PR_Unlock(exitlock); @@ -465,7 +472,7 @@ CondVarTestPUK(void *_arg) PR_DELETE(saved_tcount); } -void +void CondVarTest(void *_arg) { PRInt32 arg = (PRInt32)_arg; @@ -532,7 +539,7 @@ CondVarTest(void *_arg) PR_FALSE, PR_LOCAL_THREAD); index++; - ptcount++; + ptcount++; list[index].lock = PR_NewLock(); list[index].cvar = PR_NewCondVar(list[index].lock); CreateTestThread(&list[index], @@ -549,7 +556,7 @@ CondVarTest(void *_arg) PR_GLOBAL_THREAD); index++; - ptcount++; + ptcount++; } for (loops = 0; loops < count; loops++) { @@ -568,8 +575,9 @@ CondVarTest(void *_arg) /* Wait for threads to finish */ PR_Lock(exitlock); - while(exitcount < arg*4) + while(exitcount < arg*4) { PR_WaitCondVar(exitcvar, PR_SecondsToInterval(60)); + } PR_ASSERT(exitcount >= arg*4); exitcount -= arg*4; PR_Unlock(exitlock); @@ -598,7 +606,7 @@ CondVarTest(void *_arg) PR_DELETE(saved_ptcount); } -void +void CondVarTimeoutTest(void *_arg) { PRInt32 arg = (PRInt32)_arg; @@ -682,8 +690,9 @@ CondVarTimeoutTest(void *_arg) /* Wait for threads to finish */ PR_Lock(exitlock); - while(exitcount < arg*4) + while(exitcount < arg*4) { PR_WaitCondVar(exitcvar, PR_SecondsToInterval(60)); + } PR_ASSERT(exitcount >= arg*4); exitcount -= arg*4; PR_Unlock(exitlock); @@ -709,7 +718,7 @@ CondVarTimeoutTest(void *_arg) PR_DELETE(list); } -void +void CondVarMixedTest(void *_arg) { PRInt32 arg = (PRInt32)_arg; @@ -774,7 +783,7 @@ CondVarMixedTest(void *_arg) PR_FALSE, PR_LOCAL_THREAD); index++; - ptcount++; + ptcount++; list[index].lock = PR_NewLock(); list[index].cvar = PR_NewCondVar(list[index].lock); @@ -791,7 +800,7 @@ CondVarMixedTest(void *_arg) PR_FALSE, PR_GLOBAL_THREAD); index++; - ptcount++; + ptcount++; } @@ -809,8 +818,9 @@ CondVarMixedTest(void *_arg) } /* Wait for threads to finish */ PR_Lock(exitlock); - while(exitcount < arg*4) + while(exitcount < arg*4) { PR_WaitCondVar(exitcvar, PR_SecondsToInterval(60)); + } PR_ASSERT(exitcount >= arg*4); exitcount -= arg*4; PR_Unlock(exitlock); @@ -833,7 +843,7 @@ CondVarMixedTest(void *_arg) PR_DELETE(list); } -void +void CondVarCombinedTest(void *arg) { PRThread *threads[3]; @@ -884,30 +894,36 @@ static void Measure(void (*func)(void *), PRInt32 arg, const char *msg) static PRIntn PR_CALLBACK RealMain(int argc, char **argv) { PRInt32 threads, default_threads = DEFAULT_THREADS; - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "vc:t:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "vc:t:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'v': /* debug mode */ - _debug_on = 1; - break; - case 'c': /* loop counter */ - count = atoi(opt->value); - break; - case 't': /* number of threads involved */ - default_threads = atoi(opt->value); - break; - default: - break; + case 'v': /* debug mode */ + _debug_on = 1; + break; + case 'c': /* loop counter */ + count = atoi(opt->value); + break; + case 't': /* number of threads involved */ + default_threads = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); - if (0 == count) count = DEFAULT_COUNT; - if (0 == default_threads) default_threads = DEFAULT_THREADS; + if (0 == count) { + count = DEFAULT_COUNT; + } + if (0 == default_threads) { + default_threads = DEFAULT_THREADS; + } printf("\n\ CondVar Test: \n\ @@ -927,7 +943,7 @@ Lastly, the combined test creates a thread for each of the above three \n\ cases and they all run simultaneously. \n\ \n\ This test is run with %d, %d, %d, and %d threads of each type.\n\n", -default_threads, default_threads*2, default_threads*3, default_threads*4); + default_threads, default_threads*2, default_threads*3, default_threads*4); PR_SetConcurrency(2); @@ -953,7 +969,7 @@ default_threads, default_threads*2, default_threads*3, default_threads*4); int main(int argc, char **argv) { PRIntn rv; - + PR_STDIO_INIT(); rv = PR_Initialize(RealMain, argc, argv, 0); return rv; diff --git a/nsprpub/pr/tests/dbmalloc.c b/nsprpub/pr/tests/dbmalloc.c index 67173fe62..2a7ad4fa8 100644 --- a/nsprpub/pr/tests/dbmalloc.c +++ b/nsprpub/pr/tests/dbmalloc.c @@ -11,10 +11,10 @@ ** ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ***********************************************************************/ #include <stdio.h> #include <stdlib.h> @@ -38,15 +38,17 @@ typedef struct node_struct int line; char value[4]; } - node_t, - *node_pt; +node_t, +*node_pt; node_pt get_node(const char *line) { node_pt rv; int l = strlen(line); rv = (node_pt)PR_MALLOC(sizeof(node_t) + l + 1 - 4); - if( (node_pt)0 == rv ) return (node_pt)0; + if( (node_pt)0 == rv ) { + return (node_pt)0; + } memcpy(&rv->value[0], line, l+1); rv->next = rv->prev = (node_pt)0; return rv; @@ -61,10 +63,18 @@ dump int debug ) { - if( (node_pt)0 != node->prev ) dump(name, node->prev, mf, debug); - if( 0 != debug ) printf("[%s]: %6d: %s", name, node->line, node->value); - if( node->line == mf ) fprintf(stderr, "[%s]: Line %d was allocated!\n", name, node->line); - if( (node_pt)0 != node->next ) dump(name, node->next, mf, debug); + if( (node_pt)0 != node->prev ) { + dump(name, node->prev, mf, debug); + } + if( 0 != debug ) { + printf("[%s]: %6d: %s", name, node->line, node->value); + } + if( node->line == mf ) { + fprintf(stderr, "[%s]: Line %d was allocated!\n", name, node->line); + } + if( (node_pt)0 != node->next ) { + dump(name, node->next, mf, debug); + } return; } @@ -74,8 +84,12 @@ release node_pt node ) { - if( (node_pt)0 != node->prev ) release(node->prev); - if( (node_pt)0 != node->next ) release(node->next); + if( (node_pt)0 != node->prev ) { + release(node->prev); + } + if( (node_pt)0 != node->next ) { + release(node->next); + } PR_DELETE(node); } @@ -129,13 +143,14 @@ t2 node_pt n; node_pt *w = &head; - if( (strlen(buffer) == (BUFSIZ-1)) && (buffer[BUFSIZ-2] != '\n') ) + if( (strlen(buffer) == (BUFSIZ-1)) && (buffer[BUFSIZ-2] != '\n') ) { buffer[BUFSIZ-2] == '\n'; + } l++; n = get_node(buffer); - if( (node_pt)0 == n ) + if( (node_pt)0 == n ) { printf("[%s]: Line %d: malloc failure!\n", name, l); continue; @@ -154,8 +169,12 @@ t2 } comp = strcmp((*w)->value, n->value); - if( comp < 0 ) w = &(*w)->next; - else w = &(*w)->prev; + if( comp < 0 ) { + w = &(*w)->next; + } + else { + w = &(*w)->prev; + } } } @@ -186,16 +205,24 @@ test printf("[%s]: starting test 0\n", name); n = t2(name, 0, debug); - if( -1 == n ) return; + if( -1 == n ) { + return; + } printf("[%s]: test 0 had %ld allocations.\n", name, n); - if( 0 >= n ) return; + if( 0 >= n ) { + return; + } for( i = 0; i < nf; i++ ) { int which = rand() % n; - if( 0 == which ) printf("[%s]: starting test %d -- no allocation should fail\n", name, i+1); - else printf("[%s]: starting test %d -- allocation %d should fail\n", name, i+1, which); + if( 0 == which ) { + printf("[%s]: starting test %d -- no allocation should fail\n", name, i+1); + } + else { + printf("[%s]: starting test %d -- allocation %d should fail\n", name, i+1, which); + } (void)t2(name, which, debug); printf("[%s]: test %d done.\n", name, i+1); } @@ -213,7 +240,7 @@ int main(int argc, char **argv) struct threadlist *next; PRThread *thread; } - *threadhead = (struct threadlist *)0; + *threadhead = (struct threadlist *)0; extern int nf, debug; @@ -268,15 +295,15 @@ int main(int argc, char **argv) struct threadlist *n; n = (struct threadlist *)malloc(sizeof(struct threadlist)); - if( (struct threadlist *)0 == n ) + if( (struct threadlist *)0 == n ) { fprintf(stderr, "This is getting tedious. \"%s\"\n", *argv); continue; } n->next = threadhead; - n->thread = PR_CreateThread(PR_USER_THREAD, (void (*)(void *))test, - *argv, PR_PRIORITY_NORMAL, + n->thread = PR_CreateThread(PR_USER_THREAD, (void (*)(void *))test, + *argv, PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); if( (PRThread *)0 == n->thread ) @@ -296,14 +323,16 @@ int main(int argc, char **argv) } } - if( okay == 0 ) usage(); - else while( (struct threadlist *)0 != threadhead ) - { - struct threadlist *x = threadhead->next; - (void)PR_JoinThread(threadhead->thread); - PR_DELETE(threadhead); - threadhead = x; + if( okay == 0 ) { + usage(); } + else while( (struct threadlist *)0 != threadhead ) + { + struct threadlist *x = threadhead->next; + (void)PR_JoinThread(threadhead->thread); + PR_DELETE(threadhead); + threadhead = x; + } return 0; } diff --git a/nsprpub/pr/tests/dbmalloc1.c b/nsprpub/pr/tests/dbmalloc1.c index 4069afd31..a7e995c40 100644 --- a/nsprpub/pr/tests/dbmalloc1.c +++ b/nsprpub/pr/tests/dbmalloc1.c @@ -11,12 +11,12 @@ ** ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ** ** 12-June-97 AGarcia Revert to return code 0 and 1, remove debug option (obsolete). ***********************************************************************/ @@ -44,18 +44,22 @@ r1 ) { int i; - actually_failed=0; + actually_failed=0; for( i = 0; i < 5; i++ ) { void *x = PR_MALLOC(128); if( (void *)0 == x ) { - if (debug_mode) printf("\tMalloc %d failed.\n", i+1); - actually_failed = 1; - } + if (debug_mode) { + printf("\tMalloc %d failed.\n", i+1); + } + actually_failed = 1; + } PR_DELETE(x); } - if (((should_fail != actually_failed) & (!debug_mode))) failed_already=1; + if (((should_fail != actually_failed) & (!debug_mode))) { + failed_already=1; + } return; @@ -71,14 +75,18 @@ r2 for( i = 0; i <= 5; i++ ) { - should_fail =0; + should_fail =0; if( 0 == i ) { - if (debug_mode) printf("No malloc should fail:\n"); - } + if (debug_mode) { + printf("No malloc should fail:\n"); + } + } else { - if (debug_mode) printf("Malloc %d should fail:\n", i); - should_fail = 1; - } + if (debug_mode) { + printf("Malloc %d should fail:\n", i); + } + should_fail = 1; + } PR_SetMallocCountdown(i); r1(); PR_ClearMallocCountdown(); @@ -88,17 +96,19 @@ r2 int main(int argc, char **argv) { - /* main test */ - + /* main test */ + PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); r2(); - if(failed_already) + if(failed_already) { return 1; - else + } + else { return 0; + } + - } diff --git a/nsprpub/pr/tests/dceemu.c b/nsprpub/pr/tests/dceemu.c index 99fd6cb7c..2b1d0901a 100644 --- a/nsprpub/pr/tests/dceemu.c +++ b/nsprpub/pr/tests/dceemu.c @@ -9,8 +9,8 @@ ** ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements ** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to @@ -41,38 +41,54 @@ static PRIntn prmain(PRIntn argc, char **argv) rv = PRP_TryLock(ml); PR_ASSERT(PR_SUCCESS == rv); - if ((rv != PR_SUCCESS) & (!debug_mode)) failed_already=1; - + if ((rv != PR_SUCCESS) & (!debug_mode)) { + failed_already=1; + } + rv = PRP_TryLock(ml); PR_ASSERT(PR_FAILURE == rv); - if ((rv != PR_FAILURE) & (!debug_mode)) failed_already=1; + if ((rv != PR_FAILURE) & (!debug_mode)) { + failed_already=1; + } rv = PRP_NakedNotify(cv); PR_ASSERT(PR_SUCCESS == rv); - if ((rv != PR_SUCCESS) & (!debug_mode)) failed_already=1; + if ((rv != PR_SUCCESS) & (!debug_mode)) { + failed_already=1; + } rv = PRP_NakedBroadcast(cv); PR_ASSERT(PR_SUCCESS == rv); - if ((rv != PR_SUCCESS) & (!debug_mode)) failed_already=1; + if ((rv != PR_SUCCESS) & (!debug_mode)) { + failed_already=1; + } rv = PRP_NakedWait(cv, ml, tenmsecs); PR_ASSERT(PR_SUCCESS == rv); - if ((rv != PR_SUCCESS) & (!debug_mode)) failed_already=1; + if ((rv != PR_SUCCESS) & (!debug_mode)) { + failed_already=1; + } + + PR_Unlock(ml); - PR_Unlock(ml); - rv = PRP_NakedNotify(cv); PR_ASSERT(PR_SUCCESS == rv); - if ((rv != PR_SUCCESS) & (!debug_mode)) failed_already=1; + if ((rv != PR_SUCCESS) & (!debug_mode)) { + failed_already=1; + } rv = PRP_NakedBroadcast(cv); PR_ASSERT(PR_SUCCESS == rv); - if ((rv != PR_SUCCESS) & (!debug_mode)) failed_already=1; + if ((rv != PR_SUCCESS) & (!debug_mode)) { + failed_already=1; + } PRP_DestroyNakedCondVar(cv); PR_DestroyLock(ml); - if (debug_mode) printf("Test succeeded\n"); + if (debug_mode) { + printf("Test succeeded\n"); + } return 0; @@ -81,10 +97,12 @@ static PRIntn prmain(PRIntn argc, char **argv) int main(int argc, char **argv) { PR_Initialize(prmain, argc, argv, 0); - if(failed_already) + if(failed_already) { return 1; - else + } + else { return 0; + } } /* main */ diff --git a/nsprpub/pr/tests/depend.c b/nsprpub/pr/tests/depend.c index 6df38c113..f3689bc46 100644 --- a/nsprpub/pr/tests/depend.c +++ b/nsprpub/pr/tests/depend.c @@ -7,15 +7,15 @@ ** 1996 - Netscape Communications Corporation ** ** -** Name: depend.c +** Name: depend.c ** Description: Test to enumerate the dependencies * ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ***********************************************************************/ #include "prinit.h" @@ -35,13 +35,16 @@ static void PrintVersion( static const char *tabs = {" "}; tab *= 2; - if (tab > len) tab = len; + if (tab > len) { + tab = len; + } printf("%s", &tabs[len - tab]); printf("%s ", msg); printf("%s ", info->id); printf("%d.%d", info->major, info->minor); - if (0 != info->patch) + if (0 != info->patch) { printf(".p%d", info->patch); + } printf("\n"); } /* PrintDependency */ @@ -77,9 +80,15 @@ static const PRVersionInfo *HackExportInfo(void) static const PRDependencyInfo *DummyImports( const PRDependencyInfo *previous) { - if (NULL == previous) return &dummy_imports[0]; - else if (&dummy_imports[0] == previous) return &dummy_imports[1]; - else if (&dummy_imports[1] == previous) return NULL; + if (NULL == previous) { + return &dummy_imports[0]; + } + else if (&dummy_imports[0] == previous) { + return &dummy_imports[1]; + } + else if (&dummy_imports[1] == previous) { + return NULL; + } } /* DummyImports */ static const PRVersionInfo *DummyLibVersion(void) @@ -112,8 +121,10 @@ int main(int argc, char **argv) const char *buildDate = __DATE__, *buildTime = __TIME__; printf("Depend.c build time is %s %s\n", buildDate, buildTime); - - if (NULL != info) ChaseDependents(info, tab); + + if (NULL != info) { + ChaseDependents(info, tab); + } return 0; } /* main */ diff --git a/nsprpub/pr/tests/dll/mygetval.c b/nsprpub/pr/tests/dll/mygetval.c index 53a6408e6..7fb700244 100644 --- a/nsprpub/pr/tests/dll/mygetval.c +++ b/nsprpub/pr/tests/dll/mygetval.c @@ -17,7 +17,7 @@ PR_IMPLEMENT(PRIntn) My_GetValue() } #if defined(WIN16) -int CALLBACK LibMain( HINSTANCE hInst, WORD wDataSeg, +int CALLBACK LibMain( HINSTANCE hInst, WORD wDataSeg, WORD cbHeapSize, LPSTR lpszCmdLine ) { return TRUE; diff --git a/nsprpub/pr/tests/dlltest.c b/nsprpub/pr/tests/dlltest.c index 1cf82bc84..d68732281 100644 --- a/nsprpub/pr/tests/dlltest.c +++ b/nsprpub/pr/tests/dlltest.c @@ -11,12 +11,12 @@ ** ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ** 12-June-97 Revert to return code 0 and 1. ***********************************************************************/ @@ -61,7 +61,9 @@ int main(int argc, char** argv) */ libName = PR_GetLibraryName("dll", "my"); - if (debug_mode) printf("Loading library %s\n", libName); + if (debug_mode) { + printf("Loading library %s\n", libName); + } lib = PR_LoadLibrary(libName); PR_FreeLibraryName(libName); if (lib == NULL) { @@ -72,7 +74,9 @@ int main(int argc, char** argv) fprintf( stderr, "PR_LoadLibrary failed (%d, %d, %s)\n", PR_GetError(), PR_GetOSError(), text); - if (!debug_mode) failed_already=1; + if (!debug_mode) { + failed_already=1; + } } getFcn = (GetFcnType) PR_FindSymbol(lib, "My_GetValue"); setFcn = (SetFcnType) PR_FindFunctionSymbol(lib, "My_SetValue"); @@ -80,9 +84,13 @@ int main(int argc, char** argv) value = (*getFcn)(); if (value != 888) { fprintf(stderr, "Test 1 failed: set value to 888, but got %d\n", value); - if (!debug_mode) failed_already=1; + if (!debug_mode) { + failed_already=1; + } + } + if (debug_mode) { + printf("Test 1 passed\n"); } - if (debug_mode) printf("Test 1 passed\n"); /* * Test 2: get a second handle to the same library (this should increment @@ -93,24 +101,32 @@ int main(int argc, char** argv) getFcn = (GetFcnType) PR_FindSymbolAndLibrary("My_GetValue", &lib2); if (NULL == getFcn || lib != lib2) { fprintf(stderr, "Test 2 failed: handles for the same library are not " - "equal: handle 1: %p, handle 2: %p\n", lib, lib2); - if (!debug_mode) failed_already=1; + "equal: handle 1: %p, handle 2: %p\n", lib, lib2); + if (!debug_mode) { + failed_already=1; + } } setFcn = (SetFcnType) PR_FindSymbol(lib2, "My_SetValue"); value = (*getFcn)(); if (value != 888) { fprintf(stderr, "Test 2 failed: value should be 888, but got %d\n", - value); - if (!debug_mode) failed_already=1; + value); + if (!debug_mode) { + failed_already=1; + } } (*setFcn)(777); value = (*getFcn)(); if (value != 777) { fprintf(stderr, "Test 2 failed: set value to 777, but got %d\n", value); - if (!debug_mode) failed_already=1; + if (!debug_mode) { + failed_already=1; + } goto exit_now; } - if (debug_mode) printf("Test 2 passed\n"); + if (debug_mode) { + printf("Test 2 passed\n"); + } /* * Test 3: unload the library. The library should still be accessible @@ -120,8 +136,10 @@ int main(int argc, char** argv) status = PR_UnloadLibrary(lib); if (PR_FAILURE == status) { fprintf(stderr, "Test 3 failed: cannot unload library: (%d, %d)\n", - PR_GetError(), PR_GetOSError()); - if (!debug_mode) failed_already=1; + PR_GetError(), PR_GetOSError()); + if (!debug_mode) { + failed_already=1; + } goto exit_now; } getFcn = (GetFcnType) PR_FindFunctionSymbol(lib2, "My_GetValue"); @@ -130,10 +148,14 @@ int main(int argc, char** argv) value = (*getFcn)(); if (value != 666) { fprintf(stderr, "Test 3 failed: set value to 666, but got %d\n", value); - if (!debug_mode) failed_already=1; + if (!debug_mode) { + failed_already=1; + } goto exit_now; } - if (debug_mode) printf("Test 3 passed\n"); + if (debug_mode) { + printf("Test 3 passed\n"); + } /* * Test 4: unload the library, testing the reference count mechanism. @@ -142,15 +164,19 @@ int main(int argc, char** argv) status = PR_UnloadLibrary(lib2); if (PR_FAILURE == status) { fprintf(stderr, "Test 4 failed: cannot unload library: (%d, %d)\n", - PR_GetError(), PR_GetOSError()); - if (!debug_mode) failed_already=1; + PR_GetError(), PR_GetOSError()); + if (!debug_mode) { + failed_already=1; + } goto exit_now; } getFcn = (GetFcnType) PR_FindFunctionSymbolAndLibrary("My_GetValue", &lib2); if (NULL != getFcn) { fprintf(stderr, "Test 4 failed: how can we find a symbol " - "in an already unloaded library?\n"); - if (!debug_mode) failed_already=1; + "in an already unloaded library?\n"); + if (!debug_mode) { + failed_already=1; + } goto exit_now; } if (debug_mode) { @@ -163,7 +189,7 @@ int main(int argc, char** argv) { PRStaticLinkTable slt[10]; PRLibrary *lib; - + lib = PR_LoadStaticLibrary( "my.dll", slt ); if ( lib == NULL ) { @@ -177,7 +203,7 @@ int main(int argc, char** argv) } goto exit_now; -exit_now: +exit_now: PR_Cleanup(); if (failed_already) { diff --git a/nsprpub/pr/tests/dtoa.c b/nsprpub/pr/tests/dtoa.c index 59c6db981..ef2e4dc4d 100644 --- a/nsprpub/pr/tests/dtoa.c +++ b/nsprpub/pr/tests/dtoa.c @@ -31,107 +31,107 @@ int main(int argc, char **argv) double zero = 0.0; char cnvt[50]; char *thousands; - + num = 1e24; num1 = PR_strtod("1e24",NULL); - if(num1 != num){ - fprintf(stderr,"Failed to convert numeric value %s\n","1e24"); + if(num1 != num) { + fprintf(stderr,"Failed to convert numeric value %s\n","1e24"); failed_already = 1; } PR_cnvtf(cnvt,sizeof(cnvt),20,num); - if(strcmp("1e+24",cnvt) != 0){ - fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); + if(strcmp("1e+24",cnvt) != 0) { + fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); failed_already = 1; } num = 0.001e7; num1 = PR_strtod("0.001e7",NULL); - if(num1 != num){ - fprintf(stderr,"Failed to convert numeric value %s\n","0.001e7"); + if(num1 != num) { + fprintf(stderr,"Failed to convert numeric value %s\n","0.001e7"); failed_already = 1; } PR_cnvtf(cnvt,sizeof(cnvt),20,num); - if(strcmp("10000",cnvt) != 0){ - fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); + if(strcmp("10000",cnvt) != 0) { + fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); failed_already = 1; } num = 0.0000000000000753; num1 = PR_strtod("0.0000000000000753",NULL); - if(num1 != num){ - fprintf(stderr,"Failed to convert numeric value %s\n", - "0.0000000000000753"); + if(num1 != num) { + fprintf(stderr,"Failed to convert numeric value %s\n", + "0.0000000000000753"); failed_already = 1; } PR_cnvtf(cnvt,sizeof(cnvt),20,num); - if(strcmp("7.53e-14",cnvt) != 0){ - fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); + if(strcmp("7.53e-14",cnvt) != 0) { + fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); failed_already = 1; } num = 1.867e73; num1 = PR_strtod("1.867e73",NULL); - if(num1 != num){ - fprintf(stderr,"Failed to convert numeric value %s\n","1.867e73"); + if(num1 != num) { + fprintf(stderr,"Failed to convert numeric value %s\n","1.867e73"); failed_already = 1; } PR_cnvtf(cnvt,sizeof(cnvt),20,num); - if(strcmp("1.867e+73",cnvt) != 0){ - fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); + if(strcmp("1.867e+73",cnvt) != 0) { + fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); failed_already = 1; } num = -1.867e73; num1 = PR_strtod("-1.867e73",NULL); - if(num1 != num){ - fprintf(stderr,"Failed to convert numeric value %s\n","-1.867e73"); + if(num1 != num) { + fprintf(stderr,"Failed to convert numeric value %s\n","-1.867e73"); failed_already = 1; } PR_cnvtf(cnvt,sizeof(cnvt),20,num); - if(strcmp("-1.867e+73",cnvt) != 0){ - fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); + if(strcmp("-1.867e+73",cnvt) != 0) { + fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); failed_already = 1; } num = -1.867e-73; num1 = PR_strtod("-1.867e-73",NULL); - if(num1 != num){ - fprintf(stderr,"Failed to convert numeric value %s\n","-1.867e-73"); + if(num1 != num) { + fprintf(stderr,"Failed to convert numeric value %s\n","-1.867e-73"); failed_already = 1; } PR_cnvtf(cnvt,sizeof(cnvt),20,num); - if(strcmp("-1.867e-73",cnvt) != 0){ - fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); + if(strcmp("-1.867e-73",cnvt) != 0) { + fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); failed_already = 1; } /* Testing for infinity */ num = 1.0 / zero; num1 = PR_strtod("1.867e765",NULL); - if(num1 != num){ - fprintf(stderr,"Failed to convert numeric value %s\n","1.867e765"); + if(num1 != num) { + fprintf(stderr,"Failed to convert numeric value %s\n","1.867e765"); failed_already = 1; } PR_cnvtf(cnvt,sizeof(cnvt),20,num); - if(strcmp("Infinity",cnvt) != 0){ - fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); + if(strcmp("Infinity",cnvt) != 0) { + fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); failed_already = 1; } num = -1.0 / zero; num1 = PR_strtod("-1.867e765",NULL); - if(num1 != num){ - fprintf(stderr,"Failed to convert numeric value %s\n","-1.867e765"); + if(num1 != num) { + fprintf(stderr,"Failed to convert numeric value %s\n","-1.867e765"); failed_already = 1; } PR_cnvtf(cnvt,sizeof(cnvt),20,num); - if(strcmp("-Infinity",cnvt) != 0){ - fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); + if(strcmp("-Infinity",cnvt) != 0) { + fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); failed_already = 1; } @@ -139,42 +139,42 @@ int main(int argc, char **argv) num = zero / zero; PR_cnvtf(cnvt,sizeof(cnvt),20,num); - if(strcmp("NaN",cnvt) != 0){ - fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); + if(strcmp("NaN",cnvt) != 0) { + fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); failed_already = 1; } num = - zero / zero; PR_cnvtf(cnvt,sizeof(cnvt),20,num); - if(strcmp("NaN",cnvt) != 0){ - fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); + if(strcmp("NaN",cnvt) != 0) { + fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); failed_already = 1; } num = 1.0000000001e21; num1 = PR_strtod("1.0000000001e21",NULL); - if(num1 != num){ - fprintf(stderr,"Failed to convert numeric value %s\n", - "1.0000000001e21"); + if(num1 != num) { + fprintf(stderr,"Failed to convert numeric value %s\n", + "1.0000000001e21"); failed_already = 1; } PR_cnvtf(cnvt,sizeof(cnvt),20,num); - if(strcmp("1.0000000001e+21",cnvt) != 0){ - fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); + if(strcmp("1.0000000001e+21",cnvt) != 0) { + fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); failed_already = 1; } num = -1.0000000001e-21; num1 = PR_strtod("-1.0000000001e-21",NULL); - if(num1 != num){ - fprintf(stderr,"Failed to convert numeric value %s\n", - "-1.0000000001e-21"); + if(num1 != num) { + fprintf(stderr,"Failed to convert numeric value %s\n", + "-1.0000000001e-21"); failed_already = 1; } PR_cnvtf(cnvt,sizeof(cnvt),20,num); - if(strcmp("-1.0000000001e-21",cnvt) != 0){ - fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); + if(strcmp("-1.0000000001e-21",cnvt) != 0) { + fprintf(stderr,"Failed to convert numeric value %lf %s\n",num,cnvt); failed_already = 1; } @@ -198,7 +198,7 @@ int main(int argc, char **argv) num = 0; num1 = PR_strtod(thousands,NULL); free(thousands); - if(num1 != num){ + if(num1 != num) { fprintf(stderr,"Failed to convert numeric value %s\n", "0.1111111111111111..."); failed_already = 1; diff --git a/nsprpub/pr/tests/env.c b/nsprpub/pr/tests/env.c index c11588d67..17b0eeb9b 100644 --- a/nsprpub/pr/tests/env.c +++ b/nsprpub/pr/tests/env.c @@ -46,34 +46,36 @@ int main(int argc, char **argv) PLOptStatus os; PLOptState *opt = PL_CreateOptState(argc, argv, "vds"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug */ - debug = 1; - break; - case 'v': /* verbose */ - verbose = 1; - break; - case 's': /* secure / set[ug]id */ - /* - ** To test PR_GetEnvSecure, make this executable (or a - ** copy of it) setuid / setgid / otherwise inherently - ** privileged (e.g., file capabilities) and run it - ** with this flag. - */ - secure = 1; - break; - default: - break; + case 'd': /* debug */ + debug = 1; + break; + case 'v': /* verbose */ + verbose = 1; + break; + case 's': /* secure / set[ug]id */ + /* + ** To test PR_GetEnvSecure, make this executable (or a + ** copy of it) setuid / setgid / otherwise inherently + ** privileged (e.g., file capabilities) and run it + ** with this flag. + */ + secure = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); } /* end block "Get command line options" */ -#if 0 +#if 0 { /* ** This uses Windows native environment manipulation @@ -83,24 +85,36 @@ int main(int argc, char **argv) DWORD size; rv = SetEnvironmentVariable( ENVNAME, ENVVALUE ); if ( rv == 0 ) { - if (debug) printf("env: Shit! SetEnvironmentVariable() failed\n"); + if (debug) { + printf("env: Shit! SetEnvironmentVariable() failed\n"); + } failedAlready = PR_TRUE; } - if (verbose) printf("env: SetEnvironmentVariable() worked\n"); + if (verbose) { + printf("env: SetEnvironmentVariable() worked\n"); + } - size = GetEnvironmentVariable( ENVNAME, envBuf, ENVBUFSIZE ); + size = GetEnvironmentVariable( ENVNAME, envBuf, ENVBUFSIZE ); if ( size == 0 ) { - if (debug) printf("env: Shit! GetEnvironmentVariable() failed. Found: %s\n", envBuf ); + if (debug) { + printf("env: Shit! GetEnvironmentVariable() failed. Found: %s\n", envBuf ); + } failedAlready = PR_TRUE; } - if (verbose) printf("env: GetEnvironmentVariable() worked. Found: %s\n", envBuf); + if (verbose) { + printf("env: GetEnvironmentVariable() worked. Found: %s\n", envBuf); + } value = PR_GetEnv( ENVNAME ); if ( (NULL == value ) || (strcmp( value, ENVVALUE))) { - if (debug) printf( "env: PR_GetEnv() failed retrieving WinNative. Found: %s\n", value); + if (debug) { + printf( "env: PR_GetEnv() failed retrieving WinNative. Found: %s\n", value); + } failedAlready = PR_TRUE; } - if (verbose) printf("env: PR_GetEnv() worked. Found: %s\n", value); + if (verbose) { + printf("env: PR_GetEnv() worked. Found: %s\n", value); + } } #endif @@ -109,18 +123,26 @@ int main(int argc, char **argv) sprintf( envBuf, ENVNAME "=" ENVVALUE ); rc = PR_SetEnv( envBuf ); if ( PR_FAILURE == rc ) { - if (debug) printf( "env: PR_SetEnv() failed setting\n"); + if (debug) { + printf( "env: PR_SetEnv() failed setting\n"); + } failedAlready = PR_TRUE; } else { - if (verbose) printf("env: PR_SetEnv() worked.\n"); + if (verbose) { + printf("env: PR_SetEnv() worked.\n"); + } } value = PR_GetEnv( ENVNAME ); if ( (NULL == value ) || (strcmp( value, ENVVALUE))) { - if (debug) printf( "env: PR_GetEnv() Failed after setting\n" ); + if (debug) { + printf( "env: PR_GetEnv() Failed after setting\n" ); + } failedAlready = PR_TRUE; } else { - if (verbose) printf("env: PR_GetEnv() worked after setting it. Found: %s\n", value ); + if (verbose) { + printf("env: PR_GetEnv() worked after setting it. Found: %s\n", value ); + } } if ( secure ) { @@ -130,10 +152,14 @@ int main(int argc, char **argv) */ value = PR_GetEnvSecure( ENVNAME ); if ( NULL != value ) { - if (debug) printf( "env: PR_GetEnvSecure() failed; expected NULL, found \"%s\"\n", value ); + if (debug) { + printf( "env: PR_GetEnvSecure() failed; expected NULL, found \"%s\"\n", value ); + } failedAlready = PR_TRUE; } else { - if (verbose) printf("env: PR_GetEnvSecure() worked\n" ); + if (verbose) { + printf("env: PR_GetEnvSecure() worked\n" ); + } } } else { /* @@ -142,14 +168,18 @@ int main(int argc, char **argv) */ value = PR_GetEnvSecure( ENVNAME ); if ( (NULL == value ) || (strcmp( value, ENVVALUE))) { - if (debug) printf( "env: PR_GetEnvSecure() Failed after setting\n" ); + if (debug) { + printf( "env: PR_GetEnvSecure() Failed after setting\n" ); + } failedAlready = PR_TRUE; } else { - if (verbose) printf("env: PR_GetEnvSecure() worked after setting it. Found: %s\n", value ); + if (verbose) { + printf("env: PR_GetEnvSecure() worked after setting it. Found: %s\n", value ); + } } } -/* ---------------------------------------------------------------------- */ + /* ---------------------------------------------------------------------- */ /* check that PR_DuplicateEnvironment() agrees with PR_GetEnv() */ { #if defined(XP_UNIX) && (!defined(DARWIN) || defined(HAVE_CRT_EXTERNS_H)) @@ -163,9 +193,11 @@ int main(int argc, char **argv) if ( NULL == dupenv ) { if (expect_failure) { if (verbose) printf("env: PR_DuplicateEnvironment failed, " - "as expected on this platform.\n"); + "as expected on this platform.\n"); } else { - if (debug) printf("env: PR_DuplicateEnvironment() failed.\n"); + if (debug) { + printf("env: PR_DuplicateEnvironment() failed.\n"); + } failedAlready = PR_TRUE; } } else { @@ -173,17 +205,19 @@ int main(int argc, char **argv) if (expect_failure) { if (debug) printf("env: PR_DuplicateEnvironment() succeeded, " - "but failure is expected on this platform.\n"); + "but failure is expected on this platform.\n"); failedAlready = PR_TRUE; } else { - if (verbose) printf("env: PR_DuplicateEnvironment() succeeded.\n"); + if (verbose) { + printf("env: PR_DuplicateEnvironment() succeeded.\n"); + } } for (i = dupenv; *i; i++) { char *equals = strchr(*i, '='); if ( equals == NULL ) { if (debug) printf("env: PR_DuplicateEnvironment() returned a string" - " with no '=': %s\n", *i); + " with no '=': %s\n", *i); failedAlready = PR_TRUE; } else { /* We own this string, so we can temporarily alter it */ @@ -193,23 +227,23 @@ int main(int argc, char **argv) if ( strcmp(*i, ENVNAME) == 0) { found++; if (verbose) printf("env: PR_DuplicateEnvironment() found " ENVNAME - " (%u so far).\n", found); + " (%u so far).\n", found); } /* Multiple values for the same name can't happen, according to POSIX. */ value = PR_GetEnv(*i); if ( value == NULL ) { if (debug) printf("env: PR_DuplicateEnvironment() returned a name" - " which PR_GetEnv() failed to find: %s\n", *i); + " which PR_GetEnv() failed to find: %s\n", *i); failedAlready = PR_TRUE; } else if ( strcmp(equals + 1, value) != 0) { if (debug) printf("env: PR_DuplicateEnvironment() returned the wrong" - " value for %s: expected %s; found %s\n", - *i, value, equals + 1); + " value for %s: expected %s; found %s\n", + *i, value, equals + 1); failedAlready = PR_TRUE; } else { if (verbose) printf("env: PR_DuplicateEnvironment() agreed with" - " PR_GetEnv() about %s\n", *i); + " PR_GetEnv() about %s\n", *i); } } PR_Free(*i); @@ -218,44 +252,58 @@ int main(int argc, char **argv) if (found != 1) { if (debug) printf("env: PR_DuplicateEnvironment() found %u entries for " ENVNAME - " (expected 1)\n", found); + " (expected 1)\n", found); failedAlready = PR_TRUE; } else { - if (verbose) printf("env: PR_DuplicateEnvironment() found 1 entry for " ENVNAME "\n"); + if (verbose) { + printf("env: PR_DuplicateEnvironment() found 1 entry for " ENVNAME "\n"); + } } } } -/* ---------------------------------------------------------------------- */ + /* ---------------------------------------------------------------------- */ /* un-set the variable, using RAW name... should not work */ envBuf = NewBuffer( ENVBUFSIZE ); sprintf( envBuf, ENVNAME ); rc = PR_SetEnv( envBuf ); if ( PR_FAILURE == rc ) { - if (verbose) printf( "env: PR_SetEnv() not un-set using RAW name. Good!\n"); + if (verbose) { + printf( "env: PR_SetEnv() not un-set using RAW name. Good!\n"); + } } else { - if (debug) printf("env: PR_SetEnv() un-set using RAW name. Bad!\n" ); + if (debug) { + printf("env: PR_SetEnv() un-set using RAW name. Bad!\n" ); + } failedAlready = PR_TRUE; } value = PR_GetEnv( ENVNAME ); if ( NULL == value ) { - if (debug) printf("env: PR_GetEnv() after un-set using RAW name. Bad!\n" ); + if (debug) { + printf("env: PR_GetEnv() after un-set using RAW name. Bad!\n" ); + } failedAlready = PR_TRUE; } else { - if (verbose) printf( "env: PR_GetEnv() after RAW un-set found: %s\n", value ); + if (verbose) { + printf( "env: PR_GetEnv() after RAW un-set found: %s\n", value ); + } } - -/* ---------------------------------------------------------------------- */ + + /* ---------------------------------------------------------------------- */ /* set it again ... */ envBuf = NewBuffer( ENVBUFSIZE ); sprintf( envBuf, ENVNAME "=" ENVVALUE ); rc = PR_SetEnv( envBuf ); if ( PR_FAILURE == rc ) { - if (debug) printf( "env: PR_SetEnv() failed setting the second time.\n"); + if (debug) { + printf( "env: PR_SetEnv() failed setting the second time.\n"); + } failedAlready = PR_TRUE; } else { - if (verbose) printf("env: PR_SetEnv() worked.\n"); + if (verbose) { + printf("env: PR_SetEnv() worked.\n"); + } } /* un-set the variable using the form name= */ @@ -263,41 +311,59 @@ int main(int argc, char **argv) sprintf( envBuf, ENVNAME "=" ); rc = PR_SetEnv( envBuf ); if ( PR_FAILURE == rc ) { - if (debug) printf( "env: PR_SetEnv() failed un-setting using name=\n"); + if (debug) { + printf( "env: PR_SetEnv() failed un-setting using name=\n"); + } failedAlready = PR_TRUE; } else { - if (verbose) printf("env: PR_SetEnv() un-set using name= worked\n" ); + if (verbose) { + printf("env: PR_SetEnv() un-set using name= worked\n" ); + } } value = PR_GetEnv( ENVNAME ); if (( NULL == value ) || ( 0x00 == *value )) { - if (verbose) printf("env: PR_GetEnv() after un-set using name= worked\n" ); + if (verbose) { + printf("env: PR_GetEnv() after un-set using name= worked\n" ); + } } else { - if (debug) printf( "env: PR_GetEnv() after un-set using name=. Found: %s\n", value ); + if (debug) { + printf( "env: PR_GetEnv() after un-set using name=. Found: %s\n", value ); + } failedAlready = PR_TRUE; } -/* ---------------------------------------------------------------------- */ + /* ---------------------------------------------------------------------- */ /* un-set the variable using the form name= */ envBuf = NewBuffer( ENVBUFSIZE ); sprintf( envBuf, ENVNAME "999=" ); rc = PR_SetEnv( envBuf ); if ( PR_FAILURE == rc ) { - if (debug) printf( "env: PR_SetEnv() failed un-setting using name=\n"); + if (debug) { + printf( "env: PR_SetEnv() failed un-setting using name=\n"); + } failedAlready = PR_TRUE; } else { - if (verbose) printf("env: PR_SetEnv() un-set using name= worked\n" ); + if (verbose) { + printf("env: PR_SetEnv() un-set using name= worked\n" ); + } } value = PR_GetEnv( ENVNAME "999" ); if (( NULL == value ) || ( 0x00 == *value )) { - if (verbose) printf("env: PR_GetEnv() after un-set using name= worked\n" ); + if (verbose) { + printf("env: PR_GetEnv() after un-set using name= worked\n" ); + } } else { - if (debug) printf( "env: PR_GetEnv() after un-set using name=. Found: %s\n", value ); + if (debug) { + printf( "env: PR_GetEnv() after un-set using name=. Found: %s\n", value ); + } failedAlready = PR_TRUE; } -/* ---------------------------------------------------------------------- */ - if (debug || verbose) printf("\n%s\n", (failedAlready)? "FAILED" : "PASSED" ); + /* ---------------------------------------------------------------------- */ + if (debug || verbose) { + printf("\n%s\n", (failedAlready)? "FAILED" : "PASSED" ); + } return( (failedAlready)? 1 : 0 ); } /* main() */ diff --git a/nsprpub/pr/tests/errcodes.c b/nsprpub/pr/tests/errcodes.c index 2ef00b247..591b630b2 100644 --- a/nsprpub/pr/tests/errcodes.c +++ b/nsprpub/pr/tests/errcodes.c @@ -18,90 +18,90 @@ static int _debug_on = 0; struct errinfo { - PRErrorCode errcode; - char *errname; + PRErrorCode errcode; + char *errname; }; struct errinfo errcodes[] = { -{PR_OUT_OF_MEMORY_ERROR, "PR_OUT_OF_MEMORY_ERROR"}, -{PR_BAD_DESCRIPTOR_ERROR, "PR_BAD_DESCRIPTOR_ERROR"}, -{PR_WOULD_BLOCK_ERROR, "PR_WOULD_BLOCK_ERROR"}, -{PR_ACCESS_FAULT_ERROR, "PR_ACCESS_FAULT_ERROR"}, -{PR_INVALID_METHOD_ERROR, "PR_INVALID_METHOD_ERROR"}, -{PR_ILLEGAL_ACCESS_ERROR, "PR_ILLEGAL_ACCESS_ERROR"}, -{PR_UNKNOWN_ERROR, "PR_UNKNOWN_ERROR"}, -{PR_PENDING_INTERRUPT_ERROR, "PR_PENDING_INTERRUPT_ERROR"}, -{PR_NOT_IMPLEMENTED_ERROR, "PR_NOT_IMPLEMENTED_ERROR"}, -{PR_IO_ERROR, "PR_IO_ERROR"}, -{PR_IO_TIMEOUT_ERROR, "PR_IO_TIMEOUT_ERROR"}, -{PR_IO_PENDING_ERROR, "PR_IO_PENDING_ERROR"}, -{PR_DIRECTORY_OPEN_ERROR, "PR_DIRECTORY_OPEN_ERROR"}, -{PR_INVALID_ARGUMENT_ERROR, "PR_INVALID_ARGUMENT_ERROR"}, -{PR_ADDRESS_NOT_AVAILABLE_ERROR, "PR_ADDRESS_NOT_AVAILABLE_ERROR"}, -{PR_ADDRESS_NOT_SUPPORTED_ERROR, "PR_ADDRESS_NOT_SUPPORTED_ERROR"}, -{PR_IS_CONNECTED_ERROR, "PR_IS_CONNECTED_ERROR"}, -{PR_BAD_ADDRESS_ERROR, "PR_BAD_ADDRESS_ERROR"}, -{PR_ADDRESS_IN_USE_ERROR, "PR_ADDRESS_IN_USE_ERROR"}, -{PR_CONNECT_REFUSED_ERROR, "PR_CONNECT_REFUSED_ERROR"}, -{PR_NETWORK_UNREACHABLE_ERROR, "PR_NETWORK_UNREACHABLE_ERROR"}, -{PR_CONNECT_TIMEOUT_ERROR, "PR_CONNECT_TIMEOUT_ERROR"}, -{PR_NOT_CONNECTED_ERROR, "PR_NOT_CONNECTED_ERROR"}, -{PR_LOAD_LIBRARY_ERROR, "PR_LOAD_LIBRARY_ERROR"}, -{PR_UNLOAD_LIBRARY_ERROR, "PR_UNLOAD_LIBRARY_ERROR"}, -{PR_FIND_SYMBOL_ERROR, "PR_FIND_SYMBOL_ERROR"}, -{PR_INSUFFICIENT_RESOURCES_ERROR, "PR_INSUFFICIENT_RESOURCES_ERROR"}, -{PR_DIRECTORY_LOOKUP_ERROR, "PR_DIRECTORY_LOOKUP_ERROR"}, -{PR_TPD_RANGE_ERROR, "PR_TPD_RANGE_ERROR"}, -{PR_PROC_DESC_TABLE_FULL_ERROR, "PR_PROC_DESC_TABLE_FULL_ERROR"}, -{PR_SYS_DESC_TABLE_FULL_ERROR, "PR_SYS_DESC_TABLE_FULL_ERROR"}, -{PR_NOT_SOCKET_ERROR, "PR_NOT_SOCKET_ERROR"}, -{PR_NOT_TCP_SOCKET_ERROR, "PR_NOT_TCP_SOCKET_ERROR"}, -{PR_SOCKET_ADDRESS_IS_BOUND_ERROR, "PR_SOCKET_ADDRESS_IS_BOUND_ERROR"}, -{PR_NO_ACCESS_RIGHTS_ERROR, "PR_NO_ACCESS_RIGHTS_ERROR"}, -{PR_OPERATION_NOT_SUPPORTED_ERROR, "PR_OPERATION_NOT_SUPPORTED_ERROR"}, -{PR_PROTOCOL_NOT_SUPPORTED_ERROR, "PR_PROTOCOL_NOT_SUPPORTED_ERROR"}, -{PR_REMOTE_FILE_ERROR, "PR_REMOTE_FILE_ERROR"}, -{PR_BUFFER_OVERFLOW_ERROR, "PR_BUFFER_OVERFLOW_ERROR"}, -{PR_CONNECT_RESET_ERROR, "PR_CONNECT_RESET_ERROR"}, -{PR_RANGE_ERROR, "PR_RANGE_ERROR"}, -{PR_DEADLOCK_ERROR, "PR_DEADLOCK_ERROR"}, -{PR_FILE_IS_LOCKED_ERROR, "PR_FILE_IS_LOCKED_ERROR"}, -{PR_FILE_TOO_BIG_ERROR, "PR_FILE_TOO_BIG_ERROR"}, -{PR_NO_DEVICE_SPACE_ERROR, "PR_NO_DEVICE_SPACE_ERROR"}, -{PR_PIPE_ERROR, "PR_PIPE_ERROR"}, -{PR_NO_SEEK_DEVICE_ERROR, "PR_NO_SEEK_DEVICE_ERROR"}, -{PR_IS_DIRECTORY_ERROR, "PR_IS_DIRECTORY_ERROR"}, -{PR_LOOP_ERROR, "PR_LOOP_ERROR"}, -{PR_NAME_TOO_LONG_ERROR, "PR_NAME_TOO_LONG_ERROR"}, -{PR_FILE_NOT_FOUND_ERROR, "PR_FILE_NOT_FOUND_ERROR"}, -{PR_NOT_DIRECTORY_ERROR, "PR_NOT_DIRECTORY_ERROR"}, -{PR_READ_ONLY_FILESYSTEM_ERROR, "PR_READ_ONLY_FILESYSTEM_ERROR"}, -{PR_DIRECTORY_NOT_EMPTY_ERROR, "PR_DIRECTORY_NOT_EMPTY_ERROR"}, -{PR_FILESYSTEM_MOUNTED_ERROR, "PR_FILESYSTEM_MOUNTED_ERROR"}, -{PR_NOT_SAME_DEVICE_ERROR, "PR_NOT_SAME_DEVICE_ERROR"}, -{PR_DIRECTORY_CORRUPTED_ERROR, "PR_DIRECTORY_CORRUPTED_ERROR"}, -{PR_FILE_EXISTS_ERROR, "PR_FILE_EXISTS_ERROR"}, -{PR_MAX_DIRECTORY_ENTRIES_ERROR, "PR_MAX_DIRECTORY_ENTRIES_ERROR"}, -{PR_INVALID_DEVICE_STATE_ERROR, "PR_INVALID_DEVICE_STATE_ERROR"}, -{PR_DEVICE_IS_LOCKED_ERROR, "PR_DEVICE_IS_LOCKED_ERROR"}, -{PR_NO_MORE_FILES_ERROR, "PR_NO_MORE_FILES_ERROR"}, -{PR_END_OF_FILE_ERROR, "PR_END_OF_FILE_ERROR"}, -{PR_FILE_SEEK_ERROR, "PR_FILE_SEEK_ERROR"}, -{PR_FILE_IS_BUSY_ERROR, "PR_FILE_IS_BUSY_ERROR"}, -{PR_IN_PROGRESS_ERROR, "PR_IN_PROGRESS_ERROR"}, -{PR_ALREADY_INITIATED_ERROR, "PR_ALREADY_INITIATED_ERROR"}, -{PR_GROUP_EMPTY_ERROR, "PR_GROUP_EMPTY_ERROR"}, -{PR_INVALID_STATE_ERROR, "PR_INVALID_STATE_ERROR"}, -{PR_NETWORK_DOWN_ERROR, "PR_NETWORK_DOWN_ERROR"}, -{PR_SOCKET_SHUTDOWN_ERROR, "PR_SOCKET_SHUTDOWN_ERROR"}, -{PR_CONNECT_ABORTED_ERROR, "PR_CONNECT_ABORTED_ERROR"}, -{PR_HOST_UNREACHABLE_ERROR, "PR_HOST_UNREACHABLE_ERROR"} + {PR_OUT_OF_MEMORY_ERROR, "PR_OUT_OF_MEMORY_ERROR"}, + {PR_BAD_DESCRIPTOR_ERROR, "PR_BAD_DESCRIPTOR_ERROR"}, + {PR_WOULD_BLOCK_ERROR, "PR_WOULD_BLOCK_ERROR"}, + {PR_ACCESS_FAULT_ERROR, "PR_ACCESS_FAULT_ERROR"}, + {PR_INVALID_METHOD_ERROR, "PR_INVALID_METHOD_ERROR"}, + {PR_ILLEGAL_ACCESS_ERROR, "PR_ILLEGAL_ACCESS_ERROR"}, + {PR_UNKNOWN_ERROR, "PR_UNKNOWN_ERROR"}, + {PR_PENDING_INTERRUPT_ERROR, "PR_PENDING_INTERRUPT_ERROR"}, + {PR_NOT_IMPLEMENTED_ERROR, "PR_NOT_IMPLEMENTED_ERROR"}, + {PR_IO_ERROR, "PR_IO_ERROR"}, + {PR_IO_TIMEOUT_ERROR, "PR_IO_TIMEOUT_ERROR"}, + {PR_IO_PENDING_ERROR, "PR_IO_PENDING_ERROR"}, + {PR_DIRECTORY_OPEN_ERROR, "PR_DIRECTORY_OPEN_ERROR"}, + {PR_INVALID_ARGUMENT_ERROR, "PR_INVALID_ARGUMENT_ERROR"}, + {PR_ADDRESS_NOT_AVAILABLE_ERROR, "PR_ADDRESS_NOT_AVAILABLE_ERROR"}, + {PR_ADDRESS_NOT_SUPPORTED_ERROR, "PR_ADDRESS_NOT_SUPPORTED_ERROR"}, + {PR_IS_CONNECTED_ERROR, "PR_IS_CONNECTED_ERROR"}, + {PR_BAD_ADDRESS_ERROR, "PR_BAD_ADDRESS_ERROR"}, + {PR_ADDRESS_IN_USE_ERROR, "PR_ADDRESS_IN_USE_ERROR"}, + {PR_CONNECT_REFUSED_ERROR, "PR_CONNECT_REFUSED_ERROR"}, + {PR_NETWORK_UNREACHABLE_ERROR, "PR_NETWORK_UNREACHABLE_ERROR"}, + {PR_CONNECT_TIMEOUT_ERROR, "PR_CONNECT_TIMEOUT_ERROR"}, + {PR_NOT_CONNECTED_ERROR, "PR_NOT_CONNECTED_ERROR"}, + {PR_LOAD_LIBRARY_ERROR, "PR_LOAD_LIBRARY_ERROR"}, + {PR_UNLOAD_LIBRARY_ERROR, "PR_UNLOAD_LIBRARY_ERROR"}, + {PR_FIND_SYMBOL_ERROR, "PR_FIND_SYMBOL_ERROR"}, + {PR_INSUFFICIENT_RESOURCES_ERROR, "PR_INSUFFICIENT_RESOURCES_ERROR"}, + {PR_DIRECTORY_LOOKUP_ERROR, "PR_DIRECTORY_LOOKUP_ERROR"}, + {PR_TPD_RANGE_ERROR, "PR_TPD_RANGE_ERROR"}, + {PR_PROC_DESC_TABLE_FULL_ERROR, "PR_PROC_DESC_TABLE_FULL_ERROR"}, + {PR_SYS_DESC_TABLE_FULL_ERROR, "PR_SYS_DESC_TABLE_FULL_ERROR"}, + {PR_NOT_SOCKET_ERROR, "PR_NOT_SOCKET_ERROR"}, + {PR_NOT_TCP_SOCKET_ERROR, "PR_NOT_TCP_SOCKET_ERROR"}, + {PR_SOCKET_ADDRESS_IS_BOUND_ERROR, "PR_SOCKET_ADDRESS_IS_BOUND_ERROR"}, + {PR_NO_ACCESS_RIGHTS_ERROR, "PR_NO_ACCESS_RIGHTS_ERROR"}, + {PR_OPERATION_NOT_SUPPORTED_ERROR, "PR_OPERATION_NOT_SUPPORTED_ERROR"}, + {PR_PROTOCOL_NOT_SUPPORTED_ERROR, "PR_PROTOCOL_NOT_SUPPORTED_ERROR"}, + {PR_REMOTE_FILE_ERROR, "PR_REMOTE_FILE_ERROR"}, + {PR_BUFFER_OVERFLOW_ERROR, "PR_BUFFER_OVERFLOW_ERROR"}, + {PR_CONNECT_RESET_ERROR, "PR_CONNECT_RESET_ERROR"}, + {PR_RANGE_ERROR, "PR_RANGE_ERROR"}, + {PR_DEADLOCK_ERROR, "PR_DEADLOCK_ERROR"}, + {PR_FILE_IS_LOCKED_ERROR, "PR_FILE_IS_LOCKED_ERROR"}, + {PR_FILE_TOO_BIG_ERROR, "PR_FILE_TOO_BIG_ERROR"}, + {PR_NO_DEVICE_SPACE_ERROR, "PR_NO_DEVICE_SPACE_ERROR"}, + {PR_PIPE_ERROR, "PR_PIPE_ERROR"}, + {PR_NO_SEEK_DEVICE_ERROR, "PR_NO_SEEK_DEVICE_ERROR"}, + {PR_IS_DIRECTORY_ERROR, "PR_IS_DIRECTORY_ERROR"}, + {PR_LOOP_ERROR, "PR_LOOP_ERROR"}, + {PR_NAME_TOO_LONG_ERROR, "PR_NAME_TOO_LONG_ERROR"}, + {PR_FILE_NOT_FOUND_ERROR, "PR_FILE_NOT_FOUND_ERROR"}, + {PR_NOT_DIRECTORY_ERROR, "PR_NOT_DIRECTORY_ERROR"}, + {PR_READ_ONLY_FILESYSTEM_ERROR, "PR_READ_ONLY_FILESYSTEM_ERROR"}, + {PR_DIRECTORY_NOT_EMPTY_ERROR, "PR_DIRECTORY_NOT_EMPTY_ERROR"}, + {PR_FILESYSTEM_MOUNTED_ERROR, "PR_FILESYSTEM_MOUNTED_ERROR"}, + {PR_NOT_SAME_DEVICE_ERROR, "PR_NOT_SAME_DEVICE_ERROR"}, + {PR_DIRECTORY_CORRUPTED_ERROR, "PR_DIRECTORY_CORRUPTED_ERROR"}, + {PR_FILE_EXISTS_ERROR, "PR_FILE_EXISTS_ERROR"}, + {PR_MAX_DIRECTORY_ENTRIES_ERROR, "PR_MAX_DIRECTORY_ENTRIES_ERROR"}, + {PR_INVALID_DEVICE_STATE_ERROR, "PR_INVALID_DEVICE_STATE_ERROR"}, + {PR_DEVICE_IS_LOCKED_ERROR, "PR_DEVICE_IS_LOCKED_ERROR"}, + {PR_NO_MORE_FILES_ERROR, "PR_NO_MORE_FILES_ERROR"}, + {PR_END_OF_FILE_ERROR, "PR_END_OF_FILE_ERROR"}, + {PR_FILE_SEEK_ERROR, "PR_FILE_SEEK_ERROR"}, + {PR_FILE_IS_BUSY_ERROR, "PR_FILE_IS_BUSY_ERROR"}, + {PR_IN_PROGRESS_ERROR, "PR_IN_PROGRESS_ERROR"}, + {PR_ALREADY_INITIATED_ERROR, "PR_ALREADY_INITIATED_ERROR"}, + {PR_GROUP_EMPTY_ERROR, "PR_GROUP_EMPTY_ERROR"}, + {PR_INVALID_STATE_ERROR, "PR_INVALID_STATE_ERROR"}, + {PR_NETWORK_DOWN_ERROR, "PR_NETWORK_DOWN_ERROR"}, + {PR_SOCKET_SHUTDOWN_ERROR, "PR_SOCKET_SHUTDOWN_ERROR"}, + {PR_CONNECT_ABORTED_ERROR, "PR_CONNECT_ABORTED_ERROR"}, + {PR_HOST_UNREACHABLE_ERROR, "PR_HOST_UNREACHABLE_ERROR"} }; int main(int argc, char **argv) { - int count, errnum; + int count, errnum; /* * -d debug mode @@ -111,24 +111,26 @@ int main(int argc, char **argv) PLOptState *opt = PL_CreateOptState(argc, argv, "d"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - _debug_on = 1; - break; - default: - break; + case 'd': /* debug mode */ + _debug_on = 1; + break; + default: + break; } } PL_DestroyOptState(opt); - count = sizeof(errcodes)/sizeof(errcodes[0]); - printf("\nNumber of error codes = %d\n\n",count); - for (errnum = 0; errnum < count; errnum++) { - printf("%-40s = %d\n",errcodes[errnum].errname, - errcodes[errnum].errcode); - } + count = sizeof(errcodes)/sizeof(errcodes[0]); + printf("\nNumber of error codes = %d\n\n",count); + for (errnum = 0; errnum < count; errnum++) { + printf("%-40s = %d\n",errcodes[errnum].errname, + errcodes[errnum].errcode); + } - return 0; + return 0; } diff --git a/nsprpub/pr/tests/errset.c b/nsprpub/pr/tests/errset.c index b0e924879..fb76a6fa9 100644 --- a/nsprpub/pr/tests/errset.c +++ b/nsprpub/pr/tests/errset.c @@ -25,91 +25,91 @@ static int _debug_on = 0; struct errinfo { - PRErrorCode errcode; - char *errname; + PRErrorCode errcode; + char *errname; }; struct errinfo errcodes[] = { -{PR_OUT_OF_MEMORY_ERROR, "PR_OUT_OF_MEMORY_ERROR"}, -{PR_UNKNOWN_ERROR, "An intentionally long error message text intended to force a delete of the current errorString buffer and get another one."}, -{PR_BAD_DESCRIPTOR_ERROR, "PR_BAD_DESCRIPTOR_ERROR"}, -{PR_WOULD_BLOCK_ERROR, "PR_WOULD_BLOCK_ERROR"}, -{PR_ACCESS_FAULT_ERROR, "PR_ACCESS_FAULT_ERROR"}, -{PR_INVALID_METHOD_ERROR, "PR_INVALID_METHOD_ERROR"}, -{PR_ILLEGAL_ACCESS_ERROR, "PR_ILLEGAL_ACCESS_ERROR"}, -{PR_UNKNOWN_ERROR, "PR_UNKNOWN_ERROR"}, -{PR_PENDING_INTERRUPT_ERROR, "PR_PENDING_INTERRUPT_ERROR"}, -{PR_NOT_IMPLEMENTED_ERROR, "PR_NOT_IMPLEMENTED_ERROR"}, -{PR_IO_ERROR, "PR_IO_ERROR"}, -{PR_IO_TIMEOUT_ERROR, "PR_IO_TIMEOUT_ERROR"}, -{PR_IO_PENDING_ERROR, "PR_IO_PENDING_ERROR"}, -{PR_DIRECTORY_OPEN_ERROR, "PR_DIRECTORY_OPEN_ERROR"}, -{PR_INVALID_ARGUMENT_ERROR, "PR_INVALID_ARGUMENT_ERROR"}, -{PR_ADDRESS_NOT_AVAILABLE_ERROR, "PR_ADDRESS_NOT_AVAILABLE_ERROR"}, -{PR_ADDRESS_NOT_SUPPORTED_ERROR, "PR_ADDRESS_NOT_SUPPORTED_ERROR"}, -{PR_IS_CONNECTED_ERROR, "PR_IS_CONNECTED_ERROR"}, -{PR_BAD_ADDRESS_ERROR, "PR_BAD_ADDRESS_ERROR"}, -{PR_ADDRESS_IN_USE_ERROR, "PR_ADDRESS_IN_USE_ERROR"}, -{PR_CONNECT_REFUSED_ERROR, "PR_CONNECT_REFUSED_ERROR"}, -{PR_NETWORK_UNREACHABLE_ERROR, "PR_NETWORK_UNREACHABLE_ERROR"}, -{PR_CONNECT_TIMEOUT_ERROR, "PR_CONNECT_TIMEOUT_ERROR"}, -{PR_NOT_CONNECTED_ERROR, "PR_NOT_CONNECTED_ERROR"}, -{PR_LOAD_LIBRARY_ERROR, "PR_LOAD_LIBRARY_ERROR"}, -{PR_UNLOAD_LIBRARY_ERROR, "PR_UNLOAD_LIBRARY_ERROR"}, -{PR_FIND_SYMBOL_ERROR, "PR_FIND_SYMBOL_ERROR"}, -{PR_INSUFFICIENT_RESOURCES_ERROR, "PR_INSUFFICIENT_RESOURCES_ERROR"}, -{PR_DIRECTORY_LOOKUP_ERROR, "PR_DIRECTORY_LOOKUP_ERROR"}, -{PR_TPD_RANGE_ERROR, "PR_TPD_RANGE_ERROR"}, -{PR_PROC_DESC_TABLE_FULL_ERROR, "PR_PROC_DESC_TABLE_FULL_ERROR"}, -{PR_SYS_DESC_TABLE_FULL_ERROR, "PR_SYS_DESC_TABLE_FULL_ERROR"}, -{PR_NOT_SOCKET_ERROR, "PR_NOT_SOCKET_ERROR"}, -{PR_NOT_TCP_SOCKET_ERROR, "PR_NOT_TCP_SOCKET_ERROR"}, -{PR_SOCKET_ADDRESS_IS_BOUND_ERROR, "PR_SOCKET_ADDRESS_IS_BOUND_ERROR"}, -{PR_NO_ACCESS_RIGHTS_ERROR, "PR_NO_ACCESS_RIGHTS_ERROR"}, -{PR_OPERATION_NOT_SUPPORTED_ERROR, "PR_OPERATION_NOT_SUPPORTED_ERROR"}, -{PR_PROTOCOL_NOT_SUPPORTED_ERROR, "PR_PROTOCOL_NOT_SUPPORTED_ERROR"}, -{PR_REMOTE_FILE_ERROR, "PR_REMOTE_FILE_ERROR"}, -{PR_BUFFER_OVERFLOW_ERROR, "PR_BUFFER_OVERFLOW_ERROR"}, -{PR_CONNECT_RESET_ERROR, "PR_CONNECT_RESET_ERROR"}, -{PR_RANGE_ERROR, "PR_RANGE_ERROR"}, -{PR_DEADLOCK_ERROR, "PR_DEADLOCK_ERROR"}, -{PR_FILE_IS_LOCKED_ERROR, "PR_FILE_IS_LOCKED_ERROR"}, -{PR_FILE_TOO_BIG_ERROR, "PR_FILE_TOO_BIG_ERROR"}, -{PR_NO_DEVICE_SPACE_ERROR, "PR_NO_DEVICE_SPACE_ERROR"}, -{PR_PIPE_ERROR, "PR_PIPE_ERROR"}, -{PR_NO_SEEK_DEVICE_ERROR, "PR_NO_SEEK_DEVICE_ERROR"}, -{PR_IS_DIRECTORY_ERROR, "PR_IS_DIRECTORY_ERROR"}, -{PR_LOOP_ERROR, "PR_LOOP_ERROR"}, -{PR_NAME_TOO_LONG_ERROR, "PR_NAME_TOO_LONG_ERROR"}, -{PR_FILE_NOT_FOUND_ERROR, "PR_FILE_NOT_FOUND_ERROR"}, -{PR_NOT_DIRECTORY_ERROR, "PR_NOT_DIRECTORY_ERROR"}, -{PR_READ_ONLY_FILESYSTEM_ERROR, "PR_READ_ONLY_FILESYSTEM_ERROR"}, -{PR_DIRECTORY_NOT_EMPTY_ERROR, "PR_DIRECTORY_NOT_EMPTY_ERROR"}, -{PR_FILESYSTEM_MOUNTED_ERROR, "PR_FILESYSTEM_MOUNTED_ERROR"}, -{PR_NOT_SAME_DEVICE_ERROR, "PR_NOT_SAME_DEVICE_ERROR"}, -{PR_DIRECTORY_CORRUPTED_ERROR, "PR_DIRECTORY_CORRUPTED_ERROR"}, -{PR_FILE_EXISTS_ERROR, "PR_FILE_EXISTS_ERROR"}, -{PR_MAX_DIRECTORY_ENTRIES_ERROR, "PR_MAX_DIRECTORY_ENTRIES_ERROR"}, -{PR_INVALID_DEVICE_STATE_ERROR, "PR_INVALID_DEVICE_STATE_ERROR"}, -{PR_DEVICE_IS_LOCKED_ERROR, "PR_DEVICE_IS_LOCKED_ERROR"}, -{PR_NO_MORE_FILES_ERROR, "PR_NO_MORE_FILES_ERROR"}, -{PR_END_OF_FILE_ERROR, "PR_END_OF_FILE_ERROR"}, -{PR_FILE_SEEK_ERROR, "PR_FILE_SEEK_ERROR"}, -{PR_FILE_IS_BUSY_ERROR, "PR_FILE_IS_BUSY_ERROR"}, -{PR_IN_PROGRESS_ERROR, "PR_IN_PROGRESS_ERROR"}, -{PR_ALREADY_INITIATED_ERROR, "PR_ALREADY_INITIATED_ERROR"}, -{PR_GROUP_EMPTY_ERROR, "PR_GROUP_EMPTY_ERROR"}, -{PR_INVALID_STATE_ERROR, "PR_INVALID_STATE_ERROR"}, -{PR_NETWORK_DOWN_ERROR, "PR_NETWORK_DOWN_ERROR"}, -{PR_SOCKET_SHUTDOWN_ERROR, "PR_SOCKET_SHUTDOWN_ERROR"}, -{PR_CONNECT_ABORTED_ERROR, "PR_CONNECT_ABORTED_ERROR"}, -{PR_HOST_UNREACHABLE_ERROR, "PR_HOST_UNREACHABLE_ERROR"} + {PR_OUT_OF_MEMORY_ERROR, "PR_OUT_OF_MEMORY_ERROR"}, + {PR_UNKNOWN_ERROR, "An intentionally long error message text intended to force a delete of the current errorString buffer and get another one."}, + {PR_BAD_DESCRIPTOR_ERROR, "PR_BAD_DESCRIPTOR_ERROR"}, + {PR_WOULD_BLOCK_ERROR, "PR_WOULD_BLOCK_ERROR"}, + {PR_ACCESS_FAULT_ERROR, "PR_ACCESS_FAULT_ERROR"}, + {PR_INVALID_METHOD_ERROR, "PR_INVALID_METHOD_ERROR"}, + {PR_ILLEGAL_ACCESS_ERROR, "PR_ILLEGAL_ACCESS_ERROR"}, + {PR_UNKNOWN_ERROR, "PR_UNKNOWN_ERROR"}, + {PR_PENDING_INTERRUPT_ERROR, "PR_PENDING_INTERRUPT_ERROR"}, + {PR_NOT_IMPLEMENTED_ERROR, "PR_NOT_IMPLEMENTED_ERROR"}, + {PR_IO_ERROR, "PR_IO_ERROR"}, + {PR_IO_TIMEOUT_ERROR, "PR_IO_TIMEOUT_ERROR"}, + {PR_IO_PENDING_ERROR, "PR_IO_PENDING_ERROR"}, + {PR_DIRECTORY_OPEN_ERROR, "PR_DIRECTORY_OPEN_ERROR"}, + {PR_INVALID_ARGUMENT_ERROR, "PR_INVALID_ARGUMENT_ERROR"}, + {PR_ADDRESS_NOT_AVAILABLE_ERROR, "PR_ADDRESS_NOT_AVAILABLE_ERROR"}, + {PR_ADDRESS_NOT_SUPPORTED_ERROR, "PR_ADDRESS_NOT_SUPPORTED_ERROR"}, + {PR_IS_CONNECTED_ERROR, "PR_IS_CONNECTED_ERROR"}, + {PR_BAD_ADDRESS_ERROR, "PR_BAD_ADDRESS_ERROR"}, + {PR_ADDRESS_IN_USE_ERROR, "PR_ADDRESS_IN_USE_ERROR"}, + {PR_CONNECT_REFUSED_ERROR, "PR_CONNECT_REFUSED_ERROR"}, + {PR_NETWORK_UNREACHABLE_ERROR, "PR_NETWORK_UNREACHABLE_ERROR"}, + {PR_CONNECT_TIMEOUT_ERROR, "PR_CONNECT_TIMEOUT_ERROR"}, + {PR_NOT_CONNECTED_ERROR, "PR_NOT_CONNECTED_ERROR"}, + {PR_LOAD_LIBRARY_ERROR, "PR_LOAD_LIBRARY_ERROR"}, + {PR_UNLOAD_LIBRARY_ERROR, "PR_UNLOAD_LIBRARY_ERROR"}, + {PR_FIND_SYMBOL_ERROR, "PR_FIND_SYMBOL_ERROR"}, + {PR_INSUFFICIENT_RESOURCES_ERROR, "PR_INSUFFICIENT_RESOURCES_ERROR"}, + {PR_DIRECTORY_LOOKUP_ERROR, "PR_DIRECTORY_LOOKUP_ERROR"}, + {PR_TPD_RANGE_ERROR, "PR_TPD_RANGE_ERROR"}, + {PR_PROC_DESC_TABLE_FULL_ERROR, "PR_PROC_DESC_TABLE_FULL_ERROR"}, + {PR_SYS_DESC_TABLE_FULL_ERROR, "PR_SYS_DESC_TABLE_FULL_ERROR"}, + {PR_NOT_SOCKET_ERROR, "PR_NOT_SOCKET_ERROR"}, + {PR_NOT_TCP_SOCKET_ERROR, "PR_NOT_TCP_SOCKET_ERROR"}, + {PR_SOCKET_ADDRESS_IS_BOUND_ERROR, "PR_SOCKET_ADDRESS_IS_BOUND_ERROR"}, + {PR_NO_ACCESS_RIGHTS_ERROR, "PR_NO_ACCESS_RIGHTS_ERROR"}, + {PR_OPERATION_NOT_SUPPORTED_ERROR, "PR_OPERATION_NOT_SUPPORTED_ERROR"}, + {PR_PROTOCOL_NOT_SUPPORTED_ERROR, "PR_PROTOCOL_NOT_SUPPORTED_ERROR"}, + {PR_REMOTE_FILE_ERROR, "PR_REMOTE_FILE_ERROR"}, + {PR_BUFFER_OVERFLOW_ERROR, "PR_BUFFER_OVERFLOW_ERROR"}, + {PR_CONNECT_RESET_ERROR, "PR_CONNECT_RESET_ERROR"}, + {PR_RANGE_ERROR, "PR_RANGE_ERROR"}, + {PR_DEADLOCK_ERROR, "PR_DEADLOCK_ERROR"}, + {PR_FILE_IS_LOCKED_ERROR, "PR_FILE_IS_LOCKED_ERROR"}, + {PR_FILE_TOO_BIG_ERROR, "PR_FILE_TOO_BIG_ERROR"}, + {PR_NO_DEVICE_SPACE_ERROR, "PR_NO_DEVICE_SPACE_ERROR"}, + {PR_PIPE_ERROR, "PR_PIPE_ERROR"}, + {PR_NO_SEEK_DEVICE_ERROR, "PR_NO_SEEK_DEVICE_ERROR"}, + {PR_IS_DIRECTORY_ERROR, "PR_IS_DIRECTORY_ERROR"}, + {PR_LOOP_ERROR, "PR_LOOP_ERROR"}, + {PR_NAME_TOO_LONG_ERROR, "PR_NAME_TOO_LONG_ERROR"}, + {PR_FILE_NOT_FOUND_ERROR, "PR_FILE_NOT_FOUND_ERROR"}, + {PR_NOT_DIRECTORY_ERROR, "PR_NOT_DIRECTORY_ERROR"}, + {PR_READ_ONLY_FILESYSTEM_ERROR, "PR_READ_ONLY_FILESYSTEM_ERROR"}, + {PR_DIRECTORY_NOT_EMPTY_ERROR, "PR_DIRECTORY_NOT_EMPTY_ERROR"}, + {PR_FILESYSTEM_MOUNTED_ERROR, "PR_FILESYSTEM_MOUNTED_ERROR"}, + {PR_NOT_SAME_DEVICE_ERROR, "PR_NOT_SAME_DEVICE_ERROR"}, + {PR_DIRECTORY_CORRUPTED_ERROR, "PR_DIRECTORY_CORRUPTED_ERROR"}, + {PR_FILE_EXISTS_ERROR, "PR_FILE_EXISTS_ERROR"}, + {PR_MAX_DIRECTORY_ENTRIES_ERROR, "PR_MAX_DIRECTORY_ENTRIES_ERROR"}, + {PR_INVALID_DEVICE_STATE_ERROR, "PR_INVALID_DEVICE_STATE_ERROR"}, + {PR_DEVICE_IS_LOCKED_ERROR, "PR_DEVICE_IS_LOCKED_ERROR"}, + {PR_NO_MORE_FILES_ERROR, "PR_NO_MORE_FILES_ERROR"}, + {PR_END_OF_FILE_ERROR, "PR_END_OF_FILE_ERROR"}, + {PR_FILE_SEEK_ERROR, "PR_FILE_SEEK_ERROR"}, + {PR_FILE_IS_BUSY_ERROR, "PR_FILE_IS_BUSY_ERROR"}, + {PR_IN_PROGRESS_ERROR, "PR_IN_PROGRESS_ERROR"}, + {PR_ALREADY_INITIATED_ERROR, "PR_ALREADY_INITIATED_ERROR"}, + {PR_GROUP_EMPTY_ERROR, "PR_GROUP_EMPTY_ERROR"}, + {PR_INVALID_STATE_ERROR, "PR_INVALID_STATE_ERROR"}, + {PR_NETWORK_DOWN_ERROR, "PR_NETWORK_DOWN_ERROR"}, + {PR_SOCKET_SHUTDOWN_ERROR, "PR_SOCKET_SHUTDOWN_ERROR"}, + {PR_CONNECT_ABORTED_ERROR, "PR_CONNECT_ABORTED_ERROR"}, + {PR_HOST_UNREACHABLE_ERROR, "PR_HOST_UNREACHABLE_ERROR"} }; int main(int argc, char **argv) { - int count, errnum; + int count, errnum; /* * -d debug mode @@ -119,21 +119,23 @@ int main(int argc, char **argv) PLOptState *opt = PL_CreateOptState(argc, argv, "d"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - _debug_on = 1; - break; - default: - break; + case 'd': /* debug mode */ + _debug_on = 1; + break; + default: + break; } } PL_DestroyOptState(opt); - count = sizeof(errcodes)/sizeof(errcodes[0]); - printf("\nNumber of error codes = %d\n\n",count); - for (errnum = 0; errnum < count; errnum++) { + count = sizeof(errcodes)/sizeof(errcodes[0]); + printf("\nNumber of error codes = %d\n\n",count); + for (errnum = 0; errnum < count; errnum++) { PRInt32 len1, len2, err; char msg[256]; @@ -149,5 +151,5 @@ int main(int argc, char **argv) printf("%5.5d -- %s\n", errnum, msg ); } - return 0; + return 0; } diff --git a/nsprpub/pr/tests/exit.c b/nsprpub/pr/tests/exit.c index 258868dd5..dd3d44427 100644 --- a/nsprpub/pr/tests/exit.c +++ b/nsprpub/pr/tests/exit.c @@ -30,8 +30,9 @@ static void Help(void) static void Dull(void *arg) { PR_Sleep(PR_SecondsToInterval(dally)); - if (verbose && force) + if (verbose && force) { PR_fprintf(err, "If you see this, the test failed\n"); + } } /* Dull */ static PRIntn PR_CALLBACK RealMain(PRIntn argc, char **argv) @@ -43,38 +44,42 @@ static PRIntn PR_CALLBACK RealMain(PRIntn argc, char **argv) while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* verbosity */ - verbose = PR_TRUE; - break; - case 'x': /* force exit */ - force = PR_TRUE; - break; - case 't': /* seconds to dally in child */ - dally = atoi(opt->value); - break; - case 'h': /* user wants some guidance */ - default: - Help(); /* so give him an earful */ - return 2; /* but not a lot else */ + case 'd': /* verbosity */ + verbose = PR_TRUE; + break; + case 'x': /* force exit */ + force = PR_TRUE; + break; + case 't': /* seconds to dally in child */ + dally = atoi(opt->value); + break; + case 'h': /* user wants some guidance */ + default: + Help(); /* so give him an earful */ + return 2; /* but not a lot else */ } } PL_DestroyOptState(opt); - if (0 == dally) dally = 10; + if (0 == dally) { + dally = 10; + } - /* - * Create LOCAL and GLOBAL threads - */ + /* + * Create LOCAL and GLOBAL threads + */ (void)PR_CreateThread( PR_USER_THREAD, Dull, NULL, PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, PR_UNJOINABLE_THREAD, 0); + PR_LOCAL_THREAD, PR_UNJOINABLE_THREAD, 0); (void)PR_CreateThread( PR_USER_THREAD, Dull, NULL, PR_PRIORITY_NORMAL, - PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, 0); + PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, 0); if (verbose) PR_fprintf( @@ -91,14 +96,14 @@ static PRIntn PR_CALLBACK RealMain(PRIntn argc, char **argv) } } return 0; - + } int main(int argc, char **argv) { PRIntn rv; - + PR_STDIO_INIT(); rv = PR_Initialize(RealMain, argc, argv, 0); return rv; diff --git a/nsprpub/pr/tests/fdcach.c b/nsprpub/pr/tests/fdcach.c index 37bec0d83..2fb2e5b81 100644 --- a/nsprpub/pr/tests/fdcach.c +++ b/nsprpub/pr/tests/fdcach.c @@ -55,7 +55,7 @@ int main(int argc, char **argv) if (PR_Close(savefds[i]) == PR_FAILURE) { fprintf(stderr, "PR_Close failed\n"); exit(1); - } + } } /* @@ -79,7 +79,7 @@ int main(int argc, char **argv) if (PR_Close(savefds[i]) == PR_FAILURE) { fprintf(stderr, "PR_Close failed\n"); exit(1); - } + } } /* Switch to the fd stack. */ @@ -109,7 +109,7 @@ int main(int argc, char **argv) if (PR_Close(savefds[i]) == PR_FAILURE) { fprintf(stderr, "PR_Close failed\n"); exit(1); - } + } } /* @@ -132,7 +132,7 @@ int main(int argc, char **argv) if (PR_Close(savefds[i]) == PR_FAILURE) { fprintf(stderr, "PR_Close failed\n"); exit(1); - } + } } /* Switch to the fd cache. */ @@ -157,7 +157,7 @@ int main(int argc, char **argv) if (PR_Close(savefds[i]) == PR_FAILURE) { fprintf(stderr, "PR_Close failed\n"); exit(1); - } + } } for (i = 0; i < numfds; i++) { @@ -175,7 +175,7 @@ int main(int argc, char **argv) if (PR_Close(savefds[i]) == PR_FAILURE) { fprintf(stderr, "PR_Close failed\n"); exit(1); - } + } } /* Switch to the fd stack. */ @@ -200,7 +200,7 @@ int main(int argc, char **argv) if (PR_Close(savefds[i]) == PR_FAILURE) { fprintf(stderr, "PR_Close failed\n"); exit(1); - } + } } for (i = 0; i < numfds; i++) { @@ -218,7 +218,7 @@ int main(int argc, char **argv) if (PR_Close(savefds[i]) == PR_FAILURE) { fprintf(stderr, "PR_Close failed\n"); exit(1); - } + } } PR_Cleanup(); diff --git a/nsprpub/pr/tests/fileio.c b/nsprpub/pr/tests/fileio.c index be611a358..a0be3bb10 100644 --- a/nsprpub/pr/tests/fileio.c +++ b/nsprpub/pr/tests/fileio.c @@ -7,16 +7,16 @@ ** ** Name: fileio.c ** -** Description: Program to copy one file to another. +** Description: Program to copy one file to another. ** ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ** 12-June-97 Revert to return code 0 and 1, remove debug option (obsolete). ***********************************************************************/ @@ -47,137 +47,145 @@ PRIntn failed_already=0; PRIntn debug_mode; static void InitialSetup(void) { - PRUintn i; - PRInt32 nWritten, rv; - - t1 = PR_Open("t1.tmp", PR_CREATE_FILE | PR_RDWR, 0); - PR_ASSERT(t1 != NULL); - - for (i=0; i<TBSIZE; i++) - tbuf[i] = i; - - nWritten = PR_Write((PRFileDesc*)t1, tbuf, TBSIZE); - PR_ASSERT(nWritten == TBSIZE); - - rv = PR_Seek(t1,0,PR_SEEK_SET); - PR_ASSERT(rv == 0); - - t2 = PR_Open("t2.tmp", PR_CREATE_FILE | PR_RDWR, 0); - PR_ASSERT(t2 != NULL); + PRUintn i; + PRInt32 nWritten, rv; + + t1 = PR_Open("t1.tmp", PR_CREATE_FILE | PR_RDWR, 0); + PR_ASSERT(t1 != NULL); + + for (i=0; i<TBSIZE; i++) { + tbuf[i] = i; + } + + nWritten = PR_Write((PRFileDesc*)t1, tbuf, TBSIZE); + PR_ASSERT(nWritten == TBSIZE); + + rv = PR_Seek(t1,0,PR_SEEK_SET); + PR_ASSERT(rv == 0); + + t2 = PR_Open("t2.tmp", PR_CREATE_FILE | PR_RDWR, 0); + PR_ASSERT(t2 != NULL); } static void VerifyAndCleanup(void) { - PRUintn i; - PRInt32 nRead, rv; - - for (i=0; i<TBSIZE; i++) - tbuf[i] = 0; - - rv = PR_Seek(t2,0,PR_SEEK_SET); - PR_ASSERT(rv == 0); - - nRead = PR_Read((PRFileDesc*)t2, tbuf, TBSIZE); - PR_ASSERT(nRead == TBSIZE); - - for (i=0; i<TBSIZE; i++) - if (tbuf[i] != (PRUint8)i) { - if (debug_mode) printf("data mismatch for index= %d \n", i); - else failed_already=1; - } - PR_Close(t1); - PR_Close(t2); - - PR_Delete("t1.tmp"); - PR_Delete("t2.tmp"); - - if (debug_mode) printf("fileio test passed\n"); + PRUintn i; + PRInt32 nRead, rv; + + for (i=0; i<TBSIZE; i++) { + tbuf[i] = 0; + } + + rv = PR_Seek(t2,0,PR_SEEK_SET); + PR_ASSERT(rv == 0); + + nRead = PR_Read((PRFileDesc*)t2, tbuf, TBSIZE); + PR_ASSERT(nRead == TBSIZE); + + for (i=0; i<TBSIZE; i++) + if (tbuf[i] != (PRUint8)i) { + if (debug_mode) { + printf("data mismatch for index= %d \n", i); + } + else { + failed_already=1; + } + } + PR_Close(t1); + PR_Close(t2); + + PR_Delete("t1.tmp"); + PR_Delete("t2.tmp"); + + if (debug_mode) { + printf("fileio test passed\n"); + } } /*------------------ Following is the real test program ---------*/ /* - Program to copy one file to another. Two temporary files get - created. First one gets written in one write call. Then, - a reader thread reads from this file into a double buffer. - The writer thread writes from double buffer into the other - temporary file. The second temporary file gets verified - for accurate data. + Program to copy one file to another. Two temporary files get + created. First one gets written in one write call. Then, + a reader thread reads from this file into a double buffer. + The writer thread writes from double buffer into the other + temporary file. The second temporary file gets verified + for accurate data. */ -PRSemaphore *emptyBufs; /* number of empty buffers */ -PRSemaphore *fullBufs; /* number of buffers that are full */ +PRSemaphore *emptyBufs; /* number of empty buffers */ +PRSemaphore *fullBufs; /* number of buffers that are full */ -#define BSIZE 100 +#define BSIZE 100 struct { - char data[BSIZE]; - PRUintn nbytes; /* number of bytes in this buffer */ + char data[BSIZE]; + PRUintn nbytes; /* number of bytes in this buffer */ } buf[2]; static void PR_CALLBACK reader(void *arg) { - PRUintn i = 0; - PRInt32 nbytes; - - do { - (void) PR_WaitSem(emptyBufs); - nbytes = PR_Read((PRFileDesc*)arg, buf[i].data, BSIZE); - if (nbytes >= 0) { - buf[i].nbytes = nbytes; - PR_PostSem(fullBufs); - i = (i + 1) % 2; - } - } while (nbytes > 0); + PRUintn i = 0; + PRInt32 nbytes; + + do { + (void) PR_WaitSem(emptyBufs); + nbytes = PR_Read((PRFileDesc*)arg, buf[i].data, BSIZE); + if (nbytes >= 0) { + buf[i].nbytes = nbytes; + PR_PostSem(fullBufs); + i = (i + 1) % 2; + } + } while (nbytes > 0); } static void PR_CALLBACK writer(void *arg) { - PRUintn i = 0; - PRInt32 nbytes; - - do { - (void) PR_WaitSem(fullBufs); - nbytes = buf[i].nbytes; - if (nbytes > 0) { - nbytes = PR_Write((PRFileDesc*)arg, buf[i].data, nbytes); - PR_PostSem(emptyBufs); - i = (i + 1) % 2; - } - } while (nbytes > 0); + PRUintn i = 0; + PRInt32 nbytes; + + do { + (void) PR_WaitSem(fullBufs); + nbytes = buf[i].nbytes; + if (nbytes > 0) { + nbytes = PR_Write((PRFileDesc*)arg, buf[i].data, nbytes); + PR_PostSem(emptyBufs); + i = (i + 1) % 2; + } + } while (nbytes > 0); } int main(int argc, char **argv) { - PRThread *r, *w; + PRThread *r, *w; - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); + PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); - emptyBufs = PR_NewSem(2); /* two empty buffers */ - - fullBufs = PR_NewSem(0); /* zero full buffers */ - - /* Create initial temp file setup */ - InitialSetup(); - - /* create the reader thread */ - - r = PR_CreateThread(PR_USER_THREAD, - reader, t1, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_JOINABLE_THREAD, - 0); - - w = PR_CreateThread(PR_USER_THREAD, - writer, t2, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_JOINABLE_THREAD, - 0); + emptyBufs = PR_NewSem(2); /* two empty buffers */ + + fullBufs = PR_NewSem(0); /* zero full buffers */ + + /* Create initial temp file setup */ + InitialSetup(); + + /* create the reader thread */ + + r = PR_CreateThread(PR_USER_THREAD, + reader, t1, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_JOINABLE_THREAD, + 0); + + w = PR_CreateThread(PR_USER_THREAD, + writer, t2, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_JOINABLE_THREAD, + 0); /* Do the joining for both threads */ (void) PR_JoinThread(r); diff --git a/nsprpub/pr/tests/foreign.c b/nsprpub/pr/tests/foreign.c index cfb2e56ef..a711b7580 100644 --- a/nsprpub/pr/tests/foreign.c +++ b/nsprpub/pr/tests/foreign.c @@ -13,7 +13,7 @@ ** in. ** ** The goal: try to survive. -** +** */ #include "prcvar.h" @@ -48,9 +48,9 @@ static PRFileDesc *output; static int _debug_on = 0; -#define DEFAULT_THREAD_COUNT 10 +#define DEFAULT_THREAD_COUNT 10 -#define DPRINTF(arg) if (_debug_on) PR_fprintf arg +#define DPRINTF(arg) if (_debug_on) PR_fprintf arg #if defined(_PR_PTHREADS) #include <pthread.h> @@ -65,19 +65,6 @@ static void *pthread_start(void *arg) } /* pthread_start */ #endif /* defined(_PR_PTHREADS) */ -#if defined(IRIX) && !defined(_PR_PTHREADS) -#include <sys/types.h> -#include <sys/prctl.h> -static void sproc_start(void *arg, PRSize size) -{ - StartObject *so = (StartObject*)arg; - StartFn start = so->start; - void *data = so->arg; - PR_Free(so); - start(data); -} /* sproc_start */ -#endif /* defined(IRIX) && !defined(_PR_PTHREADS) */ - #if defined(WIN32) #include <windows.h> #include <process.h> /* for _beginthreadex() */ @@ -99,16 +86,16 @@ static PRStatus NSPRPUB_TESTS_CreateThread(StartFn start, void *arg) switch (thread_provider) { - case thread_nspr: + case thread_nspr: { PRThread *thread = PR_CreateThread( - PR_USER_THREAD, start, arg, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, - PR_UNJOINABLE_THREAD, 0); + PR_USER_THREAD, start, arg, + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, + PR_UNJOINABLE_THREAD, 0); rv = (NULL == thread) ? PR_FAILURE : PR_SUCCESS; } break; - case thread_pthread: + case thread_pthread: #if defined(_PR_PTHREADS) { int rv; @@ -139,41 +126,27 @@ static PRStatus NSPRPUB_TESTS_CreateThread(StartFn start, void *arg) break; #endif /* defined(_PR_PTHREADS) */ - case thread_sproc: -#if defined(IRIX) && !defined(_PR_PTHREADS) - { - PRInt32 pid; - StartObject *start_object; - start_object = PR_NEW(StartObject); - PR_ASSERT(NULL != start_object); - start_object->start = start; - start_object->arg = arg; - pid = sprocsp( - sproc_start, PR_SALL, start_object, NULL, 64 * 1024); - rv = (0 < pid) ? PR_SUCCESS : PR_FAILURE; - } -#else - PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); - rv = PR_FAILURE; -#endif /* defined(IRIX) && !defined(_PR_PTHREADS) */ - break; - case thread_win32: + case thread_sproc: + PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); + rv = PR_FAILURE; + break; + case thread_win32: #if defined(WIN32) { void *th; - PRUintn id; + PRUintn id; StartObject *start_object; start_object = PR_NEW(StartObject); PR_ASSERT(NULL != start_object); start_object->start = start; start_object->arg = arg; th = (void*)_beginthreadex( - NULL, /* LPSECURITY_ATTRIBUTES - pointer to thread security attributes */ - 0U, /* DWORD - initial thread stack size, in bytes */ - windows_start, /* LPTHREAD_START_ROUTINE - pointer to thread function */ - start_object, /* LPVOID - argument for new thread */ - STACK_SIZE_PARAM_IS_A_RESERVATION, /*DWORD dwCreationFlags - creation flags */ - &id /* LPDWORD - pointer to returned thread identifier */ ); + NULL, /* LPSECURITY_ATTRIBUTES - pointer to thread security attributes */ + 0U, /* DWORD - initial thread stack size, in bytes */ + windows_start, /* LPTHREAD_START_ROUTINE - pointer to thread function */ + start_object, /* LPVOID - argument for new thread */ + STACK_SIZE_PARAM_IS_A_RESERVATION, /*DWORD dwCreationFlags - creation flags */ + &id /* LPDWORD - pointer to returned thread identifier */ ); rv = (NULL == th) ? PR_FAILURE : PR_SUCCESS; } @@ -182,9 +155,9 @@ static PRStatus NSPRPUB_TESTS_CreateThread(StartFn start, void *arg) rv = PR_FAILURE; #endif break; - default: - PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); - rv = PR_FAILURE; + default: + PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); + rv = PR_FAILURE; } return rv; } /* NSPRPUB_TESTS_CreateThread */ @@ -204,139 +177,135 @@ static void OneShot(void *arg) PRFileDesc *pair[2]; PRIntn test = (PRIntn)arg; - for (test = 0; test < 12; ++test) { + for (test = 0; test < 12; ++test) { - switch (test) - { - case 0: - lock = PR_NewLock(); - DPRINTF((output,"Thread[0x%x] called PR_NewLock\n", - PR_GetCurrentThread())); - PR_DestroyLock(lock); - break; - - case 1: - (void)PR_SecondsToInterval(1); - DPRINTF((output,"Thread[0x%x] called PR_SecondsToInterval\n", - PR_GetCurrentThread())); - break; - - case 2: (void)PR_CreateThread( - PR_USER_THREAD, lazyEntry, NULL, PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, PR_UNJOINABLE_THREAD, 0); - DPRINTF((output,"Thread[0x%x] called PR_CreateThread\n", - PR_GetCurrentThread())); - break; - - case 3: - fd = PR_Open("foreign.tmp", PR_CREATE_FILE | PR_RDWR, 0666); - DPRINTF((output,"Thread[0x%x] called PR_Open\n", - PR_GetCurrentThread())); - PR_Close(fd); - break; - - case 4: - fd = PR_NewUDPSocket(); - DPRINTF((output,"Thread[0x%x] called PR_NewUDPSocket\n", - PR_GetCurrentThread())); - PR_Close(fd); - break; - - case 5: - fd = PR_NewTCPSocket(); - DPRINTF((output,"Thread[0x%x] called PR_NewTCPSocket\n", - PR_GetCurrentThread())); - PR_Close(fd); - break; - - case 6: -#ifdef SYMBIAN -#define TEMP_DIR "c:\\data\\" -#else + switch (test) + { + case 0: + lock = PR_NewLock(); + DPRINTF((output,"Thread[0x%x] called PR_NewLock\n", + PR_GetCurrentThread())); + PR_DestroyLock(lock); + break; + + case 1: + (void)PR_SecondsToInterval(1); + DPRINTF((output,"Thread[0x%x] called PR_SecondsToInterval\n", + PR_GetCurrentThread())); + break; + + case 2: (void)PR_CreateThread( + PR_USER_THREAD, lazyEntry, NULL, PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, PR_UNJOINABLE_THREAD, 0); + DPRINTF((output,"Thread[0x%x] called PR_CreateThread\n", + PR_GetCurrentThread())); + break; + + case 3: + fd = PR_Open("foreign.tmp", PR_CREATE_FILE | PR_RDWR, 0666); + DPRINTF((output,"Thread[0x%x] called PR_Open\n", + PR_GetCurrentThread())); + PR_Close(fd); + break; + + case 4: + fd = PR_NewUDPSocket(); + DPRINTF((output,"Thread[0x%x] called PR_NewUDPSocket\n", + PR_GetCurrentThread())); + PR_Close(fd); + break; + + case 5: + fd = PR_NewTCPSocket(); + DPRINTF((output,"Thread[0x%x] called PR_NewTCPSocket\n", + PR_GetCurrentThread())); + PR_Close(fd); + break; + + case 6: #define TEMP_DIR "/tmp/" -#endif - dir = PR_OpenDir(TEMP_DIR); - DPRINTF((output,"Thread[0x%x] called PR_OpenDir\n", - PR_GetCurrentThread())); - PR_CloseDir(dir); - break; - - case 7: - (void)PR_NewThreadPrivateIndex(&pdkey, NULL); - DPRINTF((output,"Thread[0x%x] called PR_NewThreadPrivateIndex\n", - PR_GetCurrentThread())); - break; - - case 8: - (void)PR_GetEnv("PATH"); - DPRINTF((output,"Thread[0x%x] called PR_GetEnv\n", - PR_GetCurrentThread())); - break; - - case 9: - (void)PR_NewTCPSocketPair(pair); - DPRINTF((output,"Thread[0x%x] called PR_NewTCPSocketPair\n", - PR_GetCurrentThread())); - PR_Close(pair[0]); - PR_Close(pair[1]); - break; - - case 10: - PR_SetConcurrency(2); - DPRINTF((output,"Thread[0x%x] called PR_SetConcurrency\n", - PR_GetCurrentThread())); - break; - - case 11: - PR_SetThreadPriority(PR_GetCurrentThread(), PR_PRIORITY_HIGH); - DPRINTF((output,"Thread[0x%x] called PR_SetThreadPriority\n", - PR_GetCurrentThread())); - break; - - default: - break; - } /* switch() */ - } + dir = PR_OpenDir(TEMP_DIR); + DPRINTF((output,"Thread[0x%x] called PR_OpenDir\n", + PR_GetCurrentThread())); + PR_CloseDir(dir); + break; + + case 7: + (void)PR_NewThreadPrivateIndex(&pdkey, NULL); + DPRINTF((output,"Thread[0x%x] called PR_NewThreadPrivateIndex\n", + PR_GetCurrentThread())); + break; + + case 8: + (void)PR_GetEnv("PATH"); + DPRINTF((output,"Thread[0x%x] called PR_GetEnv\n", + PR_GetCurrentThread())); + break; + + case 9: + (void)PR_NewTCPSocketPair(pair); + DPRINTF((output,"Thread[0x%x] called PR_NewTCPSocketPair\n", + PR_GetCurrentThread())); + PR_Close(pair[0]); + PR_Close(pair[1]); + break; + + case 10: + PR_SetConcurrency(2); + DPRINTF((output,"Thread[0x%x] called PR_SetConcurrency\n", + PR_GetCurrentThread())); + break; + + case 11: + PR_SetThreadPriority(PR_GetCurrentThread(), PR_PRIORITY_HIGH); + DPRINTF((output,"Thread[0x%x] called PR_SetThreadPriority\n", + PR_GetCurrentThread())); + break; + + default: + break; + } /* switch() */ + } } /* OneShot */ int main(int argc, char **argv) { PRStatus rv; - PRInt32 thread_cnt = DEFAULT_THREAD_COUNT; - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "dt:"); + PRInt32 thread_cnt = DEFAULT_THREAD_COUNT; + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "dt:"); #if defined(WIN32) - thread_provider = thread_win32; + thread_provider = thread_win32; #elif defined(_PR_PTHREADS) - thread_provider = thread_pthread; -#elif defined(IRIX) - thread_provider = thread_sproc; + thread_provider = thread_pthread; #else thread_provider = thread_nspr; #endif - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - _debug_on = 1; - break; - case 't': /* thread count */ - thread_cnt = atoi(opt->value); - break; - default: - break; + case 'd': /* debug mode */ + _debug_on = 1; + break; + case 't': /* thread count */ + thread_cnt = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); - PR_SetConcurrency(2); + PR_SetConcurrency(2); - output = PR_GetSpecialFD(PR_StandardOutput); + output = PR_GetSpecialFD(PR_StandardOutput); while (thread_cnt-- > 0) { diff --git a/nsprpub/pr/tests/forktest.c b/nsprpub/pr/tests/forktest.c index 66dc64575..a6d4bc4bb 100644 --- a/nsprpub/pr/tests/forktest.c +++ b/nsprpub/pr/tests/forktest.c @@ -62,13 +62,13 @@ ClientThreadFunc(void *arg) addr.inet.port = 0; if ((sock = PR_NewTCPSocket()) == NULL) { fprintf(stderr, "failed to create TCP socket: error code %d\n", - PR_GetError()); + PR_GetError()); failed_already = 1; goto finish; } if (PR_Bind(sock, &addr) != PR_SUCCESS) { fprintf(stderr, "PR_Bind failed: error code %d\n", - PR_GetError()); + PR_GetError()); failed_already = 1; goto finish; } @@ -79,7 +79,7 @@ ClientThreadFunc(void *arg) if (PR_Connect(sock, &addr, PR_SecondsToInterval(5)) != PR_SUCCESS) { fprintf(stderr, "PR_Connect failed: error code %d\n", - PR_GetError()); + PR_GetError()); failed_already = 1; goto finish; } @@ -88,7 +88,7 @@ ClientThreadFunc(void *arg) if (PR_Send(sock, message, strlen(message) + 1, 0, PR_INTERVAL_NO_TIMEOUT) == -1) { fprintf(stderr, "PR_Send failed: error code %d\n", - PR_GetError()); + PR_GetError()); failed_already = 1; goto finish; } @@ -117,7 +117,7 @@ DoIO(void) listenSock = PR_NewTCPSocket(); if (!listenSock) { fprintf(stderr, "failed to create a TCP socket: error code %d\n", - PR_GetError()); + PR_GetError()); failed_already = 1; goto finish; } @@ -126,28 +126,28 @@ DoIO(void) addr.inet.port = 0; if (PR_Bind(listenSock, &addr) == PR_FAILURE) { fprintf(stderr, "failed to bind socket: error code %d\n", - PR_GetError()); + PR_GetError()); failed_already = 1; goto finish; } if (PR_GetSockName(listenSock, &addr) == PR_FAILURE) { fprintf(stderr, "failed to get socket port number: error code %d\n", - PR_GetError()); + PR_GetError()); failed_already = 1; goto finish; } if (PR_Listen(listenSock, 5) == PR_FAILURE) { fprintf(stderr, "PR_Listen failed: error code %d\n", - PR_GetError()); + PR_GetError()); failed_already = 1; goto finish; } clientThread = PR_CreateThread( PR_USER_THREAD, ClientThreadFunc, - (void *) PR_ntohs(addr.inet.port), PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, - PR_JOINABLE_THREAD, 0); + (void *) PR_ntohs(addr.inet.port), PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, + PR_JOINABLE_THREAD, 0); if (clientThread == NULL) { fprintf(stderr, "Cannot create client thread: (%d, %d)\n", - PR_GetError(), PR_GetOSError()); + PR_GetError(), PR_GetOSError()); failed_already = 1; goto finish; } @@ -156,20 +156,20 @@ DoIO(void) sock = PR_Accept(listenSock, &addr, PR_SecondsToInterval(5)); if (!sock) { fprintf(stderr, "PR_Accept failed: error code %d\n", - PR_GetError()); + PR_GetError()); failed_already = 1; goto finish; } nBytes = PR_Recv(sock, buf, sizeof(buf), 0, PR_INTERVAL_NO_TIMEOUT); if (nBytes == -1) { fprintf(stderr, "PR_Recv failed: error code %d\n", - PR_GetError()); + PR_GetError()); failed_already = 1; goto finish; } /* - * Make sure it has proper null byte to mark end of string + * Make sure it has proper null byte to mark end of string */ buf[sizeof(buf) - 1] = '\0'; @@ -182,7 +182,7 @@ DoIO(void) fflush(stdout); } else { fprintf(stderr, "The message should be \"%s\"\n", - message); + message); failed_already = 1; } @@ -199,7 +199,6 @@ finish: int main(int argc, char **argv) { pid_t pid; - int rv; /* main test program */ @@ -216,20 +215,13 @@ int main(int argc, char **argv) printf("Fork succeeded. Parent process continues.\n"); DoIO(); - if ((rv = waitpid(pid, &childStatus, 0)) != pid) { -#if defined(IRIX) && !defined(_PR_PTHREADS) - /* - * nspr may handle SIGCLD signal - */ - if ((rv < 0) && (errno == ECHILD)) { - } else -#endif - { - fprintf(stderr, "waitpid failed: %d\n", errno); - failed_already = 1; - } + if (waitpid(pid, &childStatus, 0) != pid) { + { + fprintf(stderr, "waitpid failed: %d\n", errno); + failed_already = 1; + } } else if (!WIFEXITED(childStatus) - || WEXITSTATUS(childStatus) != 0) { + || WEXITSTATUS(childStatus) != 0) { failed_already = 1; } printf("Parent process exits.\n"); @@ -240,10 +232,6 @@ int main(int argc, char **argv) } return failed_already; } else { -#if defined(IRIX) && !defined(_PR_PTHREADS) - extern void _PR_IRIX_CHILD_PROCESS(void); - _PR_IRIX_CHILD_PROCESS(); -#endif printf("Fork succeeded. Child process continues.\n"); DoIO(); printf("Child process exits.\n"); @@ -254,8 +242,8 @@ int main(int argc, char **argv) #else /* XP_UNIX */ int main( int argc, -char *argv[] -) + char *argv[] + ) { printf("The fork test is applicable to Unix only.\n"); diff --git a/nsprpub/pr/tests/formattm.c b/nsprpub/pr/tests/formattm.c index 88b9fdf21..63355b28b 100644 --- a/nsprpub/pr/tests/formattm.c +++ b/nsprpub/pr/tests/formattm.c @@ -20,7 +20,7 @@ int main(int argc, char **argv) PR_ExplodeTime(now, PR_LocalTimeParameters, &tod); if (PR_FormatTime(buffer, sizeof(buffer), - "%a %b %d %H:%M:%S %Z %Y", &tod) != 0) { + "%a %b %d %H:%M:%S %Z %Y", &tod) != 0) { printf("%s\n", buffer); } else { fprintf(stderr, "PR_FormatTime(buffer) failed\n"); @@ -29,21 +29,21 @@ int main(int argc, char **argv) small_buffer[0] = '?'; if (PR_FormatTime(small_buffer, sizeof(small_buffer), - "%a %b %d %H:%M:%S %Z %Y", &tod) == 0) { + "%a %b %d %H:%M:%S %Z %Y", &tod) == 0) { if (small_buffer[0] != '\0') { fprintf(stderr, "PR_FormatTime(small_buffer) did not output " - "an empty string on failure\n"); + "an empty string on failure\n"); return 1; } printf("%s\n", small_buffer); } else { fprintf(stderr, "PR_FormatTime(small_buffer) succeeded " - "unexpectedly\n"); + "unexpectedly\n"); return 1; } (void)PR_FormatTimeUSEnglish(buffer, sizeof(buffer), - "%a %b %d %H:%M:%S %Z %Y", &tod); + "%a %b %d %H:%M:%S %Z %Y", &tod); printf("%s\n", buffer); return 0; diff --git a/nsprpub/pr/tests/freeif.c b/nsprpub/pr/tests/freeif.c index edf005e49..1d38d0e31 100644 --- a/nsprpub/pr/tests/freeif.c +++ b/nsprpub/pr/tests/freeif.c @@ -27,16 +27,20 @@ int main(int argc, char **argv) char *ptr = NULL; /* this fails to compile with the old definition of PR_DELETE */ - if (foo) + if (foo) { PR_DELETE(ptr); - else + } + else { Noop(); + } /* this nests incorrectly with the old definition of PR_FREEIF */ - if (foo) + if (foo) { PR_FREEIF(ptr); - else + } + else { Fail(); + } printf("PASS\n"); return 0; diff --git a/nsprpub/pr/tests/fsync.c b/nsprpub/pr/tests/fsync.c index 01c71c4c6..ee2eeff7d 100644 --- a/nsprpub/pr/tests/fsync.c +++ b/nsprpub/pr/tests/fsync.c @@ -39,25 +39,27 @@ int main(int argc, char **argv) while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 0: /* Name of file to create */ - filename = opt->value; - break; - case 'S': /* Use sych option on file */ - flags |= PR_SYNC; - break; - case 'K': /* Size of file to write */ - filesize = atoi(opt->value); - break; - case 'c': /* Number of iterations */ - iterations = atoi(opt->value); - break; - case 'h': /* user wants some guidance */ - default: /* user needs some guidance */ - Help(); /* so give him an earful */ - return 2; /* but not a lot else */ + case 0: /* Name of file to create */ + filename = opt->value; + break; + case 'S': /* Use sych option on file */ + flags |= PR_SYNC; + break; + case 'K': /* Size of file to write */ + filesize = atoi(opt->value); + break; + case 'c': /* Number of iterations */ + iterations = atoi(opt->value); + break; + case 'h': /* user wants some guidance */ + default: /* user needs some guidance */ + Help(); /* so give him an earful */ + return 2; /* but not a lot else */ } } PL_DestroyOptState(opt); @@ -76,8 +78,9 @@ int main(int argc, char **argv) return 1; } - for (index = 0; index < sizeof(buffer); ++index) + for (index = 0; index < sizeof(buffer); ++index) { buffer[index] = (PRUint8)index; + } for (loops = 0; loops < iterations; ++loops) { @@ -89,12 +92,16 @@ int main(int argc, char **argv) time = (PR_IntervalNow() - time); total += time; - if (time < shortest) shortest = time; - else if (time > longest) longest = time; + if (time < shortest) { + shortest = time; + } + else if (time > longest) { + longest = time; + } if (0 != PR_Seek(file, 0, PR_SEEK_SET)) { - PL_FPrintError(err, "Rewinding file"); - return 1; + PL_FPrintError(err, "Rewinding file"); + return 1; } } diff --git a/nsprpub/pr/tests/getai.c b/nsprpub/pr/tests/getai.c index f398ca3b2..d759ed827 100644 --- a/nsprpub/pr/tests/getai.c +++ b/nsprpub/pr/tests/getai.c @@ -17,7 +17,7 @@ int main(int argc, char **argv) ai = PR_GetAddrInfoByName(argv[1], PR_AF_UNSPEC, PR_AI_ADDRCONFIG); if (ai == NULL) { fprintf(stderr, "PR_GetAddrInfoByName failed: (%d, %d)\n", - PR_GetError(), PR_GetOSError()); + PR_GetError(), PR_GetOSError()); exit(1); } printf("%s\n", PR_GetCanonNameFromAddrInfo(ai)); diff --git a/nsprpub/pr/tests/gethost.c b/nsprpub/pr/tests/gethost.c index 779bce45e..8a15cb61c 100644 --- a/nsprpub/pr/tests/gethost.c +++ b/nsprpub/pr/tests/gethost.c @@ -45,7 +45,9 @@ void PrintHostent(const PRHostEnt *he) for (i = 0; he->h_addr_list[i]; i++) { printf("h_addr_list[%d]: ", i); for (j = 0; j < he->h_length; j++) { - if (j != 0) printf("."); + if (j != 0) { + printf("."); + } printf("%u", (unsigned char)he->h_addr_list[i][j]); } printf("\n"); @@ -64,7 +66,9 @@ int main(int argc, char **argv) PLOptState *opt = PL_CreateOptState(argc, argv, "h"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { case 0: /* naked */ hostName = opt->value; @@ -89,10 +93,12 @@ int main(int argc, char **argv) fprintf(stderr, "PR_EnumerateHostEnt failed\n"); exit(1); } - if (idx == 0) break; /* normal loop termination */ + if (idx == 0) { + break; /* normal loop termination */ + } printf("reverse lookup\n"); if (PR_GetHostByAddr(&addr, reversebuf, sizeof(reversebuf), - &reversehe) == PR_FAILURE) { + &reversehe) == PR_FAILURE) { fprintf(stderr, "PR_GetHostByAddr failed\n"); exit(1); } @@ -101,14 +107,14 @@ int main(int argc, char **argv) printf("PR_GetIPNodeByName with PR_AF_INET\n"); if (PR_GetIPNodeByName(hostName, PR_AF_INET, PR_AI_DEFAULT, - buf, sizeof(buf), &he) == PR_FAILURE) { + buf, sizeof(buf), &he) == PR_FAILURE) { fprintf(stderr, "PR_GetIPNodeByName failed\n"); exit(1); } PrintHostent(&he); printf("PR_GetIPNodeByName with PR_AF_INET6\n"); if (PR_GetIPNodeByName(hostName, PR_AF_INET6, PR_AI_DEFAULT, - buf, sizeof(buf), &he) == PR_FAILURE) { + buf, sizeof(buf), &he) == PR_FAILURE) { fprintf(stderr, "PR_GetIPNodeByName failed\n"); exit(1); } @@ -121,17 +127,19 @@ int main(int argc, char **argv) fprintf(stderr, "PR_EnumerateHostEnt failed\n"); exit(1); } - if (idx == 0) break; /* normal loop termination */ + if (idx == 0) { + break; /* normal loop termination */ + } printf("reverse lookup\n"); if (PR_GetHostByAddr(&addr, reversebuf, sizeof(reversebuf), - &reversehe) == PR_FAILURE) { + &reversehe) == PR_FAILURE) { fprintf(stderr, "PR_GetHostByAddr failed\n"); exit(1); } PrintHostent(&reversehe); } printf("PR_GetHostByAddr with PR_AF_INET6 done\n"); - + PR_StringToNetAddr("::1", &addr); if (PR_IsNetAddrType(&addr, PR_IpAddrV4Mapped) == PR_TRUE) { fprintf(stderr, "addr should not be ipv4 mapped address\n"); @@ -198,11 +206,11 @@ int main(int argc, char **argv) fprintf(stderr, "addr should be unspecified address\n"); exit(1); } - { - char buf[256]; - PR_NetAddrToString(&addr, buf, 256); - printf("IPv4 INADDRANY: %s\n", buf); - } + { + char buf[256]; + PR_NetAddrToString(&addr, buf, 256); + printf("IPv4 INADDRANY: %s\n", buf); + } addr.inet.family = PR_AF_INET; addr.inet.port = 0; addr.inet.ip = PR_htonl(PR_INADDR_LOOPBACK); @@ -210,11 +218,11 @@ int main(int argc, char **argv) fprintf(stderr, "addr should be loopback address\n"); exit(1); } - { - char buf[256]; - PR_NetAddrToString(&addr, buf, 256); - printf("IPv4 LOOPBACK: %s\n", buf); - } + { + char buf[256]; + PR_NetAddrToString(&addr, buf, 256); + printf("IPv4 LOOPBACK: %s\n", buf); + } if (PR_SetNetAddr(PR_IpAddrAny, PR_AF_INET6, 0, &addr) == PR_FAILURE) { fprintf(stderr, "PR_SetNetAddr failed\n"); @@ -224,11 +232,11 @@ int main(int argc, char **argv) fprintf(stderr, "addr should be unspecified address\n"); exit(1); } - { - char buf[256]; - PR_NetAddrToString(&addr, buf, 256); - printf("IPv6 INADDRANY: %s\n", buf); - } + { + char buf[256]; + PR_NetAddrToString(&addr, buf, 256); + printf("IPv6 INADDRANY: %s\n", buf); + } if (PR_SetNetAddr(PR_IpAddrLoopback, PR_AF_INET6, 0, &addr) == PR_FAILURE) { fprintf(stderr, "PR_SetNetAddr failed\n"); exit(1); @@ -237,23 +245,23 @@ int main(int argc, char **argv) fprintf(stderr, "addr should be loopback address\n"); exit(1); } - { - char buf[256]; - PR_NetAddrToString(&addr, buf, 256); - printf("IPv6 LOOPBACK: %s\n", buf); - } - { - PRIPv6Addr v6addr; - char tmp_buf[256]; + { + char buf[256]; + PR_NetAddrToString(&addr, buf, 256); + printf("IPv6 LOOPBACK: %s\n", buf); + } + { + PRIPv6Addr v6addr; + char tmp_buf[256]; - PR_SetNetAddr(PR_IpAddrLoopback, PR_AF_INET, 0, &addr); + PR_SetNetAddr(PR_IpAddrLoopback, PR_AF_INET, 0, &addr); - PR_ConvertIPv4AddrToIPv6(addr.inet.ip, &v6addr); - PR_SetNetAddr(PR_IpAddrAny, PR_AF_INET6, 0, &addr); - addr.ipv6.ip = v6addr; - PR_NetAddrToString(&addr, tmp_buf, 256); - printf("IPv4-mapped IPv6 LOOPBACK: %s\n", tmp_buf); - } + PR_ConvertIPv4AddrToIPv6(addr.inet.ip, &v6addr); + PR_SetNetAddr(PR_IpAddrAny, PR_AF_INET6, 0, &addr); + addr.ipv6.ip = v6addr; + PR_NetAddrToString(&addr, tmp_buf, 256); + printf("IPv4-mapped IPv6 LOOPBACK: %s\n", tmp_buf); + } printf("PASS\n"); return 0; } diff --git a/nsprpub/pr/tests/getproto.c b/nsprpub/pr/tests/getproto.c index f63a4dfd0..1a33b1f25 100644 --- a/nsprpub/pr/tests/getproto.c +++ b/nsprpub/pr/tests/getproto.c @@ -39,7 +39,9 @@ int main(int argc, char **argv) prstderr,"tcp is usually 6, but is %d on this machine\n", proto.p_num); } - else PR_fprintf(prstderr, "tcp is protocol number %d\n", proto.p_num); + else { + PR_fprintf(prstderr, "tcp is protocol number %d\n", proto.p_num); + } rv = PR_GetProtoByName("udp", buf, sizeof(buf), &proto); if (PR_FAILURE == rv) { @@ -51,7 +53,9 @@ int main(int argc, char **argv) prstderr, "udp is usually 17, but is %d on this machine\n", proto.p_num); } - else PR_fprintf(prstderr, "udp is protocol number %d\n", proto.p_num); + else { + PR_fprintf(prstderr, "udp is protocol number %d\n", proto.p_num); + } rv = PR_GetProtoByNumber(6, buf, sizeof(buf), &proto); if (PR_FAILURE == rv) { @@ -63,7 +67,9 @@ int main(int argc, char **argv) prstderr, "Protocol number 6 is usually tcp, but is %s" " on this platform\n", proto.p_name); } - else PR_fprintf(prstderr, "Protocol number 6 is %s\n", proto.p_name); + else { + PR_fprintf(prstderr, "Protocol number 6 is %s\n", proto.p_name); + } rv = PR_GetProtoByNumber(17, buf, sizeof(buf), &proto); if (PR_FAILURE == rv) { @@ -75,7 +81,9 @@ int main(int argc, char **argv) prstderr, "Protocol number 17 is usually udp, but is %s" " on this platform\n", proto.p_name); } - else PR_fprintf(prstderr, "Protocol number 17 is %s\n", proto.p_name); + else { + PR_fprintf(prstderr, "Protocol number 17 is %s\n", proto.p_name); + } PR_fprintf(prstderr, (failed) ? "FAILED\n" : "PASSED\n"); return (failed) ? 1 : 0; diff --git a/nsprpub/pr/tests/i2l.c b/nsprpub/pr/tests/i2l.c index cd96edef1..a28cd16a8 100644 --- a/nsprpub/pr/tests/i2l.c +++ b/nsprpub/pr/tests/i2l.c @@ -46,21 +46,23 @@ static PRIntn PR_CALLBACK RealMain(PRIntn argc, char **argv) while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'i': /* signed integer */ - si.i = (PRInt32)atoi(opt->value); - bsi = PR_TRUE; - break; - case 'u': /* unsigned */ - ui.i = (PRUint32)atoi(opt->value); - bui = PR_TRUE; - break; - case 'h': /* user wants some guidance */ - default: - Help(); /* so give him an earful */ - return 2; /* but not a lot else */ + case 'i': /* signed integer */ + si.i = (PRInt32)atoi(opt->value); + bsi = PR_TRUE; + break; + case 'u': /* unsigned */ + ui.i = (PRUint32)atoi(opt->value); + bui = PR_TRUE; + break; + case 'h': /* user wants some guidance */ + default: + Help(); /* so give him an earful */ + return 2; /* but not a lot else */ } } PL_DestroyOptState(opt); @@ -92,7 +94,7 @@ static PRIntn PR_CALLBACK RealMain(PRIntn argc, char **argv) int main(int argc, char **argv) { PRIntn rv; - + PR_STDIO_INIT(); rv = PR_Initialize(RealMain, argc, argv, 0); return rv; diff --git a/nsprpub/pr/tests/initclk.c b/nsprpub/pr/tests/initclk.c index 37e4c0504..65d8b17e7 100644 --- a/nsprpub/pr/tests/initclk.c +++ b/nsprpub/pr/tests/initclk.c @@ -49,13 +49,13 @@ int main(int argc, char **argv) PR_ASSERT(NULL != cv2); start = PR_IntervalNow(); thread = PR_CreateThread( - PR_USER_THREAD, - ThreadFunc, - NULL, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_JOINABLE_THREAD, - 0); + PR_USER_THREAD, + ThreadFunc, + NULL, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_JOINABLE_THREAD, + 0); PR_ASSERT(NULL != thread); PR_Lock(lock2); PR_WaitCondVar(cv2, PR_MillisecondsToInterval(LONG_TIMEOUT)); @@ -66,12 +66,12 @@ int main(int argc, char **argv) /* Allow 100ms imprecision */ if (elapsed_ms < LONG_TIMEOUT - 100 || elapsed_ms > LONG_TIMEOUT + 100) { printf("Elapsed time should be %u ms but is %u ms\n", - LONG_TIMEOUT, elapsed_ms); + LONG_TIMEOUT, elapsed_ms); printf("FAIL\n"); exit(1); } - printf("Elapsed time: %u ms, expected time: %u ms\n", - LONG_TIMEOUT, elapsed_ms); + printf("Elapsed time: %u ms, expected time: %u ms\n", + LONG_TIMEOUT, elapsed_ms); printf("PASS\n"); return 0; } diff --git a/nsprpub/pr/tests/inrval.c b/nsprpub/pr/tests/inrval.c index e8eadaa36..52f7b71da 100644 --- a/nsprpub/pr/tests/inrval.c +++ b/nsprpub/pr/tests/inrval.c @@ -8,12 +8,12 @@ ** description: Interval conversion test. ** Modification History: ** 15-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. **/ /*********************************************************************** ** Includes @@ -45,25 +45,25 @@ static void TestConversions(void) { PRIntervalTime ticks = PR_TicksPerSecond(); - if (debug_mode) { - PR_fprintf(output, "PR_TicksPerSecond: %ld\n\n", ticks); - PR_fprintf(output, "PR_SecondsToInterval(1): %ld\n", PR_SecondsToInterval(1)); - PR_fprintf(output, "PR_MillisecondsToInterval(1000): %ld\n", PR_MillisecondsToInterval(1000)); - PR_fprintf(output, "PR_MicrosecondsToInterval(1000000): %ld\n\n", PR_MicrosecondsToInterval(1000000)); - - PR_fprintf(output, "PR_SecondsToInterval(3): %ld\n", PR_SecondsToInterval(3)); - PR_fprintf(output, "PR_MillisecondsToInterval(3000): %ld\n", PR_MillisecondsToInterval(3000)); - PR_fprintf(output, "PR_MicrosecondsToInterval(3000000): %ld\n\n", PR_MicrosecondsToInterval(3000000)); - - PR_fprintf(output, "PR_IntervalToSeconds(%ld): %ld\n", ticks, PR_IntervalToSeconds(ticks)); - PR_fprintf(output, "PR_IntervalToMilliseconds(%ld): %ld\n", ticks, PR_IntervalToMilliseconds(ticks)); - PR_fprintf(output, "PR_IntervalToMicroseconds(%ld): %ld\n\n", ticks, PR_IntervalToMicroseconds(ticks)); - - ticks *= 3; - PR_fprintf(output, "PR_IntervalToSeconds(%ld): %ld\n", ticks, PR_IntervalToSeconds(ticks)); - PR_fprintf(output, "PR_IntervalToMilliseconds(%ld): %ld\n", ticks, PR_IntervalToMilliseconds(ticks)); - PR_fprintf(output, "PR_IntervalToMicroseconds(%ld): %ld\n\n", ticks, PR_IntervalToMicroseconds(ticks)); - } /*end debug mode */ + if (debug_mode) { + PR_fprintf(output, "PR_TicksPerSecond: %ld\n\n", ticks); + PR_fprintf(output, "PR_SecondsToInterval(1): %ld\n", PR_SecondsToInterval(1)); + PR_fprintf(output, "PR_MillisecondsToInterval(1000): %ld\n", PR_MillisecondsToInterval(1000)); + PR_fprintf(output, "PR_MicrosecondsToInterval(1000000): %ld\n\n", PR_MicrosecondsToInterval(1000000)); + + PR_fprintf(output, "PR_SecondsToInterval(3): %ld\n", PR_SecondsToInterval(3)); + PR_fprintf(output, "PR_MillisecondsToInterval(3000): %ld\n", PR_MillisecondsToInterval(3000)); + PR_fprintf(output, "PR_MicrosecondsToInterval(3000000): %ld\n\n", PR_MicrosecondsToInterval(3000000)); + + PR_fprintf(output, "PR_IntervalToSeconds(%ld): %ld\n", ticks, PR_IntervalToSeconds(ticks)); + PR_fprintf(output, "PR_IntervalToMilliseconds(%ld): %ld\n", ticks, PR_IntervalToMilliseconds(ticks)); + PR_fprintf(output, "PR_IntervalToMicroseconds(%ld): %ld\n\n", ticks, PR_IntervalToMicroseconds(ticks)); + + ticks *= 3; + PR_fprintf(output, "PR_IntervalToSeconds(%ld): %ld\n", ticks, PR_IntervalToSeconds(ticks)); + PR_fprintf(output, "PR_IntervalToMilliseconds(%ld): %ld\n", ticks, PR_IntervalToMilliseconds(ticks)); + PR_fprintf(output, "PR_IntervalToMicroseconds(%ld): %ld\n\n", ticks, PR_IntervalToMicroseconds(ticks)); + } /*end debug mode */ } /* TestConversions */ static void TestIntervalOverhead(void) @@ -72,8 +72,9 @@ static void TestIntervalOverhead(void) PRUint32 elapsed, per_call, loops = 1000000; PRIntervalTime timeout, timein = PR_IntervalNow(); - while (--loops > 0) + while (--loops > 0) { timeout = PR_IntervalNow(); + } elapsed = 1000U * PR_IntervalToMicroseconds(timeout - timein); per_call = elapsed / 1000000U; @@ -91,8 +92,9 @@ static void TestNowOverhead(void) LL_I2L(ten26th, 1000000); timein = PR_Now(); - while (--loops > 0) + while (--loops > 0) { timeout = PR_Now(); + } LL_SUB(elapsed, timeout, timein); LL_MUL(elapsed, elapsed, ten23rd); @@ -123,55 +125,63 @@ static void TestIntervals(void) 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); + 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"); + if (debug_mode) { + PR_fprintf(output, "\n"); + } } /* TestIntervals */ static PRIntn PR_CALLBACK RealMain(int argc, char** argv) { PRUint32 vcpu, cpus = 0, loops = 1000; - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - - /* main test */ - - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "dl:c:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + + /* main test */ + + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "dl:c:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - case 'c': /* concurrency counter */ - cpus = atoi(opt->value); - break; - case 'l': /* loop counter */ - loops = atoi(opt->value); - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + case 'c': /* concurrency counter */ + cpus = atoi(opt->value); + break; + case 'l': /* loop counter */ + loops = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); - + PL_DestroyOptState(opt); + output = PR_GetSpecialFD(PR_StandardOutput); PR_fprintf(output, "inrval: Examine stdout to determine results.\n"); - if (cpus == 0) cpus = 8; - if (loops == 0) loops = 1000; + if (cpus == 0) { + cpus = 8; + } + if (loops == 0) { + loops = 1000; + } if (debug_mode > 0) { @@ -181,8 +191,9 @@ static PRIntn PR_CALLBACK RealMain(int argc, char** argv) for (vcpu = 1; vcpu <= cpus; vcpu += cpus - 1) { - if (debug_mode) + if (debug_mode) { PR_fprintf(output, "\nInrval: Using %d CPU(s)\n\n", vcpu); + } PR_SetConcurrency(vcpu); TestNowOverhead(); @@ -190,7 +201,7 @@ static PRIntn PR_CALLBACK RealMain(int argc, char** argv) TestConversions(); TestIntervals(); } - + return 0; } @@ -198,7 +209,7 @@ static PRIntn PR_CALLBACK RealMain(int argc, char** argv) int main(int argc, char **argv) { PRIntn rv; - + PR_STDIO_INIT(); rv = PR_Initialize(RealMain, argc, argv, 0); return rv; diff --git a/nsprpub/pr/tests/instrumt.c b/nsprpub/pr/tests/instrumt.c index 5094e5dbc..e1ca94d03 100644 --- a/nsprpub/pr/tests/instrumt.c +++ b/nsprpub/pr/tests/instrumt.c @@ -39,19 +39,19 @@ #include <plstr.h> #include <prclist.h> #include <prmem.h> -#include <plgetopt.h> -#include <prlog.h> -#include <prmon.h> -#include <pratom.h> -#include <prtrace.h> -#include <prcountr.h> -#include <prolock.h> +#include <plgetopt.h> +#include <prlog.h> +#include <prmon.h> +#include <pratom.h> +#include <prtrace.h> +#include <prcountr.h> +#include <prolock.h> #define COUNT_LIMIT (10 * ( 1024)) #define SMALL_TRACE_BUFSIZE ( 60 * 1024 ) -typedef enum +typedef enum { CountLoop = 1, TraceLoop = 2, @@ -74,7 +74,7 @@ PR_DEFINE_TRACE( hTrace ); static void Help(void) { printf("Help? ... Ha!\n"); -} +} static void ListCounters(void) { @@ -95,13 +95,13 @@ static void ListCounters(void) PR_GET_COUNTER_NAME_FROM_HANDLE( rh, qname, rname, desc ); PR_GET_COUNTER(tCtr, rh); PR_LOG( lm, msgLevel, - ( "QName: %s RName: %s Desc: %s Value: %ld\n", - qn, rn, dn, tCtr )); + ( "QName: %s RName: %s Desc: %s Value: %ld\n", + qn, rn, dn, tCtr )); PR_FIND_NEXT_COUNTER_RNAME(rh, rh, qh ); - } + } PR_FIND_NEXT_COUNTER_QNAME(qh, qh); } - return; + return; } /* end ListCounters() */ static void ListTraces(void) @@ -121,13 +121,13 @@ static void ListTraces(void) { PR_GET_TRACE_NAME_FROM_HANDLE( rh, qname, rname, desc ); PR_LOG( lm, msgLevel, - ( "QName: %s RName: %s Desc: %s", - qn, rn, dn )); + ( "QName: %s RName: %s Desc: %s", + qn, rn, dn )); PR_FIND_NEXT_TRACE_RNAME(rh, rh, qh ); - } + } PR_FIND_NEXT_TRACE_QNAME(qh, qh); } - return; + return; } /* end ListCounters() */ @@ -145,40 +145,40 @@ static void PR_CALLBACK CountSomething( void *arg ) PRInt32 i; PR_LOG( lm, msgLevel, - ("CountSomething: begin thread %ld", switchVar )); - + ("CountSomething: begin thread %ld", switchVar )); + for ( i = 0; i < COUNT_LIMIT ; i++) { switch ( switchVar ) { - case 1 : - PR_INCREMENT_COUNTER( hCounter ); - break; - case 2 : - PR_DECREMENT_COUNTER( hCounter ); - break; - case 3 : - PR_ADD_TO_COUNTER( hCounter, 1 ); - break; - case 4 : - PR_SUBTRACT_FROM_COUNTER( hCounter, 1 ); - break; - default : - PR_ASSERT( 0 ); - break; + case 1 : + PR_INCREMENT_COUNTER( hCounter ); + break; + case 2 : + PR_DECREMENT_COUNTER( hCounter ); + break; + case 3 : + PR_ADD_TO_COUNTER( hCounter, 1 ); + break; + case 4 : + PR_SUBTRACT_FROM_COUNTER( hCounter, 1 ); + break; + default : + PR_ASSERT( 0 ); + break; } PR_TRACE( hTrace, CountLoop, switchVar, i, 0, 0, 0, 0, 0 ); } /* end for() */ PR_LOG( lm, msgLevel, - ("CounterSomething: end thread %ld", switchVar )); - + ("CounterSomething: end thread %ld", switchVar )); + PR_EnterMonitor(mon); --activeThreads; PR_Notify( mon ); PR_ExitMonitor(mon); - return; + return; } /* end CountSomething() */ /* @@ -192,8 +192,8 @@ static void CounterTest( void ) PR_DEFINE_COUNTER( zCounter ); PR_LOG( lm, msgLevel, - ("Begin CounterTest")); - + ("Begin CounterTest")); + /* ** Test Get and Set of a counter. ** @@ -205,7 +205,7 @@ static void CounterTest( void ) { failed = PR_TRUE; PR_LOG( lm, msgLevel, - ("Counter set/get failed")); + ("Counter set/get failed")); } activeThreads += 4; @@ -214,40 +214,40 @@ static void CounterTest( void ) PR_GET_COUNTER_HANDLE_FROM_NAME( tc, "Atomic", "SMP Tests" ); PR_ASSERT( tc == hCounter ); - t1 = PR_CreateThread(PR_USER_THREAD, - CountSomething, &one, - PR_PRIORITY_NORMAL, - PR_GLOBAL_THREAD, - PR_UNJOINABLE_THREAD, - 0); - PR_ASSERT(t1); - - t2 = PR_CreateThread(PR_USER_THREAD, - CountSomething, &two, - PR_PRIORITY_NORMAL, - PR_GLOBAL_THREAD, - PR_UNJOINABLE_THREAD, - 0); - PR_ASSERT(t2); - - t3 = PR_CreateThread(PR_USER_THREAD, - CountSomething, &three, - PR_PRIORITY_NORMAL, - PR_GLOBAL_THREAD, - PR_UNJOINABLE_THREAD, - 0); - PR_ASSERT(t3); - - t4 = PR_CreateThread(PR_USER_THREAD, - CountSomething, &four, - PR_PRIORITY_NORMAL, - PR_GLOBAL_THREAD, - PR_UNJOINABLE_THREAD, - 0); - PR_ASSERT(t4); + t1 = PR_CreateThread(PR_USER_THREAD, + CountSomething, &one, + PR_PRIORITY_NORMAL, + PR_GLOBAL_THREAD, + PR_UNJOINABLE_THREAD, + 0); + PR_ASSERT(t1); + + t2 = PR_CreateThread(PR_USER_THREAD, + CountSomething, &two, + PR_PRIORITY_NORMAL, + PR_GLOBAL_THREAD, + PR_UNJOINABLE_THREAD, + 0); + PR_ASSERT(t2); + + t3 = PR_CreateThread(PR_USER_THREAD, + CountSomething, &three, + PR_PRIORITY_NORMAL, + PR_GLOBAL_THREAD, + PR_UNJOINABLE_THREAD, + 0); + PR_ASSERT(t3); + + t4 = PR_CreateThread(PR_USER_THREAD, + CountSomething, &four, + PR_PRIORITY_NORMAL, + PR_GLOBAL_THREAD, + PR_UNJOINABLE_THREAD, + 0); + PR_ASSERT(t4); PR_LOG( lm, msgLevel, - ("Counter Threads started")); + ("Counter Threads started")); ListCounters(); return; @@ -265,7 +265,7 @@ static void PR_CALLBACK RecordTrace(void *arg ) PR_Notify( mon ); PR_ExitMonitor(mon); - return; + return; } /* end RecordTrace() */ @@ -280,7 +280,7 @@ static void PR_CALLBACK SampleTrace( void *arg ) PRInt32 found, rc; PRTraceEntry *foundEntries; PRInt32 i; - + foundEntries = (PRTraceEntry *)PR_Malloc( NUM_TRACE_RECORDS * sizeof(PRTraceEntry)); PR_ASSERT(foundEntries != NULL ); @@ -288,19 +288,19 @@ static void PR_CALLBACK SampleTrace( void *arg ) { rc = PR_GetTraceEntries( foundEntries, NUM_TRACE_RECORDS, &found); PR_LOG( lm, msgLevel, - ("SampleTrace: Lost Data: %ld found: %ld", rc, found )); + ("SampleTrace: Lost Data: %ld found: %ld", rc, found )); if ( found != 0) { for ( i = 0 ; i < found; i++ ) { PR_LOG( lm, msgLevel, - ("SampleTrace, detail: Thread: %p, Time: %llX, UD0: %ld, UD1: %ld, UD2: %8.8ld", - (foundEntries +i)->thread, - (foundEntries +i)->time, - (foundEntries +i)->userData[0], - (foundEntries +i)->userData[1], - (foundEntries +i)->userData[2] )); + ("SampleTrace, detail: Thread: %p, Time: %llX, UD0: %ld, UD1: %ld, UD2: %8.8ld", + (foundEntries +i)->thread, + (foundEntries +i)->time, + (foundEntries +i)->userData[0], + (foundEntries +i)->userData[1], + (foundEntries +i)->userData[2] )); } } PR_Sleep(PR_MillisecondsToInterval(50)); @@ -315,10 +315,10 @@ static void PR_CALLBACK SampleTrace( void *arg ) PR_ExitMonitor(mon); PR_LOG( lm, msgLevel, - ("SampleTrace(): exiting")); + ("SampleTrace(): exiting")); #endif - return; + return; } /* end RecordTrace() */ /* @@ -330,14 +330,14 @@ static void TraceTest( void ) PRInt32 size; PR_DEFINE_TRACE( th ); PRThread *t1, *t2; - + PR_LOG( lm, msgLevel, - ("Begin TraceTest")); + ("Begin TraceTest")); size = SMALL_TRACE_BUFSIZE; PR_SET_TRACE_OPTION( PRTraceBufSize, &size ); PR_GET_TRACE_OPTION( PRTraceBufSize, &i ); - + PR_CREATE_TRACE( th, "TraceTest", "tt2", "A description for the trace test" ); PR_CREATE_TRACE( th, "TraceTest", "tt3", "A description for the trace test" ); PR_CREATE_TRACE( th, "TraceTest", "tt4", "A description for the trace test" ); @@ -361,29 +361,29 @@ static void TraceTest( void ) activeThreads += 2; - t1 = PR_CreateThread(PR_USER_THREAD, - RecordTrace, NULL, - PR_PRIORITY_NORMAL, - PR_GLOBAL_THREAD, - PR_UNJOINABLE_THREAD, - 0); - PR_ASSERT(t1); - - t2 = PR_CreateThread(PR_USER_THREAD, - SampleTrace, 0, - PR_PRIORITY_NORMAL, - PR_GLOBAL_THREAD, - PR_UNJOINABLE_THREAD, - 0); - PR_ASSERT(t2); - + t1 = PR_CreateThread(PR_USER_THREAD, + RecordTrace, NULL, + PR_PRIORITY_NORMAL, + PR_GLOBAL_THREAD, + PR_UNJOINABLE_THREAD, + 0); + PR_ASSERT(t1); + + t2 = PR_CreateThread(PR_USER_THREAD, + SampleTrace, 0, + PR_PRIORITY_NORMAL, + PR_GLOBAL_THREAD, + PR_UNJOINABLE_THREAD, + 0); + PR_ASSERT(t2); + ListTraces(); PR_GET_TRACE_HANDLE_FROM_NAME( th, "TraceTest","tt1" ); PR_ASSERT( th == hTrace ); PR_LOG( lm, msgLevel, - ("End TraceTest")); + ("End TraceTest")); return; } /* end TraceTest() */ @@ -394,9 +394,9 @@ static void TraceTest( void ) static void OrderedLockTest( void ) { PR_LOG( lm, msgLevel, - ("Begin OrderedLockTest")); + ("Begin OrderedLockTest")); + - } /* end OrderedLockTest() */ @@ -408,23 +408,25 @@ int main(int argc, char **argv) PLOptState *opt = PL_CreateOptState(argc, argv, "hdv:"); lm = PR_NewLogModule("Test"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'v': /* verbose mode */ - msgLevel = (PRLogModuleLevel)atol( opt->value); - break; - case 'h': /* help message */ - Help(); - help = PR_TRUE; - break; - default: - break; + case 'v': /* verbose mode */ + msgLevel = (PRLogModuleLevel)atol( opt->value); + break; + case 'h': /* help message */ + Help(); + help = PR_TRUE; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); PR_CREATE_TRACE( hTrace, "TraceTest", "tt1", "A description for the trace test" ); mon = PR_NewMonitor(); @@ -436,9 +438,10 @@ int main(int argc, char **argv) /* Wait for all threads to exit */ while ( activeThreads > 0 ) { - if ( activeThreads == 1 ) + if ( activeThreads == 1 ) { PR_SET_TRACE_OPTION( PRTraceStopRecording, NULL ); - PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT); + } + PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT); PR_GET_COUNTER( counter, hCounter ); } PR_ExitMonitor( mon ); @@ -451,7 +454,7 @@ int main(int argc, char **argv) { failed = PR_TRUE; PR_LOG( lm, msgLevel, - ("Expected counter == 0, found: %ld", counter)); + ("Expected counter == 0, found: %ld", counter)); printf("FAIL\n"); } else diff --git a/nsprpub/pr/tests/intrio.c b/nsprpub/pr/tests/intrio.c index 691ed8158..23d834d66 100644 --- a/nsprpub/pr/tests/intrio.c +++ b/nsprpub/pr/tests/intrio.c @@ -62,7 +62,7 @@ static void PR_CALLBACK IOThread(void *arg) } if (PR_GetError() != PR_PENDING_INTERRUPT_ERROR) { fprintf(stderr, "PR_Accept failed (%d, %d)\n", - PR_GetError(), PR_GetOSError()); + PR_GetError(), PR_GetOSError()); exit(1); } printf("PR_Accept() is interrupted as expected\n"); @@ -77,23 +77,24 @@ static void Test(PRThreadScope scope1, PRThreadScope scope2) PRThread *iothread, *abortio; printf("A %s thread will be interrupted by a %s thread\n", - (scope1 == PR_LOCAL_THREAD ? "local" : "global"), - (scope2 == PR_LOCAL_THREAD ? "local" : "global")); + (scope1 == PR_LOCAL_THREAD ? "local" : "global"), + (scope2 == PR_LOCAL_THREAD ? "local" : "global")); iothread_ready = PR_FALSE; iothread = PR_CreateThread( - PR_USER_THREAD, IOThread, NULL, PR_PRIORITY_NORMAL, - scope1, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, IOThread, NULL, PR_PRIORITY_NORMAL, + scope1, PR_JOINABLE_THREAD, 0); if (iothread == NULL) { fprintf(stderr, "cannot create thread\n"); exit(1); } PR_Lock(lock); - while (!iothread_ready) + while (!iothread_ready) { PR_WaitCondVar(cvar, PR_INTERVAL_NO_TIMEOUT); + } PR_Unlock(lock); abortio = PR_CreateThread( - PR_USER_THREAD, AbortIO, iothread, PR_PRIORITY_NORMAL, - scope2, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, AbortIO, iothread, PR_PRIORITY_NORMAL, + scope2, PR_JOINABLE_THREAD, 0); if (abortio == NULL) { fprintf(stderr, "cannot create thread\n"); exit(1); diff --git a/nsprpub/pr/tests/intrupt.c b/nsprpub/pr/tests/intrupt.c index b59708085..950d30d46 100644 --- a/nsprpub/pr/tests/intrupt.c +++ b/nsprpub/pr/tests/intrupt.c @@ -40,22 +40,30 @@ static void PR_CALLBACK AbortCV(void *arg) /* some other thread (main) is doing the interrupt */ PR_Lock(ml); rv = PR_WaitCondVar(cv, PR_INTERVAL_NO_TIMEOUT); - if (debug_mode) printf( "Expected interrupt on wait CV and "); + if (debug_mode) { + printf( "Expected interrupt on wait CV and "); + } if (PR_FAILURE == rv) { if (PR_PENDING_INTERRUPT_ERROR == PR_GetError()) { - if (debug_mode) printf("got it\n"); + if (debug_mode) { + printf("got it\n"); + } } else { - if (debug_mode) printf("got random error\n"); + if (debug_mode) { + printf("got random error\n"); + } passed = PR_FALSE; } } else { - if (debug_mode) printf("got a successful completion\n"); + if (debug_mode) { + printf("got a successful completion\n"); + } passed = PR_FALSE; } @@ -88,22 +96,30 @@ static void PR_CALLBACK AbortCV(void *arg) /* set, then wait - interrupt - then wait again */ PR_Interrupt(me); rv = PR_WaitCondVar(cv, 10); - if (debug_mode) printf( "Expected interrupt on wait CV and "); + if (debug_mode) { + printf( "Expected interrupt on wait CV and "); + } if (PR_FAILURE == rv) { if (PR_PENDING_INTERRUPT_ERROR == PR_GetError()) { - if (debug_mode) printf("got it\n"); + if (debug_mode) { + printf("got it\n"); + } } else { - if (debug_mode) printf("failed\n"); + if (debug_mode) { + printf("failed\n"); + } passed = PR_FALSE; } } else { - if (debug_mode) printf("got a successful completion\n"); + if (debug_mode) { + printf("got a successful completion\n"); + } passed = PR_FALSE; } @@ -152,11 +168,13 @@ static void setup_listen_socket(PRFileDesc **listner, PRNetAddr *netaddr) rv = PR_Listen(*listner, 5); - if (PR_GetSockName(*listner, netaddr) < 0) { - if (debug_mode) printf("intrupt: ERROR - PR_GetSockName failed\n"); - passed = PR_FALSE; - return; - } + if (PR_GetSockName(*listner, netaddr) < 0) { + if (debug_mode) { + printf("intrupt: ERROR - PR_GetSockName failed\n"); + } + passed = PR_FALSE; + return; + } } @@ -167,11 +185,11 @@ static void PR_CALLBACK IntrBlock(void *arg) PRFileDesc *listner; /* some other thread (main) is doing the interrupt */ - /* block the interrupt */ - PR_BlockInterrupt(); + /* block the interrupt */ + PR_BlockInterrupt(); PR_Lock(ml); rv = PR_WaitCondVar(cv, PR_SecondsToInterval(4)); - PR_Unlock(ml); + PR_Unlock(ml); if (debug_mode) { printf("Expected success on wait CV and "); @@ -180,30 +198,39 @@ static void PR_CALLBACK IntrBlock(void *arg) printf( "%s\n", (PR_PENDING_INTERRUPT_ERROR == PR_GetError()) ? "got interrupted" : "got a random failure"); - } else - printf("got it\n"); + } else { + printf("got it\n"); + } } passed = ((PR_TRUE == passed) && (PR_SUCCESS == rv)) ? PR_TRUE : PR_FALSE; - setup_listen_socket(&listner, &netaddr); - PR_UnblockInterrupt(); + setup_listen_socket(&listner, &netaddr); + PR_UnblockInterrupt(); if (PR_Accept(listner, &netaddr, PR_INTERVAL_NO_TIMEOUT) == NULL) { PRInt32 error = PR_GetError(); - if (debug_mode) printf("Expected interrupt on PR_Accept() and "); + if (debug_mode) { + printf("Expected interrupt on PR_Accept() and "); + } if (PR_PENDING_INTERRUPT_ERROR == error) { - if (debug_mode) printf("got it\n"); + if (debug_mode) { + printf("got it\n"); + } } else { - if (debug_mode) printf("failed\n"); + if (debug_mode) { + printf("failed\n"); + } passed = PR_FALSE; } } else { - if (debug_mode) printf("Failed to interrupt PR_Accept()\n"); + if (debug_mode) { + printf("Failed to interrupt PR_Accept()\n"); + } passed = PR_FALSE; } @@ -221,10 +248,12 @@ void PR_CALLBACK Intrupt(void *arg) cv = PR_NewCondVar(ml); /* Part I */ - if (debug_mode) printf("Part I\n"); + if (debug_mode) { + printf("Part I\n"); + } abortCV = PR_CreateThread( - PR_USER_THREAD, AbortCV, 0, PR_PRIORITY_NORMAL, - thread_scope, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, AbortCV, 0, PR_PRIORITY_NORMAL, + thread_scope, PR_JOINABLE_THREAD, 0); PR_Sleep(PR_SecondsToInterval(2)); rv = PR_Interrupt(abortCV); @@ -233,42 +262,58 @@ void PR_CALLBACK Intrupt(void *arg) PR_ASSERT(PR_SUCCESS == rv); /* Part II */ - if (debug_mode) printf("Part II\n"); + if (debug_mode) { + printf("Part II\n"); + } abortJoin = PR_CreateThread( - PR_USER_THREAD, AbortJoin, 0, PR_PRIORITY_NORMAL, - thread_scope, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, AbortJoin, 0, PR_PRIORITY_NORMAL, + thread_scope, PR_JOINABLE_THREAD, 0); PR_Sleep(PR_SecondsToInterval(2)); - if (debug_mode) printf("Expecting to interrupt an exited thread "); + if (debug_mode) { + printf("Expecting to interrupt an exited thread "); + } rv = PR_Interrupt(abortJoin); PR_ASSERT(PR_SUCCESS == rv); rv = PR_JoinThread(abortJoin); PR_ASSERT(PR_SUCCESS == rv); - if (debug_mode) printf("and succeeded\n"); + if (debug_mode) { + printf("and succeeded\n"); + } /* Part III */ - if (debug_mode) printf("Part III\n"); - setup_listen_socket(&listner, &netaddr); + if (debug_mode) { + printf("Part III\n"); + } + setup_listen_socket(&listner, &netaddr); abortIO = PR_CreateThread( - PR_USER_THREAD, AbortIO, PR_GetCurrentThread(), PR_PRIORITY_NORMAL, - thread_scope, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, AbortIO, PR_GetCurrentThread(), PR_PRIORITY_NORMAL, + thread_scope, PR_JOINABLE_THREAD, 0); if (PR_Accept(listner, &netaddr, PR_INTERVAL_NO_TIMEOUT) == NULL) { PRInt32 error = PR_GetError(); - if (debug_mode) printf("Expected interrupt on PR_Accept() and "); + if (debug_mode) { + printf("Expected interrupt on PR_Accept() and "); + } if (PR_PENDING_INTERRUPT_ERROR == error) { - if (debug_mode) printf("got it\n"); + if (debug_mode) { + printf("got it\n"); + } } else { - if (debug_mode) printf("failed\n"); + if (debug_mode) { + printf("failed\n"); + } passed = PR_FALSE; } } else { - if (debug_mode) printf("Failed to interrupt PR_Accept()\n"); + if (debug_mode) { + printf("Failed to interrupt PR_Accept()\n"); + } passed = PR_FALSE; } @@ -277,10 +322,12 @@ void PR_CALLBACK Intrupt(void *arg) rv = PR_JoinThread(abortIO); PR_ASSERT(PR_SUCCESS == rv); /* Part VI */ - if (debug_mode) printf("Part VI\n"); + if (debug_mode) { + printf("Part VI\n"); + } intrBlock = PR_CreateThread( - PR_USER_THREAD, IntrBlock, 0, PR_PRIORITY_NORMAL, - thread_scope, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, IntrBlock, 0, PR_PRIORITY_NORMAL, + thread_scope, PR_JOINABLE_THREAD, 0); PR_Sleep(PR_SecondsToInterval(2)); rv = PR_Interrupt(intrBlock); @@ -289,32 +336,34 @@ void PR_CALLBACK Intrupt(void *arg) PR_ASSERT(PR_SUCCESS == rv); PR_DestroyCondVar(cv); - PR_DestroyLock(ml); + PR_DestroyLock(ml); } /* Intrupt */ int main(int argc, char **argv) { PRThread *intrupt; - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "dG"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "dG"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = PR_TRUE; - break; - case 'G': /* use global threads */ - thread_scope = PR_GLOBAL_THREAD; - break; + case 'd': /* debug mode */ + debug_mode = PR_TRUE; + break; + case 'G': /* use global threads */ + thread_scope = PR_GLOBAL_THREAD; + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); PR_STDIO_INIT(); intrupt = PR_CreateThread( - PR_USER_THREAD, Intrupt, NULL, PR_PRIORITY_NORMAL, - thread_scope, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, Intrupt, NULL, PR_PRIORITY_NORMAL, + thread_scope, PR_JOINABLE_THREAD, 0); if (intrupt == NULL) { fprintf(stderr, "cannot create thread\n"); passed = PR_FALSE; @@ -324,7 +373,7 @@ int main(int argc, char **argv) PR_ASSERT(rv == PR_SUCCESS); } printf("%s\n", ((passed) ? "PASSED" : "FAILED")); - return ((passed) ? 0 : 1); + return ((passed) ? 0 : 1); } /* main */ /* intrupt.c */ diff --git a/nsprpub/pr/tests/io_timeout.c b/nsprpub/pr/tests/io_timeout.c index fa6399c11..19d3daecc 100644 --- a/nsprpub/pr/tests/io_timeout.c +++ b/nsprpub/pr/tests/io_timeout.c @@ -11,10 +11,10 @@ ** ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ***********************************************************************/ /*********************************************************************** ** Includes @@ -40,11 +40,11 @@ typedef struct threadInfo { PRIntn failed_already = 0; PRIntn debug_mode = 0; -#define LOCAL_SCOPE_STRING "LOCAL scope" -#define GLOBAL_SCOPE_STRING "GLOBAL scope" -#define GLOBAL_BOUND_SCOPE_STRING "GLOBAL_BOUND scope" +#define LOCAL_SCOPE_STRING "LOCAL scope" +#define GLOBAL_SCOPE_STRING "GLOBAL scope" +#define GLOBAL_BOUND_SCOPE_STRING "GLOBAL_BOUND scope" -void +void thread_main(void *_info) { threadInfo *info = (threadInfo *)_info; @@ -53,94 +53,100 @@ thread_main(void *_info) PRFileDesc *listenSock = NULL; PRFileDesc *clientSock; PRStatus rv; - PRThreadScope tscope; - char *scope_str; - - - if (debug_mode) - printf("thread %d is alive\n", info->id); - tscope = PR_GetThreadScope(PR_GetCurrentThread()); - - switch(tscope) { - case PR_LOCAL_THREAD: - scope_str = LOCAL_SCOPE_STRING; - break; - case PR_GLOBAL_THREAD: - scope_str = GLOBAL_SCOPE_STRING; - break; - case PR_GLOBAL_BOUND_THREAD: - scope_str = GLOBAL_BOUND_SCOPE_STRING; - break; - default: - PR_NOT_REACHED("Invalid thread scope"); - break; - } - printf("thread id %d, scope %s\n", info->id, scope_str); + PRThreadScope tscope; + char *scope_str; + + + if (debug_mode) { + printf("thread %d is alive\n", info->id); + } + tscope = PR_GetThreadScope(PR_GetCurrentThread()); + + switch(tscope) { + case PR_LOCAL_THREAD: + scope_str = LOCAL_SCOPE_STRING; + break; + case PR_GLOBAL_THREAD: + scope_str = GLOBAL_SCOPE_STRING; + break; + case PR_GLOBAL_BOUND_THREAD: + scope_str = GLOBAL_BOUND_SCOPE_STRING; + break; + default: + PR_NOT_REACHED("Invalid thread scope"); + break; + } + printf("thread id %d, scope %s\n", info->id, scope_str); listenSock = PR_NewTCPSocket(); if (!listenSock) { - if (debug_mode) - printf("unable to create listen socket\n"); - failed_already=1; + if (debug_mode) { + printf("unable to create listen socket\n"); + } + failed_already=1; goto dead; } - + listenAddr.inet.family = PR_AF_INET; listenAddr.inet.port = PR_htons(BASE_PORT + info->id); listenAddr.inet.ip = PR_htonl(PR_INADDR_ANY); rv = PR_Bind(listenSock, &listenAddr); if (rv == PR_FAILURE) { - if (debug_mode) - printf("unable to bind\n"); - failed_already=1; + if (debug_mode) { + printf("unable to bind\n"); + } + failed_already=1; goto dead; } rv = PR_Listen(listenSock, 4); if (rv == PR_FAILURE) { - if (debug_mode) - printf("unable to listen\n"); - failed_already=1; + if (debug_mode) { + printf("unable to listen\n"); + } + failed_already=1; goto dead; } - if (debug_mode) - printf("thread %d going into accept for %d seconds\n", - info->id, info->accept_timeout + info->id); + if (debug_mode) + printf("thread %d going into accept for %d seconds\n", + info->id, info->accept_timeout + info->id); clientSock = PR_Accept(listenSock, &clientAddr, PR_SecondsToInterval(info->accept_timeout +info->id)); if (clientSock == NULL) { if (PR_GetError() == PR_IO_TIMEOUT_ERROR) { - if (debug_mode) { - printf("PR_Accept() timeout worked!\n"); - printf("TEST PASSED! PR_Accept() returned error %d\n", - PR_IO_TIMEOUT_ERROR); - } - } else { - if (debug_mode) - printf("TEST FAILED! PR_Accept() returned error %d\n", - PR_GetError()); - failed_already=1; - } + if (debug_mode) { + printf("PR_Accept() timeout worked!\n"); + printf("TEST PASSED! PR_Accept() returned error %d\n", + PR_IO_TIMEOUT_ERROR); + } + } else { + if (debug_mode) + printf("TEST FAILED! PR_Accept() returned error %d\n", + PR_GetError()); + failed_already=1; + } } else { - if (debug_mode) - printf ("TEST FAILED! PR_Accept() succeeded?\n"); - failed_already=1; - PR_Close(clientSock); + if (debug_mode) { + printf ("TEST FAILED! PR_Accept() succeeded?\n"); + } + failed_already=1; + PR_Close(clientSock); } dead: if (listenSock) { - PR_Close(listenSock); + PR_Close(listenSock); } PR_Lock(info->dead_lock); (*info->alive)--; PR_NotifyCondVar(info->dead_cv); PR_Unlock(info->dead_lock); - if (debug_mode) - printf("thread %d is dead\n", info->id); + if (debug_mode) { + printf("thread %d is dead\n", info->id); + } PR_Free(info); } @@ -154,13 +160,14 @@ thread_test(PRThreadScope scope, PRInt32 num_threads) PRCondVar *dead_cv; PRInt32 alive; - if (debug_mode) - printf("IO Timeout test started with %d threads\n", num_threads); + if (debug_mode) { + printf("IO Timeout test started with %d threads\n", num_threads); + } dead_lock = PR_NewLock(); dead_cv = PR_NewCondVar(dead_lock); alive = num_threads; - + for (index = 0; index < num_threads; index++) { threadInfo *info = (threadInfo *)PR_Malloc(sizeof(threadInfo)); @@ -169,7 +176,7 @@ thread_test(PRThreadScope scope, PRInt32 num_threads) info->dead_cv = dead_cv; info->alive = &alive; info->accept_timeout = DEFAULT_ACCEPT_TIMEOUT; - + thr = PR_CreateThread( PR_USER_THREAD, thread_main, (void *)info, @@ -179,9 +186,9 @@ thread_test(PRThreadScope scope, PRInt32 num_threads) 0); if (!thr) { - printf("Failed to create thread, error = %d(%d)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; + printf("Failed to create thread, error = %d(%d)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; PR_Lock(dead_lock); alive--; @@ -191,8 +198,9 @@ thread_test(PRThreadScope scope, PRInt32 num_threads) PR_Lock(dead_lock); while(alive) { - if (debug_mode) - printf("main loop awake; alive = %d\n", alive); + if (debug_mode) { + printf("main loop awake; alive = %d\n", alive); + } PR_WaitCondVar(dead_cv, PR_INTERVAL_NO_TIMEOUT); } PR_Unlock(dead_lock); @@ -205,35 +213,38 @@ int main(int argc, char **argv) { PRInt32 num_threads = 0; - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name [-d] [-t <threads>] - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "dt:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name [-d] [-t <threads>] + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "dt:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - case 't': /* threads to involve */ - num_threads = atoi(opt->value); - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + case 't': /* threads to involve */ + num_threads = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - - if (0 == num_threads) + if (0 == num_threads) { num_threads = NUM_THREADS; + } PR_Init(PR_USER_THREAD, PR_PRIORITY_LOW, 0); PR_STDIO_INIT(); @@ -249,8 +260,10 @@ int main(int argc, char **argv) PR_Cleanup(); - if (failed_already) - return 1; - else - return 0; + if (failed_already) { + return 1; + } + else { + return 0; + } } diff --git a/nsprpub/pr/tests/io_timeoutk.c b/nsprpub/pr/tests/io_timeoutk.c index cf6cb491b..a058655fd 100644 --- a/nsprpub/pr/tests/io_timeoutk.c +++ b/nsprpub/pr/tests/io_timeoutk.c @@ -9,12 +9,12 @@ ** ** Modification History: ** 19-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** ** Includes @@ -41,7 +41,7 @@ PRIntn failed_already=0; PRIntn debug_mode; -void +void thread_main(void *_info) { threadInfo *info = (threadInfo *)_info; @@ -50,59 +50,75 @@ thread_main(void *_info) PRFileDesc *listenSock = NULL; PRFileDesc *clientSock; PRStatus rv; - - if (debug_mode) printf("thread %d is alive\n", info->id); + + if (debug_mode) { + printf("thread %d is alive\n", info->id); + } listenSock = PR_NewTCPSocket(); if (!listenSock) { - if (debug_mode) printf("unable to create listen socket\n"); + if (debug_mode) { + printf("unable to create listen socket\n"); + } goto dead; } - + listenAddr.inet.family = AF_INET; listenAddr.inet.port = PR_htons(BASE_PORT + info->id); listenAddr.inet.ip = PR_htonl(INADDR_ANY); rv = PR_Bind(listenSock, &listenAddr); if (rv == PR_FAILURE) { - if (debug_mode) printf("unable to bind\n"); + if (debug_mode) { + printf("unable to bind\n"); + } goto dead; } rv = PR_Listen(listenSock, 4); if (rv == PR_FAILURE) { - if (debug_mode) printf("unable to listen\n"); + if (debug_mode) { + printf("unable to listen\n"); + } goto dead; } - if (debug_mode) printf("thread %d going into accept for %d seconds\n", - info->id, info->accept_timeout + info->id); + if (debug_mode) printf("thread %d going into accept for %d seconds\n", + info->id, info->accept_timeout + info->id); clientSock = PR_Accept(listenSock, &clientAddr, PR_SecondsToInterval(info->accept_timeout +info->id)); if (clientSock == NULL) { - if (PR_GetError() == PR_IO_TIMEOUT_ERROR) + if (PR_GetError() == PR_IO_TIMEOUT_ERROR) if (debug_mode) { - printf("PR_Accept() timeout worked!\n"); + printf("PR_Accept() timeout worked!\n"); printf("TEST FAILED! PR_Accept() returned error %d\n", - PR_GetError()); - } - else failed_already=1; + PR_GetError()); + } + else { + failed_already=1; + } } else { - if (debug_mode) printf ("TEST FAILED! PR_Accept() succeeded?\n"); - else failed_already=1; - PR_Close(clientSock); + if (debug_mode) { + printf ("TEST FAILED! PR_Accept() succeeded?\n"); + } + else { + failed_already=1; + } + PR_Close(clientSock); } dead: if (listenSock) { - PR_Close(listenSock); + PR_Close(listenSock); } PR_Lock(info->dead_lock); (*info->alive)--; PR_NotifyCondVar(info->dead_cv); PR_Unlock(info->dead_lock); - if (debug_mode) printf("thread %d is dead\n", info->id); + if (debug_mode) { + printf("thread %d is dead\n", info->id); + } } void @@ -114,12 +130,14 @@ thread_test(PRInt32 scope, PRInt32 num_threads) PRCondVar *dead_cv; PRInt32 alive; - if (debug_mode) printf("IO Timeout test started with %d threads\n", num_threads); + if (debug_mode) { + printf("IO Timeout test started with %d threads\n", num_threads); + } dead_lock = PR_NewLock(); dead_cv = PR_NewCondVar(dead_lock); alive = num_threads; - + for (index = 0; index < num_threads; index++) { threadInfo *info = (threadInfo *)malloc(sizeof(threadInfo)); @@ -128,7 +146,7 @@ thread_test(PRInt32 scope, PRInt32 num_threads) info->dead_cv = dead_cv; info->alive = &alive; info->accept_timeout = DEFAULT_ACCEPT_TIMEOUT; - + thr = PR_CreateThread( PR_USER_THREAD, thread_main, (void *)info, @@ -146,7 +164,9 @@ thread_test(PRInt32 scope, PRInt32 num_threads) PR_Lock(dead_lock); while(alive) { - if (debug_mode) printf("main loop awake; alive = %d\n", alive); + if (debug_mode) { + printf("main loop awake; alive = %d\n", alive); + } PR_WaitCondVar(dead_cv, PR_INTERVAL_NO_TIMEOUT); } PR_Unlock(dead_lock); @@ -156,46 +176,54 @@ int main(int argc, char **argv) { PRInt32 num_threads; - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - - if (argc > 2) + if (argc > 2) { num_threads = atoi(argv[2]); - else + } + else { num_threads = NUM_THREADS; + } PR_Init(PR_USER_THREAD, PR_PRIORITY_LOW, 0); PR_STDIO_INIT(); - if (debug_mode) printf("kernel level test\n"); + if (debug_mode) { + printf("kernel level test\n"); + } thread_test(PR_GLOBAL_THREAD, num_threads); - PR_Cleanup(); - - if(failed_already) + PR_Cleanup(); + + if(failed_already) { return 1; - else + } + else { return 0; + } } diff --git a/nsprpub/pr/tests/io_timeoutu.c b/nsprpub/pr/tests/io_timeoutu.c index 7b3ba7c92..b6d9ccfa3 100644 --- a/nsprpub/pr/tests/io_timeoutu.c +++ b/nsprpub/pr/tests/io_timeoutu.c @@ -10,12 +10,12 @@ ** ** Modification History: ** 19-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** ** Includes @@ -40,7 +40,7 @@ typedef struct threadInfo { PRIntn failed_already=0; PRIntn debug_mode; -void +void thread_main(void *_info) { threadInfo *info = (threadInfo *)_info; @@ -49,61 +49,77 @@ thread_main(void *_info) PRFileDesc *listenSock = NULL; PRFileDesc *clientSock; PRStatus rv; - - if (debug_mode) printf("thread %d is alive\n", info->id); + + if (debug_mode) { + printf("thread %d is alive\n", info->id); + } listenSock = PR_NewTCPSocket(); if (!listenSock) { - if (debug_mode) printf("unable to create listen socket\n"); + if (debug_mode) { + printf("unable to create listen socket\n"); + } goto dead; } - + listenAddr.inet.family = AF_INET; listenAddr.inet.port = PR_htons(BASE_PORT + info->id); listenAddr.inet.ip = PR_htonl(INADDR_ANY); rv = PR_Bind(listenSock, &listenAddr); if (rv == PR_FAILURE) { - if (debug_mode) printf("unable to bind\n"); + if (debug_mode) { + printf("unable to bind\n"); + } goto dead; } rv = PR_Listen(listenSock, 4); if (rv == PR_FAILURE) { - if (debug_mode) printf("unable to listen\n"); + if (debug_mode) { + printf("unable to listen\n"); + } goto dead; } - if (debug_mode) printf("thread %d going into accept for %d seconds\n", - info->id, info->accept_timeout + info->id); + if (debug_mode) printf("thread %d going into accept for %d seconds\n", + info->id, info->accept_timeout + info->id); clientSock = PR_Accept( - listenSock, &clientAddr, PR_SecondsToInterval( - info->accept_timeout + info->id)); + listenSock, &clientAddr, PR_SecondsToInterval( + info->accept_timeout + info->id)); if (clientSock == NULL) { - if (PR_GetError() == PR_IO_TIMEOUT_ERROR) + if (PR_GetError() == PR_IO_TIMEOUT_ERROR) if (debug_mode) { - printf("PR_Accept() timeout worked!\n"); + printf("PR_Accept() timeout worked!\n"); printf("TEST FAILED! PR_Accept() returned error %d\n", - } - PR_GetError()); - else failed_already=1; + } + PR_GetError()); + else { + failed_already=1; + } } else { - if (debug_mode) printf ("TEST FAILED! PR_Accept() succeeded?\n"); - else failed_already=1; - PR_Close(clientSock); + if (debug_mode) { + printf ("TEST FAILED! PR_Accept() succeeded?\n"); + } + else { + failed_already=1; + } + PR_Close(clientSock); } dead: if (listenSock) { - PR_Close(listenSock); + PR_Close(listenSock); } PR_Lock(info->dead_lock); (*info->alive)--; PR_NotifyCondVar(info->dead_cv); PR_Unlock(info->dead_lock); - if (debug_mode) printf("thread %d is dead\n", info->id); + if (debug_mode) { + printf("thread %d is dead\n", info->id); + } } void @@ -115,12 +131,14 @@ thread_test(PRInt32 scope, PRInt32 num_threads) PRCondVar *dead_cv; PRInt32 alive; - if (debug_mode) printf("IO Timeout test started with %d threads\n", num_threads); + if (debug_mode) { + printf("IO Timeout test started with %d threads\n", num_threads); + } dead_lock = PR_NewLock(); dead_cv = PR_NewCondVar(dead_lock); alive = num_threads; - + for (index = 0; index < num_threads; index++) { threadInfo *info = (threadInfo *)malloc(sizeof(threadInfo)); @@ -129,7 +147,7 @@ thread_test(PRInt32 scope, PRInt32 num_threads) info->dead_cv = dead_cv; info->alive = &alive; info->accept_timeout = DEFAULT_ACCEPT_TIMEOUT; - + thr = PR_CreateThread( PR_USER_THREAD, thread_main, (void *)info, @@ -147,7 +165,9 @@ thread_test(PRInt32 scope, PRInt32 num_threads) PR_Lock(dead_lock); while(alive) { - if (debug_mode) printf("main loop awake; alive = %d\n", alive); + if (debug_mode) { + printf("main loop awake; alive = %d\n", alive); + } PR_WaitCondVar(dead_cv, PR_INTERVAL_NO_TIMEOUT); } PR_Unlock(dead_lock); @@ -157,46 +177,54 @@ int main(int argc, char **argv) { PRInt32 num_threads; - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - - if (argc > 2) + if (argc > 2) { num_threads = atoi(argv[2]); - else + } + else { num_threads = NUM_THREADS; + } PR_Init(PR_USER_THREAD, PR_PRIORITY_LOW, 0); PR_STDIO_INIT(); - if (debug_mode) printf("user level test\n"); + if (debug_mode) { + printf("user level test\n"); + } thread_test(PR_LOCAL_THREAD, num_threads); - PR_Cleanup(); - if(failed_already) + PR_Cleanup(); + if(failed_already) { return 1; - else + } + else { return 0; - + } + } diff --git a/nsprpub/pr/tests/ioconthr.c b/nsprpub/pr/tests/ioconthr.c index 0a1dda874..3f5adcd57 100644 --- a/nsprpub/pr/tests/ioconthr.c +++ b/nsprpub/pr/tests/ioconthr.c @@ -62,8 +62,8 @@ int main(int argc, char **argv) PR_ProcessExit(1); } threads[index] = PR_CreateThread( - PR_USER_THREAD, ThreadFunc, fds[2 * index], - PR_PRIORITY_NORMAL, thread_scope, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, ThreadFunc, fds[2 * index], + PR_PRIORITY_NORMAL, thread_scope, PR_JOINABLE_THREAD, 0); if (NULL == threads[index]) { fprintf(stderr, "PR_CreateThread failed\n"); PR_ProcessExit(1); @@ -90,9 +90,9 @@ int main(int argc, char **argv) } elapsed = (PRIntervalTime)(PR_IntervalNow() - start); printf("Threads terminated in %d milliseconds\n", - PR_IntervalToMilliseconds(elapsed)); + PR_IntervalToMilliseconds(elapsed)); fflush(stdout); - + /* We are being very generous and allow 10 seconds. */ if (elapsed >= PR_SecondsToInterval(10)) { fprintf(stderr, "Interrupting threads took longer than 10 seconds!!\n"); diff --git a/nsprpub/pr/tests/ipv6.c b/nsprpub/pr/tests/ipv6.c index af27d03cd..cc323e1e6 100644 --- a/nsprpub/pr/tests/ipv6.c +++ b/nsprpub/pr/tests/ipv6.c @@ -55,13 +55,17 @@ static PRStatus PrintAddress(const PRNetAddr* address) PRNetAddr translation; char buffer[ADDR_BUFFER]; PRStatus rv = PR_NetAddrToString(address, buffer, sizeof(buffer)); - if (PR_FAILURE == rv) PL_FPrintError(err, "PR_NetAddrToString"); + if (PR_FAILURE == rv) { + PL_FPrintError(err, "PR_NetAddrToString"); + } else { PR_fprintf(err, "\t%s\n", buffer); memset(&translation, 0, sizeof(translation)); rv = PR_StringToNetAddr(buffer, &translation); - if (PR_FAILURE == rv) PL_FPrintError(err, "PR_StringToNetAddr"); + if (PR_FAILURE == rv) { + PL_FPrintError(err, "PR_StringToNetAddr"); + } else { PRSize addr_len = NETADDR_SIZE(address); @@ -91,19 +95,21 @@ int main(int argc, char **argv) while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 0: /* Name of host to lookup */ - name = opt->value; - break; - case 'V': /* Do version discovery */ - version = PR_TRUE; - break; - case 'h': /* user wants some guidance */ - default: - Help(); /* so give him an earful */ - return 2; /* but not a lot else */ + case 0: /* Name of host to lookup */ + name = opt->value; + break; + case 'V': /* Do version discovery */ + version = PR_TRUE; + break; + case 'h': /* user wants some guidance */ + default: + Help(); /* so give him an earful */ + return 2; /* but not a lot else */ } } PL_DestroyOptState(opt); @@ -119,14 +125,16 @@ int main(int argc, char **argv) char *nspr_path = PR_GetEnv("LD_LIBRARY_PATH"); char *nspr_name = PR_GetLibraryName(nspr_path, NSPR_LIB); PRLibrary *runtime = PR_LoadLibrary(nspr_name); - if (NULL == runtime) + if (NULL == runtime) { PL_FPrintError(err, "PR_LoadLibrary"); + } else { versionEntryPointType versionPoint = (versionEntryPointType) - PR_FindSymbol(runtime, "libVersionPoint"); - if (NULL == versionPoint) + PR_FindSymbol(runtime, "libVersionPoint"); + if (NULL == versionPoint) { PL_FPrintError(err, "PR_FindSymbol"); + } else { char buffer[100]; @@ -155,7 +163,9 @@ int main(int argc, char **argv) (void)PR_fprintf(err, " comment: %s\n", version_info->comment); } } - if (NULL != nspr_name) PR_FreeLibraryName(nspr_name); + if (NULL != nspr_name) { + PR_FreeLibraryName(nspr_name); + } } { @@ -192,7 +202,9 @@ int main(int argc, char **argv) do { index = PR_EnumerateHostEnt(index, &host, 0, &address); - if (index > 0) PrintAddress(&address); + if (index > 0) { + PrintAddress(&address); + } else if (-1 == index) { failed = PR_TRUE; diff --git a/nsprpub/pr/tests/join.c b/nsprpub/pr/tests/join.c index ae3873fae..24238e6e0 100644 --- a/nsprpub/pr/tests/join.c +++ b/nsprpub/pr/tests/join.c @@ -10,13 +10,13 @@ ** Description: Tests PR_SetMallocCountdown PR_ClearMallocCountdown functions. ** ** Modification History: -** +** ** 19-May-97 AGarcia - separate the four join tests into different unit test modules. -** AGarcia- Converted the test to accomodate the debug_mode flag. +** AGarcia- Converted the test to accomodate the debug_mode flag. ** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ***********************************************************************/ /*********************************************************************** @@ -35,26 +35,28 @@ /*********************************************************************** ** PRIVATE FUNCTION: Test_Result ** DESCRIPTION: Used in conjunction with the regress tool, prints out the -** status of the test case. +** status of the test case. ** INPUTS: PASS/FAIL ** OUTPUTS: None ** RETURN: None ** SIDE EFFECTS: -** +** ** RESTRICTIONS: ** None ** MEMORY: NA ** ALGORITHM: Determine what the status is and print accordingly. -** +** ***********************************************************************/ static void Test_Result (int result) { - if (result == PASS) + if (result == PASS) { printf ("PASS\n"); - else + } + else { printf ("FAIL\n"); + } exit (1); } @@ -84,45 +86,65 @@ void runTest(PRThreadScope scope1, PRThreadScope scope2) PRThread *low,*high; /* create the low and high priority threads */ - + low = PR_CreateThread(PR_USER_THREAD, - lowPriority, 0, - PR_PRIORITY_LOW, - scope1, - PR_JOINABLE_THREAD, - 0); + lowPriority, 0, + PR_PRIORITY_LOW, + scope1, + PR_JOINABLE_THREAD, + 0); if (!low) { - if (debug_mode) printf("\tcannot create low priority thread\n"); - else Test_Result(FAIL); + if (debug_mode) { + printf("\tcannot create low priority thread\n"); + } + else { + Test_Result(FAIL); + } return; } high = PR_CreateThread(PR_USER_THREAD, - highPriority, 0, - PR_PRIORITY_HIGH, - scope2, - PR_JOINABLE_THREAD, - 0); + highPriority, 0, + PR_PRIORITY_HIGH, + scope2, + PR_JOINABLE_THREAD, + 0); if (!high) { - if (debug_mode) printf("\tcannot create high priority thread\n"); - else Test_Result(FAIL); + if (debug_mode) { + printf("\tcannot create high priority thread\n"); + } + else { + Test_Result(FAIL); + } return; } /* Do the joining for both threads */ if (PR_JoinThread(low) == PR_FAILURE) { - if (debug_mode) printf("\tcannot join low priority thread\n"); - else Test_Result (FAIL); + if (debug_mode) { + printf("\tcannot join low priority thread\n"); + } + else { + Test_Result (FAIL); + } return; } else { - if (debug_mode) printf("\tjoined low priority thread\n"); + if (debug_mode) { + printf("\tjoined low priority thread\n"); + } } if (PR_JoinThread(high) == PR_FAILURE) { - if (debug_mode) printf("\tcannot join high priority thread\n"); - else Test_Result(FAIL); + if (debug_mode) { + printf("\tcannot join high priority thread\n"); + } + else { + Test_Result(FAIL); + } return; } else { - if (debug_mode) printf("\tjoined high priority thread\n"); + if (debug_mode) { + printf("\tjoined high priority thread\n"); + } } } @@ -131,37 +153,57 @@ void joinWithUnjoinable(void) PRThread *thread; /* create the unjoinable thread */ - + thread = PR_CreateThread(PR_USER_THREAD, - unjoinable, 0, - PR_PRIORITY_NORMAL, - PR_GLOBAL_THREAD, - PR_UNJOINABLE_THREAD, - 0); + unjoinable, 0, + PR_PRIORITY_NORMAL, + PR_GLOBAL_THREAD, + PR_UNJOINABLE_THREAD, + 0); if (!thread) { - if (debug_mode) printf("\tcannot create unjoinable thread\n"); - else Test_Result(FAIL); + if (debug_mode) { + printf("\tcannot create unjoinable thread\n"); + } + else { + Test_Result(FAIL); + } return; } if (PR_JoinThread(thread) == PR_SUCCESS) { - if (debug_mode) printf("\tsuccessfully joined with unjoinable thread?!\n"); - else Test_Result(FAIL); + if (debug_mode) { + printf("\tsuccessfully joined with unjoinable thread?!\n"); + } + else { + Test_Result(FAIL); + } return; } else { - if (debug_mode) printf("\tcannot join with unjoinable thread, as expected\n"); + if (debug_mode) { + printf("\tcannot join with unjoinable thread, as expected\n"); + } if (PR_GetError() != PR_INVALID_ARGUMENT_ERROR) { - if (debug_mode) printf("\tWrong error code\n"); - else Test_Result(FAIL); + if (debug_mode) { + printf("\tWrong error code\n"); + } + else { + Test_Result(FAIL); + } return; } } if (PR_Interrupt(thread) == PR_FAILURE) { - if (debug_mode) printf("\tcannot interrupt unjoinable thread\n"); - else Test_Result(FAIL); + if (debug_mode) { + printf("\tcannot interrupt unjoinable thread\n"); + } + else { + Test_Result(FAIL); + } return; } else { - if (debug_mode) printf("\tinterrupted unjoinable thread\n"); + if (debug_mode) { + printf("\tinterrupted unjoinable thread\n"); + } } } @@ -173,24 +215,26 @@ static PRIntn PR_CALLBACK RealMain(int argc, char **argv) test. Usage: test_name -d */ - + PLOptStatus os; PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } PL_DestroyOptState(opt); - /* main test */ + /* main test */ printf("User-User test\n"); runTest(PR_LOCAL_THREAD, PR_LOCAL_THREAD); printf("User-Kernel test\n"); @@ -213,7 +257,7 @@ static PRIntn PR_CALLBACK RealMain(int argc, char **argv) int main(int argc, char **argv) { PRIntn rv; - + PR_STDIO_INIT(); rv = PR_Initialize(RealMain, argc, argv, 0); return rv; diff --git a/nsprpub/pr/tests/joinkk.c b/nsprpub/pr/tests/joinkk.c index dde5d62b1..4e7b2b5e1 100644 --- a/nsprpub/pr/tests/joinkk.c +++ b/nsprpub/pr/tests/joinkk.c @@ -10,15 +10,15 @@ ** Description: Tests PR_SetMallocCountdown PR_ClearMallocCountdown functions. ** ** Modification History: -** +** ** 19-May-97 AGarcia - separate the four join tests into different unit test modules. -** AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** AGarcia- Converted the test to accomodate the debug_mode flag. +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** @@ -36,9 +36,9 @@ PRIntn failed_already=0; PRIntn debug_mode; /* - Program to test joining of threads. Two threads are created. One - to be waited upon until it has started. The other to join after it has - completed. + Program to test joining of threads. Two threads are created. One + to be waited upon until it has started. The other to join after it has + completed. */ @@ -52,98 +52,122 @@ static void highPriority(void *arg) void runTest(PRThreadScope scope1, PRThreadScope scope2) { - PRThread *low,*high; - - /* create the low and high priority threads */ - - low = PR_CreateThread(PR_USER_THREAD, - lowPriority, 0, - PR_PRIORITY_LOW, - scope1, - PR_JOINABLE_THREAD, - 0); - if (!low) { - if (debug_mode) printf("\tcannot create low priority thread\n"); - else failed_already=1; - return; - } - - high = PR_CreateThread(PR_USER_THREAD, - highPriority, 0, - PR_PRIORITY_HIGH, - scope2, - PR_JOINABLE_THREAD, - 0); - if (!high) { - if (debug_mode) printf("\tcannot create high priority thread\n"); - else failed_already=1; - return; - } - - /* Do the joining for both threads */ - if (PR_JoinThread(low) == PR_FAILURE) { - if (debug_mode) printf("\tcannot join low priority thread\n"); - else failed_already=1; - return; - } else { - if (debug_mode) printf("\tjoined low priority thread\n"); + PRThread *low,*high; + + /* create the low and high priority threads */ + + low = PR_CreateThread(PR_USER_THREAD, + lowPriority, 0, + PR_PRIORITY_LOW, + scope1, + PR_JOINABLE_THREAD, + 0); + if (!low) { + if (debug_mode) { + printf("\tcannot create low priority thread\n"); + } + else { + failed_already=1; + } + return; + } + + high = PR_CreateThread(PR_USER_THREAD, + highPriority, 0, + PR_PRIORITY_HIGH, + scope2, + PR_JOINABLE_THREAD, + 0); + if (!high) { + if (debug_mode) { + printf("\tcannot create high priority thread\n"); + } + else { + failed_already=1; + } + return; + } + + /* Do the joining for both threads */ + if (PR_JoinThread(low) == PR_FAILURE) { + if (debug_mode) { + printf("\tcannot join low priority thread\n"); + } + else { + failed_already=1; + } + return; + } else { + if (debug_mode) { + printf("\tjoined low priority thread\n"); + } } - if (PR_JoinThread(high) == PR_FAILURE) { - if (debug_mode) printf("\tcannot join high priority thread\n"); - else failed_already=1; - return; - } else { - if (debug_mode) printf("\tjoined high priority thread\n"); + if (PR_JoinThread(high) == PR_FAILURE) { + if (debug_mode) { + printf("\tcannot join high priority thread\n"); + } + else { + failed_already=1; + } + return; + } else { + if (debug_mode) { + printf("\tjoined high priority thread\n"); + } } } static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) { - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); - /* main test */ + /* main test */ - if (debug_mode) printf("Kernel-Kernel test\n"); + if (debug_mode) { + printf("Kernel-Kernel test\n"); + } runTest(PR_GLOBAL_THREAD, PR_GLOBAL_THREAD); - if(failed_already) - { + if(failed_already) + { printf("FAIL\n"); - return 1; - } - else - { + return 1; + } + else + { printf("PASS\n"); - return 0; - } + return 0; + } } int main(int argc, char **argv) { PRIntn rv; - + PR_STDIO_INIT(); rv = PR_Initialize(RealMain, argc, argv, 0); return rv; diff --git a/nsprpub/pr/tests/joinku.c b/nsprpub/pr/tests/joinku.c index f18894cde..cd83b6cb4 100644 --- a/nsprpub/pr/tests/joinku.c +++ b/nsprpub/pr/tests/joinku.c @@ -10,15 +10,15 @@ ** Description: Tests PR_SetMallocCountdown PR_ClearMallocCountdown functions. ** ** Modification History: -** +** ** 19-May-97 AGarcia - separate the four join tests into different unit test modules. -** AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** AGarcia- Converted the test to accomodate the debug_mode flag. +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** @@ -38,9 +38,9 @@ PRIntn debug_mode; /* - Program to test joining of threads. Two threads are created. One - to be waited upon until it has started. The other to join after it has - completed. + Program to test joining of threads. Two threads are created. One + to be waited upon until it has started. The other to join after it has + completed. */ @@ -54,95 +54,119 @@ static void highPriority(void *arg) void runTest(PRThreadScope scope1, PRThreadScope scope2) { - PRThread *low,*high; - - /* create the low and high priority threads */ - - low = PR_CreateThread(PR_USER_THREAD, - lowPriority, 0, - PR_PRIORITY_LOW, - scope1, - PR_JOINABLE_THREAD, - 0); - if (!low) { - if (debug_mode) printf("\tcannot create low priority thread\n"); - else failed_already=1; - return; - } - - high = PR_CreateThread(PR_USER_THREAD, - highPriority, 0, - PR_PRIORITY_HIGH, - scope2, - PR_JOINABLE_THREAD, - 0); - if (!high) { - if (debug_mode) printf("\tcannot create high priority thread\n"); - else failed_already=1; - return; - } - - /* Do the joining for both threads */ - if (PR_JoinThread(low) == PR_FAILURE) { - if (debug_mode) printf("\tcannot join low priority thread\n"); - else failed_already=1; - return; - } else { - if (debug_mode) printf("\tjoined low priority thread\n"); + PRThread *low,*high; + + /* create the low and high priority threads */ + + low = PR_CreateThread(PR_USER_THREAD, + lowPriority, 0, + PR_PRIORITY_LOW, + scope1, + PR_JOINABLE_THREAD, + 0); + if (!low) { + if (debug_mode) { + printf("\tcannot create low priority thread\n"); + } + else { + failed_already=1; + } + return; } - if (PR_JoinThread(high) == PR_FAILURE) { - if (debug_mode) printf("\tcannot join high priority thread\n"); - else failed_already=1; - return; - } else { - if (debug_mode) printf("\tjoined high priority thread\n"); + + high = PR_CreateThread(PR_USER_THREAD, + highPriority, 0, + PR_PRIORITY_HIGH, + scope2, + PR_JOINABLE_THREAD, + 0); + if (!high) { + if (debug_mode) { + printf("\tcannot create high priority thread\n"); + } + else { + failed_already=1; + } + return; + } + + /* Do the joining for both threads */ + if (PR_JoinThread(low) == PR_FAILURE) { + if (debug_mode) { + printf("\tcannot join low priority thread\n"); + } + else { + failed_already=1; + } + return; + } else { + if (debug_mode) { + printf("\tjoined low priority thread\n"); + } + } + if (PR_JoinThread(high) == PR_FAILURE) { + if (debug_mode) { + printf("\tcannot join high priority thread\n"); + } + else { + failed_already=1; + } + return; + } else { + if (debug_mode) { + printf("\tjoined high priority thread\n"); + } } } static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) { - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); - /* main test */ + /* main test */ - if (debug_mode) printf("Kernel-User test\n"); + if (debug_mode) { + printf("Kernel-User test\n"); + } runTest(PR_GLOBAL_THREAD, PR_LOCAL_THREAD); - if(failed_already) + if(failed_already) + { + printf("FAIL\n"); + return 1; + } + else { - printf("FAIL\n"); - return 1; - } - else - { - printf("PASS\n"); - return 0; - } + printf("PASS\n"); + return 0; + } } @@ -150,7 +174,7 @@ static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) int main(int argc, char **argv) { PRIntn rv; - + PR_STDIO_INIT(); rv = PR_Initialize(RealMain, argc, argv, 0); return rv; diff --git a/nsprpub/pr/tests/joinuk.c b/nsprpub/pr/tests/joinuk.c index 3b496fcd3..418c5e0e9 100644 --- a/nsprpub/pr/tests/joinuk.c +++ b/nsprpub/pr/tests/joinuk.c @@ -10,15 +10,15 @@ ** Description: Join kernel - user ** ** Modification History: -** +** ** 19-May-97 AGarcia - separate the four join tests into different unit test modules. -** AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** AGarcia- Converted the test to accomodate the debug_mode flag. +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** @@ -36,9 +36,9 @@ PRIntn failed_already=0; PRIntn debug_mode; /* - Program to test joining of threads. Two threads are created. One - to be waited upon until it has started. The other to join after it has - completed. + Program to test joining of threads. Two threads are created. One + to be waited upon until it has started. The other to join after it has + completed. */ @@ -52,93 +52,117 @@ static void highPriority(void *arg) void runTest(PRThreadScope scope1, PRThreadScope scope2) { - PRThread *low,*high; - - /* create the low and high priority threads */ - - low = PR_CreateThread(PR_USER_THREAD, - lowPriority, 0, - PR_PRIORITY_LOW, - scope1, - PR_JOINABLE_THREAD, - 0); - if (!low) { - if (debug_mode) printf("\tcannot create low priority thread\n"); - else failed_already=1; - return; - } - - high = PR_CreateThread(PR_USER_THREAD, - highPriority, 0, - PR_PRIORITY_HIGH, - scope2, - PR_JOINABLE_THREAD, - 0); - if (!high) { - if (debug_mode) printf("\tcannot create high priority thread\n"); - else failed_already=1; - return; - } - - /* Do the joining for both threads */ - if (PR_JoinThread(low) == PR_FAILURE) { - if (debug_mode) printf("\tcannot join low priority thread\n"); - else failed_already=1; - return; - } else { - if (debug_mode) printf("\tjoined low priority thread\n"); + PRThread *low,*high; + + /* create the low and high priority threads */ + + low = PR_CreateThread(PR_USER_THREAD, + lowPriority, 0, + PR_PRIORITY_LOW, + scope1, + PR_JOINABLE_THREAD, + 0); + if (!low) { + if (debug_mode) { + printf("\tcannot create low priority thread\n"); + } + else { + failed_already=1; + } + return; } - if (PR_JoinThread(high) == PR_FAILURE) { - if (debug_mode) printf("\tcannot join high priority thread\n"); - else failed_already=1; - return; - } else { - if (debug_mode) printf("\tjoined high priority thread\n"); + + high = PR_CreateThread(PR_USER_THREAD, + highPriority, 0, + PR_PRIORITY_HIGH, + scope2, + PR_JOINABLE_THREAD, + 0); + if (!high) { + if (debug_mode) { + printf("\tcannot create high priority thread\n"); + } + else { + failed_already=1; + } + return; + } + + /* Do the joining for both threads */ + if (PR_JoinThread(low) == PR_FAILURE) { + if (debug_mode) { + printf("\tcannot join low priority thread\n"); + } + else { + failed_already=1; + } + return; + } else { + if (debug_mode) { + printf("\tjoined low priority thread\n"); + } + } + if (PR_JoinThread(high) == PR_FAILURE) { + if (debug_mode) { + printf("\tcannot join high priority thread\n"); + } + else { + failed_already=1; + } + return; + } else { + if (debug_mode) { + printf("\tjoined high priority thread\n"); + } } } static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) { - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); - /* main test */ + /* main test */ - if (debug_mode) printf("User-Kernel test\n"); + if (debug_mode) { + printf("User-Kernel test\n"); + } runTest(PR_LOCAL_THREAD, PR_GLOBAL_THREAD); - if(failed_already) - { + if(failed_already) + { printf("FAIL\n"); - return 1; - } else + return 1; + } else { printf("PASS\n"); - return 0; + return 0; } } @@ -146,7 +170,7 @@ static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) int main(int argc, char **argv) { PRIntn rv; - + PR_STDIO_INIT(); rv = PR_Initialize(RealMain, argc, argv, 0); return rv; diff --git a/nsprpub/pr/tests/joinuu.c b/nsprpub/pr/tests/joinuu.c index 9b7d8c212..4d30bfa7c 100644 --- a/nsprpub/pr/tests/joinuu.c +++ b/nsprpub/pr/tests/joinuu.c @@ -10,15 +10,15 @@ ** Description: Join tests user - user ** ** Modification History: -** +** ** 19-May-97 AGarcia - separate the four join tests into different unit test modules. -** AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** AGarcia- Converted the test to accomodate the debug_mode flag. +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** @@ -38,9 +38,9 @@ PRIntn debug_mode; /* - Program to test joining of threads. Two threads are created. One - to be waited upon until it has started. The other to join after it has - completed. + Program to test joining of threads. Two threads are created. One + to be waited upon until it has started. The other to join after it has + completed. */ @@ -54,91 +54,115 @@ static void highPriority(void *arg) void runTest(PRThreadScope scope1, PRThreadScope scope2) { - PRThread *low,*high; - - /* create the low and high priority threads */ - - low = PR_CreateThread(PR_USER_THREAD, - lowPriority, 0, - PR_PRIORITY_LOW, - scope1, - PR_JOINABLE_THREAD, - 0); - if (!low) { - if (debug_mode) printf("\tcannot create low priority thread\n"); - else failed_already=1; - return; - } - - high = PR_CreateThread(PR_USER_THREAD, - highPriority, 0, - PR_PRIORITY_HIGH, - scope2, - PR_JOINABLE_THREAD, - 0); - if (!high) { - if (debug_mode) printf("\tcannot create high priority thread\n"); - else failed_already=1; - return; - } - - /* Do the joining for both threads */ - if (PR_JoinThread(low) == PR_FAILURE) { - if (debug_mode) printf("\tcannot join low priority thread\n"); - else failed_already=1; - return; - } else { - if (debug_mode) printf("\tjoined low priority thread\n"); + PRThread *low,*high; + + /* create the low and high priority threads */ + + low = PR_CreateThread(PR_USER_THREAD, + lowPriority, 0, + PR_PRIORITY_LOW, + scope1, + PR_JOINABLE_THREAD, + 0); + if (!low) { + if (debug_mode) { + printf("\tcannot create low priority thread\n"); + } + else { + failed_already=1; + } + return; } - if (PR_JoinThread(high) == PR_FAILURE) { - if (debug_mode) printf("\tcannot join high priority thread\n"); - else failed_already=1; - return; - } else { - if (debug_mode) printf("\tjoined high priority thread\n"); + + high = PR_CreateThread(PR_USER_THREAD, + highPriority, 0, + PR_PRIORITY_HIGH, + scope2, + PR_JOINABLE_THREAD, + 0); + if (!high) { + if (debug_mode) { + printf("\tcannot create high priority thread\n"); + } + else { + failed_already=1; + } + return; + } + + /* Do the joining for both threads */ + if (PR_JoinThread(low) == PR_FAILURE) { + if (debug_mode) { + printf("\tcannot join low priority thread\n"); + } + else { + failed_already=1; + } + return; + } else { + if (debug_mode) { + printf("\tjoined low priority thread\n"); + } + } + if (PR_JoinThread(high) == PR_FAILURE) { + if (debug_mode) { + printf("\tcannot join high priority thread\n"); + } + else { + failed_already=1; + } + return; + } else { + if (debug_mode) { + printf("\tjoined high priority thread\n"); + } } } static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) { - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); - /* main test */ - if (debug_mode) printf("User-User test\n"); + /* main test */ + if (debug_mode) { + printf("User-User test\n"); + } runTest(PR_LOCAL_THREAD, PR_LOCAL_THREAD); - if(failed_already) - { + if(failed_already) + { printf("FAIL\n"); - return 1; - } else + return 1; + } else { printf("PASS\n"); - return 0; + return 0; } @@ -148,7 +172,7 @@ static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) int main(int argc, char **argv) { PRIntn rv; - + PR_STDIO_INIT(); rv = PR_Initialize(RealMain, argc, argv, 0); return rv; diff --git a/nsprpub/pr/tests/layer.c b/nsprpub/pr/tests/layer.c index 82af3d392..8579394dc 100644 --- a/nsprpub/pr/tests/layer.c +++ b/nsprpub/pr/tests/layer.c @@ -46,42 +46,43 @@ static PRFileDesc *PushLayer(PRFileDesc *stack) { PRFileDesc *layer = PR_CreateIOLayerStub(identity, &myMethods); PRStatus rv = PR_PushIOLayer(stack, PR_GetLayersIdentity(stack), layer); - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(logFile, "Pushed layer(0x%x) onto stack(0x%x)\n", layer, stack); + } PR_ASSERT(PR_SUCCESS == rv); return stack; } /* PushLayer */ static PRFileDesc *PushNewLayers(PRFileDesc *stack) { - PRDescIdentity tmp_identity; + PRDescIdentity tmp_identity; PRFileDesc *layer; PRStatus rv; - /* push a dummy layer */ + /* push a dummy layer */ tmp_identity = PR_GetUniqueIdentity("Dummy 1"); layer = PR_CreateIOLayerStub(tmp_identity, PR_GetDefaultIOMethods()); rv = PR_PushIOLayer(stack, PR_GetLayersIdentity(stack), layer); if (verbosity > quiet) PR_fprintf(logFile, "Pushed layer(0x%x) onto stack(0x%x)\n", layer, - stack); + stack); PR_ASSERT(PR_SUCCESS == rv); - /* push a data procesing layer */ + /* push a data processing layer */ layer = PR_CreateIOLayerStub(identity, &myMethods); rv = PR_PushIOLayer(stack, PR_GetLayersIdentity(stack), layer); if (verbosity > quiet) PR_fprintf(logFile, "Pushed layer(0x%x) onto stack(0x%x)\n", layer, - stack); + stack); PR_ASSERT(PR_SUCCESS == rv); - /* push another dummy layer */ + /* push another dummy layer */ tmp_identity = PR_GetUniqueIdentity("Dummy 2"); layer = PR_CreateIOLayerStub(tmp_identity, PR_GetDefaultIOMethods()); rv = PR_PushIOLayer(stack, PR_GetLayersIdentity(stack), layer); if (verbosity > quiet) PR_fprintf(logFile, "Pushed layer(0x%x) onto stack(0x%x)\n", layer, - stack); + stack); PR_ASSERT(PR_SUCCESS == rv); return stack; } /* PushLayer */ @@ -90,10 +91,11 @@ static PRFileDesc *PushNewLayers(PRFileDesc *stack) static PRFileDesc *PopLayer(PRFileDesc *stack) { PRFileDesc *popped = PR_PopIOLayer(stack, identity); - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(logFile, "Popped layer(0x%x) from stack(0x%x)\n", popped, stack); + } popped->dtor(popped); - + return stack; } /* PopLayer */ #endif @@ -114,20 +116,23 @@ static void PR_CALLBACK Client(void *arg) while (minor_iterations-- > 0) { bytes_sent = PR_Send( - stack, buffer, sizeof(buffer), empty_flags, PR_INTERVAL_NO_TIMEOUT); + stack, buffer, sizeof(buffer), empty_flags, PR_INTERVAL_NO_TIMEOUT); PR_ASSERT(sizeof(buffer) == bytes_sent); - if (verbosity > chatty) + if (verbosity > chatty) { PR_fprintf(logFile, "Client sending %d bytes\n", bytes_sent); + } bytes_read = PR_Recv( - stack, buffer, bytes_sent, empty_flags, PR_INTERVAL_NO_TIMEOUT); - if (verbosity > chatty) + stack, buffer, bytes_sent, empty_flags, PR_INTERVAL_NO_TIMEOUT); + if (verbosity > chatty) { PR_fprintf(logFile, "Client receiving %d bytes\n", bytes_read); + } PR_ASSERT(bytes_read == bytes_sent); } - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(logFile, "Client shutting down stack\n"); - + } + rv = PR_Shutdown(stack, PR_SHUTDOWN_BOTH); PR_ASSERT(PR_SUCCESS == rv); } /* Client */ @@ -142,29 +147,33 @@ static void PR_CALLBACK Server(void *arg) PRNetAddr client_address; service = PR_Accept(stack, &client_address, PR_INTERVAL_NO_TIMEOUT); - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(logFile, "Server accepting connection\n"); + } do { bytes_read = PR_Recv( - service, buffer, sizeof(buffer), empty_flags, PR_INTERVAL_NO_TIMEOUT); + service, buffer, sizeof(buffer), empty_flags, PR_INTERVAL_NO_TIMEOUT); if (0 != bytes_read) { - if (verbosity > chatty) + if (verbosity > chatty) { PR_fprintf(logFile, "Server receiving %d bytes\n", bytes_read); + } PR_ASSERT(bytes_read > 0); bytes_sent = PR_Send( - service, buffer, bytes_read, empty_flags, PR_INTERVAL_NO_TIMEOUT); - if (verbosity > chatty) + service, buffer, bytes_read, empty_flags, PR_INTERVAL_NO_TIMEOUT); + if (verbosity > chatty) { PR_fprintf(logFile, "Server sending %d bytes\n", bytes_sent); + } PR_ASSERT(bytes_read == bytes_sent); } } while (0 != bytes_read); - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(logFile, "Server shutting down and closing stack\n"); + } rv = PR_Shutdown(service, PR_SHUTDOWN_BOTH); PR_ASSERT(PR_SUCCESS == rv); rv = PR_Close(service); PR_ASSERT(PR_SUCCESS == rv); @@ -179,24 +188,26 @@ static PRInt32 PR_CALLBACK MyRecv( PRInt32 rv, readin = 0, request = 0; rv = lo->methods->recv(lo, &request, sizeof(request), flags, timeout); if (verbosity > chatty) PR_fprintf( - logFile, "MyRecv sending permission for %d bytes\n", request); + logFile, "MyRecv sending permission for %d bytes\n", request); if (0 < rv) { if (verbosity > chatty) PR_fprintf( - logFile, "MyRecv received permission request for %d bytes\n", request); + logFile, "MyRecv received permission request for %d bytes\n", request); rv = lo->methods->send( - lo, &request, sizeof(request), flags, timeout); + lo, &request, sizeof(request), flags, timeout); if (0 < rv) { if (verbosity > chatty) PR_fprintf( - logFile, "MyRecv sending permission for %d bytes\n", request); + logFile, "MyRecv sending permission for %d bytes\n", request); while (readin < request) { rv = lo->methods->recv( - lo, b + readin, amount - readin, flags, timeout); - if (rv <= 0) break; + lo, b + readin, amount - readin, flags, timeout); + if (rv <= 0) { + break; + } if (verbosity > chatty) PR_fprintf( - logFile, "MyRecv received %d bytes\n", rv); + logFile, "MyRecv received %d bytes\n", rv); readin += rv; } rv = readin; @@ -213,24 +224,26 @@ static PRInt32 PR_CALLBACK MySend( const char *b = (const char*)buf; PRInt32 rv, wroteout = 0, request; if (verbosity > chatty) PR_fprintf( - logFile, "MySend asking permission to send %d bytes\n", amount); + logFile, "MySend asking permission to send %d bytes\n", amount); rv = lo->methods->send(lo, &amount, sizeof(amount), flags, timeout); if (0 < rv) { rv = lo->methods->recv( - lo, &request, sizeof(request), flags, timeout); + lo, &request, sizeof(request), flags, timeout); if (0 < rv) { PR_ASSERT(request == amount); if (verbosity > chatty) PR_fprintf( - logFile, "MySend got permission to send %d bytes\n", request); + logFile, "MySend got permission to send %d bytes\n", request); while (wroteout < request) { rv = lo->methods->send( - lo, b + wroteout, request - wroteout, flags, timeout); - if (rv <= 0) break; + lo, b + wroteout, request - wroteout, flags, timeout); + if (rv <= 0) { + break; + } if (verbosity > chatty) PR_fprintf( - logFile, "MySend wrote %d bytes\n", rv); + logFile, "MySend wrote %d bytes\n", rv); wroteout += rv; } rv = amount; @@ -242,8 +255,12 @@ static PRInt32 PR_CALLBACK MySend( static Verbosity ChangeVerbosity(Verbosity verbosity, PRIntn delta) { PRIntn verbage = (PRIntn)verbosity + delta; - if (verbage < (PRIntn)silent) verbage = (PRIntn)silent; - else if (verbage > (PRIntn)noisy) verbage = (PRIntn)noisy; + if (verbage < (PRIntn)silent) { + verbage = (PRIntn)silent; + } + else if (verbage > (PRIntn)noisy) { + verbage = (PRIntn)noisy; + } return (Verbosity)verbage; } /* ChangeVerbosity */ @@ -262,34 +279,38 @@ int main(int argc, char **argv) PLOptState *opt = PL_CreateOptState(argc, argv, "dqGC:c:p:"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 0: - server_name = opt->value; - break; - case 'd': /* debug mode */ - if (verbosity < noisy) - verbosity = ChangeVerbosity(verbosity, 1); - break; - case 'q': /* debug mode */ - if (verbosity > silent) - verbosity = ChangeVerbosity(verbosity, -1); - break; - case 'G': /* use global threads */ - thread_scope = PR_GLOBAL_THREAD; - break; - case 'C': /* number of threads waiting */ - major_iterations = atoi(opt->value); - break; - case 'c': /* number of client threads */ - minor_iterations = atoi(opt->value); - break; - case 'p': /* default port */ - default_port = atoi(opt->value); - break; - default: - break; + case 0: + server_name = opt->value; + break; + case 'd': /* debug mode */ + if (verbosity < noisy) { + verbosity = ChangeVerbosity(verbosity, 1); + } + break; + case 'q': /* debug mode */ + if (verbosity > silent) { + verbosity = ChangeVerbosity(verbosity, -1); + } + break; + case 'G': /* use global threads */ + thread_scope = PR_GLOBAL_THREAD; + break; + case 'C': /* number of threads waiting */ + major_iterations = atoi(opt->value); + break; + case 'c': /* number of client threads */ + minor_iterations = atoi(opt->value); + break; + case 'p': /* default port */ + default_port = atoi(opt->value); + break; + default: + break; } } PL_DestroyOptState(opt); @@ -311,13 +332,13 @@ int main(int argc, char **argv) if (NULL == server_name) rv = PR_InitializeNetAddr( - PR_IpAddrLoopback, default_port, &server_address); + PR_IpAddrLoopback, default_port, &server_address); else { rv = PR_StringToNetAddr(server_name, &server_address); PR_ASSERT(PR_SUCCESS == rv); rv = PR_InitializeNetAddr( - PR_IpAddrNull, default_port, &server_address); + PR_IpAddrNull, default_port, &server_address); } PR_ASSERT(PR_SUCCESS == rv); @@ -326,8 +347,9 @@ int main(int argc, char **argv) mits = minor_iterations; while (major_iterations-- > 0) { - if (verbosity > silent) + if (verbosity > silent) { PR_fprintf(logFile, "Beginning non-layered test\n"); + } client = PR_NewTCPSocket(); PR_ASSERT(NULL != client); service = PR_NewTCPSocket(); PR_ASSERT(NULL != service); rv = PR_InitializeNetAddr(PR_IpAddrAny, default_port, &any_address); @@ -337,15 +359,15 @@ int main(int argc, char **argv) minor_iterations = mits; server_thread = PR_CreateThread( - PR_USER_THREAD, Server, service, - PR_PRIORITY_HIGH, thread_scope, - PR_JOINABLE_THREAD, 16 * 1024); + PR_USER_THREAD, Server, service, + PR_PRIORITY_HIGH, thread_scope, + PR_JOINABLE_THREAD, 16 * 1024); PR_ASSERT(NULL != server_thread); client_thread = PR_CreateThread( - PR_USER_THREAD, Client, client, - PR_PRIORITY_NORMAL, thread_scope, - PR_JOINABLE_THREAD, 16 * 1024); + PR_USER_THREAD, Client, client, + PR_PRIORITY_NORMAL, thread_scope, + PR_JOINABLE_THREAD, 16 * 1024); PR_ASSERT(NULL != client_thread); rv = PR_JoinThread(client_thread); @@ -355,12 +377,14 @@ int main(int argc, char **argv) rv = PR_Close(client); PR_ASSERT(PR_SUCCESS == rv); rv = PR_Close(service); PR_ASSERT(PR_SUCCESS == rv); - if (verbosity > silent) + if (verbosity > silent) { PR_fprintf(logFile, "Ending non-layered test\n"); + } /* with layering */ - if (verbosity > silent) + if (verbosity > silent) { PR_fprintf(logFile, "Beginning layered test\n"); + } client = PR_NewTCPSocket(); PR_ASSERT(NULL != client); PushLayer(client); service = PR_NewTCPSocket(); PR_ASSERT(NULL != service); @@ -372,15 +396,15 @@ int main(int argc, char **argv) minor_iterations = mits; server_thread = PR_CreateThread( - PR_USER_THREAD, Server, service, - PR_PRIORITY_HIGH, thread_scope, - PR_JOINABLE_THREAD, 16 * 1024); + PR_USER_THREAD, Server, service, + PR_PRIORITY_HIGH, thread_scope, + PR_JOINABLE_THREAD, 16 * 1024); PR_ASSERT(NULL != server_thread); client_thread = PR_CreateThread( - PR_USER_THREAD, Client, client, - PR_PRIORITY_NORMAL, thread_scope, - PR_JOINABLE_THREAD, 16 * 1024); + PR_USER_THREAD, Client, client, + PR_PRIORITY_NORMAL, thread_scope, + PR_JOINABLE_THREAD, 16 * 1024); PR_ASSERT(NULL != client_thread); rv = PR_JoinThread(client_thread); @@ -393,12 +417,12 @@ int main(int argc, char **argv) /* with layering, using new style stack */ if (verbosity > silent) PR_fprintf(logFile, - "Beginning layered test with new style stack\n"); + "Beginning layered test with new style stack\n"); client = PR_NewTCPSocket(); PR_ASSERT(NULL != client); - client_stack = PR_CreateIOLayer(client); + client_stack = PR_CreateIOLayer(client); PushNewLayers(client_stack); service = PR_NewTCPSocket(); PR_ASSERT(NULL != service); - service_stack = PR_CreateIOLayer(service); + service_stack = PR_CreateIOLayer(service); PushNewLayers(service_stack); rv = PR_InitializeNetAddr(PR_IpAddrAny, default_port, &any_address); PR_ASSERT(PR_SUCCESS == rv); @@ -407,15 +431,15 @@ int main(int argc, char **argv) minor_iterations = mits; server_thread = PR_CreateThread( - PR_USER_THREAD, Server, service_stack, - PR_PRIORITY_HIGH, thread_scope, - PR_JOINABLE_THREAD, 16 * 1024); + PR_USER_THREAD, Server, service_stack, + PR_PRIORITY_HIGH, thread_scope, + PR_JOINABLE_THREAD, 16 * 1024); PR_ASSERT(NULL != server_thread); client_thread = PR_CreateThread( - PR_USER_THREAD, Client, client_stack, - PR_PRIORITY_NORMAL, thread_scope, - PR_JOINABLE_THREAD, 16 * 1024); + PR_USER_THREAD, Client, client_stack, + PR_PRIORITY_NORMAL, thread_scope, + PR_JOINABLE_THREAD, 16 * 1024); PR_ASSERT(NULL != client_thread); rv = PR_JoinThread(client_thread); @@ -425,8 +449,9 @@ int main(int argc, char **argv) rv = PR_Close(client_stack); PR_ASSERT(PR_SUCCESS == rv); rv = PR_Close(service_stack); PR_ASSERT(PR_SUCCESS == rv); - if (verbosity > silent) + if (verbosity > silent) { PR_fprintf(logFile, "Ending layered test\n"); + } } return 0; } /* main */ diff --git a/nsprpub/pr/tests/lazyinit.c b/nsprpub/pr/tests/lazyinit.c index 4b9a910c3..5ec1c9578 100644 --- a/nsprpub/pr/tests/lazyinit.c +++ b/nsprpub/pr/tests/lazyinit.c @@ -53,49 +53,50 @@ int main(int argc, char **argv) { test = 0; } - else + else { test = atoi(argv[1]); - + } + switch (test) { - case 0: ml = PR_NewLock(); + case 0: ml = PR_NewLock(); break; - + case 1: interval = PR_SecondsToInterval(1); break; - + case 2: thread = PR_CreateThread( - PR_USER_THREAD, lazyEntry, NULL, PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, lazyEntry, NULL, PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); break; - - case 3: file = PR_Open("/usr/tmp/", PR_RDONLY, 0); + + case 3: file = PR_Open("/usr/tmp/", PR_RDONLY, 0); break; - - case 4: udp = PR_NewUDPSocket(); + + case 4: udp = PR_NewUDPSocket(); break; - - case 5: tcp = PR_NewTCPSocket(); + + case 5: tcp = PR_NewTCPSocket(); break; - - case 6: dir = PR_OpenDir("/usr/tmp/"); + + case 6: dir = PR_OpenDir("/usr/tmp/"); break; - + case 7: (void)PR_NewThreadPrivateIndex(&pdkey, NULL); break; - + case 8: path = PR_GetEnv("PATH"); break; - + case 9: status = PR_NewTCPSocketPair(pair); break; - + case 10: PR_SetConcurrency(2); break; - - default: + + default: printf( - "lazyinit: unrecognized command line argument: %s\n", + "lazyinit: unrecognized command line argument: %s\n", argv[1] ); printf( "FAIL\n" ); exit( 1 ); diff --git a/nsprpub/pr/tests/libfilename.c b/nsprpub/pr/tests/libfilename.c index 66bb45c89..09d0980de 100644 --- a/nsprpub/pr/tests/libfilename.c +++ b/nsprpub/pr/tests/libfilename.c @@ -34,7 +34,9 @@ static PRStatus RunTest(const char *name, PRFuncPtr addr) return PR_FAILURE; } - if (debug_mode) printf("Pathname is %s\n", pathname); + if (debug_mode) { + printf("Pathname is %s\n", pathname); + } fd = PR_OpenFile(pathname, PR_RDONLY, 0); if (fd == NULL) { fprintf(stderr, "PR_Open failed: %d\n", (int)PR_GetError()); @@ -74,7 +76,9 @@ int main(int argc, char **argv) /* Next test a library that is dynamically loaded. */ name = PR_GetLibraryName("dll", "my"); - if (debug_mode) printf("Loading library %s\n", name); + if (debug_mode) { + printf("Loading library %s\n", name); + } lib = PR_LoadLibrary(name); if (!lib) { fprintf(stderr, "PR_LoadLibrary failed\n"); diff --git a/nsprpub/pr/tests/lltest.c b/nsprpub/pr/tests/lltest.c index 7e21e76f3..26f7d8ead 100644 --- a/nsprpub/pr/tests/lltest.c +++ b/nsprpub/pr/tests/lltest.c @@ -2,7 +2,7 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - + /* ** testll.c -- test suite for 64bit integer (longlong) operations ** @@ -15,11 +15,11 @@ ** ** Description: ** lltest.c tests the functions defined in NSPR 2.0's prlong.h. -** +** ** Successive tests begin to depend on other LL functions working ** correctly. So, ... Do not change the order of the tests as run ** from main(). -** +** ** Caveats: ** Do not even begin to think that this is an exhaustive test! ** @@ -54,8 +54,8 @@ static PRBool verboseMode = PR_FALSE; const PRInt64 bigZero = LL_INIT( 0, 0 ); const PRInt64 bigOne = LL_INIT( 0, 1 ); const PRInt64 bigTwo = LL_INIT( 0, 2 ); -const PRInt64 bigSixTeen = LL_INIT( 0, 16 ); -const PRInt64 bigThirtyTwo = LL_INIT( 0, 32 ); +const PRInt64 bigSixTeen = LL_INIT( 0, 16 ); +const PRInt64 bigThirtyTwo = LL_INIT( 0, 32 ); const PRInt64 bigMinusOne = LL_INIT( 0xffffffff, 0xffffffff ); const PRInt64 bigMinusTwo = LL_INIT( 0xffffffff, 0xfffffffe ); const PRInt64 bigNumber = LL_INIT( 0x7fffffff, 0xffffffff ); @@ -93,8 +93,9 @@ static void SetFailed( char *what, char *how ) { failedAlready = 1; - if ( debugMode ) + if ( debugMode ) { PR_fprintf(output, "%s: failed: %s\n", what, how ); + } return; } @@ -107,7 +108,7 @@ ResultFailed( char *what, char *how, PRInt64 expected, PRInt64 got) PR_fprintf(output, "Expected: 0x%llx Got: 0x%llx\n", expected, got ); } return; -} +} /* @@ -118,241 +119,313 @@ static void TestAssignment( void ) PRInt64 zero = LL_Zero(); PRInt64 min = LL_MinInt(); PRInt64 max = LL_MaxInt(); - if (!LL_EQ(zero, bigZero)) + if (!LL_EQ(zero, bigZero)) { SetFailed("LL_EQ(zero, bigZero)", "!="); - if (!LL_CMP(max, >, min)) + } + if (!LL_CMP(max, >, min)) { SetFailed("LL_CMP(max, >, min)", "!>"); + } } /* ** TestComparisons() -- Test the longlong comparison operations */ -static void +static void TestComparisons( void ) { ReportProgress("Testing Comparisons Operations\n"); - - /* test for zero */ - if ( !LL_IS_ZERO( bigZero )) + + /* test for zero */ + if ( !LL_IS_ZERO( bigZero )) { SetFailed( "LL_IS_ZERO", "Zero is not zero" ); - - if ( LL_IS_ZERO( bigOne )) + } + + if ( LL_IS_ZERO( bigOne )) { SetFailed( "LL_IS_ZERO", "One tests as zero" ); - - if ( LL_IS_ZERO( bigMinusOne )) + } + + if ( LL_IS_ZERO( bigMinusOne )) { SetFailed( "LL_IS_ZERO", "Minus One tests as zero" ); - + } + /* test equal */ - if ( !LL_EQ( bigZero, bigZero )) + if ( !LL_EQ( bigZero, bigZero )) { SetFailed( "LL_EQ", "zero EQ zero"); - - if ( !LL_EQ( bigOne, bigOne )) + } + + if ( !LL_EQ( bigOne, bigOne )) { SetFailed( "LL_EQ", "one EQ one" ); - - if ( !LL_EQ( bigNumber, bigNumber )) + } + + if ( !LL_EQ( bigNumber, bigNumber )) { SetFailed( "LL_EQ", "bigNumber EQ bigNumber" ); - - if ( !LL_EQ( bigMinusOne, bigMinusOne )) + } + + if ( !LL_EQ( bigMinusOne, bigMinusOne )) { SetFailed( "LL_EQ", "minus one EQ minus one"); - - if ( LL_EQ( bigZero, bigOne )) + } + + if ( LL_EQ( bigZero, bigOne )) { SetFailed( "LL_EQ", "zero EQ one"); - - if ( LL_EQ( bigOne, bigZero )) + } + + if ( LL_EQ( bigOne, bigZero )) { SetFailed( "LL_EQ", "one EQ zero" ); - - if ( LL_EQ( bigMinusOne, bigOne )) + } + + if ( LL_EQ( bigMinusOne, bigOne )) { SetFailed( "LL_EQ", "minus one EQ one"); - - if ( LL_EQ( bigNumber, bigOne )) + } + + if ( LL_EQ( bigNumber, bigOne )) { SetFailed( "LL_EQ", "bigNumber EQ one"); - + } + /* test not equal */ - if ( LL_NE( bigZero, bigZero )) + if ( LL_NE( bigZero, bigZero )) { SetFailed( "LL_NE", "0 NE 0"); - - if ( LL_NE( bigOne, bigOne )) + } + + if ( LL_NE( bigOne, bigOne )) { SetFailed( "LL_NE", "1 NE 1"); - - if ( LL_NE( bigMinusOne, bigMinusOne )) + } + + if ( LL_NE( bigMinusOne, bigMinusOne )) { SetFailed( "LL_NE", "-1 NE -1"); - - if ( LL_NE( bigNumber, bigNumber )) + } + + if ( LL_NE( bigNumber, bigNumber )) { SetFailed( "LL_NE", "n NE n"); - - if ( LL_NE( bigMinusNumber, bigMinusNumber )) + } + + if ( LL_NE( bigMinusNumber, bigMinusNumber )) { SetFailed( "LL_NE", "-n NE -n"); - - if ( !LL_NE( bigZero, bigOne)) + } + + if ( !LL_NE( bigZero, bigOne)) { SetFailed( "LL_NE", "0 NE 1"); - - if ( !LL_NE( bigOne, bigMinusNumber)) + } + + if ( !LL_NE( bigOne, bigMinusNumber)) { SetFailed( "LL_NE", "1 NE -n"); - + } + /* Greater than or equal to zero */ - if ( !LL_GE_ZERO( bigZero )) + if ( !LL_GE_ZERO( bigZero )) { SetFailed( "LL_GE_ZERO", "0"); - - if ( !LL_GE_ZERO( bigOne )) + } + + if ( !LL_GE_ZERO( bigOne )) { SetFailed( "LL_GE_ZERO", "1"); - - if ( !LL_GE_ZERO( bigNumber )) + } + + if ( !LL_GE_ZERO( bigNumber )) { SetFailed( "LL_GE_ZERO", "n"); - - if ( LL_GE_ZERO( bigMinusOne )) + } + + if ( LL_GE_ZERO( bigMinusOne )) { SetFailed( "LL_GE_ZERO", "-1"); - - if ( LL_GE_ZERO( bigMinusNumber )) + } + + if ( LL_GE_ZERO( bigMinusNumber )) { SetFailed( "LL_GE_ZERO", "-n"); - + } + /* Algebraic Compare two values */ - if ( !LL_CMP( bigZero, ==, bigZero )) + if ( !LL_CMP( bigZero, ==, bigZero )) { SetFailed( "LL_CMP", "0 == 0"); - - if ( LL_CMP( bigZero, >, bigZero )) + } + + if ( LL_CMP( bigZero, >, bigZero )) { SetFailed( "LL_CMP", "0 > 0"); - - if ( LL_CMP( bigZero, <, bigZero )) + } + + if ( LL_CMP( bigZero, <, bigZero )) { SetFailed( "LL_CMP", "0 < 0"); - - if ( LL_CMP( bigNumber, <, bigOne )) + } + + if ( LL_CMP( bigNumber, <, bigOne )) { SetFailed( "LL_CMP", "n < 1"); - - if ( !LL_CMP( bigNumber, >, bigOne )) + } + + if ( !LL_CMP( bigNumber, >, bigOne )) { SetFailed( "LL_CMP", "n <= 1"); - - if ( LL_CMP( bigOne, >, bigNumber )) + } + + if ( LL_CMP( bigOne, >, bigNumber )) { SetFailed( "LL_CMP", "1 > n"); - - if ( LL_CMP( bigMinusNumber, >, bigNumber )) + } + + if ( LL_CMP( bigMinusNumber, >, bigNumber )) { SetFailed( "LL_CMP", "-n > n"); - - if ( LL_CMP( bigNumber, !=, bigNumber)) + } + + if ( LL_CMP( bigNumber, !=, bigNumber)) { SetFailed( "LL_CMP", "n != n"); + } - if ( !LL_CMP( bigMinusOne, >, bigMinusTwo )) + if ( !LL_CMP( bigMinusOne, >, bigMinusTwo )) { SetFailed( "LL_CMP", "-1 <= -2"); + } - if ( !LL_CMP( bigMaxInt32, <, big2To31 )) + if ( !LL_CMP( bigMaxInt32, <, big2To31 )) { SetFailed( "LL_CMP", "Max 32-bit signed int >= 2^31"); + } /* Two positive numbers */ - if ( !LL_CMP( bigInt0, <=, bigInt0 )) + if ( !LL_CMP( bigInt0, <=, bigInt0 )) { SetFailed( "LL_CMP", "LL_CMP(<=) failed"); + } - if ( !LL_CMP( bigInt0, <=, bigInt1 )) + if ( !LL_CMP( bigInt0, <=, bigInt1 )) { SetFailed( "LL_CMP", "LL_CMP(<=) failed"); + } - if ( LL_CMP( bigInt0, <=, bigInt2 )) + if ( LL_CMP( bigInt0, <=, bigInt2 )) { SetFailed( "LL_CMP", "LL_CMP(<=) failed"); + } - if ( !LL_CMP( bigInt0, <=, bigInt3 )) + if ( !LL_CMP( bigInt0, <=, bigInt3 )) { SetFailed( "LL_CMP", "LL_CMP(<=) failed"); + } - if ( !LL_CMP( bigInt0, <=, bigInt4 )) + if ( !LL_CMP( bigInt0, <=, bigInt4 )) { SetFailed( "LL_CMP", "LL_CMP(<=) failed"); + } - if ( !LL_CMP( bigInt0, <=, bigInt5 )) + if ( !LL_CMP( bigInt0, <=, bigInt5 )) { SetFailed( "LL_CMP", "LL_CMP(<=) failed"); + } /* Two negative numbers */ - if ( !LL_CMP( bigInt6, <=, bigInt6 )) + if ( !LL_CMP( bigInt6, <=, bigInt6 )) { SetFailed( "LL_CMP", "LL_CMP(<=) failed"); + } - if ( !LL_CMP( bigInt6, <=, bigInt7 )) + if ( !LL_CMP( bigInt6, <=, bigInt7 )) { SetFailed( "LL_CMP", "LL_CMP(<=) failed"); + } - if ( LL_CMP( bigInt6, <=, bigInt8 )) + if ( LL_CMP( bigInt6, <=, bigInt8 )) { SetFailed( "LL_CMP", "LL_CMP(<=) failed"); + } - if ( !LL_CMP( bigInt6, <=, bigInt9 )) + if ( !LL_CMP( bigInt6, <=, bigInt9 )) { SetFailed( "LL_CMP", "LL_CMP(<=) failed"); + } - if ( !LL_CMP( bigInt6, <=, bigInt10 )) + if ( !LL_CMP( bigInt6, <=, bigInt10 )) { SetFailed( "LL_CMP", "LL_CMP(<=) failed"); + } - if ( !LL_CMP( bigInt6, <=, bigInt11 )) + if ( !LL_CMP( bigInt6, <=, bigInt11 )) { SetFailed( "LL_CMP", "LL_CMP(<=) failed"); + } /* One positive, one negative */ - if ( LL_CMP( bigInt0, <=, bigInt6 )) + if ( LL_CMP( bigInt0, <=, bigInt6 )) { SetFailed( "LL_CMP", "LL_CMP(<=) failed"); + } - if ( LL_CMP( bigInt0, <=, bigInt7 )) + if ( LL_CMP( bigInt0, <=, bigInt7 )) { SetFailed( "LL_CMP", "LL_CMP(<=) failed"); + } - if ( LL_CMP( bigInt0, <=, bigInt8 )) + if ( LL_CMP( bigInt0, <=, bigInt8 )) { SetFailed( "LL_CMP", "LL_CMP(<=) failed"); + } /* Bitwise Compare two numbers */ - if ( !LL_UCMP( bigZero, ==, bigZero )) + if ( !LL_UCMP( bigZero, ==, bigZero )) { SetFailed( "LL_UCMP", "0 == 0"); - - if ( LL_UCMP( bigZero, >, bigZero )) + } + + if ( LL_UCMP( bigZero, >, bigZero )) { SetFailed( "LL_UCMP", "0 > 0"); - - if ( LL_UCMP( bigZero, <, bigZero )) + } + + if ( LL_UCMP( bigZero, <, bigZero )) { SetFailed( "LL_UCMP", "0 < 0"); - - if ( LL_UCMP( bigNumber, <, bigOne )) + } + + if ( LL_UCMP( bigNumber, <, bigOne )) { SetFailed( "LL_UCMP", "n < 1"); - - if ( !LL_UCMP( bigNumber, >, bigOne )) + } + + if ( !LL_UCMP( bigNumber, >, bigOne )) { SetFailed( "LL_UCMP", "n < 1"); - - if ( LL_UCMP( bigOne, >, bigNumber )) + } + + if ( LL_UCMP( bigOne, >, bigNumber )) { SetFailed( "LL_UCMP", "1 > n"); - - if ( LL_UCMP( bigMinusNumber, <, bigNumber )) + } + + if ( LL_UCMP( bigMinusNumber, <, bigNumber )) { SetFailed( "LL_UCMP", "-n < n"); + } /* Two positive numbers */ - if ( !LL_UCMP( bigInt0, <=, bigInt0 )) + if ( !LL_UCMP( bigInt0, <=, bigInt0 )) { SetFailed( "LL_UCMP", "LL_UCMP(<=) failed"); + } - if ( !LL_UCMP( bigInt0, <=, bigInt1 )) + if ( !LL_UCMP( bigInt0, <=, bigInt1 )) { SetFailed( "LL_UCMP", "LL_UCMP(<=) failed"); + } - if ( LL_UCMP( bigInt0, <=, bigInt2 )) + if ( LL_UCMP( bigInt0, <=, bigInt2 )) { SetFailed( "LL_UCMP", "LL_UCMP(<=) failed"); + } - if ( !LL_UCMP( bigInt0, <=, bigInt3 )) + if ( !LL_UCMP( bigInt0, <=, bigInt3 )) { SetFailed( "LL_UCMP", "LL_UCMP(<=) failed"); + } - if ( !LL_UCMP( bigInt0, <=, bigInt4 )) + if ( !LL_UCMP( bigInt0, <=, bigInt4 )) { SetFailed( "LL_UCMP", "LL_UCMP(<=) failed"); + } - if ( !LL_UCMP( bigInt0, <=, bigInt5 )) + if ( !LL_UCMP( bigInt0, <=, bigInt5 )) { SetFailed( "LL_UCMP", "LL_UCMP(<=) failed"); + } /* Two negative numbers */ - if ( !LL_UCMP( bigInt6, <=, bigInt6 )) + if ( !LL_UCMP( bigInt6, <=, bigInt6 )) { SetFailed( "LL_UCMP", "LL_UCMP(<=) failed"); + } - if ( !LL_UCMP( bigInt6, <=, bigInt7 )) + if ( !LL_UCMP( bigInt6, <=, bigInt7 )) { SetFailed( "LL_UCMP", "LL_UCMP(<=) failed"); + } - if ( LL_UCMP( bigInt6, <=, bigInt8 )) + if ( LL_UCMP( bigInt6, <=, bigInt8 )) { SetFailed( "LL_UCMP", "LL_UCMP(<=) failed"); + } - if ( !LL_UCMP( bigInt6, <=, bigInt9 )) + if ( !LL_UCMP( bigInt6, <=, bigInt9 )) { SetFailed( "LL_UCMP", "LL_UCMP(<=) failed"); + } - if ( !LL_UCMP( bigInt6, <=, bigInt10 )) + if ( !LL_UCMP( bigInt6, <=, bigInt10 )) { SetFailed( "LL_UCMP", "LL_UCMP(<=) failed"); + } - if ( !LL_UCMP( bigInt6, <=, bigInt11 )) + if ( !LL_UCMP( bigInt6, <=, bigInt11 )) { SetFailed( "LL_UCMP", "LL_UCMP(<=) failed"); + } /* One positive, one negative */ - if ( !LL_UCMP( bigInt0, <=, bigInt6 )) + if ( !LL_UCMP( bigInt0, <=, bigInt6 )) { SetFailed( "LL_UCMP", "LL_UCMP(<=) failed"); + } - if ( !LL_UCMP( bigInt0, <=, bigInt7 )) + if ( !LL_UCMP( bigInt0, <=, bigInt7 )) { SetFailed( "LL_UCMP", "LL_UCMP(<=) failed"); + } - if ( !LL_UCMP( bigInt0, <=, bigInt8 )) + if ( !LL_UCMP( bigInt0, <=, bigInt8 )) { SetFailed( "LL_UCMP", "LL_UCMP(<=) failed"); + } return; } @@ -365,87 +438,104 @@ static void TestLogicalOperations( void ) { PRUint64 result, result2; - + ReportProgress("Testing Logical Operations\n"); - + /* Test AND */ LL_AND( result, bigZero, bigZero ); - if ( !LL_IS_ZERO( result )) + if ( !LL_IS_ZERO( result )) { ResultFailed( "LL_AND", "0 & 0", bigZero, result ); - + } + LL_AND( result, bigOne, bigOne ); - if ( LL_IS_ZERO( result )) + if ( LL_IS_ZERO( result )) { ResultFailed( "LL_AND", "1 & 1", bigOne, result ); + } LL_AND( result, bigZero, bigOne ); - if ( !LL_IS_ZERO( result )) + if ( !LL_IS_ZERO( result )) { ResultFailed( "LL_AND", "1 & 1", bigZero, result ); + } LL_AND( result, bigMinusOne, bigMinusOne ); - if ( !LL_UCMP( result, ==, bigMinusOne )) + if ( !LL_UCMP( result, ==, bigMinusOne )) { ResultFailed( "LL_AND", "-1 & -1", bigMinusOne, result ); - + } + /* test OR */ LL_OR( result, bigZero, bigZero ); - if ( !LL_IS_ZERO( result )) + if ( !LL_IS_ZERO( result )) { ResultFailed( "LL_OR", "0 | 1", bigZero, result); - + } + LL_OR( result, bigZero, bigOne ); - if ( LL_IS_ZERO( result )) + if ( LL_IS_ZERO( result )) { ResultFailed( "LL_OR", "0 | 1", bigOne, result ); - + } + LL_OR( result, bigZero, bigMinusNumber ); - if ( !LL_UCMP( result, ==, bigMinusNumber )) + if ( !LL_UCMP( result, ==, bigMinusNumber )) { ResultFailed( "LL_OR", "0 | -n", bigMinusNumber, result); - + } + LL_OR( result, bigMinusNumber, bigZero ); - if ( !LL_UCMP( result, ==, bigMinusNumber )) + if ( !LL_UCMP( result, ==, bigMinusNumber )) { ResultFailed( "LL_OR", "-n | 0", bigMinusNumber, result ); - + } + /* test XOR */ LL_XOR( result, bigZero, bigZero ); - if ( LL_UCMP( result, !=, bigZero )) + if ( LL_UCMP( result, !=, bigZero )) { ResultFailed( "LL_XOR", "0 ^ 0", bigZero, result); - + } + LL_XOR( result, bigOne, bigZero ); - if ( LL_UCMP( result, !=, bigOne )) + if ( LL_UCMP( result, !=, bigOne )) { ResultFailed( "LL_XOR", "1 ^ 0", bigZero, result ); - + } + LL_XOR( result, bigMinusNumber, bigZero ); - if ( LL_UCMP( result, !=, bigMinusNumber )) + if ( LL_UCMP( result, !=, bigMinusNumber )) { ResultFailed( "LL_XOR", "-n ^ 0", bigMinusNumber, result ); - + } + LL_XOR( result, bigMinusNumber, bigMinusNumber ); - if ( LL_UCMP( result, !=, bigZero )) + if ( LL_UCMP( result, !=, bigZero )) { ResultFailed( "LL_XOR", "-n ^ -n", bigMinusNumber, result); - + } + /* test OR2. */ result = bigZero; LL_OR2( result, bigOne ); - if ( LL_UCMP( result, !=, bigOne )) + if ( LL_UCMP( result, !=, bigOne )) { ResultFailed( "LL_OR2", "(r=0) |= 1", bigOne, result); - + } + result = bigOne; LL_OR2( result, bigNumber ); - if ( LL_UCMP( result, !=, bigNumber )) + if ( LL_UCMP( result, !=, bigNumber )) { ResultFailed( "LL_OR2", "(r=1) |= n", bigNumber, result); + } result = bigMinusNumber; LL_OR2( result, bigMinusNumber ); - if ( LL_UCMP( result, !=, bigMinusNumber )) + if ( LL_UCMP( result, !=, bigMinusNumber )) { ResultFailed( "LL_OR2", "(r=-n) |= -n", bigMinusNumber, result); + } /* test NOT */ LL_NOT( result, bigMinusNumber); LL_NOT( result2, result); - if ( LL_UCMP( result2, !=, bigMinusNumber )) + if ( LL_UCMP( result2, !=, bigMinusNumber )) { ResultFailed( "LL_NOT", "r != ~(~-n)", bigMinusNumber, result); - + } + /* test Negation */ LL_NEG( result, bigMinusNumber ); LL_NEG( result2, result ); - if ( LL_CMP( result2, !=, bigMinusNumber )) + if ( LL_CMP( result2, !=, bigMinusNumber )) { ResultFailed( "LL_NEG", "r != -(-(-n))", bigMinusNumber, result); + } return; } @@ -465,82 +555,98 @@ TestConversion( void ) PRUint32 resultU32; float resultF; PRFloat64 resultD; - + ReportProgress("Testing Conversion Operations\n"); - + /* LL_L2I -- Convert to signed 32bit */ LL_L2I(result32, bigOne ); - if ( result32 != one ) + if ( result32 != one ) { SetFailed( "LL_L2I", "r != 1"); - + } + LL_L2I(result32, bigMinusOne ); - if ( result32 != minusOne ) + if ( result32 != minusOne ) { SetFailed( "LL_L2I", "r != -1"); - + } + /* LL_L2UI -- Convert 64bit to unsigned 32bit */ LL_L2UI( resultU32, bigMinusOne ); - if ( resultU32 != (PRUint32) minusOne ) + if ( resultU32 != (PRUint32) minusOne ) { SetFailed( "LL_L2UI", "r != -1"); - + } + LL_L2UI( resultU32, bigOne ); - if ( resultU32 != (PRUint32) one ) + if ( resultU32 != (PRUint32) one ) { SetFailed( "LL_L2UI", "r != 1"); - + } + /* LL_L2F -- Convert to 32bit floating point */ LL_L2F( resultF, bigOne ); - if ( resultF != 1.0 ) + if ( resultF != 1.0 ) { SetFailed( "LL_L2F", "r != 1.0"); - + } + LL_L2F( resultF, bigMinusOne ); - if ( resultF != -1.0 ) + if ( resultF != -1.0 ) { SetFailed( "LL_L2F", "r != 1.0"); - + } + /* LL_L2D -- Convert to 64bit floating point */ LL_L2D( resultD, bigOne ); - if ( resultD != 1.0L ) + if ( resultD != 1.0L ) { SetFailed( "LL_L2D", "r != 1.0"); - + } + LL_L2D( resultD, bigMinusOne ); - if ( resultD != -1.0L ) + if ( resultD != -1.0L ) { SetFailed( "LL_L2D", "r != -1.0"); - + } + /* LL_I2L -- Convert 32bit signed to 64bit signed */ LL_I2L( result, one ); - if ( LL_CMP(result, !=, bigOne )) + if ( LL_CMP(result, !=, bigOne )) { SetFailed( "LL_I2L", "r != 1"); - + } + LL_I2L( result, minusOne ); - if ( LL_CMP(result, !=, bigMinusOne )) + if ( LL_CMP(result, !=, bigMinusOne )) { SetFailed( "LL_I2L", "r != -1"); - + } + /* LL_UI2L -- Convert 32bit unsigned to 64bit unsigned */ LL_UI2L( resultU, (PRUint32) one ); - if ( LL_CMP(resultU, !=, bigOne )) + if ( LL_CMP(resultU, !=, bigOne )) { SetFailed( "LL_UI2L", "r != 1"); - - /* [lth.] This did not behave as expected, but it is correct + } + + /* [lth.] This did not behave as expected, but it is correct */ LL_UI2L( resultU, (PRUint32) minusOne ); - if ( LL_CMP(resultU, !=, bigZeroFox )) + if ( LL_CMP(resultU, !=, bigZeroFox )) { ResultFailed( "LL_UI2L", "r != -1", bigZeroFox, resultU); - + } + /* LL_F2L -- Convert 32bit float to 64bit signed */ LL_F2L( result, 1.0 ); - if ( LL_CMP(result, !=, bigOne )) + if ( LL_CMP(result, !=, bigOne )) { SetFailed( "LL_F2L", "r != 1"); - + } + LL_F2L( result, -1.0 ); - if ( LL_CMP(result, !=, bigMinusOne )) + if ( LL_CMP(result, !=, bigMinusOne )) { SetFailed( "LL_F2L", "r != -1"); - + } + /* LL_D2L -- Convert 64bit Float to 64bit signed */ LL_D2L( result, 1.0L ); - if ( LL_CMP(result, !=, bigOne )) + if ( LL_CMP(result, !=, bigOne )) { SetFailed( "LL_D2L", "r != 1"); - + } + LL_D2L( result, -1.0L ); - if ( LL_CMP(result, !=, bigMinusOne )) + if ( LL_CMP(result, !=, bigMinusOne )) { SetFailed( "LL_D2L", "r != -1"); + } return; } @@ -561,7 +667,7 @@ static void ShiftCompileOnly() LL_ISHL(ia, 49, 32); } /* ShiftCompileOnly */ - + /* ** TestShift() -- Test Shifting Operations @@ -575,53 +681,63 @@ TestShift( void ) PRUint64 resultU; ReportProgress("Testing Shifting Operations\n"); - + /* LL_SHL -- Shift left algebraic */ LL_SHL( result, bigOne, one ); - if ( LL_CMP( result, !=, bigTwo )) + if ( LL_CMP( result, !=, bigTwo )) { ResultFailed( "LL_SHL", "r != 2", bigOne, result ); - + } + LL_SHL( result, bigTwo, thirtyTwo ); - if ( LL_CMP( result, !=, largeTwoZero )) + if ( LL_CMP( result, !=, largeTwoZero )) { ResultFailed( "LL_SHL", "r != twoZero", largeTwoZero, result); - + } + /* LL_SHR -- Shift right algebraic */ LL_SHR( result, bigFoxZero, thirtyTwo ); - if ( LL_CMP( result, !=, bigMinusOne )) + if ( LL_CMP( result, !=, bigMinusOne )) { ResultFailed( "LL_SHR", "r != -1", bigMinusOne, result); - + } + LL_SHR( result, bigTwo, one ); - if ( LL_CMP( result, !=, bigOne )) + if ( LL_CMP( result, !=, bigOne )) { ResultFailed( "LL_SHR", "r != 1", bigOne, result); + } LL_SHR( result, bigFoxFox, thirtyTwo ); - if ( LL_CMP( result, !=, bigMinusOne )) + if ( LL_CMP( result, !=, bigMinusOne )) { ResultFailed( "LL_SHR", "r != -1 (was ff,ff)", bigMinusOne, result); - + } + /* LL_USHR -- Logical shift right */ LL_USHR( resultU, bigZeroFox, thirtyTwo ); - if ( LL_UCMP( resultU, !=, bigZero )) + if ( LL_UCMP( resultU, !=, bigZero )) { ResultFailed( "LL_USHR", "r != 0 ", bigZero, result); - + } + LL_USHR( resultU, bigFoxFox, thirtyTwo ); - if ( LL_UCMP( resultU, !=, bigZeroFox )) + if ( LL_UCMP( resultU, !=, bigZeroFox )) { ResultFailed( "LL_USHR", "r != 0 ", bigZeroFox, result); - + } + /* LL_ISHL -- Shift a 32bit integer into a 64bit result */ LL_ISHL( resultU, minusOne, thirtyTwo ); - if ( LL_UCMP( resultU, !=, bigFoxZero )) + if ( LL_UCMP( resultU, !=, bigFoxZero )) { ResultFailed( "LL_ISHL", "r != ff,00 ", bigFoxZero, result); - + } + LL_ISHL( resultU, one, sixtyThree ); - if ( LL_UCMP( resultU, !=, bigEightZero )) + if ( LL_UCMP( resultU, !=, bigEightZero )) { ResultFailed( "LL_ISHL", "r != 80,00 ", bigEightZero, result); - + } + LL_ISHL( resultU, one, sixteen ); - if ( LL_UCMP( resultU, !=, big64K )) + if ( LL_UCMP( resultU, !=, big64K )) { ResultFailed( "LL_ISHL", "r != 64K ", big64K, resultU); - + } + return; -} +} /* @@ -637,125 +753,148 @@ TestArithmetic( void ) PRInt64 largeMultCand = LL_INIT( 0x00000000, 0x7fffffff ); PRInt64 largeMinusMultCand = LL_INIT( 0xffffffff, 0x10000001 ); PRInt64 largeMultCandx64K = LL_INIT( 0x00007fff, 0xffff0000 ); - PRInt64 largeNumSHL5 = LL_INIT( 0x0000001f, 0xffffffe0 ); + PRInt64 largeNumSHL5 = LL_INIT( 0x0000001f, 0xffffffe0 ); PRInt64 result, result2; - /* Addition */ + /* Addition */ LL_ADD( result, bigOne, bigOne ); - if ( LL_CMP( result, !=, bigTwo )) + if ( LL_CMP( result, !=, bigTwo )) { ResultFailed( "LL_ADD", "r != 1 + 1", bigTwo, result); + } LL_ADD( result, bigMinusOne, bigOne ); - if ( LL_CMP( result, !=, bigZero )) + if ( LL_CMP( result, !=, bigZero )) { ResultFailed( "LL_ADD", "r != -1 + 1", bigOne, result); + } LL_ADD( result, largeVal, bigOne ); - if ( LL_CMP( result, !=, largeValPlusOne )) + if ( LL_CMP( result, !=, largeValPlusOne )) { ResultFailed( "LL_ADD", "lVP1 != lV + 1", largeValPlusOne, result); - + } + /* Subtraction */ LL_SUB( result, bigOne, bigOne ); - if ( LL_CMP( result, !=, bigZero )) + if ( LL_CMP( result, !=, bigZero )) { ResultFailed( "LL_SUB", "r != 1 - 1", bigZero, result); - + } + LL_SUB( result, bigTwo, bigOne ); - if ( LL_CMP( result, !=, bigOne )) + if ( LL_CMP( result, !=, bigOne )) { ResultFailed( "LL_SUB", "r != 2 - 1", bigOne, result); - + } + LL_SUB( result, largeValPlusOne, bigOne ); - if ( LL_CMP( result, !=, largeVal )) + if ( LL_CMP( result, !=, largeVal )) { ResultFailed( "LL_SUB", "r != lVP1 - 1", largeVal, result); - - + } + + /* Multiply */ LL_MUL( result, largeVal, bigTwo ); - if ( LL_CMP( result, !=, largeValTimesTwo )) + if ( LL_CMP( result, !=, largeValTimesTwo )) { ResultFailed( "LL_MUL", "r != lV*2", largeValTimesTwo, result); - + } + LL_MUL( result, largeMultCand, big64K ); - if ( LL_CMP( result, !=, largeMultCandx64K )) + if ( LL_CMP( result, !=, largeMultCandx64K )) { ResultFailed( "LL_MUL", "r != lV*64K", largeMultCandx64K, result); - + } + LL_NEG( result2, largeMultCand ); LL_MUL( result, largeMultCand, bigMinusOne ); - if ( LL_CMP( result, !=, result2 )) + if ( LL_CMP( result, !=, result2 )) { ResultFailed( "LL_MUL", "r != -lMC", result2, result); + } LL_SHL( result2, bigZeroFox, 5); LL_MUL( result, bigZeroFox, bigThirtyTwo ); - if ( LL_CMP( result, !=, largeNumSHL5 )) + if ( LL_CMP( result, !=, largeNumSHL5 )) { ResultFailed( "LL_MUL", "r != 0f<<5", largeNumSHL5, result ); + } + - /* LL_DIV() Division */ LL_DIV( result, bigOne, bigOne); - if ( LL_CMP( result, !=, bigOne )) + if ( LL_CMP( result, !=, bigOne )) { ResultFailed( "LL_DIV", "1 != 1", bigOne, result); - + } + LL_DIV( result, bigNumber, bigOne ); - if ( LL_CMP( result, !=, bigNumber )) + if ( LL_CMP( result, !=, bigNumber )) { ResultFailed( "LL_DIV", "r != n / 1", bigNumber, result); + } LL_DIV( result, bigNumber, bigMinusOne ); - if ( LL_CMP( result, !=, bigMinusNumber )) + if ( LL_CMP( result, !=, bigMinusNumber )) { ResultFailed( "LL_DIV", "r != n / -1", bigMinusNumber, result); + } LL_DIV( result, bigMinusNumber, bigMinusOne ); - if ( LL_CMP( result, !=, bigNumber )) + if ( LL_CMP( result, !=, bigNumber )) { ResultFailed( "LL_DIV", "r != -n / -1", bigNumber, result); - + } + LL_SHL( result2, bigZeroFox, 5 ); LL_DIV( result, result2, bigOne ); - if ( LL_CMP( result, !=, result2 )) + if ( LL_CMP( result, !=, result2 )) { ResultFailed( "LL_DIV", "0f<<5 != 0f<<5", result2, result); - + } + LL_SHL( result2, bigZeroFox, 5 ); LL_NEG( result2, result2 ); LL_DIV( result, result2, bigOne ); - if ( LL_CMP( result, !=, result2 )) + if ( LL_CMP( result, !=, result2 )) { ResultFailed( "LL_DIV", "-0f<<5 != -0f<<5", result2, result); - + } + LL_SHL( result2, bigZeroFox, 17 ); LL_DIV( result, result2, bigMinusOne ); LL_NEG( result2, result2 ); - if ( LL_CMP( result, !=, result2 )) + if ( LL_CMP( result, !=, result2 )) { ResultFailed( "LL_DIV", "-0f<<17 != -0f<<17", result2, result); - - + } + + /* LL_MOD() Modulo Division */ LL_ADD( result2, bigThirtyTwo, bigOne ); LL_MOD( result, result2, bigSixTeen ); - if ( LL_CMP( result, !=, bigOne )) + if ( LL_CMP( result, !=, bigOne )) { ResultFailed( "LL_MOD", "r != 1", bigSixTeen, result); - - + } + + LL_MUL( result2, bigZeroFox, bigThirtyTwo ); LL_ADD( result2, result2, bigSixTeen); LL_MOD( result, result2, bigThirtyTwo ); - if ( LL_CMP( result, !=, bigSixTeen )) + if ( LL_CMP( result, !=, bigSixTeen )) { ResultFailed( "LL_MOD", "r != 16", bigSixTeen, result); + } /* LL_UDIVMOD */ LL_DIV( result, bigOne, bigOne); - if ( LL_CMP( result, !=, bigOne )) + if ( LL_CMP( result, !=, bigOne )) { ResultFailed( "LL_DIV", "r != 16", bigSixTeen, result); - + } + return; -} +} static void TestWellknowns(void) { PRInt64 max = LL_MAXINT, min = LL_MININT, zero = LL_ZERO; PRInt64 mmax = LL_MaxInt(), mmin = LL_MinInt(), mzero = LL_Zero(); - if (LL_NE(max, mmax)) + if (LL_NE(max, mmax)) { ResultFailed( "max, mmax", "max != mmax", max, mmax); - if (LL_NE(min, mmin)) + } + if (LL_NE(min, mmin)) { ResultFailed( "min, mmin", "min != mmin", max, mmin); - if (LL_NE(zero, mzero)) + } + if (LL_NE(zero, mzero)) { ResultFailed( "zero, mzero", "zero != mzero", zero, mzero); -} /* TestWellknowns */ + } +} /* TestWellknowns */ /* ** Initialize() -- Initialize the test case @@ -771,38 +910,41 @@ Initialize( PRIntn argc, char **argv ) /* ** Parse command line options - */ + */ while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* set debug mode */ - debugMode = PR_TRUE; - break; - - case 'v': /* set verbose mode */ - verboseMode = PR_TRUE; - debugMode = PR_TRUE; - break; - - case 'h': /* user wants some guidance */ - default: - PR_fprintf(output, "You get help.\n"); - return(1); + case 'd': /* set debug mode */ + debugMode = PR_TRUE; + break; + + case 'v': /* set verbose mode */ + verboseMode = PR_TRUE; + debugMode = PR_TRUE; + break; + + case 'h': /* user wants some guidance */ + default: + PR_fprintf(output, "You get help.\n"); + return(1); } } PL_DestroyOptState(opt); return(0); -} +} int main(int argc, char **argv) { PR_STDIO_INIT(); output = PR_GetSpecialFD(PR_StandardError); - if ( Initialize( argc, argv )) + if ( Initialize( argc, argv )) { return(1); + } TestAssignment(); TestComparisons(); @@ -811,17 +953,17 @@ int main(int argc, char **argv) TestShift(); TestArithmetic(); TestWellknowns(); - + /* ** That's all folks! */ if ( failedAlready ) { - PR_fprintf(output, "FAIL\n");\ - } + PR_fprintf(output, "FAIL\n"); \ + } else { - PR_fprintf(output, "PASS\n");\ + PR_fprintf(output, "PASS\n"); \ } return failedAlready; } /* end main() */ diff --git a/nsprpub/pr/tests/lock.c b/nsprpub/pr/tests/lock.c index 178315ae6..83a4f4180 100644 --- a/nsprpub/pr/tests/lock.c +++ b/nsprpub/pr/tests/lock.c @@ -9,12 +9,12 @@ ** ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ** ** 11-Aug-97 LarryH. Win16 port of NSPR. ** - Added "PASS", "FAIL" messages on completion. @@ -25,7 +25,7 @@ ** - l <num> to control the number of loops ** - c <num> to control the number of CPUs. ** (was positional argv). -** +** ** ***********************************************************************/ @@ -149,8 +149,8 @@ static PRIntervalTime ContentiousLock(PRUint32 loops) contention->ml = PR_NewLock(); contention->interval = contention_interval; thread = PR_CreateThread( - PR_USER_THREAD, LockContender, contention, - PR_PRIORITY_LOW, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, LockContender, contention, + PR_PRIORITY_LOW, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); PR_ASSERT(thread != NULL); overhead = PR_IntervalNow() - timein; @@ -211,12 +211,18 @@ static PRIntervalTime NonContentiousMonitor(PRUint32 loops) static void PR_CALLBACK TryEntry(void *arg) { PRMonitor *ml = (PRMonitor*)arg; - if (debug_mode) PR_fprintf(std_err, "Reentrant thread created\n"); + if (debug_mode) { + PR_fprintf(std_err, "Reentrant thread created\n"); + } PR_EnterMonitor(ml); PR_ASSERT_CURRENT_THREAD_IN_MONITOR(ml); - if (debug_mode) PR_fprintf(std_err, "Reentrant thread acquired monitor\n"); + if (debug_mode) { + PR_fprintf(std_err, "Reentrant thread acquired monitor\n"); + } PR_ExitMonitor(ml); - if (debug_mode) PR_fprintf(std_err, "Reentrant thread released monitor\n"); + if (debug_mode) { + PR_fprintf(std_err, "Reentrant thread released monitor\n"); + } } /* TryEntry */ static PRIntervalTime ReentrantMonitor(PRUint32 loops) @@ -224,32 +230,40 @@ static PRIntervalTime ReentrantMonitor(PRUint32 loops) PRStatus status; PRThread *thread; PRMonitor *ml = PR_NewMonitor(); - if (debug_mode) PR_fprintf(std_err, "\nMonitor created for reentrant test\n"); + if (debug_mode) { + PR_fprintf(std_err, "\nMonitor created for reentrant test\n"); + } PR_EnterMonitor(ml); PR_ASSERT_CURRENT_THREAD_IN_MONITOR(ml); PR_EnterMonitor(ml); PR_ASSERT_CURRENT_THREAD_IN_MONITOR(ml); - if (debug_mode) PR_fprintf(std_err, "Monitor acquired twice\n"); + if (debug_mode) { + PR_fprintf(std_err, "Monitor acquired twice\n"); + } thread = PR_CreateThread( - PR_USER_THREAD, TryEntry, ml, - PR_PRIORITY_LOW, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + 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_ASSERT_CURRENT_THREAD_IN_MONITOR(ml); PR_ExitMonitor(ml); PR_ASSERT_CURRENT_THREAD_IN_MONITOR(ml); - if (debug_mode) PR_fprintf(std_err, "Monitor released first time\n"); + if (debug_mode) { + PR_fprintf(std_err, "Monitor released first time\n"); + } PR_ExitMonitor(ml); - if (debug_mode) PR_fprintf(std_err, "Monitor released second time\n"); + if (debug_mode) { + PR_fprintf(std_err, "Monitor released second time\n"); + } status = PR_JoinThread(thread); - if (debug_mode) PR_fprintf(std_err, - "Reentrant thread joined %s\n", - (status == PR_SUCCESS) ? "successfully" : "in error"); + if (debug_mode) PR_fprintf(std_err, + "Reentrant thread joined %s\n", + (status == PR_SUCCESS) ? "successfully" : "in error"); PR_DestroyMonitor(ml); return 0; @@ -283,8 +297,8 @@ static PRUint32 ContentiousMonitor(PRUint32 loops) contention->ml = PR_NewMonitor(); contention->interval = contention_interval; thread = PR_CreateThread( - PR_USER_THREAD, MonitorContender, contention, - PR_PRIORITY_LOW, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, MonitorContender, contention, + PR_PRIORITY_LOW, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); PR_ASSERT(thread != NULL); overhead = PR_IntervalNow() - timein; @@ -352,8 +366,8 @@ static PRIntervalTime ContentiousCMonitor(PRUint32 loops) contention->loops = loops; contention->interval = contention_interval; thread = PR_CreateThread( - PR_USER_THREAD, Contender, contention, - PR_PRIORITY_LOW, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, Contender, contention, + PR_PRIORITY_LOW, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); PR_ASSERT(thread != NULL); overhead = PR_IntervalNow() - timein; @@ -382,17 +396,17 @@ static PRIntervalTime ContentiousCMonitor(PRUint32 loops) static PRIntervalTime Test( const char* msg, PRUint32 (*test)(PRUint32 loops), PRUint32 loops, PRIntervalTime overhead) -{ +{ /* * overhead - overhead not measured by the test. * duration - wall clock time it took to perform test. - * predicted - extra time test says should not be counted + * predicted - extra time test says should not be counted * * Time accountable to the test is duration - overhead - predicted * All times are Intervals and accumulated for all iterations. */ PRFloat64 elapsed; - PRIntervalTime accountable, duration; + PRIntervalTime accountable, duration; PRUintn spaces = PL_strlen(msg); PRIntervalTime timeout, timein = PR_IntervalNow(); PRIntervalTime predicted = test(loops); @@ -405,11 +419,15 @@ static PRIntervalTime Test( accountable -= overhead; elapsed = (PRFloat64)PR_IntervalToMicroseconds(accountable); PR_fprintf(PR_STDOUT, "%s:", msg); - while (spaces++ < 50) PR_fprintf(PR_STDOUT, " "); - if ((PRInt32)accountable < 0) + while (spaces++ < 50) { + PR_fprintf(PR_STDOUT, " "); + } + if ((PRInt32)accountable < 0) { PR_fprintf(PR_STDOUT, "*****.** usecs/iteration\n"); - else + } + else { PR_fprintf(PR_STDOUT, "%8.2f usecs/iteration\n", elapsed/loops); + } } return duration; } /* Test */ @@ -420,62 +438,72 @@ int main(int argc, char **argv) PRIntervalTime duration; PRUint32 cpu, cpus = 2, loops = 100; - + PR_STDIO_INIT(); PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); { - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. Command line argument -l <num> sets the number of loops. Command line argument -c <num> sets the number of cpus. Usage: lock [-d] [-l <num>] [-c <num>] - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "dvl:c:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "dvl:c:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = PR_TRUE; - break; - case 'v': /* debug mode */ - verbosity = PR_TRUE; - break; - case 'l': /* number of loops */ - loops = atoi(opt->value); - break; - case 'c': /* number of cpus */ - cpus = atoi(opt->value); - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = PR_TRUE; + break; + case 'v': /* debug mode */ + verbosity = PR_TRUE; + break; + case 'l': /* number of loops */ + loops = atoi(opt->value); + break; + case 'c': /* number of cpus */ + cpus = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); } - /* main test */ + /* main test */ PR_SetConcurrency(8); - if (loops == 0) loops = 100; + if (loops == 0) { + loops = 100; + } if (debug_mode) { std_err = PR_STDERR; PR_fprintf(std_err, "Lock: Using %d loops\n", loops); } - if (cpus == 0) cpus = 2; - if (debug_mode) PR_fprintf(std_err, "Lock: Using %d cpu(s)\n", cpus); + if (cpus == 0) { + cpus = 2; + } + if (debug_mode) { + PR_fprintf(std_err, "Lock: Using %d cpu(s)\n", cpus); + } (void)Sleeper(10); /* try filling in the caches */ for (cpu = 1; cpu <= cpus; ++cpu) { - if (debug_mode) PR_fprintf(std_err, "\nLock: Using %d CPU(s)\n", cpu); + if (debug_mode) { + PR_fprintf(std_err, "\nLock: Using %d CPU(s)\n", cpu); + } PR_SetConcurrency(cpu); duration = Test("Overhead of PR_Sleep", Sleeper, loops, 0); @@ -498,20 +526,21 @@ int main(int argc, char **argv) PR_fprintf( std_err, "%s: test %s\n", "Lock(mutex) test", ((rv) ? "passed" : "failed")); - else { - if (!rv) - failed_already=1; - } - - if(failed_already) - { - PR_fprintf(PR_STDOUT, "FAIL\n"); - return 1; - } - else + else { + if (!rv) { + failed_already=1; + } + } + + if(failed_already) + { + PR_fprintf(PR_STDOUT, "FAIL\n"); + return 1; + } + else { - PR_fprintf(PR_STDOUT, "PASS\n"); - return 0; + PR_fprintf(PR_STDOUT, "PASS\n"); + return 0; } } /* main */ diff --git a/nsprpub/pr/tests/lockfile.c b/nsprpub/pr/tests/lockfile.c index 9c2de8c8f..883ef0d61 100644 --- a/nsprpub/pr/tests/lockfile.c +++ b/nsprpub/pr/tests/lockfile.c @@ -11,12 +11,12 @@ ** ** Modification History: ** 19-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** ** Includes @@ -64,8 +64,8 @@ static PRIntervalTime NonContentiousLock(PRInt32 loops) _lockfile = PR_Open(LOCKFILE, PR_CREATE_FILE|PR_RDWR, 0666); if (!_lockfile) { if (debug_mode) printf( - "could not create lockfile: %d [%d]\n", - PR_GetError(), PR_GetOSError()); + "could not create lockfile: %d [%d]\n", + PR_GetError(), PR_GetOSError()); return PR_INTERVAL_NO_TIMEOUT; } PR_LockFile(_lockfile); @@ -84,8 +84,8 @@ static void PR_CALLBACK LockContender(void *arg) _lockfile = PR_Open(LOCKFILE, PR_CREATE_FILE|PR_RDWR, 0666); if (!_lockfile) { if (debug_mode) printf( - "could not create lockfile: %d [%d]\n", - PR_GetError(), PR_GetOSError()); + "could not create lockfile: %d [%d]\n", + PR_GetError(), PR_GetOSError()); break; } PR_LockFile(_lockfile); @@ -112,8 +112,8 @@ static PRIntervalTime ContentiousLock(PRInt32 loops) contention.ml = PR_NewLock(); contention.interval = contention_interval; thread = PR_CreateThread( - PR_USER_THREAD, LockContender, &contention, - PR_PRIORITY_LOW, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, LockContender, &contention, + PR_PRIORITY_LOW, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); PR_ASSERT(thread != NULL); overhead = PR_IntervalNow() - timein; @@ -136,17 +136,17 @@ static PRIntervalTime ContentiousLock(PRInt32 loops) static PRIntervalTime Test( const char* msg, PRIntervalTime (*test)(PRInt32 loops), PRInt32 loops, PRIntervalTime overhead) -{ +{ /* * overhead - overhead not measured by the test. * duration - wall clock time it took to perform test. - * predicted - extra time test says should not be counted + * predicted - extra time test says should not be counted * * Time accountable to the test is duration - overhead - predicted * All times are Intervals and accumulated for all iterations. */ PRFloat64 elapsed; - PRIntervalTime accountable, duration; + PRIntervalTime accountable, duration; PRUintn spaces = strlen(msg); PRIntervalTime timeout, timein = PR_IntervalNow(); PRIntervalTime predicted = test(loops); @@ -155,12 +155,20 @@ static PRIntervalTime Test( accountable = duration - predicted; accountable -= overhead; elapsed = (PRFloat64)PR_IntervalToMicroseconds(accountable); - if (debug_mode) printf("%s:", msg); - while (spaces++ < 50) if (debug_mode) printf(" "); + if (debug_mode) { + printf("%s:", msg); + } + while (spaces++ < 50) if (debug_mode) { + printf(" "); + } if ((PRInt32)accountable < 0) { - if (debug_mode) printf("*****.** usecs/iteration\n"); + if (debug_mode) { + printf("*****.** usecs/iteration\n"); + } } else { - if (debug_mode) printf("%8.2f usecs/iteration\n", elapsed/loops); + if (debug_mode) { + printf("%8.2f usecs/iteration\n", elapsed/loops); + } } return duration; } /* Test */ @@ -171,59 +179,77 @@ int main(int argc, char **argv) PRUint32 cpu, cpus = 2; PRInt32 loops = 100; - - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); - if (argc > 1) loops = atoi(argv[1]); - if (loops == 0) loops = 100; - if (debug_mode) printf("Lock: Using %d loops\n", loops); + if (argc > 1) { + loops = atoi(argv[1]); + } + if (loops == 0) { + loops = 100; + } + if (debug_mode) { + printf("Lock: Using %d loops\n", loops); + } cpus = (argc < 3) ? 2 : atoi(argv[2]); - if (cpus == 0) cpus = 2; - if (debug_mode) printf("Lock: Using %d cpu(s)\n", cpus); + if (cpus == 0) { + cpus = 2; + } + if (debug_mode) { + printf("Lock: Using %d cpu(s)\n", cpus); + } for (cpu = 1; cpu <= cpus; ++cpu) { - if (debug_mode) printf("\nLockFile: Using %d CPU(s)\n", cpu); + if (debug_mode) { + printf("\nLockFile: Using %d CPU(s)\n", cpu); + } PR_SetConcurrency(cpu); - + duration = Test("LockFile non-contentious locking/unlocking", NonContentiousLock, loops, 0); (void)Test("LockFile contentious locking/unlocking", ContentiousLock, loops, duration); } PR_Delete(LOCKFILE); /* try to get rid of evidence */ - if (debug_mode) printf("%s: test %s\n", "Lock(mutex) test", ((failed_already) ? "failed" : "passed")); - if(failed_already) - return 1; - else - return 0; + if (debug_mode) { + printf("%s: test %s\n", "Lock(mutex) test", ((failed_already) ? "failed" : "passed")); + } + if(failed_already) { + return 1; + } + else { + return 0; + } } /* main */ /* testlock.c */ diff --git a/nsprpub/pr/tests/logger.c b/nsprpub/pr/tests/logger.c index a44ef4ee1..ee28d41d7 100644 --- a/nsprpub/pr/tests/logger.c +++ b/nsprpub/pr/tests/logger.c @@ -38,9 +38,9 @@ static void Error(const char* msg) static void PR_CALLBACK forked(void *arg) { PRIntn i; - PRLock *ml; - PRCondVar *cv; - + 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); @@ -53,7 +53,7 @@ static void PR_CALLBACK forked(void *arg) 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); @@ -68,18 +68,18 @@ static void UserLogStuff( void ) myLM = PR_NewLogModule( "userStuff" ); if (! myLM ) - { + { printf("UserLogStuff(): can't create new log module\n" ); return; - } + } PR_LOG( myLM, PR_LOG_NOTICE, ("Log a Notice %d\n", 1 )); for (i = 0; i < 10 ; i++ ) - { + { PR_LOG( myLM, PR_LOG_DEBUG, ("Log Debug number: %d\n", i)); PR_Sleep( 300 ); - } + } } /* end UserLogStuff() */ @@ -107,10 +107,10 @@ int main(int argc, char **argv) /* ** Now change buffering. */ - PR_SetLogBuffering( 65500 ); - thread = PR_CreateThread( - PR_USER_THREAD, forked, (void*)argv[0], PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_SetLogBuffering( 65500 ); + thread = PR_CreateThread( + PR_USER_THREAD, forked, (void*)argv[0], PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); PR_LogPrint("%s joining thread\n", argv[0]); UserLogStuff(); diff --git a/nsprpub/pr/tests/many_cv.c b/nsprpub/pr/tests/many_cv.c index 8bddd7865..8444c9957 100644 --- a/nsprpub/pr/tests/many_cv.c +++ b/nsprpub/pr/tests/many_cv.c @@ -45,22 +45,24 @@ static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 's': /* number of CVs to association with lock */ - stats = PR_TRUE; - break; - case 'c': /* number of CVs to association with lock */ - cvs = atoi(opt->value); - break; - case 'l': /* number of times to run the tests */ - loops = atoi(opt->value); - break; - case 'h': /* user wants some guidance */ - default: - Help(); /* so give him an earful */ - return 2; /* but not a lot else */ + case 's': /* number of CVs to association with lock */ + stats = PR_TRUE; + break; + case 'c': /* number of CVs to association with lock */ + cvs = atoi(opt->value); + break; + case 'l': /* number of times to run the tests */ + loops = atoi(opt->value); + break; + case 'h': /* user wants some guidance */ + default: + Help(); /* so give him an earful */ + return 2; /* but not a lot else */ } } PL_DestroyOptState(opt); @@ -87,20 +89,24 @@ static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) for (nl = 0; nl < cvs; ++nl) { PRInt32 ran = RandomNum() % 8; - if (0 == ran) PR_NotifyAllCondVar(cv[nl]); - else for (nc = 0; nc < ran; ++nc) - PR_NotifyCondVar(cv[nl]); + if (0 == ran) { + PR_NotifyAllCondVar(cv[nl]); + } + else for (nc = 0; nc < ran; ++nc) { + PR_NotifyCondVar(cv[nl]); + } } PR_Unlock(ml); } - for (index = 0; index < cvs; ++index) + for (index = 0; index < cvs; ++index) { PR_DestroyCondVar(cv[index]); + } PR_DELETE(cv); PR_DestroyLock(ml); - + printf("PASS\n"); PT_FPrintStats(err, "\nPThread Statistics\n"); @@ -111,7 +117,7 @@ static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) int main(int argc, char **argv) { PRIntn rv; - + PR_STDIO_INIT(); rv = PR_Initialize(RealMain, argc, argv, 0); return rv; diff --git a/nsprpub/pr/tests/mbcs.c b/nsprpub/pr/tests/mbcs.c index 50d5dd009..1a0d08f84 100644 --- a/nsprpub/pr/tests/mbcs.c +++ b/nsprpub/pr/tests/mbcs.c @@ -10,9 +10,9 @@ ** ** where dirName is the directory to be traversed. dirName is required. ** -** Description: +** Description: ** mbcs.c tests use of multi-byte characters, as would be passed to -** NSPR funtions by internationalized applications. +** NSPR funtions by internationalized applications. ** ** mbcs.c, when run on any single-byte platform, should run correctly. ** In truth, running the mbcs test on a single-byte platform is @@ -31,11 +31,11 @@ ** named such that when represented in the local multi-byte character ** set, one or more characters of the name is longer than a single ** byte. -** +** */ -#include <plgetopt.h> -#include <nspr.h> +#include <plgetopt.h> +#include <nspr.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -68,29 +68,29 @@ static void TraverseDirectory( unsigned char *dir ) printf("Directory: %s\n", dir ); cwd = PR_OpenDir( dir ); if ( NULL == cwd ) { - printf("PR_OpenDir() failed on directory: %s, with error: %d, %d\n", - dir, PR_GetError(), PR_GetOSError()); + printf("PR_OpenDir() failed on directory: %s, with error: %d, %d\n", + dir, PR_GetError(), PR_GetOSError()); exit(1); } while( NULL != (dirEntry = PR_ReadDir( cwd, PR_SKIP_BOTH | PR_SKIP_HIDDEN ))) { sprintf( file, "%s/%s", dir, dirEntry->name ); rc = PR_GetFileInfo( file, &info ); if ( PR_FAILURE == rc ) { - printf("PR_GetFileInfo() failed on file: %s, with error: %d, %d\n", - dirEntry->name, PR_GetError(), PR_GetOSError()); + printf("PR_GetFileInfo() failed on file: %s, with error: %d, %d\n", + dirEntry->name, PR_GetError(), PR_GetOSError()); exit(1); } if ( PR_FILE_FILE == info.type ) { printf("File: %s \tsize: %ld\n", dirEntry->name, info.size ); fd = PR_Open( file, PR_RDONLY, 0 ); if ( NULL == fd ) { - printf("PR_Open() failed. Error: %ld, OSError: %ld\n", - PR_GetError(), PR_GetOSError()); + printf("PR_Open() failed. Error: %ld, OSError: %ld\n", + PR_GetError(), PR_GetOSError()); } rc = PR_Close( fd ); if ( PR_FAILURE == rc ) { - printf("PR_Close() failed. Error: %ld, OSError: %ld\n", - PR_GetError(), PR_GetOSError()); + printf("PR_Close() failed. Error: %ld, OSError: %ld\n", + PR_GetError(), PR_GetOSError()); } } else if ( PR_FILE_DIRECTORY == info.type ) { sprintf( nextDir, "%s/%s", dir, dirEntry->name ); @@ -104,44 +104,46 @@ static void TraverseDirectory( unsigned char *dir ) rc = PR_CloseDir( cwd ); if ( PR_FAILURE == rc ) { - printf("PR_CloseDir() failed on directory: %s, with error: %d, %d\n", - dir, PR_GetError(), PR_GetOSError()); + printf("PR_CloseDir() failed on directory: %s, with error: %d, %d\n", + dir, PR_GetError(), PR_GetOSError()); } } /* end TraverseDirectory() */ int main(int argc, char **argv) { - { /* get command line options */ + { /* get command line options */ /* ** Get command line options */ PLOptStatus os; PLOptState *opt = PL_CreateOptState(argc, argv, "dv"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug */ - debug = 1; - msgLevel = PR_LOG_ERROR; - break; - case 'v': /* verbose mode */ - msgLevel = PR_LOG_DEBUG; - break; - default: - dirName = strdup(opt->value); - break; + case 'd': /* debug */ + debug = 1; + msgLevel = PR_LOG_ERROR; + break; + case 'v': /* verbose mode */ + msgLevel = PR_LOG_DEBUG; + break; + default: + dirName = strdup(opt->value); + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); } /* end get command line options */ lm = PR_NewLogModule("Test"); /* Initialize logging */ - + if ( dirName == NULL ) { printf("you gotta specify a directory as an operand!\n"); exit(1); @@ -149,7 +151,9 @@ int main(int argc, char **argv) TraverseDirectory( dirName ); - if (debug) printf("%s\n", (failed_already)? "FAIL" : "PASS"); + if (debug) { + printf("%s\n", (failed_already)? "FAIL" : "PASS"); + } return( (failed_already == PR_TRUE )? 1 : 0 ); } /* main() */ /* end template.c */ diff --git a/nsprpub/pr/tests/multiacc.c b/nsprpub/pr/tests/multiacc.c index 9382c4f68..ff8452d3d 100644 --- a/nsprpub/pr/tests/multiacc.c +++ b/nsprpub/pr/tests/multiacc.c @@ -65,7 +65,7 @@ int main(int argc, char **argv) char buf[1024]; serverThreads = (PRThread **) - PR_Malloc(num_server_threads * sizeof(PRThread *)); + PR_Malloc(num_server_threads * sizeof(PRThread *)); if (NULL == serverThreads) { fprintf(stderr, "PR_Malloc failed\n"); exit(1); @@ -132,8 +132,8 @@ int main(int argc, char **argv) printf("creating dummy thread\n"); fflush(stdout); dummyThread = PR_CreateThread(PR_USER_THREAD, - ServerThreadFunc, dummySock, PR_PRIORITY_NORMAL, - thread_scope, PR_JOINABLE_THREAD, 0); + ServerThreadFunc, dummySock, PR_PRIORITY_NORMAL, + thread_scope, PR_JOINABLE_THREAD, 0); if (NULL == dummyThread) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); @@ -143,8 +143,8 @@ int main(int argc, char **argv) PR_Sleep(PR_SecondsToInterval(1)); for (idx = 0; idx < num_server_threads; idx++) { serverThreads[idx] = PR_CreateThread(PR_USER_THREAD, - ServerThreadFunc, listenSock, PR_PRIORITY_NORMAL, - thread_scope, PR_JOINABLE_THREAD, 0); + ServerThreadFunc, listenSock, PR_PRIORITY_NORMAL, + thread_scope, PR_JOINABLE_THREAD, 0); if (NULL == serverThreads[idx]) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); diff --git a/nsprpub/pr/tests/multiwait.c b/nsprpub/pr/tests/multiwait.c index 61b08df15..243b315e8 100644 --- a/nsprpub/pr/tests/multiwait.c +++ b/nsprpub/pr/tests/multiwait.c @@ -45,7 +45,9 @@ static PRIntn client_threads = 20, worker_threads = 2, wait_objects = 50; ((_expr)?((void)0):_MW_Assert(# _expr,__FILE__,__LINE__)) static void _MW_Assert(const char *s, const char *file, PRIntn ln) { - if (NULL != debug) PL_FPrintError(debug, NULL); + if (NULL != debug) { + PL_FPrintError(debug, NULL); + } PR_Assert(s, file, ln); } /* _MW_Assert */ #else @@ -56,7 +58,8 @@ static void PrintRecvDesc(PRRecvWait *desc, const char *msg) { const char *tag[] = { "PR_MW_INTERRUPT", "PR_MW_TIMEOUT", - "PR_MW_FAILURE", "PR_MW_SUCCESS", "PR_MW_PENDING"}; + "PR_MW_FAILURE", "PR_MW_SUCCESS", "PR_MW_PENDING" + }; PR_fprintf( debug, "%s: PRRecvWait(@0x%x): {fd: 0x%x, outcome: %s, tmo: %u}\n", msg, desc, desc->fd, tag[desc->outcome + 3], desc->timeout); @@ -75,8 +78,9 @@ static Shared *MakeShared(const char *title) static void DestroyShared(Shared *shared) { PRStatus rv; - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: destroying group\n", shared->title); + } rv = PR_DestroyWaitGroup(shared->group); MW_ASSERT(PR_SUCCESS == rv); PR_DestroyLock(shared->list_lock); @@ -96,18 +100,21 @@ static PRRecvWait *CreateRecvWait(PRFileDesc *fd, PRIntervalTime timeout) PR_AtomicIncrement(&desc_allocated); - if (verbosity > chatty) + if (verbosity > chatty) { PrintRecvDesc(desc_out, "Allocated"); + } return desc_out; } /* CreateRecvWait */ static void DestroyRecvWait(PRRecvWait *desc_out) { - if (verbosity > chatty) + if (verbosity > chatty) { PrintRecvDesc(desc_out, "Destroying"); + } PR_Close(desc_out->fd); - if (NULL != desc_out->buffer.start) + if (NULL != desc_out->buffer.start) { PR_DELETE(desc_out->buffer.start); + } PR_Free(desc_out); (void)PR_AtomicDecrement(&desc_allocated); } /* DestroyRecvWait */ @@ -116,13 +123,16 @@ static void CancelGroup(Shared *shared) { PRRecvWait *desc_out; - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s Reclaiming wait descriptors\n", shared->title); + } do { desc_out = PR_CancelWaitGroup(shared->group); - if (NULL != desc_out) DestroyRecvWait(desc_out); + if (NULL != desc_out) { + DestroyRecvWait(desc_out); + } } while (NULL != desc_out); MW_ASSERT(0 == desc_allocated); @@ -139,11 +149,14 @@ static void PR_CALLBACK ClientThread(void* arg) Shared *shared = (Shared*)arg; PRFileDesc *server = PR_NewTCPSocket(); if ((NULL == server) - && (PR_PENDING_INTERRUPT_ERROR == PR_GetError())) return; + && (PR_PENDING_INTERRUPT_ERROR == PR_GetError())) { + return; + } MW_ASSERT(NULL != server); - if (verbosity > chatty) + if (verbosity > chatty) { PR_fprintf(debug, "%s: Server socket @0x%x\n", shared->title, server); + } /* Initialize the buffer so that Purify won't complain */ memset(buffer, 0, sizeof(buffer)); @@ -151,33 +164,40 @@ static void PR_CALLBACK ClientThread(void* arg) rv = PR_InitializeNetAddr(PR_IpAddrLoopback, default_port, &server_address); MW_ASSERT(PR_SUCCESS == rv); - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: Client opening connection\n", shared->title); + } rv = PR_Connect(server, &server_address, PR_INTERVAL_NO_TIMEOUT); if (PR_FAILURE == rv) { - if (verbosity > silent) PL_FPrintError(debug, "Client connect failed"); + if (verbosity > silent) { + PL_FPrintError(debug, "Client connect failed"); + } return; } while (ops_done < ops_required) { bytes = PR_Send( - server, buffer, sizeof(buffer), empty_flags, PR_INTERVAL_NO_TIMEOUT); - if ((-1 == bytes) && (PR_PENDING_INTERRUPT_ERROR == PR_GetError())) break; + server, buffer, sizeof(buffer), empty_flags, PR_INTERVAL_NO_TIMEOUT); + if ((-1 == bytes) && (PR_PENDING_INTERRUPT_ERROR == PR_GetError())) { + break; + } MW_ASSERT(sizeof(buffer) == bytes); if (verbosity > chatty) PR_fprintf( debug, "%s: Client sent %d bytes\n", shared->title, sizeof(buffer)); bytes = PR_Recv( - server, buffer, sizeof(buffer), empty_flags, PR_INTERVAL_NO_TIMEOUT); + server, buffer, sizeof(buffer), empty_flags, PR_INTERVAL_NO_TIMEOUT); if (verbosity > chatty) PR_fprintf( debug, "%s: Client received %d bytes\n", shared->title, sizeof(buffer)); - if ((-1 == bytes) && (PR_PENDING_INTERRUPT_ERROR == PR_GetError())) break; + if ((-1 == bytes) && (PR_PENDING_INTERRUPT_ERROR == PR_GetError())) { + break; + } MW_ASSERT(sizeof(buffer) == bytes); PR_Sleep(shared->timeout); } @@ -196,12 +216,16 @@ static void OneInThenCancelled(Shared *shared) desc_in->fd = PR_NewTCPSocket(); desc_in->timeout = shared->timeout; - if (verbosity > chatty) PrintRecvDesc(desc_in, "Adding desc"); + if (verbosity > chatty) { + PrintRecvDesc(desc_in, "Adding desc"); + } rv = PR_AddWaitFileDesc(shared->group, desc_in); MW_ASSERT(PR_SUCCESS == rv); - if (verbosity > chatty) PrintRecvDesc(desc_in, "Cancelling"); + if (verbosity > chatty) { + PrintRecvDesc(desc_in, "Cancelling"); + } rv = PR_CancelWaitFileDesc(shared->group, desc_in); MW_ASSERT(PR_SUCCESS == rv); @@ -209,13 +233,16 @@ static void OneInThenCancelled(Shared *shared) MW_ASSERT(desc_out == desc_in); MW_ASSERT(PR_MW_INTERRUPT == desc_out->outcome); MW_ASSERT(PR_PENDING_INTERRUPT_ERROR == PR_GetError()); - if (verbosity > chatty) PrintRecvDesc(desc_out, "Ready"); + if (verbosity > chatty) { + PrintRecvDesc(desc_out, "Ready"); + } rv = PR_Close(desc_in->fd); MW_ASSERT(PR_SUCCESS == rv); - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: destroying group\n", shared->title); + } PR_DELETE(desc_in); } /* OneInThenCancelled */ @@ -228,7 +255,9 @@ static void OneOpOneThread(Shared *shared) desc_in->fd = PR_NewTCPSocket(); desc_in->timeout = shared->timeout; - if (verbosity > chatty) PrintRecvDesc(desc_in, "Adding desc"); + if (verbosity > chatty) { + PrintRecvDesc(desc_in, "Adding desc"); + } rv = PR_AddWaitFileDesc(shared->group, desc_in); MW_ASSERT(PR_SUCCESS == rv); @@ -236,7 +265,9 @@ static void OneOpOneThread(Shared *shared) MW_ASSERT(desc_out == desc_in); MW_ASSERT(PR_MW_TIMEOUT == desc_out->outcome); MW_ASSERT(PR_IO_TIMEOUT_ERROR == PR_GetError()); - if (verbosity > chatty) PrintRecvDesc(desc_out, "Ready"); + if (verbosity > chatty) { + PrintRecvDesc(desc_out, "Ready"); + } rv = PR_Close(desc_in->fd); MW_ASSERT(PR_SUCCESS == rv); @@ -251,8 +282,9 @@ static void ManyOpOneThread(Shared *shared) PRRecvWait *desc_in; PRRecvWait *desc_out; - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: adding %d descs\n", shared->title, wait_objects); + } for (index = 0; index < wait_objects; ++index) { @@ -267,7 +299,9 @@ static void ManyOpOneThread(Shared *shared) desc_out = PR_WaitRecvReady(shared->group); MW_ASSERT(PR_MW_TIMEOUT == desc_out->outcome); MW_ASSERT(PR_IO_TIMEOUT_ERROR == PR_GetError()); - if (verbosity > chatty) PrintRecvDesc(desc_out, "Ready/readding"); + if (verbosity > chatty) { + PrintRecvDesc(desc_out, "Ready/readding"); + } rv = PR_AddWaitFileDesc(shared->group, desc_out); MW_ASSERT(PR_SUCCESS == rv); (void)PR_AtomicIncrement(&ops_done); @@ -287,18 +321,26 @@ static void PR_CALLBACK SomeOpsThread(void *arg) if (NULL == desc_out) { MW_ASSERT(PR_PENDING_INTERRUPT_ERROR == PR_GetError()); - if (verbosity > quiet) PR_fprintf(debug, "Aborted\n"); + if (verbosity > quiet) { + PR_fprintf(debug, "Aborted\n"); + } break; } MW_ASSERT(PR_MW_TIMEOUT == desc_out->outcome); MW_ASSERT(PR_IO_TIMEOUT_ERROR == PR_GetError()); - if (verbosity > chatty) PrintRecvDesc(desc_out, "Ready"); + if (verbosity > chatty) { + PrintRecvDesc(desc_out, "Ready"); + } - if (verbosity > chatty) PrintRecvDesc(desc_out, "Re-Adding"); + if (verbosity > chatty) { + PrintRecvDesc(desc_out, "Re-Adding"); + } desc_out->timeout = shared->timeout; rv = PR_AddWaitFileDesc(shared->group, desc_out); PR_AtomicIncrement(&ops_done); - if (ops_done > ops_required) break; + if (ops_done > ops_required) { + break; + } } while (PR_SUCCESS == rv); MW_ASSERT(PR_SUCCESS == rv); } /* SomeOpsThread */ @@ -314,19 +356,21 @@ static void SomeOpsSomeThreads(Shared *shared) /* Create some threads */ - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: creating threads\n", shared->title); + } for (index = 0; index < worker_threads; ++index) { thread[index] = PR_CreateThread( - PR_USER_THREAD, SomeOpsThread, shared, - PR_PRIORITY_HIGH, thread_scope, - PR_JOINABLE_THREAD, 16 * 1024); + PR_USER_THREAD, SomeOpsThread, shared, + PR_PRIORITY_HIGH, thread_scope, + PR_JOINABLE_THREAD, 16 * 1024); } /* then create some operations */ - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: creating desc\n", shared->title); + } for (index = 0; index < wait_objects; ++index) { desc_in = CreateRecvWait(PR_NewTCPSocket(), shared->timeout); @@ -334,12 +378,16 @@ static void SomeOpsSomeThreads(Shared *shared) MW_ASSERT(PR_SUCCESS == rv); } - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: sleeping\n", shared->title); - while (ops_done < ops_required) PR_Sleep(shared->timeout); + } + while (ops_done < ops_required) { + PR_Sleep(shared->timeout); + } - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: interrupting/joining threads\n", shared->title); + } for (index = 0; index < worker_threads; ++index) { rv = PR_Interrupt(thread[index]); @@ -361,19 +409,25 @@ static PRStatus ServiceRequest(Shared *shared, PRRecvWait *desc) debug, "%s: Service received %d bytes\n", shared->title, desc->bytesRecv); - if (0 == desc->bytesRecv) goto quitting; + if (0 == desc->bytesRecv) { + goto quitting; + } if ((-1 == desc->bytesRecv) - && (PR_PENDING_INTERRUPT_ERROR == PR_GetError())) goto aborted; + && (PR_PENDING_INTERRUPT_ERROR == PR_GetError())) { + goto aborted; + } bytes_out = PR_Send( - desc->fd, desc->buffer.start, desc->bytesRecv, 0, shared->timeout); + desc->fd, desc->buffer.start, desc->bytesRecv, 0, shared->timeout); if (verbosity > chatty) PR_fprintf( debug, "%s: Service sent %d bytes\n", shared->title, bytes_out); if ((-1 == bytes_out) - && (PR_PENDING_INTERRUPT_ERROR == PR_GetError())) goto aborted; + && (PR_PENDING_INTERRUPT_ERROR == PR_GetError())) { + goto aborted; + } MW_ASSERT(bytes_out == desc->bytesRecv); return PR_SUCCESS; @@ -393,8 +447,9 @@ static void PR_CALLBACK ServiceThread(void *arg) if (NULL != desc_out) { desc_out->timeout = PR_INTERVAL_NO_TIMEOUT; - if (verbosity > chatty) + if (verbosity > chatty) { PrintRecvDesc(desc_out, "Service re-adding"); + } rv = PR_AddWaitFileDesc(shared->group, desc_out); MW_ASSERT(PR_SUCCESS == rv); } @@ -411,8 +466,9 @@ static void PR_CALLBACK ServiceThread(void *arg) case PR_MW_SUCCESS: { PR_AtomicIncrement(&ops_done); - if (verbosity > chatty) + if (verbosity > chatty) { PrintRecvDesc(desc_out, "Service ready"); + } rv = ServiceRequest(shared, desc_out); break; } @@ -423,15 +479,18 @@ static void PR_CALLBACK ServiceThread(void *arg) case PR_MW_TIMEOUT: MW_ASSERT(PR_IO_TIMEOUT_ERROR == PR_GetError()); case PR_MW_FAILURE: - if (verbosity > silent) + if (verbosity > silent) { PL_FPrintError(debug, "RecvReady failure"); + } break; default: break; } } while (PR_SUCCESS == rv); - if (NULL != desc_out) DestroyRecvWait(desc_out); + if (NULL != desc_out) { + DestroyRecvWait(desc_out); + } } /* ServiceThread */ @@ -451,12 +510,14 @@ static void PR_CALLBACK EnumerationThread(void *arg) desc = NULL; while (NULL != (desc = PR_EnumerateWaitGroup(enumerator, desc))) { - if (verbosity > chatty) PrintRecvDesc(desc, shared->title); + if (verbosity > chatty) { + PrintRecvDesc(desc, shared->title); + } count += 1; } if (verbosity > silent) PR_fprintf(debug, - "%s Enumerated %d objects\n", shared->title, count); + "%s Enumerated %d objects\n", shared->title, count); } MW_ASSERT(PR_PENDING_INTERRUPT_ERROR == PR_GetError()); @@ -477,14 +538,15 @@ static void PR_CALLBACK ServerThread(void *arg) PRNetAddr server_address, client_address; worker_thread = (PRThread**)PR_CALLOC(sizeof(PRThread*) * worker_threads); - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: Server creating worker_threads\n", shared->title); + } for (index = 0; index < worker_threads; ++index) { worker_thread[index] = PR_CreateThread( - PR_USER_THREAD, ServiceThread, shared, - PR_PRIORITY_HIGH, thread_scope, - PR_JOINABLE_THREAD, 16 * 1024); + PR_USER_THREAD, ServiceThread, shared, + PR_PRIORITY_HIGH, thread_scope, + PR_JOINABLE_THREAD, 16 * 1024); } rv = PR_InitializeNetAddr(PR_IpAddrAny, default_port, &server_address); @@ -499,12 +561,15 @@ static void PR_CALLBACK ServerThread(void *arg) rv = PR_Listen(listener, 10); MW_ASSERT(PR_SUCCESS == rv); while (ops_done < ops_required) { - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: Server accepting connection\n", shared->title); + } service = PR_Accept(listener, &client_address, PR_INTERVAL_NO_TIMEOUT); if (NULL == service) { - if (PR_PENDING_INTERRUPT_ERROR == PR_GetError()) break; + if (PR_PENDING_INTERRUPT_ERROR == PR_GetError()) { + break; + } PL_PrintError("Accept failed"); MW_ASSERT(PR_FALSE && "Accept failed"); } @@ -512,15 +577,17 @@ static void PR_CALLBACK ServerThread(void *arg) { desc_in = CreateRecvWait(service, shared->timeout); desc_in->timeout = PR_INTERVAL_NO_TIMEOUT; - if (verbosity > chatty) + if (verbosity > chatty) { PrintRecvDesc(desc_in, "Service adding"); + } rv = PR_AddWaitFileDesc(shared->group, desc_in); MW_ASSERT(PR_SUCCESS == rv); } } - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: Server interrupting worker_threads\n", shared->title); + } for (index = 0; index < worker_threads; ++index) { rv = PR_Interrupt(worker_thread[index]); @@ -552,41 +619,48 @@ static void RealOneGroupIO(Shared *shared) PRIntn index; PRThread *server_thread, *enumeration_thread, **client_thread; - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: creating server_thread\n", shared->title); + } server_thread = PR_CreateThread( - PR_USER_THREAD, ServerThread, shared, - PR_PRIORITY_HIGH, thread_scope, - PR_JOINABLE_THREAD, 16 * 1024); + PR_USER_THREAD, ServerThread, shared, + PR_PRIORITY_HIGH, thread_scope, + PR_JOINABLE_THREAD, 16 * 1024); - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: creating enumeration_thread\n", shared->title); + } enumeration_thread = PR_CreateThread( - PR_USER_THREAD, EnumerationThread, shared, - PR_PRIORITY_HIGH, thread_scope, - PR_JOINABLE_THREAD, 16 * 1024); + PR_USER_THREAD, EnumerationThread, shared, + PR_PRIORITY_HIGH, thread_scope, + PR_JOINABLE_THREAD, 16 * 1024); - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: snoozing before creating clients\n", shared->title); + } PR_Sleep(5 * shared->timeout); - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: creating client_threads\n", shared->title); + } client_thread = (PRThread**)PR_CALLOC(sizeof(PRThread*) * client_threads); for (index = 0; index < client_threads; ++index) { client_thread[index] = PR_CreateThread( - PR_USER_THREAD, ClientThread, shared, - PR_PRIORITY_NORMAL, thread_scope, - PR_JOINABLE_THREAD, 16 * 1024); + PR_USER_THREAD, ClientThread, shared, + PR_PRIORITY_NORMAL, thread_scope, + PR_JOINABLE_THREAD, 16 * 1024); } - while (ops_done < ops_required) PR_Sleep(shared->timeout); + while (ops_done < ops_required) { + PR_Sleep(shared->timeout); + } - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: interrupting/joining client_threads\n", shared->title); + } for (index = 0; index < client_threads; ++index) { rv = PR_Interrupt(client_thread[index]); @@ -596,15 +670,17 @@ static void RealOneGroupIO(Shared *shared) } PR_DELETE(client_thread); - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: interrupting/joining enumeration_thread\n", shared->title); + } rv = PR_Interrupt(enumeration_thread); MW_ASSERT(PR_SUCCESS == rv); rv = PR_JoinThread(enumeration_thread); MW_ASSERT(PR_SUCCESS == rv); - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(debug, "%s: interrupting/joining server_thread\n", shared->title); + } rv = PR_Interrupt(server_thread); MW_ASSERT(PR_SUCCESS == rv); rv = PR_JoinThread(server_thread); @@ -617,8 +693,9 @@ static void RunThisOne( Shared *shared; if ((NULL == test_name) || (0 == PL_strcmp(name, test_name))) { - if (verbosity > silent) + if (verbosity > silent) { PR_fprintf(debug, "%s()\n", name); + } shared = MakeShared(name); ops_done = 0; func(shared); /* run the test */ @@ -629,8 +706,7 @@ static void RunThisOne( static Verbosity ChangeVerbosity(Verbosity verbosity, PRIntn delta) { - PRIntn verbage = (PRIntn)verbosity; - return (Verbosity)(verbage += delta); + return (Verbosity)(((PRIntn)verbosity) + delta); } /* ChangeVerbosity */ int main(int argc, char **argv) @@ -641,46 +717,51 @@ int main(int argc, char **argv) while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 0: - test_name = opt->value; - break; - case 'd': /* debug mode */ - if (verbosity < noisy) - verbosity = ChangeVerbosity(verbosity, 1); - break; - case 'q': /* debug mode */ - if (verbosity > silent) - verbosity = ChangeVerbosity(verbosity, -1); - break; - case 'G': /* use global threads */ - thread_scope = PR_GLOBAL_THREAD; - break; - case 'c': /* number of client threads */ - client_threads = atoi(opt->value); - break; - case 'o': /* operations to compelete */ - ops_required = atoi(opt->value); - break; - case 'p': /* default port */ - default_port = atoi(opt->value); - break; - case 't': /* number of threads waiting */ - worker_threads = atoi(opt->value); - break; - case 'w': /* number of wait objects */ - wait_objects = atoi(opt->value); - break; - default: - break; + case 0: + test_name = opt->value; + break; + case 'd': /* debug mode */ + if (verbosity < noisy) { + verbosity = ChangeVerbosity(verbosity, 1); + } + break; + case 'q': /* debug mode */ + if (verbosity > silent) { + verbosity = ChangeVerbosity(verbosity, -1); + } + break; + case 'G': /* use global threads */ + thread_scope = PR_GLOBAL_THREAD; + break; + case 'c': /* number of client threads */ + client_threads = atoi(opt->value); + break; + case 'o': /* operations to compelete */ + ops_required = atoi(opt->value); + break; + case 'p': /* default port */ + default_port = atoi(opt->value); + break; + case 't': /* number of threads waiting */ + worker_threads = atoi(opt->value); + break; + case 'w': /* number of wait objects */ + wait_objects = atoi(opt->value); + break; + default: + break; } } PL_DestroyOptState(opt); - if (verbosity > 0) + if (verbosity > 0) { debug = PR_GetSpecialFD(PR_StandardError); + } RunThisOne(OneInThenCancelled, "OneInThenCancelled", test_name); RunThisOne(OneOpOneThread, "OneOpOneThread", test_name); diff --git a/nsprpub/pr/tests/nameshm1.c b/nsprpub/pr/tests/nameshm1.c index 945540b52..3f7137e23 100644 --- a/nsprpub/pr/tests/nameshm1.c +++ b/nsprpub/pr/tests/nameshm1.c @@ -6,10 +6,10 @@ /* ** File: nameshm1.c -- Test Named Shared Memory ** -** Description: +** Description: ** nameshm1 tests Named Shared Memory. nameshm1 performs two tests of -** named shared memory. -** +** named shared memory. +** ** The first test is a basic test. The basic test operates as a single ** process. The process exercises all the API elements of the facility. ** This test also attempts to write to all locations in the shared @@ -31,7 +31,7 @@ ** order. ** ** Synopsis: nameshm1 [options] [name] -** +** ** Options: ** -d Enables debug trace via PR_LOG() ** -v Enables verbose mode debug trace via PR_LOG() @@ -39,7 +39,7 @@ ** mapped as read-only. When this option is specified, the ** test should crash with a seg-fault; this is a destructive ** test and is considered successful when it seg-faults. -** +** ** -C Causes nameshm1 to start as the client-side of a ** client-server pair of processes. Only the instance ** of nameshm1 operating as the server-side process should @@ -48,7 +48,7 @@ ** The client-side uses the shared memory segment created by ** the server-side to communicate with the server-side ** process. -** +** ** -p <n> Specify the number of iterations the client-server tests ** should perform. Default: 1000. ** @@ -66,23 +66,16 @@ ** /lth. Aug-1999. */ -#include <plgetopt.h> +#include <plgetopt.h> #include <nspr.h> #include <stdlib.h> #include <string.h> #include <private/primpl.h> -#ifdef SYMBIAN -#define SEM_NAME1 "c:\\data\\nameshmSEM1" -#define SEM_NAME2 "c:\\data\\nameshmSEM2" -#define OPT_NAME "c:\\data\\xxxNSPRshm" -#define EXE_NAME "nspr_tests_nameshm1.exe" -#else #define SEM_NAME1 "/tmp/nameshmSEM1" #define SEM_NAME2 "/tmp/nameshmSEM2" #define OPT_NAME "/tmp/xxxNSPRshm" #define EXE_NAME "nameshm1" -#endif #define SEM_MODE 0666 #define SHM_MODE 0666 @@ -111,7 +104,7 @@ char optName[NameSize] = OPT_NAME; char buf[1024] = ""; -static void BasicTest( void ) +static void BasicTest( void ) { PRSharedMemory *shm; char *addr; /* address of shared memory segment */ @@ -119,76 +112,76 @@ static void BasicTest( void ) PRInt32 rc; PR_LOG( lm, msgLevel, - ( "nameshm1: Begin BasicTest" )); + ( "nameshm1: Begin BasicTest" )); if ( PR_FAILURE == PR_DeleteSharedMemory( optName )) { PR_LOG( lm, msgLevel, - ("nameshm1: Initial PR_DeleteSharedMemory() failed. No problem")); + ("nameshm1: Initial PR_DeleteSharedMemory() failed. No problem")); } else PR_LOG( lm, msgLevel, - ("nameshm1: Initial PR_DeleteSharedMemory() success")); + ("nameshm1: Initial PR_DeleteSharedMemory() success")); shm = PR_OpenSharedMemory( optName, optSize, (PR_SHM_CREATE | PR_SHM_EXCL), SHM_MODE ); if ( NULL == shm ) { PR_LOG( lm, msgLevel, - ( "nameshm1: RW Create: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); + ( "nameshm1: RW Create: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: RW Create: success: %p", shm )); + ( "nameshm1: RW Create: success: %p", shm )); - addr = PR_AttachSharedMemory( shm , 0 ); - if ( NULL == addr ) + addr = PR_AttachSharedMemory( shm, 0 ); + if ( NULL == addr ) { PR_LOG( lm, msgLevel, - ( "nameshm1: RW Attach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); + ( "nameshm1: RW Attach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: RW Attach: success: %p", addr )); + ( "nameshm1: RW Attach: success: %p", addr )); /* fill memory with i */ for ( i = 0; i < optSize ; i++ ) { - *(addr + i) = i; + *(addr + i) = i; } rc = PR_DetachSharedMemory( shm, addr ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, - ( "nameshm1: RW Detach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); + ( "nameshm1: RW Detach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: RW Detach: success: " )); + ( "nameshm1: RW Detach: success: " )); rc = PR_CloseSharedMemory( shm ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, - ( "nameshm1: RW Close: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); + ( "nameshm1: RW Close: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: RW Close: success: " )); + ( "nameshm1: RW Close: success: " )); rc = PR_DeleteSharedMemory( optName ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, - ( "nameshm1: RW Delete: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); + ( "nameshm1: RW Delete: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: RW Delete: success: " )); + ( "nameshm1: RW Delete: success: " )); PR_LOG( lm, msgLevel, ("nameshm1: BasicTest(): Passed")); @@ -203,30 +196,30 @@ static void ReadOnlyTest( void ) PRInt32 rc; PR_LOG( lm, msgLevel, - ( "nameshm1: Begin ReadOnlyTest" )); + ( "nameshm1: Begin ReadOnlyTest" )); shm = PR_OpenSharedMemory( optName, optSize, (PR_SHM_CREATE | PR_SHM_EXCL), SHM_MODE); if ( NULL == shm ) { PR_LOG( lm, msgLevel, - ( "nameshm1: RO Create: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); + ( "nameshm1: RO Create: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: RO Create: success: %p", shm )); + ( "nameshm1: RO Create: success: %p", shm )); - roAddr = PR_AttachSharedMemory( shm , PR_SHM_READONLY ); - if ( NULL == roAddr ) + roAddr = PR_AttachSharedMemory( shm, PR_SHM_READONLY ); + if ( NULL == roAddr ) { PR_LOG( lm, msgLevel, - ( "nameshm1: RO Attach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); + ( "nameshm1: RO Attach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: RO Attach: success: %p", roAddr )); + ( "nameshm1: RO Attach: success: %p", roAddr )); if ( optWriteRO ) { @@ -240,37 +233,37 @@ static void ReadOnlyTest( void ) if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, - ( "nameshm1: RO Detach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); + ( "nameshm1: RO Detach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: RO Detach: success: " )); + ( "nameshm1: RO Detach: success: " )); rc = PR_CloseSharedMemory( shm ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, - ( "nameshm1: RO Close: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); + ( "nameshm1: RO Close: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: RO Close: success: " )); + ( "nameshm1: RO Close: success: " )); rc = PR_DeleteSharedMemory( optName ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, - ( "nameshm1: RO Destroy: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); + ( "nameshm1: RO Destroy: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: RO Destroy: success: " )); + ( "nameshm1: RO Destroy: success: " )); PR_LOG( lm, msgLevel, - ("nameshm1: ReadOnlyTest(): Passed")); + ("nameshm1: ReadOnlyTest(): Passed")); return; } /* end ReadOnlyTest() */ @@ -280,7 +273,7 @@ static void DoClient( void ) PRStatus rc; PRSem *sem1, *sem2; PRSharedMemory *shm; - PRUint32 *addr; + PRUint32 *addr; PRInt32 i; PR_LOG( lm, msgLevel, @@ -296,40 +289,40 @@ static void DoClient( void ) if ( NULL == shm ) { PR_LOG( lm, msgLevel, - ( "nameshm1: DoClient(): Create: Error: %ld. OSError: %ld", - PR_GetError(), PR_GetOSError())); + ( "nameshm1: DoClient(): Create: Error: %ld. OSError: %ld", + PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: DoClient(): Create: success: %p", shm )); + ( "nameshm1: DoClient(): Create: success: %p", shm )); - addr = PR_AttachSharedMemory( shm , 0 ); - if ( NULL == addr ) + addr = PR_AttachSharedMemory( shm, 0 ); + if ( NULL == addr ) { PR_LOG( lm, msgLevel, - ( "nameshm1: DoClient(): Attach: Error: %ld. OSError: %ld", - PR_GetError(), PR_GetOSError())); + ( "nameshm1: DoClient(): Attach: Error: %ld. OSError: %ld", + PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: DoClient(): Attach: success: %p", addr )); + ( "nameshm1: DoClient(): Attach: success: %p", addr )); PR_LOG( lm, msgLevel, - ( "Client found: %s", addr)); + ( "Client found: %s", addr)); PR_Sleep(PR_SecondsToInterval(4)); for ( i = 0 ; i < optPing ; i++ ) { rc = PR_WaitSemaphore( sem2 ); PR_ASSERT( PR_FAILURE != rc ); - + (*addr)++; - PR_ASSERT( (*addr % 2) == 0 ); + PR_ASSERT( (*addr % 2) == 0 ); if ( optVerbose ) PR_LOG( lm, msgLevel, - ( "nameshm1: Client ping: %d, i: %d", *addr, i)); + ( "nameshm1: Client ping: %d, i: %d", *addr, i)); rc = PR_PostSemaphore( sem1 ); PR_ASSERT( PR_FAILURE != rc ); @@ -345,25 +338,25 @@ static void DoClient( void ) if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, - ( "nameshm1: DoClient(): Detach: Error: %ld. OSError: %ld", - PR_GetError(), PR_GetOSError())); + ( "nameshm1: DoClient(): Detach: Error: %ld. OSError: %ld", + PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: DoClient(): Detach: success: " )); + ( "nameshm1: DoClient(): Detach: success: " )); rc = PR_CloseSharedMemory( shm ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, - ( "nameshm1: DoClient(): Close: Error: %ld. OSError: %ld", - PR_GetError(), PR_GetOSError())); + ( "nameshm1: DoClient(): Close: Error: %ld. OSError: %ld", + PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: DoClient(): Close: success: " )); + ( "nameshm1: DoClient(): Close: success: " )); return; } /* end DoClient() */ @@ -375,45 +368,45 @@ static void ClientServerTest( void ) PRProcess *proc; PRInt32 exit_status; PRSharedMemory *shm; - PRUint32 *addr; + PRUint32 *addr; PRInt32 i; char *child_argv[8]; char buf[24]; PR_LOG( lm, msgLevel, - ( "nameshm1: Begin ClientServerTest" )); + ( "nameshm1: Begin ClientServerTest" )); rc = PR_DeleteSharedMemory( optName ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, - ( "nameshm1: Server: Destroy: failed. No problem")); + ( "nameshm1: Server: Destroy: failed. No problem")); } else PR_LOG( lm, msgLevel, - ( "nameshm1: Server: Destroy: success" )); + ( "nameshm1: Server: Destroy: success" )); shm = PR_OpenSharedMemory( optName, optSize, (PR_SHM_CREATE | PR_SHM_EXCL), SHM_MODE); if ( NULL == shm ) { PR_LOG( lm, msgLevel, - ( "nameshm1: Server: Create: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); + ( "nameshm1: Server: Create: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: Server: Create: success: %p", shm )); + ( "nameshm1: Server: Create: success: %p", shm )); - addr = PR_AttachSharedMemory( shm , 0 ); - if ( NULL == addr ) + addr = PR_AttachSharedMemory( shm, 0 ); + if ( NULL == addr ) { PR_LOG( lm, msgLevel, - ( "nameshm1: Server: Attach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); + ( "nameshm1: Server: Attach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: Server: Attach: success: %p", addr )); + ( "nameshm1: Server: Attach: success: %p", addr )); sem1 = PR_OpenSemaphore( SEM_NAME1, PR_SEM_CREATE, SEM_MODE, 0 ); PR_ASSERT( sem1 ); @@ -438,7 +431,7 @@ static void ClientServerTest( void ) *addr = 1; for ( i = 0 ; i < optPing ; i++ ) - { + { rc = PR_WaitSemaphore( sem1 ); PR_ASSERT( PR_FAILURE != rc ); @@ -446,9 +439,9 @@ static void ClientServerTest( void ) PR_ASSERT( (*addr % 2) == 1 ); if ( optVerbose ) PR_LOG( lm, msgLevel, - ( "nameshm1: Server pong: %d, i: %d", *addr, i)); + ( "nameshm1: Server pong: %d, i: %d", *addr, i)); + - rc = PR_PostSemaphore( sem2 ); PR_ASSERT( PR_FAILURE != rc ); } @@ -472,37 +465,37 @@ static void ClientServerTest( void ) if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, - ( "nameshm1: Server: Detach: Error: %ld. OSError: %ld", - PR_GetError(), PR_GetOSError())); + ( "nameshm1: Server: Detach: Error: %ld. OSError: %ld", + PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: Server: Detach: success: " )); + ( "nameshm1: Server: Detach: success: " )); rc = PR_CloseSharedMemory( shm ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, - ( "nameshm1: Server: Close: Error: %ld. OSError: %ld", - PR_GetError(), PR_GetOSError())); + ( "nameshm1: Server: Close: Error: %ld. OSError: %ld", + PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: Server: Close: success: " )); + ( "nameshm1: Server: Close: success: " )); rc = PR_DeleteSharedMemory( optName ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, - ( "nameshm1: Server: Destroy: Error: %ld. OSError: %ld", - PR_GetError(), PR_GetOSError())); + ( "nameshm1: Server: Destroy: Error: %ld. OSError: %ld", + PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, - ( "nameshm1: Server: Destroy: success" )); + ( "nameshm1: Server: Destroy: success" )); return; } /* end ClientServerTest() */ @@ -516,61 +509,67 @@ int main(int argc, char **argv) PLOptStatus os; PLOptState *opt = PL_CreateOptState(argc, argv, "Cdvw:s:p:i:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'v': /* debug mode */ - optVerbose = 1; + case 'v': /* debug mode */ + optVerbose = 1; /* no break! fall into debug option */ - case 'd': /* debug mode */ - debug = 1; - msgLevel = PR_LOG_DEBUG; - break; - case 'w': /* try writing to memory mapped read-only */ - optWriteRO = 1; - break; - case 'C': - optClient = 1; - break; - case 's': - optSize = atol(opt->value) * 1024; - break; - case 'p': - optPing = atol(opt->value); - break; - case 'i': - optClientIterations = atol(opt->value); - break; - default: - strcpy( optName, opt->value ); - break; + case 'd': /* debug mode */ + debug = 1; + msgLevel = PR_LOG_DEBUG; + break; + case 'w': /* try writing to memory mapped read-only */ + optWriteRO = 1; + break; + case 'C': + optClient = 1; + break; + case 's': + optSize = atol(opt->value) * 1024; + break; + case 'p': + optPing = atol(opt->value); + break; + case 'i': + optClientIterations = atol(opt->value); + break; + default: + strcpy( optName, opt->value ); + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); } lm = PR_NewLogModule("Test"); /* Initialize logging */ - + PR_LOG( lm, msgLevel, - ( "nameshm1: Starting" )); + ( "nameshm1: Starting" )); if ( optClient ) { DoClient(); } else { BasicTest(); - if ( failed_already != 0 ) + if ( failed_already != 0 ) { goto Finished; + } ReadOnlyTest(); - if ( failed_already != 0 ) + if ( failed_already != 0 ) { goto Finished; + } ClientServerTest(); } Finished: - if ( debug ) printf("%s\n", (failed_already)? "FAIL" : "PASS" ); + if ( debug ) { + printf("%s\n", (failed_already)? "FAIL" : "PASS" ); + } return( (failed_already)? 1 : 0 ); } /* main() */ /* end instrumt.c */ diff --git a/nsprpub/pr/tests/nbconn.c b/nsprpub/pr/tests/nbconn.c index e113a7e18..d1dd67c04 100644 --- a/nsprpub/pr/tests/nbconn.c +++ b/nsprpub/pr/tests/nbconn.c @@ -30,12 +30,12 @@ #include <string.h> #define SERVER_MAX_BIND_COUNT 100 -#define DATA_BUF_SIZE 256 +#define DATA_BUF_SIZE 256 #define TCP_SERVER_PORT 10000 #define TCP_UNUSED_PORT 211 typedef struct Server_Param { - PRFileDesc *sp_fd; /* server port */ + PRFileDesc *sp_fd; /* server port */ } Server_Param; static void PR_CALLBACK TCP_Server(void *arg); @@ -53,9 +53,9 @@ int main(int argc, char **argv) PRPollDesc pd; PRStatus rv; PRSocketOptionData optData; - const char *hostname = NULL; + const char *hostname = NULL; PRIntn default_case, n, bytes_read, bytes_sent; - PRInt32 failed_already = 0; + PRInt32 failed_already = 0; /* * -d debug mode @@ -65,112 +65,117 @@ int main(int argc, char **argv) PLOptState *opt = PL_CreateOptState(argc, argv, "d"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 0: /* debug mode */ - hostname = opt->value; - break; - case 'd': /* debug mode */ - _debug_on = 1; - break; - default: - break; + case 0: /* debug mode */ + hostname = opt->value; + break; + case 'd': /* debug mode */ + _debug_on = 1; + break; + default: + break; } } PL_DestroyOptState(opt); PR_STDIO_INIT(); - if (hostname) - default_case = 0; - else - default_case = 1; - - if (default_case) { - - /* - * In the default case the following tests are executed: - * 1. successful connection: a server thread accepts a connection - * from the main thread - * 2. unsuccessful connection: the main thread tries to connect to a - * nonexistent port and expects to get an error - */ - rv = connection_success_test(); - if (rv == 0) - rv = connection_failure_test(); - return rv; - } else { - PRFileDesc *sock; - - if (PR_GetHostByName(argv[1], buf, sizeof(buf), &he) == PR_FAILURE) { - printf( "Unknown host: %s\n", argv[1]); - exit(1); - } else { - printf( "host: %s\n", buf); - } - PR_EnumerateHostEnt(0, &he, 80, &addr); - - sock = PR_NewTCPSocket(); - optData.option = PR_SockOpt_Nonblocking; - optData.value.non_blocking = PR_TRUE; - PR_SetSocketOption(sock, &optData); - rv = PR_Connect(sock, &addr, PR_INTERVAL_NO_TIMEOUT); - if (rv == PR_FAILURE && PR_GetError() == PR_IN_PROGRESS_ERROR) { - printf( "Connect in progress\n"); - } - - pd.fd = sock; - pd.in_flags = PR_POLL_WRITE | PR_POLL_EXCEPT; - n = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT); - if (n == -1) { - printf( "PR_Poll failed\n"); - exit(1); - } - printf( "PR_Poll returns %d\n", n); - if (pd.out_flags & PR_POLL_READ) { - printf( "PR_POLL_READ\n"); - } - if (pd.out_flags & PR_POLL_WRITE) { - printf( "PR_POLL_WRITE\n"); - } - if (pd.out_flags & PR_POLL_EXCEPT) { - printf( "PR_POLL_EXCEPT\n"); - } - if (pd.out_flags & PR_POLL_ERR) { - printf( "PR_POLL_ERR\n"); - } - if (pd.out_flags & PR_POLL_NVAL) { - printf( "PR_POLL_NVAL\n"); - } - - if (PR_GetConnectStatus(&pd) == PR_SUCCESS) { - printf("PR_GetConnectStatus: connect succeeded\n"); - PR_Write(sock, "GET /\r\n\r\n", 9); - PR_Shutdown(sock, PR_SHUTDOWN_SEND); - pd.in_flags = PR_POLL_READ; - while (1) { - n = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT); - printf( "poll returns %d\n", n); - n = PR_Read(sock, buf, sizeof(buf)); - printf( "read returns %d\n", n); - if (n <= 0) { - break; - } - PR_Write(PR_STDOUT, buf, n); - } - } else { - if (PR_GetError() == PR_IN_PROGRESS_ERROR) { - printf( "PR_GetConnectStatus: connect still in progress\n"); - exit(1); - } - printf( "PR_GetConnectStatus: connect failed: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); - } - PR_Close(sock); - printf( "PASS\n"); - return 0; - - } + if (hostname) { + default_case = 0; + } + else { + default_case = 1; + } + + if (default_case) { + + /* + * In the default case the following tests are executed: + * 1. successful connection: a server thread accepts a connection + * from the main thread + * 2. unsuccessful connection: the main thread tries to connect to a + * nonexistent port and expects to get an error + */ + rv = connection_success_test(); + if (rv == 0) { + rv = connection_failure_test(); + } + return rv; + } else { + PRFileDesc *sock; + + if (PR_GetHostByName(argv[1], buf, sizeof(buf), &he) == PR_FAILURE) { + printf( "Unknown host: %s\n", argv[1]); + exit(1); + } else { + printf( "host: %s\n", buf); + } + PR_EnumerateHostEnt(0, &he, 80, &addr); + + sock = PR_NewTCPSocket(); + optData.option = PR_SockOpt_Nonblocking; + optData.value.non_blocking = PR_TRUE; + PR_SetSocketOption(sock, &optData); + rv = PR_Connect(sock, &addr, PR_INTERVAL_NO_TIMEOUT); + if (rv == PR_FAILURE && PR_GetError() == PR_IN_PROGRESS_ERROR) { + printf( "Connect in progress\n"); + } + + pd.fd = sock; + pd.in_flags = PR_POLL_WRITE | PR_POLL_EXCEPT; + n = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT); + if (n == -1) { + printf( "PR_Poll failed\n"); + exit(1); + } + printf( "PR_Poll returns %d\n", n); + if (pd.out_flags & PR_POLL_READ) { + printf( "PR_POLL_READ\n"); + } + if (pd.out_flags & PR_POLL_WRITE) { + printf( "PR_POLL_WRITE\n"); + } + if (pd.out_flags & PR_POLL_EXCEPT) { + printf( "PR_POLL_EXCEPT\n"); + } + if (pd.out_flags & PR_POLL_ERR) { + printf( "PR_POLL_ERR\n"); + } + if (pd.out_flags & PR_POLL_NVAL) { + printf( "PR_POLL_NVAL\n"); + } + + if (PR_GetConnectStatus(&pd) == PR_SUCCESS) { + printf("PR_GetConnectStatus: connect succeeded\n"); + PR_Write(sock, "GET /\r\n\r\n", 9); + PR_Shutdown(sock, PR_SHUTDOWN_SEND); + pd.in_flags = PR_POLL_READ; + while (1) { + n = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT); + printf( "poll returns %d\n", n); + n = PR_Read(sock, buf, sizeof(buf)); + printf( "read returns %d\n", n); + if (n <= 0) { + break; + } + PR_Write(PR_STDOUT, buf, n); + } + } else { + if (PR_GetError() == PR_IN_PROGRESS_ERROR) { + printf( "PR_GetConnectStatus: connect still in progress\n"); + exit(1); + } + printf( "PR_GetConnectStatus: connect failed: (%ld, %ld)\n", + PR_GetError(), PR_GetOSError()); + } + PR_Close(sock); + printf( "PASS\n"); + return 0; + + } } @@ -184,40 +189,40 @@ TCP_Server(void *arg) { Server_Param *sp = (Server_Param *) arg; PRFileDesc *sockfd, *newsockfd; - char data_buf[DATA_BUF_SIZE]; + char data_buf[DATA_BUF_SIZE]; PRIntn rv, bytes_read; - sockfd = sp->sp_fd; - if ((newsockfd = PR_Accept(sockfd, NULL, - PR_INTERVAL_NO_TIMEOUT)) == NULL) { - fprintf(stderr,"ERROR - PR_Accept failed: (%d,%d)\n", - PR_GetError(), PR_GetOSError()); - return; - } - bytes_read = 0; - while (bytes_read != DATA_BUF_SIZE) { - rv = PR_Read(newsockfd, data_buf + bytes_read , - DATA_BUF_SIZE - bytes_read); - if (rv < 0) { - fprintf(stderr,"Error - PR_Read failed: (%d, %d)\n", - PR_GetError(), PR_GetOSError()); - PR_Close(newsockfd); - return; - } - PR_ASSERT(rv != 0); - bytes_read += rv; - } - DPRINTF(("Bytes read from client - %d\n",bytes_read)); - rv = PR_Write(newsockfd, data_buf,DATA_BUF_SIZE); - if (rv < 0) { - fprintf(stderr,"Error - PR_Write failed: (%d, %d)\n", - PR_GetError(), PR_GetOSError()); - PR_Close(newsockfd); - return; - } - PR_ASSERT(rv == DATA_BUF_SIZE); - DPRINTF(("Bytes written to client - %d\n",rv)); - PR_Close(newsockfd); + sockfd = sp->sp_fd; + if ((newsockfd = PR_Accept(sockfd, NULL, + PR_INTERVAL_NO_TIMEOUT)) == NULL) { + fprintf(stderr,"ERROR - PR_Accept failed: (%d,%d)\n", + PR_GetError(), PR_GetOSError()); + return; + } + bytes_read = 0; + while (bytes_read != DATA_BUF_SIZE) { + rv = PR_Read(newsockfd, data_buf + bytes_read, + DATA_BUF_SIZE - bytes_read); + if (rv < 0) { + fprintf(stderr,"Error - PR_Read failed: (%d, %d)\n", + PR_GetError(), PR_GetOSError()); + PR_Close(newsockfd); + return; + } + PR_ASSERT(rv != 0); + bytes_read += rv; + } + DPRINTF(("Bytes read from client - %d\n",bytes_read)); + rv = PR_Write(newsockfd, data_buf,DATA_BUF_SIZE); + if (rv < 0) { + fprintf(stderr,"Error - PR_Write failed: (%d, %d)\n", + PR_GetError(), PR_GetOSError()); + PR_Close(newsockfd); + return; + } + PR_ASSERT(rv == DATA_BUF_SIZE); + DPRINTF(("Bytes written to client - %d\n",rv)); + PR_Close(newsockfd); } @@ -227,190 +232,193 @@ TCP_Server(void *arg) static PRIntn connection_success_test() { - PRFileDesc *sockfd = NULL, *conn_fd = NULL; - PRNetAddr netaddr; - PRInt32 i, rv; + PRFileDesc *sockfd = NULL, *conn_fd = NULL; + PRNetAddr netaddr; + PRInt32 i, rv; PRPollDesc pd; PRSocketOptionData optData; - PRThread *thr = NULL; - Server_Param sp; - char send_buf[DATA_BUF_SIZE], recv_buf[DATA_BUF_SIZE]; + PRThread *thr = NULL; + Server_Param sp; + char send_buf[DATA_BUF_SIZE], recv_buf[DATA_BUF_SIZE]; PRIntn default_case, n, bytes_read, bytes_sent; PRIntn failed_already = 0; - /* - * Create a tcp socket - */ - if ((sockfd = PR_NewTCPSocket()) == NULL) { - fprintf(stderr,"Error - PR_NewTCPSocket failed\n"); - failed_already=1; - goto def_exit; - } - memset(&netaddr, 0 , sizeof(netaddr)); - netaddr.inet.family = PR_AF_INET; - netaddr.inet.port = PR_htons(TCP_SERVER_PORT); - netaddr.inet.ip = PR_htonl(PR_INADDR_ANY); - /* - * try a few times to bind server's address, if addresses are in - * use - */ - i = 0; - while (PR_Bind(sockfd, &netaddr) < 0) { - if (PR_GetError() == PR_ADDRESS_IN_USE_ERROR) { - netaddr.inet.port += 2; - if (i++ < SERVER_MAX_BIND_COUNT) - continue; - } - fprintf(stderr,"ERROR - PR_Bind failed: (%d,%d)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - goto def_exit; - } - - if (PR_Listen(sockfd, 32) < 0) { - fprintf(stderr,"ERROR - PR_Listen failed: (%d,%d)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - goto def_exit; - } - - if (PR_GetSockName(sockfd, &netaddr) < 0) { - fprintf(stderr,"ERROR - PR_GetSockName failed: (%d,%d)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - goto def_exit; - } - if ((conn_fd = PR_NewTCPSocket()) == NULL) { - fprintf(stderr,"Error - PR_NewTCPSocket failed\n"); - failed_already=1; - goto def_exit; - } - optData.option = PR_SockOpt_Nonblocking; - optData.value.non_blocking = PR_TRUE; - PR_SetSocketOption(conn_fd, &optData); - rv = PR_Connect(conn_fd, &netaddr, PR_INTERVAL_NO_TIMEOUT); - if (rv == PR_FAILURE) { - if (PR_GetError() == PR_IN_PROGRESS_ERROR) { - DPRINTF(("Connect in progress\n")); - } else { - fprintf(stderr,"Error - PR_Connect failed: (%d, %d)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - goto def_exit; - } - } - /* - * Now create a thread to accept a connection - */ - sp.sp_fd = sockfd; - thr = PR_CreateThread(PR_USER_THREAD, TCP_Server, (void *)&sp, - PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); - if (thr == NULL) { - fprintf(stderr,"Error - PR_CreateThread failed: (%d,%d)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - goto def_exit; - } - DPRINTF(("Created TCP_Server thread [0x%x]\n",thr)); - pd.fd = conn_fd; - pd.in_flags = PR_POLL_WRITE | PR_POLL_EXCEPT; - n = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT); - if (n == -1) { - fprintf(stderr,"Error - PR_Poll failed: (%d, %d)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - goto def_exit; - } - if (PR_GetConnectStatus(&pd) == PR_SUCCESS) { - PRInt32 rv; - - DPRINTF(("Connection successful\n")); - - /* - * Write some data, read it back and check data integrity to - * make sure the connection is good - */ - pd.in_flags = PR_POLL_WRITE; - bytes_sent = 0; - memset(send_buf, 'a', DATA_BUF_SIZE); - while (bytes_sent != DATA_BUF_SIZE) { - rv = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT); - if (rv < 0) { - fprintf(stderr,"Error - PR_Poll failed: (%d, %d)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - goto def_exit; - } - PR_ASSERT((rv == 1) && (pd.out_flags == PR_POLL_WRITE)); - rv = PR_Write(conn_fd, send_buf + bytes_sent, - DATA_BUF_SIZE - bytes_sent); - if (rv < 0) { - fprintf(stderr,"Error - PR_Write failed: (%d, %d)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - goto def_exit; - } - PR_ASSERT(rv > 0); - bytes_sent += rv; - } - DPRINTF(("Bytes written to server - %d\n",bytes_sent)); - PR_Shutdown(conn_fd, PR_SHUTDOWN_SEND); - pd.in_flags = PR_POLL_READ; - bytes_read = 0; - memset(recv_buf, 0, DATA_BUF_SIZE); - while (bytes_read != DATA_BUF_SIZE) { - rv = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT); - if (rv < 0) { - fprintf(stderr,"Error - PR_Poll failed: (%d, %d)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - goto def_exit; - } - PR_ASSERT((rv == 1) && (pd.out_flags == PR_POLL_READ)); - rv = PR_Read(conn_fd, recv_buf + bytes_read , - DATA_BUF_SIZE - bytes_read); - if (rv < 0) { - fprintf(stderr,"Error - PR_Read failed: (%d, %d)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - goto def_exit; - } - PR_ASSERT(rv != 0); - bytes_read += rv; - } - DPRINTF(("Bytes read from server - %d\n",bytes_read)); - /* - * verify the data read - */ - if (memcmp(send_buf, recv_buf, DATA_BUF_SIZE) != 0) { - fprintf(stderr,"ERROR - data corruption\n"); - failed_already=1; - goto def_exit; - } - DPRINTF(("Data integrity verified\n")); - } else { - fprintf(stderr,"PR_GetConnectStatus: connect failed: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); - failed_already = 1; - goto def_exit; - } + /* + * Create a tcp socket + */ + if ((sockfd = PR_NewTCPSocket()) == NULL) { + fprintf(stderr,"Error - PR_NewTCPSocket failed\n"); + failed_already=1; + goto def_exit; + } + memset(&netaddr, 0, sizeof(netaddr)); + netaddr.inet.family = PR_AF_INET; + netaddr.inet.port = PR_htons(TCP_SERVER_PORT); + netaddr.inet.ip = PR_htonl(PR_INADDR_ANY); + /* + * try a few times to bind server's address, if addresses are in + * use + */ + i = 0; + while (PR_Bind(sockfd, &netaddr) < 0) { + if (PR_GetError() == PR_ADDRESS_IN_USE_ERROR) { + netaddr.inet.port += 2; + if (i++ < SERVER_MAX_BIND_COUNT) { + continue; + } + } + fprintf(stderr,"ERROR - PR_Bind failed: (%d,%d)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + goto def_exit; + } + + if (PR_Listen(sockfd, 32) < 0) { + fprintf(stderr,"ERROR - PR_Listen failed: (%d,%d)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + goto def_exit; + } + + if (PR_GetSockName(sockfd, &netaddr) < 0) { + fprintf(stderr,"ERROR - PR_GetSockName failed: (%d,%d)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + goto def_exit; + } + if ((conn_fd = PR_NewTCPSocket()) == NULL) { + fprintf(stderr,"Error - PR_NewTCPSocket failed\n"); + failed_already=1; + goto def_exit; + } + optData.option = PR_SockOpt_Nonblocking; + optData.value.non_blocking = PR_TRUE; + PR_SetSocketOption(conn_fd, &optData); + rv = PR_Connect(conn_fd, &netaddr, PR_INTERVAL_NO_TIMEOUT); + if (rv == PR_FAILURE) { + if (PR_GetError() == PR_IN_PROGRESS_ERROR) { + DPRINTF(("Connect in progress\n")); + } else { + fprintf(stderr,"Error - PR_Connect failed: (%d, %d)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + goto def_exit; + } + } + /* + * Now create a thread to accept a connection + */ + sp.sp_fd = sockfd; + thr = PR_CreateThread(PR_USER_THREAD, TCP_Server, (void *)&sp, + PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + if (thr == NULL) { + fprintf(stderr,"Error - PR_CreateThread failed: (%d,%d)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + goto def_exit; + } + DPRINTF(("Created TCP_Server thread [0x%x]\n",thr)); + pd.fd = conn_fd; + pd.in_flags = PR_POLL_WRITE | PR_POLL_EXCEPT; + n = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT); + if (n == -1) { + fprintf(stderr,"Error - PR_Poll failed: (%d, %d)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + goto def_exit; + } + if (PR_GetConnectStatus(&pd) == PR_SUCCESS) { + PRInt32 rv; + + DPRINTF(("Connection successful\n")); + + /* + * Write some data, read it back and check data integrity to + * make sure the connection is good + */ + pd.in_flags = PR_POLL_WRITE; + bytes_sent = 0; + memset(send_buf, 'a', DATA_BUF_SIZE); + while (bytes_sent != DATA_BUF_SIZE) { + rv = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT); + if (rv < 0) { + fprintf(stderr,"Error - PR_Poll failed: (%d, %d)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + goto def_exit; + } + PR_ASSERT((rv == 1) && (pd.out_flags == PR_POLL_WRITE)); + rv = PR_Write(conn_fd, send_buf + bytes_sent, + DATA_BUF_SIZE - bytes_sent); + if (rv < 0) { + fprintf(stderr,"Error - PR_Write failed: (%d, %d)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + goto def_exit; + } + PR_ASSERT(rv > 0); + bytes_sent += rv; + } + DPRINTF(("Bytes written to server - %d\n",bytes_sent)); + PR_Shutdown(conn_fd, PR_SHUTDOWN_SEND); + pd.in_flags = PR_POLL_READ; + bytes_read = 0; + memset(recv_buf, 0, DATA_BUF_SIZE); + while (bytes_read != DATA_BUF_SIZE) { + rv = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT); + if (rv < 0) { + fprintf(stderr,"Error - PR_Poll failed: (%d, %d)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + goto def_exit; + } + PR_ASSERT((rv == 1) && (pd.out_flags == PR_POLL_READ)); + rv = PR_Read(conn_fd, recv_buf + bytes_read, + DATA_BUF_SIZE - bytes_read); + if (rv < 0) { + fprintf(stderr,"Error - PR_Read failed: (%d, %d)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + goto def_exit; + } + PR_ASSERT(rv != 0); + bytes_read += rv; + } + DPRINTF(("Bytes read from server - %d\n",bytes_read)); + /* + * verify the data read + */ + if (memcmp(send_buf, recv_buf, DATA_BUF_SIZE) != 0) { + fprintf(stderr,"ERROR - data corruption\n"); + failed_already=1; + goto def_exit; + } + DPRINTF(("Data integrity verified\n")); + } else { + fprintf(stderr,"PR_GetConnectStatus: connect failed: (%ld, %ld)\n", + PR_GetError(), PR_GetOSError()); + failed_already = 1; + goto def_exit; + } def_exit: - if (thr) { - PR_JoinThread(thr); - thr = NULL; - } - if (sockfd) { - PR_Close(sockfd); - sockfd = NULL; - } - if (conn_fd) { - PR_Close(conn_fd); - conn_fd = NULL; - } - if (failed_already) - return 1; - else - return 0; + if (thr) { + PR_JoinThread(thr); + thr = NULL; + } + if (sockfd) { + PR_Close(sockfd); + sockfd = NULL; + } + if (conn_fd) { + PR_Close(conn_fd); + conn_fd = NULL; + } + if (failed_already) { + return 1; + } + else { + return 0; + } } @@ -420,101 +428,104 @@ def_exit: static PRIntn connection_failure_test() { - PRFileDesc *sockfd = NULL, *conn_fd = NULL; - PRNetAddr netaddr; - PRInt32 i, rv; + PRFileDesc *sockfd = NULL, *conn_fd = NULL; + PRNetAddr netaddr; + PRInt32 i, rv; PRPollDesc pd; PRSocketOptionData optData; PRIntn n, failed_already = 0; - /* - * Create a tcp socket - */ - if ((sockfd = PR_NewTCPSocket()) == NULL) { - fprintf(stderr,"Error - PR_NewTCPSocket failed\n"); - failed_already=1; - goto def_exit; - } - memset(&netaddr, 0 , sizeof(netaddr)); - netaddr.inet.family = PR_AF_INET; - netaddr.inet.port = PR_htons(TCP_SERVER_PORT); - netaddr.inet.ip = PR_htonl(PR_INADDR_ANY); - /* - * try a few times to bind server's address, if addresses are in - * use - */ - i = 0; - while (PR_Bind(sockfd, &netaddr) < 0) { - if (PR_GetError() == PR_ADDRESS_IN_USE_ERROR) { - netaddr.inet.port += 2; - if (i++ < SERVER_MAX_BIND_COUNT) - continue; - } - fprintf(stderr,"ERROR - PR_Bind failed: (%d,%d)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - goto def_exit; - } - - if (PR_GetSockName(sockfd, &netaddr) < 0) { - fprintf(stderr,"ERROR - PR_GetSockName failed: (%d,%d)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - goto def_exit; - } + /* + * Create a tcp socket + */ + if ((sockfd = PR_NewTCPSocket()) == NULL) { + fprintf(stderr,"Error - PR_NewTCPSocket failed\n"); + failed_already=1; + goto def_exit; + } + memset(&netaddr, 0, sizeof(netaddr)); + netaddr.inet.family = PR_AF_INET; + netaddr.inet.port = PR_htons(TCP_SERVER_PORT); + netaddr.inet.ip = PR_htonl(PR_INADDR_ANY); + /* + * try a few times to bind server's address, if addresses are in + * use + */ + i = 0; + while (PR_Bind(sockfd, &netaddr) < 0) { + if (PR_GetError() == PR_ADDRESS_IN_USE_ERROR) { + netaddr.inet.port += 2; + if (i++ < SERVER_MAX_BIND_COUNT) { + continue; + } + } + fprintf(stderr,"ERROR - PR_Bind failed: (%d,%d)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + goto def_exit; + } + + if (PR_GetSockName(sockfd, &netaddr) < 0) { + fprintf(stderr,"ERROR - PR_GetSockName failed: (%d,%d)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + goto def_exit; + } #ifdef AIX - /* - * On AIX, set to unused/reserved port - */ - netaddr.inet.port = PR_htons(TCP_UNUSED_PORT); + /* + * On AIX, set to unused/reserved port + */ + netaddr.inet.port = PR_htons(TCP_UNUSED_PORT); #endif - if ((conn_fd = PR_NewTCPSocket()) == NULL) { - fprintf(stderr,"Error - PR_NewTCPSocket failed\n"); - failed_already=1; - goto def_exit; - } - optData.option = PR_SockOpt_Nonblocking; - optData.value.non_blocking = PR_TRUE; - PR_SetSocketOption(conn_fd, &optData); - rv = PR_Connect(conn_fd, &netaddr, PR_INTERVAL_NO_TIMEOUT); - if (rv == PR_FAILURE) { - DPRINTF(("PR_Connect to a non-listen port failed: (%d, %d)\n", - PR_GetError(), PR_GetOSError())); - } else { - PR_ASSERT(rv == PR_SUCCESS); - fprintf(stderr,"Error - PR_Connect succeeded, expected to fail\n"); - failed_already=1; - goto def_exit; - } - pd.fd = conn_fd; - pd.in_flags = PR_POLL_WRITE | PR_POLL_EXCEPT; - n = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT); - if (n == -1) { - fprintf(stderr,"Error - PR_Poll failed: (%d, %d)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - goto def_exit; - } - if (PR_GetConnectStatus(&pd) == PR_SUCCESS) { - PRInt32 rv; - fprintf(stderr,"PR_GetConnectStatus succeeded, expected to fail\n"); - failed_already = 1; - goto def_exit; - } - rv = PR_GetError(); - DPRINTF(("Connection failed, successfully with PR_Error %d\n",rv)); + if ((conn_fd = PR_NewTCPSocket()) == NULL) { + fprintf(stderr,"Error - PR_NewTCPSocket failed\n"); + failed_already=1; + goto def_exit; + } + optData.option = PR_SockOpt_Nonblocking; + optData.value.non_blocking = PR_TRUE; + PR_SetSocketOption(conn_fd, &optData); + rv = PR_Connect(conn_fd, &netaddr, PR_INTERVAL_NO_TIMEOUT); + if (rv == PR_FAILURE) { + DPRINTF(("PR_Connect to a non-listen port failed: (%d, %d)\n", + PR_GetError(), PR_GetOSError())); + } else { + PR_ASSERT(rv == PR_SUCCESS); + fprintf(stderr,"Error - PR_Connect succeeded, expected to fail\n"); + failed_already=1; + goto def_exit; + } + pd.fd = conn_fd; + pd.in_flags = PR_POLL_WRITE | PR_POLL_EXCEPT; + n = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT); + if (n == -1) { + fprintf(stderr,"Error - PR_Poll failed: (%d, %d)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + goto def_exit; + } + if (PR_GetConnectStatus(&pd) == PR_SUCCESS) { + PRInt32 rv; + fprintf(stderr,"PR_GetConnectStatus succeeded, expected to fail\n"); + failed_already = 1; + goto def_exit; + } + rv = PR_GetError(); + DPRINTF(("Connection failed, successfully with PR_Error %d\n",rv)); def_exit: - if (sockfd) { - PR_Close(sockfd); - sockfd = NULL; - } - if (conn_fd) { - PR_Close(conn_fd); - conn_fd = NULL; - } - if (failed_already) - return 1; - else - return 0; + if (sockfd) { + PR_Close(sockfd); + sockfd = NULL; + } + if (conn_fd) { + PR_Close(conn_fd); + conn_fd = NULL; + } + if (failed_already) { + return 1; + } + else { + return 0; + } } diff --git a/nsprpub/pr/tests/nblayer.c b/nsprpub/pr/tests/nblayer.c index 0d9aec421..c9e6bf245 100644 --- a/nsprpub/pr/tests/nblayer.c +++ b/nsprpub/pr/tests/nblayer.c @@ -62,16 +62,18 @@ static PRFileDesc *PushLayer(PRFileDesc *stack) layer->secret = PR_NEWZAP(PRFilePrivate); rv = PR_PushIOLayer(stack, PR_GetLayersIdentity(stack), layer); PR_ASSERT(PR_SUCCESS == rv); - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(logFile, "Pushed layer(0x%x) onto stack(0x%x)\n", layer, stack); + } return stack; } /* PushLayer */ static PRFileDesc *PopLayer(PRFileDesc *stack) { PRFileDesc *popped = PR_PopIOLayer(stack, identity); - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(logFile, "Popped layer(0x%x) from stack(0x%x)\n", popped, stack); + } PR_DELETE(popped->secret); popped->dtor(popped); return stack; @@ -94,8 +96,9 @@ static void PR_CALLBACK Client(void *arg) rv = PR_Connect(stack, &server_address, PR_INTERVAL_NO_TIMEOUT); if ((PR_FAILURE == rv) && (PR_IN_PROGRESS_ERROR == PR_GetError())) { - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(logFile, "Client connect 'in progress'\n"); + } do { polldesc.fd = stack; @@ -103,26 +106,33 @@ static void PR_CALLBACK Client(void *arg) polldesc.in_flags = PR_POLL_WRITE | PR_POLL_EXCEPT; ready = PR_Poll(&polldesc, 1, PR_INTERVAL_NO_TIMEOUT); if ((1 != ready) /* if not 1, then we're dead */ - || (0 == (polldesc.in_flags & polldesc.out_flags))) - { PR_NOT_REACHED("Whoa!"); break; } + || (0 == (polldesc.in_flags & polldesc.out_flags))) + { + PR_NOT_REACHED("Whoa!"); + break; + } if (verbosity > quiet) PR_fprintf( logFile, "Client connect 'in progress' [0x%x]\n", polldesc.out_flags); rv = PR_GetConnectStatus(&polldesc); if ((PR_FAILURE == rv) - && (PR_IN_PROGRESS_ERROR != PR_GetError())) break; + && (PR_IN_PROGRESS_ERROR != PR_GetError())) { + break; + } } while (PR_FAILURE == rv); } PR_ASSERT(PR_SUCCESS == rv); - if (verbosity > chatty) + if (verbosity > chatty) { PR_fprintf(logFile, "Client created connection\n"); + } for (mits = 0; mits < minor_iterations; ++mits) { bytes_sent = 0; - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(logFile, "Client sending %d bytes\n", sizeof(buffer)); + } do { if (verbosity > chatty) @@ -130,11 +140,14 @@ static void PR_CALLBACK Client(void *arg) logFile, "Client sending %d bytes\n", sizeof(buffer) - bytes_sent); ready = PR_Send( - stack, buffer + bytes_sent, sizeof(buffer) - bytes_sent, - empty_flags, PR_INTERVAL_NO_TIMEOUT); - if (verbosity > chatty) + stack, buffer + bytes_sent, sizeof(buffer) - bytes_sent, + empty_flags, PR_INTERVAL_NO_TIMEOUT); + if (verbosity > chatty) { PR_fprintf(logFile, "Client send status [%d]\n", ready); - if (0 < ready) bytes_sent += ready; + } + if (0 < ready) { + bytes_sent += ready; + } else if ((-1 == ready) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) { polldesc.fd = stack; @@ -142,10 +155,15 @@ static void PR_CALLBACK Client(void *arg) polldesc.in_flags = PR_POLL_WRITE; ready = PR_Poll(&polldesc, 1, PR_INTERVAL_NO_TIMEOUT); if ((1 != ready) /* if not 1, then we're dead */ - || (0 == (polldesc.in_flags & polldesc.out_flags))) - { PR_NOT_REACHED("Whoa!"); break; } + || (0 == (polldesc.in_flags & polldesc.out_flags))) + { + PR_NOT_REACHED("Whoa!"); + break; + } + } + else { + break; } - else break; } while (bytes_sent < sizeof(buffer)); PR_ASSERT(sizeof(buffer) == bytes_sent); @@ -157,12 +175,14 @@ static void PR_CALLBACK Client(void *arg) logFile, "Client receiving %d bytes\n", bytes_sent - bytes_read); ready = PR_Recv( - stack, buffer + bytes_read, bytes_sent - bytes_read, - empty_flags, PR_INTERVAL_NO_TIMEOUT); + stack, buffer + bytes_read, bytes_sent - bytes_read, + empty_flags, PR_INTERVAL_NO_TIMEOUT); if (verbosity > chatty) PR_fprintf( logFile, "Client receive status [%d]\n", ready); - if (0 < ready) bytes_read += ready; + if (0 < ready) { + bytes_read += ready; + } else if ((-1 == ready) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) { polldesc.fd = stack; @@ -170,19 +190,26 @@ static void PR_CALLBACK Client(void *arg) polldesc.in_flags = PR_POLL_READ; ready = PR_Poll(&polldesc, 1, PR_INTERVAL_NO_TIMEOUT); if ((1 != ready) /* if not 1, then we're dead */ - || (0 == (polldesc.in_flags & polldesc.out_flags))) - { PR_NOT_REACHED("Whoa!"); break; } + || (0 == (polldesc.in_flags & polldesc.out_flags))) + { + PR_NOT_REACHED("Whoa!"); + break; + } + } + else { + break; } - else break; } while (bytes_read < bytes_sent); - if (verbosity > chatty) + if (verbosity > chatty) { PR_fprintf(logFile, "Client received %d bytes\n", bytes_read); + } PR_ASSERT(bytes_read == bytes_sent); } - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(logFile, "Client shutting down stack\n"); - + } + rv = PR_Shutdown(stack, PR_SHUTDOWN_BOTH); PR_ASSERT(PR_SUCCESS == rv); } /* Client */ @@ -200,11 +227,13 @@ static void PR_CALLBACK Server(void *arg) do { - if (verbosity > chatty) + if (verbosity > chatty) { PR_fprintf(logFile, "Server accepting connection\n"); + } service = PR_Accept(stack, &client_address, PR_INTERVAL_NO_TIMEOUT); - if (verbosity > chatty) + if (verbosity > chatty) { PR_fprintf(logFile, "Server accept status [0x%p]\n", service); + } if ((NULL == service) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) { polldesc.fd = stack; @@ -212,14 +241,18 @@ static void PR_CALLBACK Server(void *arg) polldesc.in_flags = PR_POLL_READ | PR_POLL_EXCEPT; ready = PR_Poll(&polldesc, 1, PR_INTERVAL_NO_TIMEOUT); if ((1 != ready) /* if not 1, then we're dead */ - || (0 == (polldesc.in_flags & polldesc.out_flags))) - { PR_NOT_REACHED("Whoa!"); break; } + || (0 == (polldesc.in_flags & polldesc.out_flags))) + { + PR_NOT_REACHED("Whoa!"); + break; + } } } while (NULL == service); PR_ASSERT(NULL != service); - - if (verbosity > quiet) + + if (verbosity > quiet) { PR_fprintf(logFile, "Server accepting connection\n"); + } do { @@ -231,11 +264,14 @@ static void PR_CALLBACK Server(void *arg) logFile, "Server receiving %d bytes\n", sizeof(buffer) - bytes_read); ready = PR_Recv( - service, buffer + bytes_read, sizeof(buffer) - bytes_read, - empty_flags, PR_INTERVAL_NO_TIMEOUT); - if (verbosity > chatty) + service, buffer + bytes_read, sizeof(buffer) - bytes_read, + empty_flags, PR_INTERVAL_NO_TIMEOUT); + if (verbosity > chatty) { PR_fprintf(logFile, "Server receive status [%d]\n", ready); - if (0 < ready) bytes_read += ready; + } + if (0 < ready) { + bytes_read += ready; + } else if ((-1 == ready) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) { polldesc.fd = service; @@ -243,24 +279,30 @@ static void PR_CALLBACK Server(void *arg) polldesc.in_flags = PR_POLL_READ; ready = PR_Poll(&polldesc, 1, PR_INTERVAL_NO_TIMEOUT); if ((1 != ready) /* if not 1, then we're dead */ - || (0 == (polldesc.in_flags & polldesc.out_flags))) - { PR_NOT_REACHED("Whoa!"); break; } + || (0 == (polldesc.in_flags & polldesc.out_flags))) + { + PR_NOT_REACHED("Whoa!"); + break; + } + } + else { + break; } - else break; } while (bytes_read < sizeof(buffer)); if (0 != bytes_read) { - if (verbosity > chatty) + if (verbosity > chatty) { PR_fprintf(logFile, "Server received %d bytes\n", bytes_read); + } PR_ASSERT(bytes_read > 0); bytes_sent = 0; do { ready = PR_Send( - service, buffer + bytes_sent, bytes_read - bytes_sent, - empty_flags, PR_INTERVAL_NO_TIMEOUT); + service, buffer + bytes_sent, bytes_read - bytes_sent, + empty_flags, PR_INTERVAL_NO_TIMEOUT); if (0 < ready) { bytes_sent += ready; @@ -272,19 +314,26 @@ static void PR_CALLBACK Server(void *arg) polldesc.in_flags = PR_POLL_WRITE; ready = PR_Poll(&polldesc, 1, PR_INTERVAL_NO_TIMEOUT); if ((1 != ready) /* if not 1, then we're dead */ - || (0 == (polldesc.in_flags & polldesc.out_flags))) - { PR_NOT_REACHED("Whoa!"); break; } + || (0 == (polldesc.in_flags & polldesc.out_flags))) + { + PR_NOT_REACHED("Whoa!"); + break; + } + } + else { + break; } - else break; } while (bytes_sent < bytes_read); PR_ASSERT(bytes_read == bytes_sent); - if (verbosity > chatty) + if (verbosity > chatty) { PR_fprintf(logFile, "Server sent %d bytes\n", bytes_sent); + } } } while (0 != bytes_read); - if (verbosity > quiet) + if (verbosity > quiet) { PR_fprintf(logFile, "Server shutting down stack\n"); + } rv = PR_Shutdown(service, PR_SHUTDOWN_BOTH); PR_ASSERT(PR_SUCCESS == rv); rv = PR_Close(service); PR_ASSERT(PR_SUCCESS == rv); @@ -329,7 +378,9 @@ static PRInt16 PR_CALLBACK MyPoll( default: break; } } - else PR_NOT_REACHED("How'd I get here?"); + else { + PR_NOT_REACHED("How'd I get here?"); + } new_flags = (fd->lower->methods->poll)(fd->lower, my_flags, out_flags); if (verbosity > chatty) PR_fprintf( @@ -393,42 +444,58 @@ static PRInt32 PR_CALLBACK MyRecv( { switch (mine->rcvstate) { - case rcv_get_debit: - b = (char*)&mine->rcvreq; - mine->rcvreq = amount; - rv = lo->methods->recv( - lo, b + mine->rcvinprogress, - sizeof(mine->rcvreq) - mine->rcvinprogress, flags, timeout); - if (0 == rv) goto closed; - if ((-1 == rv) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) break; - mine->rcvinprogress += rv; /* accumulate the read */ - if (mine->rcvinprogress < sizeof(mine->rcvreq)) break; /* loop */ - mine->rcvstate = rcv_send_credit; - mine->rcvinprogress = 0; - case rcv_send_credit: - b = (char*)&mine->rcvreq; - rv = lo->methods->send( - lo, b + mine->rcvinprogress, - sizeof(mine->rcvreq) - mine->rcvinprogress, flags, timeout); - if ((-1 == rv) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) break; - mine->rcvinprogress += rv; /* accumulate the read */ - if (mine->rcvinprogress < sizeof(mine->rcvreq)) break; /* loop */ - mine->rcvstate = rcv_data; - mine->rcvinprogress = 0; - case rcv_data: - b = (char*)buf; - rv = lo->methods->recv( - lo, b + mine->rcvinprogress, - mine->rcvreq - mine->rcvinprogress, flags, timeout); - if (0 == rv) goto closed; - if ((-1 == rv) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) break; - mine->rcvinprogress += rv; /* accumulate the read */ - if (mine->rcvinprogress < amount) break; /* loop */ - mine->rcvstate = rcv_get_debit; - mine->rcvinprogress = 0; - return mine->rcvreq; /* << -- that's it! */ - default: - break; + case rcv_get_debit: + b = (char*)&mine->rcvreq; + mine->rcvreq = amount; + rv = lo->methods->recv( + lo, b + mine->rcvinprogress, + sizeof(mine->rcvreq) - mine->rcvinprogress, flags, timeout); + if (0 == rv) { + goto closed; + } + if ((-1 == rv) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) { + break; + } + mine->rcvinprogress += rv; /* accumulate the read */ + if (mine->rcvinprogress < sizeof(mine->rcvreq)) { + break; /* loop */ + } + mine->rcvstate = rcv_send_credit; + mine->rcvinprogress = 0; + case rcv_send_credit: + b = (char*)&mine->rcvreq; + rv = lo->methods->send( + lo, b + mine->rcvinprogress, + sizeof(mine->rcvreq) - mine->rcvinprogress, flags, timeout); + if ((-1 == rv) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) { + break; + } + mine->rcvinprogress += rv; /* accumulate the read */ + if (mine->rcvinprogress < sizeof(mine->rcvreq)) { + break; /* loop */ + } + mine->rcvstate = rcv_data; + mine->rcvinprogress = 0; + case rcv_data: + b = (char*)buf; + rv = lo->methods->recv( + lo, b + mine->rcvinprogress, + mine->rcvreq - mine->rcvinprogress, flags, timeout); + if (0 == rv) { + goto closed; + } + if ((-1 == rv) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) { + break; + } + mine->rcvinprogress += rv; /* accumulate the read */ + if (mine->rcvinprogress < amount) { + break; /* loop */ + } + mine->rcvstate = rcv_get_debit; + mine->rcvinprogress = 0; + return mine->rcvreq; /* << -- that's it! */ + default: + break; } } while (-1 != rv); return rv; @@ -451,40 +518,52 @@ static PRInt32 PR_CALLBACK MySend( { switch (mine->xmtstate) { - case xmt_send_debit: - b = (char*)&mine->xmtreq; - mine->xmtreq = amount; - rv = lo->methods->send( - lo, b - mine->xmtinprogress, - sizeof(mine->xmtreq) - mine->xmtinprogress, flags, timeout); - if ((-1 == rv) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) break; - mine->xmtinprogress += rv; - if (mine->xmtinprogress < sizeof(mine->xmtreq)) break; - mine->xmtstate = xmt_recv_credit; - mine->xmtinprogress = 0; - case xmt_recv_credit: - b = (char*)&mine->xmtreq; - rv = lo->methods->recv( - lo, b + mine->xmtinprogress, - sizeof(mine->xmtreq) - mine->xmtinprogress, flags, timeout); - if ((-1 == rv) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) break; - mine->xmtinprogress += rv; - if (mine->xmtinprogress < sizeof(mine->xmtreq)) break; - mine->xmtstate = xmt_data; - mine->xmtinprogress = 0; - case xmt_data: - b = (char*)buf; - rv = lo->methods->send( - lo, b + mine->xmtinprogress, - mine->xmtreq - mine->xmtinprogress, flags, timeout); - if ((-1 == rv) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) break; - mine->xmtinprogress += rv; - if (mine->xmtinprogress < amount) break; - mine->xmtstate = xmt_send_debit; - mine->xmtinprogress = 0; - return mine->xmtreq; /* <<-- That's the one! */ - default: - break; + case xmt_send_debit: + b = (char*)&mine->xmtreq; + mine->xmtreq = amount; + rv = lo->methods->send( + lo, b - mine->xmtinprogress, + sizeof(mine->xmtreq) - mine->xmtinprogress, flags, timeout); + if ((-1 == rv) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) { + break; + } + mine->xmtinprogress += rv; + if (mine->xmtinprogress < sizeof(mine->xmtreq)) { + break; + } + mine->xmtstate = xmt_recv_credit; + mine->xmtinprogress = 0; + case xmt_recv_credit: + b = (char*)&mine->xmtreq; + rv = lo->methods->recv( + lo, b + mine->xmtinprogress, + sizeof(mine->xmtreq) - mine->xmtinprogress, flags, timeout); + if ((-1 == rv) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) { + break; + } + mine->xmtinprogress += rv; + if (mine->xmtinprogress < sizeof(mine->xmtreq)) { + break; + } + mine->xmtstate = xmt_data; + mine->xmtinprogress = 0; + case xmt_data: + b = (char*)buf; + rv = lo->methods->send( + lo, b + mine->xmtinprogress, + mine->xmtreq - mine->xmtinprogress, flags, timeout); + if ((-1 == rv) && (PR_WOULD_BLOCK_ERROR == PR_GetError())) { + break; + } + mine->xmtinprogress += rv; + if (mine->xmtinprogress < amount) { + break; + } + mine->xmtstate = xmt_send_debit; + mine->xmtinprogress = 0; + return mine->xmtreq; /* <<-- That's the one! */ + default: + break; } } while (-1 != rv); return rv; @@ -493,8 +572,12 @@ static PRInt32 PR_CALLBACK MySend( static Verbosity ChangeVerbosity(Verbosity verbosity, PRIntn delta) { PRIntn verbage = (PRIntn)verbosity + delta; - if (verbage < (PRIntn)silent) verbage = (PRIntn)silent; - else if (verbage > (PRIntn)noisy) verbage = (PRIntn)noisy; + if (verbage < (PRIntn)silent) { + verbage = (PRIntn)silent; + } + else if (verbage > (PRIntn)noisy) { + verbage = (PRIntn)noisy; + } return (Verbosity)verbage; } /* ChangeVerbosity */ @@ -512,34 +595,38 @@ int main(int argc, char **argv) PLOptState *opt = PL_CreateOptState(argc, argv, "dqGC:c:p:"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 0: - server_name = opt->value; - break; - case 'd': /* debug mode */ - if (verbosity < noisy) - verbosity = ChangeVerbosity(verbosity, 1); - break; - case 'q': /* debug mode */ - if (verbosity > silent) - verbosity = ChangeVerbosity(verbosity, -1); - break; - case 'G': /* use global threads */ - thread_scope = PR_GLOBAL_THREAD; - break; - case 'C': /* number of threads waiting */ - major_iterations = atoi(opt->value); - break; - case 'c': /* number of client threads */ - minor_iterations = atoi(opt->value); - break; - case 'p': /* default port */ - default_port = atoi(opt->value); - break; - default: - break; + case 0: + server_name = opt->value; + break; + case 'd': /* debug mode */ + if (verbosity < noisy) { + verbosity = ChangeVerbosity(verbosity, 1); + } + break; + case 'q': /* debug mode */ + if (verbosity > silent) { + verbosity = ChangeVerbosity(verbosity, -1); + } + break; + case 'G': /* use global threads */ + thread_scope = PR_GLOBAL_THREAD; + break; + case 'C': /* number of threads waiting */ + major_iterations = atoi(opt->value); + break; + case 'c': /* number of client threads */ + minor_iterations = atoi(opt->value); + break; + case 'p': /* default port */ + default_port = atoi(opt->value); + break; + default: + break; } } PL_DestroyOptState(opt); @@ -563,13 +650,13 @@ int main(int argc, char **argv) if (NULL == server_name) rv = PR_InitializeNetAddr( - PR_IpAddrLoopback, default_port, &server_address); + PR_IpAddrLoopback, default_port, &server_address); else { rv = PR_StringToNetAddr(server_name, &server_address); PR_ASSERT(PR_SUCCESS == rv); rv = PR_InitializeNetAddr( - PR_IpAddrNull, default_port, &server_address); + PR_IpAddrNull, default_port, &server_address); } PR_ASSERT(PR_SUCCESS == rv); @@ -582,8 +669,9 @@ int main(int argc, char **argv) while (major_iterations-- > 0) { - if (verbosity > silent) + if (verbosity > silent) { PR_fprintf(logFile, "Beginning non-layered test\n"); + } client = PR_NewTCPSocket(); PR_ASSERT(NULL != client); service = PR_NewTCPSocket(); PR_ASSERT(NULL != service); @@ -603,15 +691,15 @@ int main(int argc, char **argv) rv = PR_Listen(service, 10); PR_ASSERT(PR_SUCCESS == rv); server_thread = PR_CreateThread( - PR_USER_THREAD, Server, service, - PR_PRIORITY_HIGH, thread_scope, - PR_JOINABLE_THREAD, 16 * 1024); + PR_USER_THREAD, Server, service, + PR_PRIORITY_HIGH, thread_scope, + PR_JOINABLE_THREAD, 16 * 1024); PR_ASSERT(NULL != server_thread); client_thread = PR_CreateThread( - PR_USER_THREAD, Client, client, - PR_PRIORITY_NORMAL, thread_scope, - PR_JOINABLE_THREAD, 16 * 1024); + PR_USER_THREAD, Client, client, + PR_PRIORITY_NORMAL, thread_scope, + PR_JOINABLE_THREAD, 16 * 1024); PR_ASSERT(NULL != client_thread); rv = PR_JoinThread(client_thread); @@ -621,12 +709,14 @@ int main(int argc, char **argv) rv = PR_Close(client); PR_ASSERT(PR_SUCCESS == rv); rv = PR_Close(service); PR_ASSERT(PR_SUCCESS == rv); - if (verbosity > silent) + if (verbosity > silent) { PR_fprintf(logFile, "Ending non-layered test\n"); + } /* with layering */ - if (verbosity > silent) + if (verbosity > silent) { PR_fprintf(logFile, "Beginning layered test\n"); + } client = PR_NewTCPSocket(); PR_ASSERT(NULL != client); service = PR_NewTCPSocket(); PR_ASSERT(NULL != service); @@ -648,15 +738,15 @@ int main(int argc, char **argv) rv = PR_Listen(service, 10); PR_ASSERT(PR_SUCCESS == rv); server_thread = PR_CreateThread( - PR_USER_THREAD, Server, service, - PR_PRIORITY_HIGH, thread_scope, - PR_JOINABLE_THREAD, 16 * 1024); + PR_USER_THREAD, Server, service, + PR_PRIORITY_HIGH, thread_scope, + PR_JOINABLE_THREAD, 16 * 1024); PR_ASSERT(NULL != server_thread); client_thread = PR_CreateThread( - PR_USER_THREAD, Client, client, - PR_PRIORITY_NORMAL, thread_scope, - PR_JOINABLE_THREAD, 16 * 1024); + PR_USER_THREAD, Client, client, + PR_PRIORITY_NORMAL, thread_scope, + PR_JOINABLE_THREAD, 16 * 1024); PR_ASSERT(NULL != client_thread); rv = PR_JoinThread(client_thread); @@ -666,8 +756,9 @@ int main(int argc, char **argv) rv = PR_Close(PopLayer(client)); PR_ASSERT(PR_SUCCESS == rv); rv = PR_Close(PopLayer(service)); PR_ASSERT(PR_SUCCESS == rv); - if (verbosity > silent) + if (verbosity > silent) { PR_fprintf(logFile, "Ending layered test\n"); + } } return 0; } /* main */ diff --git a/nsprpub/pr/tests/nonblock.c b/nsprpub/pr/tests/nonblock.c index e94b1b44d..f24ffb02d 100644 --- a/nsprpub/pr/tests/nonblock.c +++ b/nsprpub/pr/tests/nonblock.c @@ -23,8 +23,6 @@ ** Make win16 unit_time interval 300 milliseconds, others get 100 */ #define UNIT_TIME 200 /* unit time in milliseconds */ -#elif defined(SYMBIAN) -#define UNIT_TIME 5000 /* unit time in milliseconds */ #else #define UNIT_TIME 100 /* unit time in milliseconds */ #endif @@ -66,13 +64,13 @@ clientThreadFunc(void *arg) retVal = PR_Connect(sock, &addr, PR_INTERVAL_NO_TIMEOUT); if (retVal == PR_FAILURE && PR_GetError() == PR_IN_PROGRESS_ERROR) { #if !defined(USE_PR_SELECT) - PRPollDesc pd; - PRInt32 n; - fprintf(stderr, "connect: EWOULDBLOCK, good\n"); - pd.fd = sock; - pd.in_flags = PR_POLL_WRITE; - n = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT); - PR_ASSERT(n == 1); + PRPollDesc pd; + PRInt32 n; + fprintf(stderr, "connect: EWOULDBLOCK, good\n"); + pd.fd = sock; + pd.in_flags = PR_POLL_WRITE; + n = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT); + PR_ASSERT(n == 1); PR_ASSERT(pd.out_flags == PR_POLL_WRITE); #else PR_fd_set writeSet; @@ -91,17 +89,17 @@ clientThreadFunc(void *arg) /* time 4, 7, 11, etc. */ for (i = 0; i < NUMBER_ROUNDS; i++) { PR_Sleep(3 * unitTime); - nBytes = PR_Write(sock, buf, sizeof(buf)); - if (nBytes == -1) { - if (PR_GetError() == PR_WOULD_BLOCK_ERROR) { - fprintf(stderr, "write: EWOULDBLOCK\n"); - exit(1); + nBytes = PR_Write(sock, buf, sizeof(buf)); + if (nBytes == -1) { + if (PR_GetError() == PR_WOULD_BLOCK_ERROR) { + fprintf(stderr, "write: EWOULDBLOCK\n"); + exit(1); } else { - fprintf(stderr, "write: failed\n"); + fprintf(stderr, "write: failed\n"); } - } - printf("client sent %d bytes\n", nBytes); - fflush(stdout); + } + printf("client sent %d bytes\n", nBytes); + fflush(stdout); } PR_Close(sock); @@ -121,38 +119,38 @@ static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) /* Create a listening socket */ if ((listenSock = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - exit(1); + fprintf(stderr, "Can't create a new TCP socket\n"); + exit(1); } addr.inet.family = PR_AF_INET; addr.inet.ip = PR_htonl(PR_INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - exit(1); + fprintf(stderr, "Can't bind socket\n"); + exit(1); } if (PR_GetSockName(listenSock, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - exit(1); + fprintf(stderr, "PR_GetSockName failed\n"); + exit(1); } listenPort = PR_ntohs(addr.inet.port); if (PR_Listen(listenSock, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - exit(1); + fprintf(stderr, "Can't listen on a socket\n"); + exit(1); } PR_snprintf(buf, sizeof(buf), - "The server thread is listening on port %hu\n\n", - listenPort); + "The server thread is listening on port %hu\n\n", + listenPort); printf("%s", buf); clientThread = PR_CreateThread(PR_USER_THREAD, - clientThreadFunc, (void *) listenPort, - PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, 0); + clientThreadFunc, (void *) listenPort, + PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, 0); if (clientThread == NULL) { - fprintf(stderr, "can't create thread\n"); - exit(1); + fprintf(stderr, "can't create thread\n"); + exit(1); } printf("client thread created.\n"); @@ -165,7 +163,7 @@ static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) if (sock != NULL || PR_GetError() != PR_WOULD_BLOCK_ERROR) { PL_PrintError("First Accept\n"); fprintf(stderr, "First PR_Accept() xxx\n" ); - exit(1); + exit(1); } printf("accept: EWOULDBLOCK, good\n"); fflush(stdout); @@ -176,7 +174,7 @@ static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) PL_PrintError("Second Accept\n"); fprintf(stderr, "Second PR_Accept() failed: (%d, %d)\n", PR_GetError(), PR_GetOSError()); - exit(1); + exit(1); } printf("accept: succeeded, good\n"); fflush(stdout); @@ -186,26 +184,26 @@ static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) /* time 3, 5, 6, 8, etc. */ for (i = 0; i < NUMBER_ROUNDS; i++) { - PR_Sleep(unitTime); - retVal = PR_Recv(sock, buf, sizeof(buf), 0, PR_INTERVAL_NO_TIMEOUT); - if (retVal != -1 || PR_GetError() != PR_WOULD_BLOCK_ERROR) { - PL_PrintError("First Receive:\n"); - fprintf(stderr, "First PR_Recv: retVal: %ld, Error: %ld\n", - retVal, PR_GetError()); - exit(1); + PR_Sleep(unitTime); + retVal = PR_Recv(sock, buf, sizeof(buf), 0, PR_INTERVAL_NO_TIMEOUT); + if (retVal != -1 || PR_GetError() != PR_WOULD_BLOCK_ERROR) { + PL_PrintError("First Receive:\n"); + fprintf(stderr, "First PR_Recv: retVal: %ld, Error: %ld\n", + retVal, PR_GetError()); + exit(1); } - printf("read: EWOULDBLOCK, good\n"); - fflush(stdout); - PR_Sleep(2 * unitTime); - retVal = PR_Recv(sock, buf, sizeof(buf), 0, PR_INTERVAL_NO_TIMEOUT); - if (retVal != CHUNK_SIZE) { - PL_PrintError("Second Receive:\n"); - fprintf(stderr, "Second PR_Recv: retVal: %ld, Error: %ld\n", - retVal, PR_GetError()); - exit(1); + printf("read: EWOULDBLOCK, good\n"); + fflush(stdout); + PR_Sleep(2 * unitTime); + retVal = PR_Recv(sock, buf, sizeof(buf), 0, PR_INTERVAL_NO_TIMEOUT); + if (retVal != CHUNK_SIZE) { + PL_PrintError("Second Receive:\n"); + fprintf(stderr, "Second PR_Recv: retVal: %ld, Error: %ld\n", + retVal, PR_GetError()); + exit(1); } - printf("read: %d bytes, good\n", retVal); - fflush(stdout); + printf("read: %d bytes, good\n", retVal); + fflush(stdout); } PR_Close(sock); @@ -217,7 +215,7 @@ static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) int main(int argc, char **argv) { PRIntn rv; - + PR_STDIO_INIT(); rv = PR_Initialize(RealMain, argc, argv, 0); return rv; diff --git a/nsprpub/pr/tests/ntioto.c b/nsprpub/pr/tests/ntioto.c index 7af659445..5fb01e760 100644 --- a/nsprpub/pr/tests/ntioto.c +++ b/nsprpub/pr/tests/ntioto.c @@ -5,7 +5,7 @@ /* ** File: ntioto.c -** Description: +** Description: ** This test, ntioto.c, was designed to reproduce a bug reported by NES ** on WindowsNT (fibers implementation). NSPR was asserting in ntio.c ** after PR_AcceptRead() had timed out. I/O performed subsequent to the @@ -16,12 +16,12 @@ ** Design: ** This test will fail with an assert in ntio.c if the problem it was ** designed to catch occurs. It returns 0 otherwise. -** +** ** The main() thread initializes and tears things down. A file is ** opened for writing; this file will be written to by AcceptThread() ** and JitterThread(). Main() creates a socket for reading, listens ** and binds the socket. -** +** ** ConnectThread() connects to the socket created by main, then polls ** the "state" variable. When state is AllDone, ConnectThread() exits. ** @@ -36,11 +36,11 @@ ** AcceptThread() and JitterThread() or may take a while. The default ** iteration count, jitter, is set by DEFAULT_JITTER. This may be ** modified at the command line with the -j option. -** +** */ -#include <plgetopt.h> -#include <nspr.h> +#include <plgetopt.h> +#include <nspr.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -97,28 +97,37 @@ static void AcceptThread(void *arg) PRFileDesc *arSock; PRNetAddr *arAddr; - bytesRead = PR_AcceptRead( listenSock, - &arSock, - &arAddr, - dataBuf, - ACCEPT_READ_DATASIZE, - PR_SecondsToInterval(1)); + 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"); + if ( debug ) { + printf("AcceptRead timed out\n"); + } } else { - if ( debug ) printf("Oops! read: %d, error: %d\n", bytesRead, PR_GetError()); + if ( debug ) { + printf("Oops! read: %d, error: %d\n", bytesRead, PR_GetError()); + } } while( state != AllDone ) { PR_Lock( ml ); - while( state != RunAcceptRead ) + while( state != RunAcceptRead ) { PR_WaitCondVar( cv, PR_INTERVAL_NO_TIMEOUT ); - if ( ++iCounter >= jitter ) + } + if ( ++iCounter >= jitter ) { state = AllDone; - else + } + else { state = RunJitter; - if ( verbose ) printf("."); + } + if ( verbose ) { + printf("."); + } PR_NotifyCondVar( cv ); PR_Unlock( ml ); PR_Write( file1, ".", 1 ); @@ -131,11 +140,15 @@ static void JitterThread(void *arg) { while( state != AllDone ) { PR_Lock( ml ); - while( state != RunJitter && state != AllDone ) + while( state != RunJitter && state != AllDone ) { PR_WaitCondVar( cv, PR_INTERVAL_NO_TIMEOUT ); - if ( state != AllDone) + } + if ( state != AllDone) { state = RunAcceptRead; - if ( verbose ) printf("+"); + } + if ( verbose ) { + printf("+"); + } PR_NotifyCondVar( cv ); PR_Unlock( ml ); PR_Write( file1, "+", 1 ); @@ -153,21 +166,24 @@ static void ConnectThread( void *arg ) PR_ASSERT(clientSock); if ( resume ) { - if ( debug ) printf("pausing 3 seconds before connect\n"); + 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)); + 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 ) + while( state != AllDone ) { PR_Sleep( PR_SecondsToInterval(1)); + } return; } /* end ConnectThread() */ @@ -191,35 +207,38 @@ int main(int argc, char **argv) PLOptStatus os; PLOptState *opt = PL_CreateOptState(argc, argv, "hdrvj:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug */ - debug = 1; - msgLevel = PR_LOG_ERROR; - break; - case 'v': /* verbose mode */ - verbose = 1; - msgLevel = PR_LOG_DEBUG; - break; - case 'j': - jitter = atoi(opt->value); - if ( jitter == 0) - jitter = JITTER_DEFAULT; - break; - case 'r': - resume = PR_TRUE; - break; - case 'h': /* help message */ - Help(); - break; - default: - break; + case 'd': /* debug */ + debug = 1; + msgLevel = PR_LOG_ERROR; + break; + case 'v': /* verbose mode */ + verbose = 1; + msgLevel = PR_LOG_DEBUG; + break; + case 'j': + jitter = atoi(opt->value); + if ( jitter == 0) { + jitter = JITTER_DEFAULT; + } + break; + case 'r': + resume = PR_TRUE; + break; + case 'h': /* help message */ + Help(); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); } lm = PR_NewLogModule("Test"); /* Initialize logging */ @@ -250,23 +269,23 @@ int main(int argc, char **argv) /* create Connect thread */ tConnect = PR_CreateThread( - PR_USER_THREAD, ConnectThread, NULL, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, - PR_JOINABLE_THREAD, 0 ); + PR_USER_THREAD, ConnectThread, NULL, + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, + PR_JOINABLE_THREAD, 0 ); PR_ASSERT( tConnect ); /* create jitter off thread */ tJitter = PR_CreateThread( - PR_USER_THREAD, JitterThread, NULL, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, - PR_JOINABLE_THREAD, 0 ); + PR_USER_THREAD, JitterThread, NULL, + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, + PR_JOINABLE_THREAD, 0 ); PR_ASSERT( tJitter ); /* create acceptread thread */ tAccept = PR_CreateThread( - PR_USER_THREAD, AcceptThread, NULL, - PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, - PR_JOINABLE_THREAD, 0 ); + PR_USER_THREAD, AcceptThread, NULL, + PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, + PR_JOINABLE_THREAD, 0 ); PR_ASSERT( tAccept ); /* wait for all threads to quit, then terminate gracefully */ @@ -280,7 +299,9 @@ int main(int argc, char **argv) PR_Delete( "xxxTestFile"); /* test return and exit */ - if (debug) printf("%s\n", (failed_already)? "FAIL" : "PASS"); + if (debug) { + printf("%s\n", (failed_already)? "FAIL" : "PASS"); + } return( (failed_already == PR_TRUE )? 1 : 0 ); } /* main() */ /* end ntioto.c */ diff --git a/nsprpub/pr/tests/ntoh.c b/nsprpub/pr/tests/ntoh.c index b4ddc81e6..980a1b498 100644 --- a/nsprpub/pr/tests/ntoh.c +++ b/nsprpub/pr/tests/ntoh.c @@ -33,17 +33,17 @@ int main(int argc, char **argv) un.s = s_h; printf("%u %u\n", - un.bytes[0], un.bytes[1]); + un.bytes[0], un.bytes[1]); un.s = PR_htons(un.s); printf("%u %u\n", - un.bytes[0], un.bytes[1]); + un.bytes[0], un.bytes[1]); if (memcmp(un.bytes, bytes_n, 2)) { fprintf(stderr, "PR_htons failed\n"); exit(1); } un.s = PR_ntohs(un.s); printf("%u %u\n", - un.bytes[0], un.bytes[1]); + un.bytes[0], un.bytes[1]); if (un.s != s_h) { fprintf(stderr, "PR_ntohs failed\n"); exit(1); @@ -51,17 +51,17 @@ int main(int argc, char **argv) un.l = l_h; printf("%u %u %u %u\n", - un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3]); + un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3]); un.l = PR_htonl(un.l); printf("%u %u %u %u\n", - un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3]); + un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3]); if (memcmp(un.bytes, bytes_n, 4)) { fprintf(stderr, "PR_htonl failed\n"); exit(1); } un.l = PR_ntohl(un.l); printf("%u %u %u %u\n", - un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3]); + un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3]); if (un.l != l_h) { fprintf(stderr, "PR_ntohl failed\n"); exit(1); @@ -69,20 +69,20 @@ int main(int argc, char **argv) un.ll = ll_h; printf("%u %u %u %u %u %u %u %u\n", - un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3], - un.bytes[4], un.bytes[5], un.bytes[6], un.bytes[7]); + un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3], + un.bytes[4], un.bytes[5], un.bytes[6], un.bytes[7]); un.ll = PR_htonll(un.ll); printf("%u %u %u %u %u %u %u %u\n", - un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3], - un.bytes[4], un.bytes[5], un.bytes[6], un.bytes[7]); + un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3], + un.bytes[4], un.bytes[5], un.bytes[6], un.bytes[7]); if (memcmp(un.bytes, bytes_n, 8)) { fprintf(stderr, "PR_htonll failed\n"); exit(1); } un.ll = PR_ntohll(un.ll); printf("%u %u %u %u %u %u %u %u\n", - un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3], - un.bytes[4], un.bytes[5], un.bytes[6], un.bytes[7]); + un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3], + un.bytes[4], un.bytes[5], un.bytes[6], un.bytes[7]); if (LL_NE(un.ll, ll_h)) { fprintf(stderr, "PR_ntohll failed\n"); exit(1); diff --git a/nsprpub/pr/tests/obsints.c b/nsprpub/pr/tests/obsints.c index e7a15d9c4..30501ad74 100644 --- a/nsprpub/pr/tests/obsints.c +++ b/nsprpub/pr/tests/obsints.c @@ -4,7 +4,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* - * Test: obsints.c + * Test: obsints.c * * Description: make sure that protypes.h defines the obsolete integer * types intn, uintn, uint, int8, uint8, int16, uint16, int32, uint32, diff --git a/nsprpub/pr/tests/op_2long.c b/nsprpub/pr/tests/op_2long.c index deecf79e9..7a6b13122 100644 --- a/nsprpub/pr/tests/op_2long.c +++ b/nsprpub/pr/tests/op_2long.c @@ -31,45 +31,45 @@ PRIntn error_code; /* * should exceed any system's maximum file name length * Note: was set at 4096. This is legal on some unix (Linux 2.1+) platforms. - * + * */ #define TOO_LONG 5000 int main(int argc, char **argv) { - char nameTooLong[TOO_LONG]; - int i; + char nameTooLong[TOO_LONG]; + int i; - /* Generate a really long pathname */ - for (i = 0; i < TOO_LONG - 1; i++) { - if (i % 10 == 0) { - nameTooLong[i] = '/'; - } else { - nameTooLong[i] = 'a'; - } - } - nameTooLong[TOO_LONG - 1] = 0; + /* Generate a really long pathname */ + for (i = 0; i < TOO_LONG - 1; i++) { + if (i % 10 == 0) { + nameTooLong[i] = '/'; + } else { + nameTooLong[i] = 'a'; + } + } + nameTooLong[TOO_LONG - 1] = 0; PR_STDIO_INIT(); - t1 = PR_Open(nameTooLong, PR_RDWR, 0666); - if (t1 == NULL) { - if (PR_GetError() == PR_NAME_TOO_LONG_ERROR) { + t1 = PR_Open(nameTooLong, PR_RDWR, 0666); + if (t1 == NULL) { + if (PR_GetError() == PR_NAME_TOO_LONG_ERROR) { PL_PrintError("error code is"); - printf ("PASS\n"); - return 0; - } - else { + printf ("PASS\n"); + return 0; + } + else { PL_PrintError("error code is"); - printf ("FAIL\n"); - return 1; - } - } - - else { - printf ("Test passed\n"); - return 0; - } - + printf ("FAIL\n"); + return 1; + } + } + else { + printf ("Test passed\n"); + return 0; + } -} + + +} diff --git a/nsprpub/pr/tests/op_excl.c b/nsprpub/pr/tests/op_excl.c index 4b46891f5..e214af125 100644 --- a/nsprpub/pr/tests/op_excl.c +++ b/nsprpub/pr/tests/op_excl.c @@ -13,8 +13,8 @@ ** 27-Oct-1999 lth. Initial version ***********************************************************************/ -#include <plgetopt.h> -#include <nspr.h> +#include <plgetopt.h> +#include <nspr.h> #include <stdio.h> #include <stdlib.h> @@ -55,23 +55,25 @@ int main(int argc, char **argv) PLOptStatus os; PLOptState *opt = PL_CreateOptState(argc, argv, "hd"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug */ - debug = 1; - msgLevel = PR_LOG_ERROR; - break; - case 'h': /* help message */ - Help(); - break; - default: - break; + case 'd': /* debug */ + debug = 1; + msgLevel = PR_LOG_ERROR; + break; + case 'h': /* help message */ + Help(); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); } lm = PR_NewLogModule("Test"); /* Initialize logging */ @@ -81,21 +83,27 @@ int main(int argc, char **argv) */ fd = PR_Open( NEW_FILENAME, PR_CREATE_FILE | PR_EXCL | PR_WRONLY, 0666 ); if ( NULL == fd ) { - if (debug) fprintf( stderr, "Open exclusive. Expected success, got failure\n"); + if (debug) { + fprintf( stderr, "Open exclusive. Expected success, got failure\n"); + } failed_already = 1; goto Finished; } written = PR_Write( fd, outBuf, OUT_SIZE ); if ( OUT_SIZE != written ) { - if (debug) fprintf( stderr, "Write after open exclusive failed\n"); + if (debug) { + fprintf( stderr, "Write after open exclusive failed\n"); + } failed_already = 1; goto Finished; } rv = PR_Close(fd); if ( PR_FAILURE == rv ) { - if (debug) fprintf( stderr, "Close after open exclusive failed\n"); + if (debug) { + fprintf( stderr, "Close after open exclusive failed\n"); + } failed_already = 1; goto Finished; } @@ -105,19 +113,25 @@ int main(int argc, char **argv) */ fd = PR_Open( NEW_FILENAME, PR_CREATE_FILE | PR_EXCL | PR_WRONLY, 0666 ); if ( NULL != fd ) { - if (debug) fprintf( stderr, "Open exclusive. Expected failure, got success\n"); + if (debug) { + fprintf( stderr, "Open exclusive. Expected failure, got success\n"); + } failed_already = 1; PR_Close(fd); } rv = PR_Delete( NEW_FILENAME ); if ( PR_FAILURE == rv ) { - if (debug) fprintf( stderr, "PR_Delete() failed\n"); + if (debug) { + fprintf( stderr, "PR_Delete() failed\n"); + } failed_already = 1; } Finished: - if (debug) printf("%s\n", (failed_already)? "FAIL" : "PASS"); + if (debug) { + printf("%s\n", (failed_already)? "FAIL" : "PASS"); + } return( (failed_already == PR_TRUE )? 1 : 0 ); } /* main() */ /* end op_excl.c */ diff --git a/nsprpub/pr/tests/op_filnf.c b/nsprpub/pr/tests/op_filnf.c index da66a7ac7..1f1e8eed8 100644 --- a/nsprpub/pr/tests/op_filnf.c +++ b/nsprpub/pr/tests/op_filnf.c @@ -8,7 +8,7 @@ ** Name: op_filnf.c ** ** Description: Test Program to verify the PR_FILE_NOT_FOUND_ERROR -** This test program also uses the TRUNCATE option +** This test program also uses the TRUNCATE option ** ** Modification History: ** 03-June-97 AGarcia- Initial version @@ -31,21 +31,21 @@ PRIntn error_code; int main(int argc, char **argv) { PR_STDIO_INIT(); - t1 = PR_Open("/usr/tmp/ttools/err03.tmp", PR_TRUNCATE | PR_RDWR, 0666); - if (t1 == NULL) { - if (PR_GetError() == PR_FILE_NOT_FOUND_ERROR) { - printf ("error code is %d \n", PR_GetError()); - printf ("PASS\n"); - return 0; - } - else { - printf ("error code is %d \n", PR_GetError()); - printf ("FAIL\n"); - return 1; - } - } - PR_Close(t1); - printf ("opened a file that should not exist\n"); - printf ("FAIL\n"); - return 1; -} + t1 = PR_Open("/usr/tmp/ttools/err03.tmp", PR_TRUNCATE | PR_RDWR, 0666); + if (t1 == NULL) { + if (PR_GetError() == PR_FILE_NOT_FOUND_ERROR) { + printf ("error code is %d \n", PR_GetError()); + printf ("PASS\n"); + return 0; + } + else { + printf ("error code is %d \n", PR_GetError()); + printf ("FAIL\n"); + return 1; + } + } + PR_Close(t1); + printf ("opened a file that should not exist\n"); + printf ("FAIL\n"); + return 1; +} diff --git a/nsprpub/pr/tests/op_filok.c b/nsprpub/pr/tests/op_filok.c index 035765a86..4f8688b7f 100644 --- a/nsprpub/pr/tests/op_filok.c +++ b/nsprpub/pr/tests/op_filok.c @@ -29,20 +29,20 @@ int main(int argc, char **argv) { PR_STDIO_INIT(); - t1 = PR_Open(argv[0], PR_RDONLY, 0666); + t1 = PR_Open(argv[0], PR_RDONLY, 0666); - if (t1 == NULL) { - printf ("error code is %d \n", PR_GetError()); - printf ("File %s should be found\n", argv[0]); - return 1; - } else { - if (PR_Close(t1) == PR_SUCCESS) { - printf ("Test passed \n"); - return 0; - } else { - printf ("cannot close file\n"); - printf ("error code is %d\n", PR_GetError()); - return 1; - } - } -} + if (t1 == NULL) { + printf ("error code is %d \n", PR_GetError()); + printf ("File %s should be found\n", argv[0]); + return 1; + } else { + if (PR_Close(t1) == PR_SUCCESS) { + printf ("Test passed \n"); + return 0; + } else { + printf ("cannot close file\n"); + printf ("error code is %d\n", PR_GetError()); + return 1; + } + } +} diff --git a/nsprpub/pr/tests/op_nofil.c b/nsprpub/pr/tests/op_nofil.c index 0e51c741a..12d542017 100644 --- a/nsprpub/pr/tests/op_nofil.c +++ b/nsprpub/pr/tests/op_nofil.c @@ -34,23 +34,23 @@ static PRFileDesc *t1; int main(int argc, char **argv) { PR_STDIO_INIT(); - t1 = PR_Open(NO_SUCH_FILE, PR_RDONLY, 0666); - if (t1 == NULL) { - if (PR_GetError() == PR_FILE_NOT_FOUND_ERROR) { - printf ("error code is PR_FILE_NOT_FOUND_ERROR, as expected\n"); - printf ("PASS\n"); - return 0; - } else { - printf ("error code is %d \n", PR_GetError()); - printf ("FAIL\n"); - return 1; - } - } - printf ("File %s exists on this machine!?\n", NO_SUCH_FILE); - if (PR_Close(t1) == PR_FAILURE) { - printf ("cannot close file\n"); - printf ("error code is %d \n", PR_GetError()); - } - printf ("FAIL\n"); - return 1; -} + t1 = PR_Open(NO_SUCH_FILE, PR_RDONLY, 0666); + if (t1 == NULL) { + if (PR_GetError() == PR_FILE_NOT_FOUND_ERROR) { + printf ("error code is PR_FILE_NOT_FOUND_ERROR, as expected\n"); + printf ("PASS\n"); + return 0; + } else { + printf ("error code is %d \n", PR_GetError()); + printf ("FAIL\n"); + return 1; + } + } + printf ("File %s exists on this machine!?\n", NO_SUCH_FILE); + if (PR_Close(t1) == PR_FAILURE) { + printf ("cannot close file\n"); + printf ("error code is %d \n", PR_GetError()); + } + printf ("FAIL\n"); + return 1; +} diff --git a/nsprpub/pr/tests/openfile.c b/nsprpub/pr/tests/openfile.c index d0b664f35..265e04189 100644 --- a/nsprpub/pr/tests/openfile.c +++ b/nsprpub/pr/tests/openfile.c @@ -24,7 +24,7 @@ int main(int argc, char **argv) PRInt32 nbytes; PRFileDesc *fd; - + /* Write in text mode. Let stdio deal with line endings. */ template = fopen(TEMPLATE_FILE_NAME, "w"); fputs("line 1\nline 2\n", template); diff --git a/nsprpub/pr/tests/parent.c b/nsprpub/pr/tests/parent.c index e49af2a98..f43ce0c3f 100644 --- a/nsprpub/pr/tests/parent.c +++ b/nsprpub/pr/tests/parent.c @@ -28,7 +28,7 @@ static char *default_argv[] = {"cvar", "-c", "2000", NULL}; static void PrintUsage(void) { PR_fprintf(PR_GetSpecialFD(PR_StandardError), - "Usage: parent [-d] child [options]\n"); + "Usage: parent [-d] child [options]\n"); } int main(int argc, char **argv) @@ -49,8 +49,9 @@ int main(int argc, char **argv) argv += 1; /* don't care about our program name */ while (*argv != NULL && argv[0][0] == '-') { - if (argv[0][1] == 'd') + if (argv[0][1] == 'd') { debug = PR_GetSpecialFD(PR_StandardError); + } else { PrintUsage(); @@ -68,7 +69,9 @@ int main(int argc, char **argv) } child->name = *child->argv; - if (NULL != debug) PR_fprintf(debug, "Forking %s\n", child->name); + if (NULL != debug) { + PR_fprintf(debug, "Forking %s\n", child->name); + } child->attr = PR_NewProcessAttr(); PR_ProcessAttrSetStdioRedirect( @@ -80,7 +83,7 @@ int main(int argc, char **argv) t_start = PR_IntervalNow(); child->process = PR_CreateProcess( - child->name, child->argv, NULL, child->attr); + child->name, child->argv, NULL, child->attr); t_elapsed = (PRIntervalTime) (PR_IntervalNow() - t_start); PR_DestroyProcessAttr(child->attr); @@ -99,7 +102,9 @@ int main(int argc, char **argv) if (0 == test_status) { - if (NULL != debug) PR_fprintf(debug, "Waiting for child to exit\n"); + if (NULL != debug) { + PR_fprintf(debug, "Waiting for child to exit\n"); + } rv = PR_WaitProcess(child->process, &test_status); if (PR_SUCCESS == rv) { @@ -111,14 +116,15 @@ int main(int argc, char **argv) else { test_status = 1; - if (NULL != debug) + if (NULL != debug) { PR_fprintf(debug, "PR_WaitProcess failed\n"); + } } } PR_DELETE(child); PR_Cleanup(); return test_status; - + } /* main */ /* parent.c */ diff --git a/nsprpub/pr/tests/parsetm.c b/nsprpub/pr/tests/parsetm.c index be1fc4913..0e25ffe68 100644 --- a/nsprpub/pr/tests/parsetm.c +++ b/nsprpub/pr/tests/parsetm.c @@ -19,10 +19,11 @@ PRBool debug_mode = PR_TRUE; static char *dayOfWeek[] = - { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "???" }; +{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "???" }; static char *month[] = - { "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "???" }; +{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "???" +}; static void PrintExplodedTime(const PRExplodedTime *et) { PRInt32 totalOffset; @@ -31,27 +32,32 @@ static void PrintExplodedTime(const PRExplodedTime *et) { /* Print day of the week, month, day, hour, minute, and second */ if (debug_mode) printf("%s %s %ld %02ld:%02ld:%02ld ", - dayOfWeek[et->tm_wday], month[et->tm_month], et->tm_mday, - et->tm_hour, et->tm_min, et->tm_sec); + dayOfWeek[et->tm_wday], month[et->tm_month], et->tm_mday, + et->tm_hour, et->tm_min, et->tm_sec); /* Print time zone */ totalOffset = et->tm_params.tp_gmt_offset + et->tm_params.tp_dst_offset; if (totalOffset == 0) { - if (debug_mode) printf("UTC "); + if (debug_mode) { + printf("UTC "); + } } else { sign = "+"; if (totalOffset < 0) { - totalOffset = -totalOffset; - sign = "-"; + totalOffset = -totalOffset; + sign = "-"; } hourOffset = totalOffset / 3600; minOffset = (totalOffset % 3600) / 60; - if (debug_mode) + if (debug_mode) { printf("%s%02ld%02ld ", sign, hourOffset, minOffset); + } } /* Print year */ - if (debug_mode) printf("%hd", et->tm_year); + if (debug_mode) { + printf("%hd", et->tm_year); + } } int main(int argc, char **argv) diff --git a/nsprpub/pr/tests/peek.c b/nsprpub/pr/tests/peek.c index 5b83692f1..4dce8299d 100644 --- a/nsprpub/pr/tests/peek.c +++ b/nsprpub/pr/tests/peek.c @@ -30,9 +30,11 @@ static int iterations = 10; * send_amount[i] <= recv_amount[i]. */ static PRInt32 recv_amount[10] = { - 16, 128, 256, 1024, 512, 512, 128, 256, 32, 32}; + 16, 128, 256, 1024, 512, 512, 128, 256, 32, 32 +}; static PRInt32 send_amount[10] = { - 16, 64, 128, 1024, 512, 256, 128, 64, 16, 32}; + 16, 64, 128, 1024, 512, 256, 128, 64, 16, 32 +}; /* Blocking I/O */ static void ServerB(void *arg) @@ -53,7 +55,7 @@ static void ServerB(void *arg) for (i = 0; i < iterations; i++) { memset(buf, 0, sizeof(buf)); nbytes = PR_Recv(sock, buf, recv_amount[i], - PR_MSG_PEEK, PR_INTERVAL_NO_TIMEOUT); + PR_MSG_PEEK, PR_INTERVAL_NO_TIMEOUT); if (-1 == nbytes) { fprintf(stderr, "PR_Recv failed\n"); exit(1); @@ -73,7 +75,7 @@ static void ServerB(void *arg) memset(buf, 0, sizeof(buf)); nbytes = PR_Recv(sock, buf, recv_amount[i], - PR_MSG_PEEK, PR_INTERVAL_NO_TIMEOUT); + PR_MSG_PEEK, PR_INTERVAL_NO_TIMEOUT); if (-1 == nbytes) { fprintf(stderr, "PR_Recv failed\n"); exit(1); @@ -93,7 +95,7 @@ static void ServerB(void *arg) memset(buf, 0, sizeof(buf)); nbytes = PR_Recv(sock, buf, recv_amount[i], - 0, PR_INTERVAL_NO_TIMEOUT); + 0, PR_INTERVAL_NO_TIMEOUT); if (-1 == nbytes) { fprintf(stderr, "PR_Recv failed\n"); exit(1); @@ -114,7 +116,7 @@ static void ServerB(void *arg) PR_Sleep(PR_SecondsToInterval(1)); memset(buf, 2*i+1, send_amount[i]); nbytes = PR_Send(sock, buf, send_amount[i], - 0, PR_INTERVAL_NO_TIMEOUT); + 0, PR_INTERVAL_NO_TIMEOUT); if (-1 == nbytes) { fprintf(stderr, "PR_Send failed\n"); exit(1); @@ -157,7 +159,7 @@ static void ClientNB(void *arg) } memset(&addr, 0, sizeof(addr)); if (PR_SetNetAddr(PR_IpAddrLoopback, PR_AF_INET6, port, &addr) - == PR_FAILURE) { + == PR_FAILURE) { fprintf(stderr, "PR_SetNetAddr failed\n"); exit(1); } @@ -187,7 +189,7 @@ static void ClientNB(void *arg) PR_Sleep(PR_SecondsToInterval(1)); memset(buf, 2*i, send_amount[i]); while ((nbytes = PR_Send(sock, buf, send_amount[i], - 0, PR_INTERVAL_NO_TIMEOUT)) == -1) { + 0, PR_INTERVAL_NO_TIMEOUT)) == -1) { if (PR_GetError() != PR_WOULD_BLOCK_ERROR) { fprintf(stderr, "PR_Send failed\n"); exit(1); @@ -211,7 +213,7 @@ static void ClientNB(void *arg) memset(buf, 0, sizeof(buf)); while ((nbytes = PR_Recv(sock, buf, recv_amount[i], - PR_MSG_PEEK, PR_INTERVAL_NO_TIMEOUT)) == -1) { + PR_MSG_PEEK, PR_INTERVAL_NO_TIMEOUT)) == -1) { if (PR_GetError() != PR_WOULD_BLOCK_ERROR) { fprintf(stderr, "PR_Recv failed\n"); exit(1); @@ -243,7 +245,7 @@ static void ClientNB(void *arg) memset(buf, 0, sizeof(buf)); nbytes = PR_Recv(sock, buf, recv_amount[i], - PR_MSG_PEEK, PR_INTERVAL_NO_TIMEOUT); + PR_MSG_PEEK, PR_INTERVAL_NO_TIMEOUT); if (-1 == nbytes) { fprintf(stderr, "PR_Recv failed\n"); exit(1); @@ -263,7 +265,7 @@ static void ClientNB(void *arg) memset(buf, 0, sizeof(buf)); nbytes = PR_Recv(sock, buf, recv_amount[i], - 0, PR_INTERVAL_NO_TIMEOUT); + 0, PR_INTERVAL_NO_TIMEOUT); if (-1 == nbytes) { fprintf(stderr, "PR_Recv failed\n"); exit(1); @@ -293,14 +295,14 @@ RunTest(PRThreadScope scope, PRFileDesc *listenSock, PRUint16 port) PRThread *server, *client; server = PR_CreateThread(PR_USER_THREAD, ServerB, listenSock, - PR_PRIORITY_NORMAL, scope, PR_JOINABLE_THREAD, 0); + PR_PRIORITY_NORMAL, scope, PR_JOINABLE_THREAD, 0); if (NULL == server) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); } client = PR_CreateThread( - PR_USER_THREAD, ClientNB, (void *) port, - PR_PRIORITY_NORMAL, scope, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, ClientNB, (void *) port, + PR_PRIORITY_NORMAL, scope, PR_JOINABLE_THREAD, 0); if (NULL == client) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); diff --git a/nsprpub/pr/tests/perf.c b/nsprpub/pr/tests/perf.c index 91248eb22..cd8ac1439 100644 --- a/nsprpub/pr/tests/perf.c +++ b/nsprpub/pr/tests/perf.c @@ -32,18 +32,18 @@ static void LocalProcedureCall(void) PRInt32 i; for (i = 0; i < count; i++) { - nop(i, i, 5); + nop(i, i, 5); } } static void DLLProcedureCall(void) { PRInt32 i; - PRThreadState state; - PRThread *self = PR_GetCurrentThread(); + PRThreadState state; + PRThread *self = PR_GetCurrentThread(); for (i = 0; i < count; i++) { - state = PR_GetThreadState(self); + state = PR_GetThreadState(self); } } @@ -72,8 +72,8 @@ static void IdleLock(void) PRInt32 i; for (i = 0; i < count; i++) { - PR_Lock(lock); - PR_Unlock(lock); + PR_Lock(lock); + PR_Unlock(lock); } } @@ -82,8 +82,8 @@ static void IdleMonitor(void) PRInt32 i; for (i = 0; i < count; i++) { - PR_EnterMonitor(mon); - PR_ExitMonitor(mon); + PR_EnterMonitor(mon); + PR_ExitMonitor(mon); } } @@ -92,8 +92,8 @@ static void IdleCMonitor(void) PRInt32 i; for (i = 0; i < count; i++) { - PR_CEnterMonitor((void*)7); - PR_CExitMonitor((void*)7); + PR_CEnterMonitor((void*)7); + PR_CExitMonitor((void*)7); } } @@ -111,16 +111,17 @@ static void CDThread(void) /* * Cannot create too many threads */ - if (num_threads > 1000) - num_threads = 1000; + if (num_threads > 1000) { + num_threads = 1000; + } for (i = 0; i < num_threads; i++) { PRThread *t = PR_CreateThread(PR_USER_THREAD, - dull, 0, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, - 0); + dull, 0, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, + 0); if (NULL == t) { fprintf(stderr, "CDThread: cannot create thread %3d\n", i); } else { @@ -140,13 +141,13 @@ static void PR_CALLBACK CXReader(void *arg) PR_EnterMonitor(mon); n = count / 2; for (i = 0; i < n; i++) { - while (cxq == 0) { + while (cxq == 0) { DPRINTF(("CXReader: thread = 0x%lx waiting\n", - PR_GetCurrentThread())); - PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT); - } - --cxq; - PR_Notify(mon); + PR_GetCurrentThread())); + PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT); + } + --cxq; + PR_Notify(mon); } PR_ExitMonitor(mon); @@ -164,13 +165,13 @@ static void PR_CALLBACK CXWriter(void *arg) PR_EnterMonitor(mon); n = count / 2; for (i = 0; i < n; i++) { - while (cxq == 1) { + while (cxq == 1) { DPRINTF(("CXWriter: thread = 0x%lx waiting\n", - PR_GetCurrentThread())); - PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT); - } - ++cxq; - PR_Notify(mon); + PR_GetCurrentThread())); + PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT); + } + ++cxq; + PR_Notify(mon); } PR_ExitMonitor(mon); @@ -190,37 +191,37 @@ static void ContextSwitch(PRThreadScope scope1, PRThreadScope scope2) cxq = 0; t1 = PR_CreateThread(PR_USER_THREAD, - CXReader, 0, - PR_PRIORITY_NORMAL, - scope1, - PR_UNJOINABLE_THREAD, - 0); + CXReader, 0, + PR_PRIORITY_NORMAL, + scope1, + PR_UNJOINABLE_THREAD, + 0); if (NULL == t1) { fprintf(stderr, "ContextSwitch: cannot create thread\n"); } else { DPRINTF(("ContextSwitch: created %s thread = 0x%lx\n", - (scope1 == PR_GLOBAL_THREAD ? - "PR_GLOBAL_THREAD" : "PR_LOCAL_THREAD"), - t1)); + (scope1 == PR_GLOBAL_THREAD ? + "PR_GLOBAL_THREAD" : "PR_LOCAL_THREAD"), + t1)); } t2 = PR_CreateThread(PR_USER_THREAD, - CXWriter, 0, - PR_PRIORITY_NORMAL, - scope2, - PR_UNJOINABLE_THREAD, - 0); + CXWriter, 0, + PR_PRIORITY_NORMAL, + scope2, + PR_UNJOINABLE_THREAD, + 0); if (NULL == t2) { fprintf(stderr, "ContextSwitch: cannot create thread\n"); } else { DPRINTF(("ContextSwitch: created %s thread = 0x%lx\n", - (scope2 == PR_GLOBAL_THREAD ? - "PR_GLOBAL_THREAD" : "PR_LOCAL_THREAD"), - t2)); + (scope2 == PR_GLOBAL_THREAD ? + "PR_GLOBAL_THREAD" : "PR_LOCAL_THREAD"), + t2)); } /* Wait for both of the threads to exit */ while (alive) { - PR_Wait(mon2, PR_INTERVAL_NO_TIMEOUT); + PR_Wait(mon2, PR_INTERVAL_NO_TIMEOUT); } PR_ExitMonitor(mon2); } @@ -255,10 +256,10 @@ static void PR_CALLBACK SemaThread(void *argSema) n = count / 2; for (i = 0; i < n; i++) { DPRINTF(("SemaThread: thread = 0x%lx waiting on sem = 0x%lx\n", - PR_GetCurrentThread(), sem[0])); + PR_GetCurrentThread(), sem[0])); PR_WaitSem(sem[0]); DPRINTF(("SemaThread: thread = 0x%lx posting on sem = 0x%lx\n", - PR_GetCurrentThread(), sem[1])); + PR_GetCurrentThread(), sem[1])); PR_PostSem(sem[1]); } @@ -285,34 +286,34 @@ static void SemaContextSwitch(PRThreadScope scope1, PRThreadScope scope2) cxq = 0; t1 = PR_CreateThread(PR_USER_THREAD, - SemaThread, - sem_set1, - PR_PRIORITY_NORMAL, - scope1, - PR_UNJOINABLE_THREAD, - 0); + SemaThread, + sem_set1, + PR_PRIORITY_NORMAL, + scope1, + PR_UNJOINABLE_THREAD, + 0); if (NULL == t1) { fprintf(stderr, "SemaContextSwitch: cannot create thread\n"); } else { DPRINTF(("SemaContextSwitch: created %s thread = 0x%lx\n", - (scope1 == PR_GLOBAL_THREAD ? - "PR_GLOBAL_THREAD" : "PR_LOCAL_THREAD"), - t1)); + (scope1 == PR_GLOBAL_THREAD ? + "PR_GLOBAL_THREAD" : "PR_LOCAL_THREAD"), + t1)); } t2 = PR_CreateThread(PR_USER_THREAD, - SemaThread, - sem_set2, - PR_PRIORITY_NORMAL, - scope2, - PR_UNJOINABLE_THREAD, - 0); + SemaThread, + sem_set2, + PR_PRIORITY_NORMAL, + scope2, + PR_UNJOINABLE_THREAD, + 0); if (NULL == t2) { fprintf(stderr, "SemaContextSwitch: cannot create thread\n"); } else { DPRINTF(("SemaContextSwitch: created %s thread = 0x%lx\n", - (scope2 == PR_GLOBAL_THREAD ? - "PR_GLOBAL_THREAD" : "PR_LOCAL_THREAD"), - t2)); + (scope2 == PR_GLOBAL_THREAD ? + "PR_GLOBAL_THREAD" : "PR_LOCAL_THREAD"), + t2)); } /* Wait for both of the threads to exit */ @@ -363,30 +364,34 @@ static void Measure(void (*func)(void), const char *msg) int main(int argc, char **argv) { - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "dc:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "dc:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - _debug_on = 1; - break; - case 'c': /* loop count */ - count = atoi(opt->value); - break; - default: - break; + case 'd': /* debug mode */ + _debug_on = 1; + break; + case 'c': /* loop count */ + count = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + if (0 == count) { + count = DEFAULT_COUNT; + } - if (0 == count) count = DEFAULT_COUNT; - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); - PR_BlockClockInterrupts(); - PR_UnblockClockInterrupts(); + PR_BlockClockInterrupts(); + PR_UnblockClockInterrupts(); PR_STDIO_INIT(); lock = PR_NewLock(); diff --git a/nsprpub/pr/tests/pipeself.c b/nsprpub/pr/tests/pipeself.c index 52e6b1349..7066c58d1 100644 --- a/nsprpub/pr/tests/pipeself.c +++ b/nsprpub/pr/tests/pipeself.c @@ -94,7 +94,7 @@ int main(int argc, char **argv) } pongThread = PR_CreateThread(PR_USER_THREAD, PongThreadFunc, NULL, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); if (pongThread == NULL) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); @@ -144,72 +144,72 @@ int main(int argc, char **argv) exit(1); } -#if defined(XP_UNIX) && !defined(SYMBIAN) - /* - * Test PR_Available for pipes - */ +#if defined(XP_UNIX) + /* + * Test PR_Available for pipes + */ status = PR_CreatePipe(&ping_in, &ping_out); if (status == PR_FAILURE) { fprintf(stderr, "PR_CreatePipe failed\n"); exit(1); } - nBytes = PR_Write(ping_out, buf, 250); - if (nBytes == -1) { - fprintf(stderr, "PR_Write failed: (%d, %d)\n", PR_GetError(), - PR_GetOSError()); - exit(1); - } - nBytes = PR_Available(ping_in); - if (nBytes < 0) { - fprintf(stderr, "PR_Available failed: (%d, %d)\n", PR_GetError(), - PR_GetOSError()); - exit(1); - } else if (nBytes != 250) { - fprintf(stderr, "PR_Available: expected 250 bytes but got %d bytes\n", - nBytes); - exit(1); - } - printf("PR_Available: expected %d, got %d bytes\n",250, nBytes); - /* read some data */ - nBytes = PR_Read(ping_in, buf, 7); - if (nBytes == -1) { - fprintf(stderr, "PR_Read failed\n"); - exit(1); - } - /* check available data */ - nBytes = PR_Available(ping_in); - if (nBytes < 0) { - fprintf(stderr, "PR_Available failed: (%d, %d)\n", PR_GetError(), - PR_GetOSError()); - exit(1); - } else if (nBytes != (250 - 7)) { - fprintf(stderr, "PR_Available: expected 243 bytes but got %d bytes\n", - nBytes); - exit(1); - } - printf("PR_Available: expected %d, got %d bytes\n",243, nBytes); - /* read all data */ - nBytes = PR_Read(ping_in, buf, sizeof(buf)); - if (nBytes == -1) { - fprintf(stderr, "PR_Read failed\n"); - exit(1); - } else if (nBytes != 243) { - fprintf(stderr, "PR_Read failed: expected %d, got %d bytes\n", - 243, nBytes); - exit(1); - } - /* check available data */ - nBytes = PR_Available(ping_in); - if (nBytes < 0) { - fprintf(stderr, "PR_Available failed: (%d, %d)\n", PR_GetError(), - PR_GetOSError()); - exit(1); - } else if (nBytes != 0) { - fprintf(stderr, "PR_Available: expected 0 bytes but got %d bytes\n", - nBytes); - exit(1); - } - printf("PR_Available: expected %d, got %d bytes\n", 0, nBytes); + nBytes = PR_Write(ping_out, buf, 250); + if (nBytes == -1) { + fprintf(stderr, "PR_Write failed: (%d, %d)\n", PR_GetError(), + PR_GetOSError()); + exit(1); + } + nBytes = PR_Available(ping_in); + if (nBytes < 0) { + fprintf(stderr, "PR_Available failed: (%d, %d)\n", PR_GetError(), + PR_GetOSError()); + exit(1); + } else if (nBytes != 250) { + fprintf(stderr, "PR_Available: expected 250 bytes but got %d bytes\n", + nBytes); + exit(1); + } + printf("PR_Available: expected %d, got %d bytes\n",250, nBytes); + /* read some data */ + nBytes = PR_Read(ping_in, buf, 7); + if (nBytes == -1) { + fprintf(stderr, "PR_Read failed\n"); + exit(1); + } + /* check available data */ + nBytes = PR_Available(ping_in); + if (nBytes < 0) { + fprintf(stderr, "PR_Available failed: (%d, %d)\n", PR_GetError(), + PR_GetOSError()); + exit(1); + } else if (nBytes != (250 - 7)) { + fprintf(stderr, "PR_Available: expected 243 bytes but got %d bytes\n", + nBytes); + exit(1); + } + printf("PR_Available: expected %d, got %d bytes\n",243, nBytes); + /* read all data */ + nBytes = PR_Read(ping_in, buf, sizeof(buf)); + if (nBytes == -1) { + fprintf(stderr, "PR_Read failed\n"); + exit(1); + } else if (nBytes != 243) { + fprintf(stderr, "PR_Read failed: expected %d, got %d bytes\n", + 243, nBytes); + exit(1); + } + /* check available data */ + nBytes = PR_Available(ping_in); + if (nBytes < 0) { + fprintf(stderr, "PR_Available failed: (%d, %d)\n", PR_GetError(), + PR_GetOSError()); + exit(1); + } else if (nBytes != 0) { + fprintf(stderr, "PR_Available: expected 0 bytes but got %d bytes\n", + nBytes); + exit(1); + } + printf("PR_Available: expected %d, got %d bytes\n", 0, nBytes); status = PR_Close(ping_in); if (status == PR_FAILURE) { diff --git a/nsprpub/pr/tests/poll_er.c b/nsprpub/pr/tests/poll_er.c index a50a75fbb..b3a751d83 100755 --- a/nsprpub/pr/tests/poll_er.c +++ b/nsprpub/pr/tests/poll_er.c @@ -12,23 +12,14 @@ ** ** Modification History: ** 19-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ -#ifdef XP_BEOS -#include <stdio.h> -int main() -{ - printf( "This test is not ported to the BeOS\n" ); - return 0; -} -#else - /*********************************************************************** ** Includes ***********************************************************************/ @@ -73,92 +64,96 @@ int main(int argc, char **argv) PRIntn npds; PRInt32 retVal; - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); if (debug_mode) { - printf("This program tests PR_Poll with sockets.\n"); - printf("error reporting is tested.\n\n"); - } + printf("This program tests PR_Poll with sockets.\n"); + printf("error reporting is tested.\n\n"); + } /* Create two listening sockets */ if ((listenSock1 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't create a new TCP socket\n"); + failed_already=1; + goto exit_now; } addr.inet.family = AF_INET; addr.inet.ip = PR_htonl(INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't bind socket\n"); + failed_already=1; + goto exit_now; } if (PR_GetSockName(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "PR_GetSockName failed\n"); + failed_already=1; + goto exit_now; } listenPort1 = PR_ntohs(addr.inet.port); if (PR_Listen(listenSock1, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't listen on a socket\n"); + failed_already=1; + goto exit_now; } if ((listenSock2 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't create a new TCP socket\n"); + failed_already=1; + goto exit_now; } addr.inet.family = AF_INET; addr.inet.ip = PR_htonl(INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't bind socket\n"); + failed_already=1; + goto exit_now; } if (PR_GetSockName(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "PR_GetSockName failed\n"); + failed_already=1; + goto exit_now; } listenPort2 = PR_ntohs(addr.inet.port); if (PR_Listen(listenSock2, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't listen on a socket\n"); + failed_already=1; + goto exit_now; } PR_snprintf(buf, sizeof(buf), - "The server thread is listening on ports %hu and %hu\n\n", - listenPort1, listenPort2); - if (debug_mode) printf("%s", buf); + "The server thread is listening on ports %hu and %hu\n\n", + listenPort1, listenPort2); + if (debug_mode) { + printf("%s", buf); + } /* Set up the poll descriptor array */ pds = pds0; @@ -172,10 +167,12 @@ int main(int argc, char **argv) /* Testing bad fd */ - if (debug_mode) printf("PR_Poll should detect a bad file descriptor\n"); + if (debug_mode) { + printf("PR_Poll should detect a bad file descriptor\n"); + } if ((badFD = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a TCP socket\n"); - goto exit_now; + fprintf(stderr, "Can't create a TCP socket\n"); + goto exit_now; } pds[2].fd = badFD; @@ -183,28 +180,31 @@ int main(int argc, char **argv) npds = 3; if (PR_CreateThread(PR_USER_THREAD, ClientThreadFunc, - badFD, PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, 0) == NULL) { + badFD, PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, 0) == NULL) { fprintf(stderr, "cannot create thread\n"); exit(1); } retVal = PR_Poll(pds, npds, PR_INTERVAL_NO_TIMEOUT); if (retVal != 1 || (unsigned short) pds[2].out_flags != PR_POLL_NVAL) { - fprintf(stderr, "Failed to detect the bad fd: " - "PR_Poll returns %d, out_flags is 0x%hx\n", - retVal, pds[2].out_flags); - failed_already=1; - goto exit_now; + fprintf(stderr, "Failed to detect the bad fd: " + "PR_Poll returns %d, out_flags is 0x%hx\n", + retVal, pds[2].out_flags); + failed_already=1; + goto exit_now; + } + if (debug_mode) { + printf("PR_Poll detected the bad fd. Test passed.\n\n"); } - if (debug_mode) printf("PR_Poll detected the bad fd. Test passed.\n\n"); PR_Cleanup(); - goto exit_now; + goto exit_now; exit_now: - if(failed_already) - return 1; - else - return 0; + if(failed_already) { + return 1; + } + else { + return 0; + } } -#endif /* XP_BEOS */ diff --git a/nsprpub/pr/tests/poll_nm.c b/nsprpub/pr/tests/poll_nm.c index 4842606f7..f356d141a 100644 --- a/nsprpub/pr/tests/poll_nm.c +++ b/nsprpub/pr/tests/poll_nm.c @@ -12,12 +12,12 @@ ** ** Modification History: ** 19-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** @@ -62,17 +62,17 @@ clientThreadFunc(void *arg) PR_snprintf(buf, sizeof(buf), "%hu", port); for (i = 0; i < NUM_ITERATIONS; i++) { - sock = PR_NewTCPSocket(); - PR_ASSERT(sock != NULL); - - sts = PR_Connect(sock, &addr, PR_INTERVAL_NO_TIMEOUT); - PR_ASSERT(sts == PR_SUCCESS); + sock = PR_NewTCPSocket(); + PR_ASSERT(sock != NULL); - n = PR_Write(sock, buf, sizeof(buf)); - PR_ASSERT(n >= 0); + sts = PR_Connect(sock, &addr, PR_INTERVAL_NO_TIMEOUT); + PR_ASSERT(sts == PR_SUCCESS); - sts = PR_Close(sock); - PR_ASSERT(sts == PR_SUCCESS); + n = PR_Write(sock, buf, sizeof(buf)); + PR_ASSERT(n >= 0); + + sts = PR_Close(sock); + PR_ASSERT(sts == PR_SUCCESS); } } @@ -89,97 +89,101 @@ int main(int argc, char **argv) PRIntn i, j; PRSocketOptionData optval; - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); if (debug_mode) { - printf("This program tests PR_Poll with sockets.\n"); - printf("Normal operation are tested.\n\n"); - } + printf("This program tests PR_Poll with sockets.\n"); + printf("Normal operation are tested.\n\n"); + } /* Create two listening sockets */ if ((listenSock1 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't create a new TCP socket\n"); + failed_already=1; + goto exit_now; } memset(&addr, 0, sizeof(addr)); addr.inet.family = PR_AF_INET; addr.inet.ip = PR_htonl(PR_INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't bind socket\n"); + failed_already=1; + goto exit_now; } if (PR_GetSockName(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "PR_GetSockName failed\n"); + failed_already=1; + goto exit_now; } listenPort1 = PR_ntohs(addr.inet.port); optval.option = PR_SockOpt_Nonblocking; optval.value.non_blocking = PR_TRUE; PR_SetSocketOption(listenSock1, &optval); if (PR_Listen(listenSock1, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't listen on a socket\n"); + failed_already=1; + goto exit_now; } if ((listenSock2 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't create a new TCP socket\n"); + failed_already=1; + goto exit_now; } addr.inet.family = PR_AF_INET; addr.inet.ip = PR_htonl(PR_INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't bind socket\n"); + failed_already=1; + goto exit_now; } if (PR_GetSockName(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "PR_GetSockName failed\n"); + failed_already=1; + goto exit_now; } listenPort2 = PR_ntohs(addr.inet.port); PR_SetSocketOption(listenSock2, &optval); if (PR_Listen(listenSock2, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't listen on a socket\n"); + failed_already=1; + goto exit_now; } PR_snprintf(buf, sizeof(buf), - "The server thread is listening on ports %hu and %hu\n\n", - listenPort1, listenPort2); - if (debug_mode) printf("%s", buf); + "The server thread is listening on ports %hu and %hu\n\n", + listenPort1, listenPort2); + if (debug_mode) { + printf("%s", buf); + } /* Set up the poll descriptor array */ pds = pds0; @@ -196,80 +200,80 @@ int main(int argc, char **argv) npds = 5; clientThread = PR_CreateThread(PR_USER_THREAD, - clientThreadFunc, (void *) listenPort1, - PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, 0); + clientThreadFunc, (void *) listenPort1, + PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, 0); if (clientThread == NULL) { - fprintf(stderr, "can't create thread\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "can't create thread\n"); + failed_already=1; + goto exit_now; } clientThread = PR_CreateThread(PR_USER_THREAD, - clientThreadFunc, (void *) listenPort2, - PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, 0); + clientThreadFunc, (void *) listenPort2, + PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, 0); if (clientThread == NULL) { - fprintf(stderr, "can't create thread\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "can't create thread\n"); + failed_already=1; + goto exit_now; } if (debug_mode) { - printf("Two client threads are created. Each of them will\n"); - printf("send data to one of the two ports the server is listening on.\n"); - printf("The data they send is the port number. Each of them send\n"); - printf("the data five times, so you should see ten lines below,\n"); - printf("interleaved in an arbitrary order.\n"); - } + printf("Two client threads are created. Each of them will\n"); + printf("send data to one of the two ports the server is listening on.\n"); + printf("The data they send is the port number. Each of them send\n"); + printf("the data five times, so you should see ten lines below,\n"); + printf("interleaved in an arbitrary order.\n"); + } /* two clients, three events per iteration: accept, read, close */ i = 0; while (i < 2 * 3 * NUM_ITERATIONS) { - PRPollDesc *tmp; - int nextIndex; - int nEvents = 0; - - retVal = PR_Poll(pds, npds, PR_INTERVAL_NO_TIMEOUT); - PR_ASSERT(retVal != 0); /* no timeout */ - if (retVal == -1) { - fprintf(stderr, "PR_Poll failed\n"); - failed_already=1; - goto exit_now; - } - - nextIndex = 2; - /* the two listening sockets */ - for (j = 0; j < 2; j++) { - other_pds[j] = pds[j]; - PR_ASSERT((pds[j].out_flags & PR_POLL_WRITE) == 0 - && (pds[j].out_flags & PR_POLL_EXCEPT) == 0); - if (pds[j].out_flags & PR_POLL_READ) { - PRFileDesc *sock; - - nEvents++; - sock = PR_Accept(pds[j].fd, NULL, PR_INTERVAL_NO_TIMEOUT); - if (sock == NULL) { - fprintf(stderr, "PR_Accept() failed\n"); - failed_already=1; - goto exit_now; - } - other_pds[nextIndex].fd = sock; - other_pds[nextIndex].in_flags = PR_POLL_READ; - nextIndex++; - } else if (pds[j].out_flags & PR_POLL_ERR) { - fprintf(stderr, "PR_Poll() indicates that an fd has error\n"); - failed_already=1; - goto exit_now; - } else if (pds[j].out_flags & PR_POLL_NVAL) { - fprintf(stderr, "PR_Poll() indicates that fd %d is invalid\n", - PR_FileDesc2NativeHandle(pds[j].fd)); - failed_already=1; - goto exit_now; - } - } - - for (j = 2; j < npds; j++) { + PRPollDesc *tmp; + int nextIndex; + int nEvents = 0; + + retVal = PR_Poll(pds, npds, PR_INTERVAL_NO_TIMEOUT); + PR_ASSERT(retVal != 0); /* no timeout */ + if (retVal == -1) { + fprintf(stderr, "PR_Poll failed\n"); + failed_already=1; + goto exit_now; + } + + nextIndex = 2; + /* the two listening sockets */ + for (j = 0; j < 2; j++) { + other_pds[j] = pds[j]; + PR_ASSERT((pds[j].out_flags & PR_POLL_WRITE) == 0 + && (pds[j].out_flags & PR_POLL_EXCEPT) == 0); + if (pds[j].out_flags & PR_POLL_READ) { + PRFileDesc *sock; + + nEvents++; + sock = PR_Accept(pds[j].fd, NULL, PR_INTERVAL_NO_TIMEOUT); + if (sock == NULL) { + fprintf(stderr, "PR_Accept() failed\n"); + failed_already=1; + goto exit_now; + } + other_pds[nextIndex].fd = sock; + other_pds[nextIndex].in_flags = PR_POLL_READ; + nextIndex++; + } else if (pds[j].out_flags & PR_POLL_ERR) { + fprintf(stderr, "PR_Poll() indicates that an fd has error\n"); + failed_already=1; + goto exit_now; + } else if (pds[j].out_flags & PR_POLL_NVAL) { + fprintf(stderr, "PR_Poll() indicates that fd %d is invalid\n", + PR_FileDesc2NativeHandle(pds[j].fd)); + failed_already=1; + goto exit_now; + } + } + + for (j = 2; j < npds; j++) { if (NULL == pds[j].fd) { /* * Keep the unused entries in the poll descriptor array @@ -280,51 +284,55 @@ int main(int argc, char **argv) continue; } - PR_ASSERT((pds[j].out_flags & PR_POLL_WRITE) == 0 - && (pds[j].out_flags & PR_POLL_EXCEPT) == 0); - if (pds[j].out_flags & PR_POLL_READ) { + PR_ASSERT((pds[j].out_flags & PR_POLL_WRITE) == 0 + && (pds[j].out_flags & PR_POLL_EXCEPT) == 0); + if (pds[j].out_flags & PR_POLL_READ) { PRInt32 nAvail; - PRInt32 nRead; + PRInt32 nRead; - nEvents++; + nEvents++; nAvail = PR_Available(pds[j].fd); - nRead = PR_Read(pds[j].fd, buf, sizeof(buf)); + nRead = PR_Read(pds[j].fd, buf, sizeof(buf)); PR_ASSERT(nAvail == nRead); - if (nRead == -1) { - fprintf(stderr, "PR_Read() failed\n"); - failed_already=1; - goto exit_now; + if (nRead == -1) { + fprintf(stderr, "PR_Read() failed\n"); + failed_already=1; + goto exit_now; } else if (nRead == 0) { PR_Close(pds[j].fd); continue; } else { /* Just to be safe */ buf[127] = '\0'; - if (debug_mode) printf("The server received \"%s\" from a client\n", buf); + if (debug_mode) { + printf("The server received \"%s\" from a client\n", buf); + } } - } else if (pds[j].out_flags & PR_POLL_ERR) { - fprintf(stderr, "PR_Poll() indicates that an fd has error\n"); - failed_already=1; - goto exit_now; - } else if (pds[j].out_flags & PR_POLL_NVAL) { - fprintf(stderr, "PR_Poll() indicates that an fd is invalid\n"); - failed_already=1; - goto exit_now; - } + } else if (pds[j].out_flags & PR_POLL_ERR) { + fprintf(stderr, "PR_Poll() indicates that an fd has error\n"); + failed_already=1; + goto exit_now; + } else if (pds[j].out_flags & PR_POLL_NVAL) { + fprintf(stderr, "PR_Poll() indicates that an fd is invalid\n"); + failed_already=1; + goto exit_now; + } other_pds[nextIndex] = pds[j]; nextIndex++; - } - - PR_ASSERT(retVal == nEvents); - /* swap */ - tmp = pds; - pds = other_pds; - other_pds = tmp; - npds = nextIndex; - i += nEvents; + } + + PR_ASSERT(retVal == nEvents); + /* swap */ + tmp = pds; + pds = other_pds; + other_pds = tmp; + npds = nextIndex; + i += nEvents; } - if (debug_mode) printf("Tests passed\n"); + if (debug_mode) { + printf("Tests passed\n"); + } exit_now: @@ -336,10 +344,12 @@ exit_now: } PR_Cleanup(); - - if(failed_already) - return 1; - else - return 0; + + if(failed_already) { + return 1; + } + else { + return 0; + } } diff --git a/nsprpub/pr/tests/poll_to.c b/nsprpub/pr/tests/poll_to.c index 40d1a2612..91291bcb1 100644 --- a/nsprpub/pr/tests/poll_to.c +++ b/nsprpub/pr/tests/poll_to.c @@ -12,12 +12,12 @@ ** ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** @@ -51,93 +51,113 @@ int main(int argc, char **argv) PRIntn npds; PRInt32 retVal; - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); if (debug_mode) { - printf("This program tests PR_Poll with sockets.\n"); - printf("Timeout is tested.\n\n"); - } + printf("This program tests PR_Poll with sockets.\n"); + printf("Timeout is tested.\n\n"); + } /* Create two listening sockets */ if ((listenSock1 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - if (!debug_mode) failed_already=1; - goto exit_now; + fprintf(stderr, "Can't create a new TCP socket\n"); + if (!debug_mode) { + failed_already=1; + } + goto exit_now; } memset(&addr, 0, sizeof(addr)); addr.inet.family = PR_AF_INET; addr.inet.ip = PR_htonl(PR_INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - if (!debug_mode) failed_already=1; - goto exit_now; + fprintf(stderr, "Can't bind socket\n"); + if (!debug_mode) { + failed_already=1; + } + goto exit_now; } if (PR_GetSockName(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - if (!debug_mode) failed_already=1; - goto exit_now; + fprintf(stderr, "PR_GetSockName failed\n"); + if (!debug_mode) { + failed_already=1; + } + goto exit_now; } listenPort1 = PR_ntohs(addr.inet.port); if (PR_Listen(listenSock1, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - if (!debug_mode) failed_already=1; - goto exit_now; + fprintf(stderr, "Can't listen on a socket\n"); + if (!debug_mode) { + failed_already=1; + } + goto exit_now; } if ((listenSock2 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - if (!debug_mode) failed_already=1; - goto exit_now; + fprintf(stderr, "Can't create a new TCP socket\n"); + if (!debug_mode) { + failed_already=1; + } + goto exit_now; } addr.inet.family = PR_AF_INET; addr.inet.ip = PR_htonl(PR_INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - if (!debug_mode) failed_already=1; - goto exit_now; + fprintf(stderr, "Can't bind socket\n"); + if (!debug_mode) { + failed_already=1; + } + goto exit_now; } if (PR_GetSockName(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - if (!debug_mode) failed_already=1; - goto exit_now; + fprintf(stderr, "PR_GetSockName failed\n"); + if (!debug_mode) { + failed_already=1; + } + goto exit_now; } listenPort2 = PR_ntohs(addr.inet.port); if (PR_Listen(listenSock2, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - if (!debug_mode) failed_already=1; - goto exit_now; + fprintf(stderr, "Can't listen on a socket\n"); + if (!debug_mode) { + failed_already=1; + } + goto exit_now; } PR_snprintf(buf, sizeof(buf), - "The server thread is listening on ports %hu and %hu\n\n", - listenPort1, listenPort2); - if (debug_mode) printf("%s", buf); + "The server thread is listening on ports %hu and %hu\n\n", + listenPort1, listenPort2); + if (debug_mode) { + printf("%s", buf); + } /* Set up the poll descriptor array */ pds = pds0; @@ -150,17 +170,23 @@ int main(int argc, char **argv) npds = 2; /* Testing timeout */ - if (debug_mode) printf("PR_Poll should time out in 5 seconds\n"); + if (debug_mode) { + printf("PR_Poll should time out in 5 seconds\n"); + } retVal = PR_Poll(pds, npds, PR_SecondsToInterval(5)); if (retVal != 0) { - PR_snprintf(buf, sizeof(buf), - "PR_Poll should time out and return 0, but it returns %ld\n", - retVal); - fprintf(stderr, "%s", buf); - if (!debug_mode) failed_already=1; - goto exit_now; + PR_snprintf(buf, sizeof(buf), + "PR_Poll should time out and return 0, but it returns %ld\n", + retVal); + fprintf(stderr, "%s", buf); + if (!debug_mode) { + failed_already=1; + } + goto exit_now; + } + if (debug_mode) { + printf("PR_Poll timed out. Test passed.\n\n"); } - if (debug_mode) printf("PR_Poll timed out. Test passed.\n\n"); exit_now: @@ -173,9 +199,11 @@ exit_now: PR_Cleanup(); - if(failed_already) - return 1; - else - return 0; + if(failed_already) { + return 1; + } + else { + return 0; + } } diff --git a/nsprpub/pr/tests/pollable.c b/nsprpub/pr/tests/pollable.c index bb87f96e6..7d0b51cac 100644 --- a/nsprpub/pr/tests/pollable.c +++ b/nsprpub/pr/tests/pollable.c @@ -81,11 +81,11 @@ static void Help(void) debug_out = PR_STDOUT; PR_fprintf( - debug_out, "Usage: pollable [-c n] [-t n] [-d] [-v] [-G] [-C n] [-D n]\n"); + debug_out, "Usage: pollable [-c n] [-t n] [-d] [-v] [-G] [-C n] [-D n]\n"); PR_fprintf( - debug_out, "-c n\tloops at thread level (default: %d)\n", DEFAULT_LOOPS); + debug_out, "-c n\tloops at thread level (default: %d)\n", DEFAULT_LOOPS); PR_fprintf( - debug_out, "-t n\tnumber of threads (default: %d)\n", DEFAULT_THREADS); + debug_out, "-t n\tnumber of threads (default: %d)\n", DEFAULT_THREADS); PR_fprintf(debug_out, "-d\tturn on debugging output (default: FALSE)\n"); PR_fprintf(debug_out, "-v\tturn on verbose output (default: FALSE)\n"); PR_fprintf(debug_out, "-G\tglobal threads only (default: FALSE)\n"); @@ -158,12 +158,12 @@ int main(int argc, char **argv) if (PR_TRUE == debug_mode) { debug_out = PR_STDOUT; - PR_fprintf(debug_out, "Test parameters\n"); + PR_fprintf(debug_out, "Test parameters\n"); PR_fprintf(debug_out, "\tThreads involved: %d\n", numThreads); PR_fprintf(debug_out, "\tIteration limit: %d\n", numIterations); PR_fprintf(debug_out, "\tConcurrency: %d\n", concurrency); PR_fprintf(debug_out, "\tThread type: %s\n", - (PR_GLOBAL_THREAD == thread_scope) ? "GLOBAL" : "LOCAL"); + (PR_GLOBAL_THREAD == thread_scope) ? "GLOBAL" : "LOCAL"); } /* @@ -181,7 +181,7 @@ int main(int argc, char **argv) selfData.event = PR_NewPollableEvent(); if (selfData.event == NULL) { PR_fprintf(PR_STDERR, "cannot create event: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); + PR_GetError(), PR_GetOSError()); exit(1); } selfData.next = &data[0]; @@ -189,7 +189,7 @@ int main(int argc, char **argv) data[i].event = PR_NewPollableEvent(); if (data[i].event == NULL) { PR_fprintf(PR_STDERR, "cannot create event: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); + PR_GetError(), PR_GetOSError()); exit(1); } data[i].index = i; @@ -200,8 +200,8 @@ int main(int argc, char **argv) } thread[i] = PR_CreateThread(PR_USER_THREAD, - ThreadRoutine, &data[i], PR_PRIORITY_NORMAL, - thread_scope, PR_JOINABLE_THREAD, 0); + ThreadRoutine, &data[i], PR_PRIORITY_NORMAL, + thread_scope, PR_JOINABLE_THREAD, 0); if (thread[i] == NULL) { PR_fprintf(PR_STDERR, "cannot create thread\n"); exit(1); @@ -232,7 +232,7 @@ int main(int argc, char **argv) if (verbosity) { PR_fprintf(debug_out, "main thread awakened\n"); } - if (PR_WaitForPollableEvent(selfData.event) == PR_FAILURE) { + if (PR_WaitForPollableEvent(selfData.event) == PR_FAILURE) { PR_fprintf(PR_STDERR, "consume event failed\n"); exit(1); } @@ -241,9 +241,9 @@ int main(int argc, char **argv) if (debug_mode) { average = PR_IntervalToMicroseconds(timeEnd - timeStart) - / (numIterations * numThreads); + / (numIterations * numThreads); PR_fprintf(debug_out, "Average switch times %d usecs for %d threads\n", - average, numThreads); + average, numThreads); } for (i = 0; i < numThreads; i++) { @@ -254,7 +254,7 @@ int main(int argc, char **argv) PR_DestroyPollableEvent(data[i].event); } PR_DELETE(block); - PR_DestroyPollableEvent(selfData.event); + PR_DestroyPollableEvent(selfData.event); PR_fprintf(PR_STDOUT, "PASSED\n"); return 0; diff --git a/nsprpub/pr/tests/prftest.c b/nsprpub/pr/tests/prftest.c index ac49460af..091c990a7 100644 --- a/nsprpub/pr/tests/prftest.c +++ b/nsprpub/pr/tests/prftest.c @@ -4,7 +4,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* - * File: prftest.c + * File: prftest.c * Description: * This is a simple test of the PR_snprintf() function defined * in prprf.c. @@ -35,17 +35,17 @@ int main(int argc, char **argv) PR_snprintf(buf, BUF_SIZE, "%hx %x %lx %llx", i16, n, i32, i64); strcpy(answer, "ffff "); for (i = PR_BYTES_PER_INT * 2; i; i--) { - strcat(answer, "f"); + strcat(answer, "f"); } strcat(answer, " ffffffff ffffffffffffffff"); if (!strcmp(buf, answer)) { - printf("PR_snprintf test 1 passed\n"); + printf("PR_snprintf test 1 passed\n"); } else { - printf("PR_snprintf test 1 failed\n"); - printf("Converted string is %s\n", buf); - printf("Should be %s\n", answer); - rv = 1; + printf("PR_snprintf test 1 failed\n"); + printf("Converted string is %s\n", buf); + printf("Should be %s\n", answer); + rv = 1; } i16 = -32; @@ -54,12 +54,12 @@ int main(int argc, char **argv) LL_I2L(i64, 333); PR_snprintf(buf, BUF_SIZE, "%d %hd %lld %ld", n, i16, i64, i32); if (!strcmp(buf, "30 -32 333 64")) { - printf("PR_snprintf test 2 passed\n"); + printf("PR_snprintf test 2 passed\n"); } else { - printf("PR_snprintf test 2 failed\n"); - printf("Converted string is %s\n", buf); - printf("Should be 30 -32 333 64\n"); - rv = 1; + printf("PR_snprintf test 2 failed\n"); + printf("Converted string is %s\n", buf); + printf("Should be 30 -32 333 64\n"); + rv = 1; } return rv; diff --git a/nsprpub/pr/tests/prftest1.c b/nsprpub/pr/tests/prftest1.c index 0e9ca49f9..5d6374a45 100644 --- a/nsprpub/pr/tests/prftest1.c +++ b/nsprpub/pr/tests/prftest1.c @@ -4,17 +4,17 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* -** File: prftest1.c +** File: prftest1.c ** Description: ** This is a simple test of the PR_snprintf() function defined ** in prprf.c. ** ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ***********************************************************************/ /*********************************************************************** ** Includes @@ -34,26 +34,28 @@ /*********************************************************************** ** PRIVATE FUNCTION: Test_Result ** DESCRIPTION: Used in conjunction with the regress tool, prints out the -** status of the test case. +** status of the test case. ** INPUTS: PASS/FAIL ** OUTPUTS: None ** RETURN: None ** SIDE EFFECTS: -** +** ** RESTRICTIONS: ** None ** MEMORY: NA ** ALGORITHM: Determine what the status is and print accordingly. -** +** ***********************************************************************/ static void Test_Result (int result) { - if (result == PASS) - printf ("PASS\n"); - else - printf ("FAIL\n"); + if (result == PASS) { + printf ("PASS\n"); + } + else { + printf ("FAIL\n"); + } } int main(int argc, char **argv) @@ -66,31 +68,33 @@ int main(int argc, char **argv) char answer[BUF_SIZE]; int i; - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); - /* main test */ + /* main test */ PR_STDIO_INIT(); - + i16 = -1; n = -1; i32 = -1; @@ -99,21 +103,26 @@ int main(int argc, char **argv) PR_snprintf(buf, BUF_SIZE, "%hx %x %lx %llx", i16, n, i32, i64); strcpy(answer, "ffff "); for (i = PR_BYTES_PER_INT * 2; i; i--) { - strcat(answer, "f"); + strcat(answer, "f"); } strcat(answer, " ffffffff ffffffffffffffff"); if (!strcmp(buf, answer)) { - if (debug_mode) printf("PR_snprintf test 1 passed\n"); - else Test_Result (PASS); + if (debug_mode) { + printf("PR_snprintf test 1 passed\n"); + } + else { + Test_Result (PASS); + } } else { - if (debug_mode) { - printf("PR_snprintf test 1 failed\n"); - printf("Converted string is %s\n", buf); - printf("Should be %s\n", answer); - } - else - Test_Result (FAIL); + if (debug_mode) { + printf("PR_snprintf test 1 failed\n"); + printf("Converted string is %s\n", buf); + printf("Should be %s\n", answer); + } + else { + Test_Result (FAIL); + } } return 0; diff --git a/nsprpub/pr/tests/prftest2.c b/nsprpub/pr/tests/prftest2.c index 6a62a2604..6376fd2ff 100644 --- a/nsprpub/pr/tests/prftest2.c +++ b/nsprpub/pr/tests/prftest2.c @@ -4,19 +4,19 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* -** File: prftest2.c +** File: prftest2.c ** Description: ** This is a simple test of the PR_snprintf() function defined ** in prprf.c. ** ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** ** Includes @@ -43,30 +43,32 @@ int main(int argc, char **argv) PRInt64 i64; char buf[BUF_SIZE]; - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - PR_STDIO_INIT(); i16 = -32; @@ -75,23 +77,27 @@ int main(int argc, char **argv) LL_I2L(i64, 333); PR_snprintf(buf, BUF_SIZE, "%d %hd %lld %ld", n, i16, i64, i32); if (!strcmp(buf, "30 -32 333 64")) { - if (debug_mode) printf("PR_snprintf test 2 passed\n"); + if (debug_mode) { + printf("PR_snprintf test 2 passed\n"); + } } else { - if (debug_mode) { - printf("PR_snprintf test 2 failed\n"); - printf("Converted string is %s\n", buf); - printf("Should be 30 -32 333 64\n"); - } - else failed_already=1; + if (debug_mode) { + printf("PR_snprintf test 2 failed\n"); + printf("Converted string is %s\n", buf); + printf("Should be 30 -32 333 64\n"); + } + else { + failed_already=1; + } } - if(failed_already) - { + if(failed_already) + { printf("FAILED\n"); - return 1; - } - else - { + return 1; + } + else + { printf("PASSED\n"); - return 0; - } + return 0; + } } diff --git a/nsprpub/pr/tests/primblok.c b/nsprpub/pr/tests/primblok.c index e036572ba..1182d3ed7 100644 --- a/nsprpub/pr/tests/primblok.c +++ b/nsprpub/pr/tests/primblok.c @@ -79,8 +79,8 @@ int main(int argc, char **argv) /* Must be a global thread */ iothread = PR_CreateThread( - PR_USER_THREAD, IOThread, NULL, PR_PRIORITY_NORMAL, - PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, IOThread, NULL, PR_PRIORITY_NORMAL, + PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); if (iothread == NULL) { fprintf(stderr, "cannot create thread\n"); exit(1); diff --git a/nsprpub/pr/tests/priotest.c b/nsprpub/pr/tests/priotest.c index 577d55333..1e2249de6 100644 --- a/nsprpub/pr/tests/priotest.c +++ b/nsprpub/pr/tests/priotest.c @@ -34,8 +34,9 @@ static PRBool debug_mode = PR_FALSE; static PRUint32 PerSecond(PRIntervalTime timein) { PRUint32 loop = 0; - while (((PRIntervalTime)(PR_IntervalNow()) - timein) < oneSecond) + while (((PRIntervalTime)(PR_IntervalNow()) - timein) < oneSecond) { loop += 1; + } return loop; } /* PerSecond */ @@ -66,9 +67,9 @@ static void PR_CALLBACK High(void *arg) static void Help(void) { PR_fprintf( - debug_out, "Usage: priotest [-d] [-c n]\n"); + debug_out, "Usage: priotest [-d] [-c n]\n"); PR_fprintf( - debug_out, "-c n\tduration of test in seconds (default: %d)\n", DEFAULT_DURATION); + debug_out, "-c n\tduration of test in seconds (default: %d)\n", DEFAULT_DURATION); PR_fprintf( debug_out, "-d\tturn on debugging output (default: FALSE)\n"); } /* Help */ @@ -84,7 +85,7 @@ static void RudimentaryTests(void) PR_SetThreadPriority(PR_GetCurrentThread(), PR_PRIORITY_URGENT); priority = PR_GetThreadPriority(PR_GetCurrentThread()); failed = ((PR_TRUE == failed) || (PR_PRIORITY_URGENT != priority)) - ? PR_TRUE : PR_FALSE; + ? PR_TRUE : PR_FALSE; if (debug_mode && (PR_PRIORITY_URGENT != priority)) { PR_fprintf(debug_out, "PR_[S/G]etThreadPriority() failed\n"); @@ -95,7 +96,7 @@ static void RudimentaryTests(void) PR_GetCurrentThread(), (PRThreadPriority)(PR_PRIORITY_FIRST - 1)); priority = PR_GetThreadPriority(PR_GetCurrentThread()); failed = ((PR_TRUE == failed) || (PR_PRIORITY_FIRST != priority)) - ? PR_TRUE : PR_FALSE; + ? PR_TRUE : PR_FALSE; if (debug_mode && (PR_PRIORITY_FIRST != priority)) { PR_fprintf(debug_out, "PR_SetThreadPriority(-1) failed\n"); @@ -105,7 +106,7 @@ static void RudimentaryTests(void) PR_GetCurrentThread(), (PRThreadPriority)(PR_PRIORITY_LAST + 1)); priority = PR_GetThreadPriority(PR_GetCurrentThread()); failed = ((PR_TRUE == failed) || (PR_PRIORITY_LAST != priority)) - ? PR_TRUE : PR_FALSE; + ? PR_TRUE : PR_FALSE; if (debug_mode && (PR_PRIORITY_LAST != priority)) { PR_fprintf(debug_out, "PR_SetThreadPriority(+1) failed\n"); @@ -128,32 +129,36 @@ int main(int argc, char **argv) PLOptStatus os; PRIntn duration = DEFAULT_DURATION; PRUint32 totalCount, highCount = 0, lowCount = 0; - PLOptState *opt = PL_CreateOptState(argc, argv, "hdc:"); + PLOptState *opt = PL_CreateOptState(argc, argv, "hdc:"); debug_out = PR_STDOUT; oneSecond = PR_SecondsToInterval(1); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = PR_TRUE; - break; - case 'c': /* test duration */ - duration = atoi(opt->value); - break; - case 'h': /* help message */ - default: - Help(); - return 2; + case 'd': /* debug mode */ + debug_mode = PR_TRUE; + break; + case 'c': /* test duration */ + duration = atoi(opt->value); + break; + case 'h': /* help message */ + default: + Help(); + return 2; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); PR_STDIO_INIT(); - if (duration == 0) duration = DEFAULT_DURATION; + if (duration == 0) { + duration = DEFAULT_DURATION; + } RudimentaryTests(); @@ -167,9 +172,9 @@ int main(int argc, char **argv) if (debug_mode) { PR_fprintf(debug_out, - "The high priority thread should get approximately three\n"); + "The high priority thread should get approximately three\n"); PR_fprintf( debug_out, - "times what the low priority thread manages. A maximum of \n"); + "times what the low priority thread manages. A maximum of \n"); PR_fprintf( debug_out, "%d cycles are available.\n\n", totalCount); } @@ -178,16 +183,19 @@ int main(int argc, char **argv) while (duration--) { PRIntn loop = 5; - while (loop--) PR_Sleep(oneSecond); - if (debug_mode) + while (loop--) { + PR_Sleep(oneSecond); + } + if (debug_mode) { PR_fprintf(debug_out, "high : low :: %d : %d\n", highCount, lowCount); + } } PR_ProcessExit((failed) ? 1 : 0); - PR_NOT_REACHED("You can't get here -- but you did!"); - return 1; /* or here */ + PR_NOT_REACHED("You can't get here -- but you did!"); + return 1; /* or here */ } /* main */ diff --git a/nsprpub/pr/tests/provider.c b/nsprpub/pr/tests/provider.c index 932241ec3..1bd15fb6f 100644 --- a/nsprpub/pr/tests/provider.c +++ b/nsprpub/pr/tests/provider.c @@ -23,7 +23,7 @@ * The debug mode will print all of the printfs associated with this test. * The regress mode will be the default mode. Since the regress tool limits * the output to a one line status:PASS or FAIL,all of the printf statements - * have been handled with an if (debug_mode) statement. + * have been handled with an if (debug_mode) statement. */ #include "prclist.h" @@ -184,7 +184,7 @@ static void _MY_Assert(const char *s, const char *file, PRIntn ln) static PRBool Aborted(PRStatus rv) { return ((PR_FAILURE == rv) && (PR_PENDING_INTERRUPT_ERROR == PR_GetError())) ? - PR_TRUE : PR_FALSE; + PR_TRUE : PR_FALSE; } static void TimeOfDayMessage(const char *msg, PRThread* me) @@ -213,8 +213,9 @@ static void PR_CALLBACK Client(void *arg) PRIntervalTime timeout = PR_MillisecondsToInterval(DEFAULT_CLIENT_TIMEOUT); - for (index = 0; index < sizeof(buffer); ++index) + for (index = 0; index < sizeof(buffer); ++index) { buffer[index] = (char)index; + } client->started = PR_IntervalNow(); @@ -230,8 +231,8 @@ static void PR_CALLBACK Client(void *arg) PRInt32 bytes, descbytes, filebytes, netbytes; (void)PR_NetAddrToString(&client->serverAddress, buffer, sizeof(buffer)); - TEST_LOG(cltsrv_log_file, TEST_LOG_INFO, - ("\tClient(0x%p): connecting to server at %s\n", me, buffer)); + TEST_LOG(cltsrv_log_file, TEST_LOG_INFO, + ("\tClient(0x%p): connecting to server at %s\n", me, buffer)); fd = PR_Socket(domain, SOCK_STREAM, protocol); TEST_ASSERT(NULL != fd); @@ -253,10 +254,12 @@ static void PR_CALLBACK Client(void *arg) cltsrv_log_file, TEST_LOG_VERBOSE, ("\tClient(0x%p): sending descriptor for %u bytes\n", me, descbytes)); bytes = PR_Send( - fd, descriptor, sizeof(*descriptor), SEND_FLAGS, timeout); + fd, descriptor, sizeof(*descriptor), SEND_FLAGS, timeout); if (sizeof(CSDescriptor_t) != bytes) { - if (Aborted(PR_FAILURE)) goto aborted; + if (Aborted(PR_FAILURE)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( @@ -271,15 +274,18 @@ static void PR_CALLBACK Client(void *arg) while (netbytes < descbytes) { filebytes = sizeof(buffer); - if ((descbytes - netbytes) < filebytes) + if ((descbytes - netbytes) < filebytes) { filebytes = descbytes - netbytes; + } TEST_LOG( cltsrv_log_file, TEST_LOG_VERBOSE, ("\tClient(0x%p): sending %d bytes\n", me, filebytes)); bytes = PR_Send(fd, buffer, filebytes, SEND_FLAGS, timeout); if (filebytes != bytes) { - if (Aborted(PR_FAILURE)) goto aborted; + if (Aborted(PR_FAILURE)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( @@ -295,8 +301,9 @@ static void PR_CALLBACK Client(void *arg) while (filebytes < descbytes) { netbytes = sizeof(buffer); - if ((descbytes - filebytes) < netbytes) + if ((descbytes - filebytes) < netbytes) { netbytes = descbytes - filebytes; + } TEST_LOG( cltsrv_log_file, TEST_LOG_VERBOSE, ("\tClient(0x%p): receiving %d bytes\n", me, netbytes)); @@ -314,26 +321,28 @@ static void PR_CALLBACK Client(void *arg) TEST_LOG( cltsrv_log_file, TEST_LOG_ERROR, ("\tClient(0x%p): receive data timeout\n", me)); - else + else TEST_LOG( cltsrv_log_file, TEST_LOG_ERROR, ("\tClient(0x%p): receive error (%d, %d)\n", - me, PR_GetError(), PR_GetOSError())); + me, PR_GetError(), PR_GetOSError())); goto retry; - } + } if (0 == bytes) { TEST_LOG( cltsrv_log_file, TEST_LOG_ERROR, ("\t\tClient(0x%p): unexpected end of stream\n", - PR_GetCurrentThread())); + PR_GetCurrentThread())); break; } filebytes += bytes; } rv = PR_Shutdown(fd, PR_SHUTDOWN_BOTH); - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } TEST_ASSERT(PR_SUCCESS == rv); retry: (void)PR_Close(fd); fd = NULL; @@ -346,14 +355,18 @@ retry: client->bytesTransferred += 2 * descbytes; rv = PR_WaitCondVar(client->stateChange, rand() % clipping); PR_Unlock(client->ml); - if (Aborted(rv)) break; + if (Aborted(rv)) { + break; + } } aborted: client->stopped = PR_IntervalNow(); PR_ClearInterrupt(); - if (NULL != fd) rv = PR_Close(fd); + if (NULL != fd) { + rv = PR_Close(fd); + } PR_Lock(client->ml); client->state = cs_exit; @@ -363,7 +376,7 @@ aborted: TEST_LOG( cltsrv_log_file, TEST_LOG_ALWAYS, ("\tClient(0x%p): stopped after %u operations and %u bytes\n", - PR_GetCurrentThread(), client->operations, client->bytesTransferred)); + PR_GetCurrentThread(), client->operations, client->bytesTransferred)); } /* Client */ @@ -381,11 +394,13 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) cltsrv_log_file, TEST_LOG_VERBOSE, ("\tProcessRequest(0x%p): receiving desciptor\n", me)); bytes = PR_Recv( - fd, descriptor, sizeof(*descriptor), RECV_FLAGS, timeout); + fd, descriptor, sizeof(*descriptor), RECV_FLAGS, timeout); if (-1 == bytes) { rv = PR_FAILURE; - if (Aborted(rv)) goto exit; + if (Aborted(rv)) { + goto exit; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( @@ -406,16 +421,18 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) TEST_ASSERT(sizeof(*descriptor) == bytes); TEST_LOG( - cltsrv_log_file, TEST_LOG_VERBOSE, + cltsrv_log_file, TEST_LOG_VERBOSE, ("\t\tProcessRequest(0x%p): read descriptor {%d, %s}\n", - me, descbytes, descriptor->filename)); + me, descbytes, descriptor->filename)); file = PR_Open( - descriptor->filename, (PR_CREATE_FILE | PR_WRONLY), 0666); + descriptor->filename, (PR_CREATE_FILE | PR_WRONLY), 0666); if (NULL == file) { rv = PR_FAILURE; - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( @@ -430,8 +447,9 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) while (filebytes < descbytes) { netbytes = sizeof(buffer); - if ((descbytes - filebytes) < netbytes) + if ((descbytes - filebytes) < netbytes) { netbytes = descbytes - filebytes; + } TEST_LOG( cltsrv_log_file, TEST_LOG_VERBOSE, ("\tProcessRequest(0x%p): receive %d bytes\n", me, netbytes)); @@ -439,7 +457,9 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) if (-1 == bytes) { rv = PR_FAILURE; - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( @@ -455,7 +475,7 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) TEST_LOG( cltsrv_log_file, TEST_LOG_WARNING, ("\t\tProcessRequest(0x%p): unexpected error (%d, %d)\n", - me, PR_GetError(), PR_GetOSError())); + me, PR_GetError(), PR_GetOSError())); goto aborted; } if(0 == bytes) @@ -477,7 +497,9 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) if (netbytes != bytes) { rv = PR_FAILURE; - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( @@ -495,7 +517,9 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) PR_Unlock(server->ml); rv = PR_Close(file); file = NULL; - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } TEST_ASSERT(PR_SUCCESS == rv); TEST_LOG( @@ -505,19 +529,21 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) if (NULL == file) { rv = PR_FAILURE; - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( cltsrv_log_file, TEST_LOG_ERROR, ("\t\tProcessRequest(0x%p): open file timeout\n", - PR_GetCurrentThread())); + PR_GetCurrentThread())); goto aborted; } TEST_LOG( cltsrv_log_file, TEST_LOG_ERROR, ("\t\tProcessRequest(0x%p): other file open error (%u, %u)\n", - me, PR_GetError(), PR_GetOSError())); + me, PR_GetError(), PR_GetOSError())); goto aborted; } TEST_ASSERT(NULL != file); @@ -526,8 +552,9 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) while (netbytes < descbytes) { filebytes = sizeof(buffer); - if ((descbytes - netbytes) < filebytes) + if ((descbytes - netbytes) < filebytes) { filebytes = descbytes - netbytes; + } TEST_LOG( cltsrv_log_file, TEST_LOG_VERBOSE, ("\tProcessRequest(0x%p): read %d bytes from file\n", me, filebytes)); @@ -535,7 +562,9 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) if (filebytes != bytes) { rv = PR_FAILURE; - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) TEST_LOG( cltsrv_log_file, TEST_LOG_ERROR, @@ -544,7 +573,7 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) TEST_LOG( cltsrv_log_file, TEST_LOG_ERROR, ("\t\tProcessRequest(0x%p): other file error (%d, %d)\n", - me, PR_GetError(), PR_GetOSError())); + me, PR_GetError(), PR_GetOSError())); goto aborted; } TEST_ASSERT(bytes > 0); @@ -557,7 +586,9 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) if (filebytes != bytes) { rv = PR_FAILURE; - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } if (PR_IO_TIMEOUT_ERROR == PR_GetError()) { TEST_LOG( @@ -567,23 +598,29 @@ static PRStatus ProcessRequest(PRFileDesc *fd, CSServer_t *server) } break; } - TEST_ASSERT(bytes > 0); + TEST_ASSERT(bytes > 0); } - + PR_Lock(server->ml); server->bytesTransferred += filebytes; PR_Unlock(server->ml); rv = PR_Shutdown(fd, PR_SHUTDOWN_BOTH); - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } rv = PR_Close(file); file = NULL; - if (Aborted(rv)) goto aborted; + if (Aborted(rv)) { + goto aborted; + } TEST_ASSERT(PR_SUCCESS == rv); aborted: PR_ClearInterrupt(); - if (NULL != file) PR_Close(file); + if (NULL != file) { + PR_Close(file); + } drv = PR_Delete(descriptor->filename); TEST_ASSERT(PR_SUCCESS == drv); exit: @@ -621,19 +658,6 @@ static void *pthread_start(void *arg) } /* pthread_start */ #endif /* defined(_PR_PTHREADS) */ -#if defined(IRIX) && !defined(_PR_PTHREADS) -#include <sys/types.h> -#include <sys/prctl.h> -static void sproc_start(void *arg, PRSize size) -{ - StartObject *so = (StartObject*)arg; - StartFn start = so->start; - void *data = so->arg; - PR_Free(so); - start(data); -} /* sproc_start */ -#endif /* defined(IRIX) && !defined(_PR_PTHREADS) */ - #if defined(WIN32) #include <process.h> /* for _beginthreadex() */ @@ -653,24 +677,24 @@ static PRStatus JoinThread(PRThread *thread) PRStatus rv; switch (thread_provider) { - case thread_nspr: - rv = PR_JoinThread(thread); - break; - case thread_pthread: + case thread_nspr: + rv = PR_JoinThread(thread); + break; + case thread_pthread: #if defined(_PR_PTHREADS) - rv = PR_SUCCESS; - break; + rv = PR_SUCCESS; + break; #endif /* defined(_PR_PTHREADS) */ - case thread_win32: + case thread_win32: #if defined(WIN32) - rv = PR_SUCCESS; - break; + rv = PR_SUCCESS; + break; #endif - default: - rv = PR_FAILURE; - break; + default: + rv = PR_FAILURE; + break; } - return rv; + return rv; } /* JoinThread */ static PRStatus NewThread( @@ -680,16 +704,16 @@ static PRStatus NewThread( switch (thread_provider) { - case thread_nspr: + case thread_nspr: { PRThread *thread = PR_CreateThread( - PR_USER_THREAD, start, arg, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, - PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, start, arg, + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, + PR_JOINABLE_THREAD, 0); rv = (NULL == thread) ? PR_FAILURE : PR_SUCCESS; } break; - case thread_pthread: + case thread_pthread: #if defined(_PR_PTHREADS) { int rv; @@ -720,41 +744,27 @@ static PRStatus NewThread( #endif /* defined(_PR_PTHREADS) */ break; - case thread_sproc: -#if defined(IRIX) && !defined(_PR_PTHREADS) - { - PRInt32 pid; - StartObject *start_object; - start_object = PR_NEW(StartObject); - PR_ASSERT(NULL != start_object); - start_object->start = start; - start_object->arg = arg; - pid = sprocsp( - sproc_start, PR_SALL, start_object, NULL, 64 * 1024); - rv = (0 < pid) ? PR_SUCCESS : PR_FAILURE; - } -#else - PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); - rv = PR_FAILURE; -#endif /* defined(IRIX) && !defined(_PR_PTHREADS) */ - break; - case thread_win32: + case thread_sproc: + PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); + rv = PR_FAILURE; + break; + case thread_win32: #if defined(WIN32) { void *th; - PRUintn id; + PRUintn id; StartObject *start_object; start_object = PR_NEW(StartObject); PR_ASSERT(NULL != start_object); start_object->start = start; start_object->arg = arg; th = (void*)_beginthreadex( - NULL, /* LPSECURITY_ATTRIBUTES - pointer to thread security attributes */ - 0U, /* DWORD - initial thread stack size, in bytes */ - windows_start, /* LPTHREAD_START_ROUTINE - pointer to thread function */ - start_object, /* LPVOID - argument for new thread */ - STACK_SIZE_PARAM_IS_A_RESERVATION, /*DWORD dwCreationFlags - creation flags */ - &id /* LPDWORD - pointer to returned thread identifier */ ); + NULL, /* LPSECURITY_ATTRIBUTES - pointer to thread security attributes */ + 0U, /* DWORD - initial thread stack size, in bytes */ + windows_start, /* LPTHREAD_START_ROUTINE - pointer to thread function */ + start_object, /* LPVOID - argument for new thread */ + STACK_SIZE_PARAM_IS_A_RESERVATION, /*DWORD dwCreationFlags - creation flags */ + &id /* LPDWORD - pointer to returned thread identifier */ ); rv = (NULL == th) ? PR_FAILURE : PR_SUCCESS; } @@ -763,9 +773,9 @@ static PRStatus NewThread( rv = PR_FAILURE; #endif break; - default: - PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); - rv = PR_FAILURE; + default: + PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); + rv = PR_FAILURE; } return rv; } /* NewThread */ @@ -777,12 +787,14 @@ static PRStatus CreateWorker(CSServer_t *server, CSPool_t *pool) worker->server = server; PR_INIT_CLIST(&worker->element); rv = NewThread( - Worker, worker, DEFAULT_SERVER_PRIORITY, PR_UNJOINABLE_THREAD); - if (PR_FAILURE == rv) PR_DELETE(worker); + Worker, worker, DEFAULT_SERVER_PRIORITY, PR_UNJOINABLE_THREAD); + if (PR_FAILURE == rv) { + PR_DELETE(worker); + } - TEST_LOG(cltsrv_log_file, TEST_LOG_STATUS, - ("\tCreateWorker(0x%p): create new worker (0x%p)\n", - PR_GetCurrentThread(), worker->thread)); + TEST_LOG(cltsrv_log_file, TEST_LOG_STATUS, + ("\tCreateWorker(0x%p): create new worker (0x%p)\n", + PR_GetCurrentThread(), worker->thread)); return rv; } /* CreateWorker */ @@ -813,17 +825,17 @@ static void PR_CALLBACK Worker(void *arg) TEST_LOG( cltsrv_log_file, TEST_LOG_VERBOSE, ("\t\tWorker(0x%p): waiting for accept slot[%d]\n", - me, pool->accepting)); + me, pool->accepting)); rv = PR_WaitCondVar(pool->acceptComplete, PR_INTERVAL_NO_TIMEOUT); if (Aborted(rv) || (cs_run != server->state)) { TEST_LOG( cltsrv_log_file, TEST_LOG_NOTICE, ("\tWorker(0x%p): has been %s\n", - me, (Aborted(rv) ? "interrupted" : "stopped"))); + me, (Aborted(rv) ? "interrupted" : "stopped"))); goto exit; } - } + } pool->accepting += 1; /* how many are really in accept */ PR_Unlock(server->ml); @@ -832,7 +844,7 @@ static void PR_CALLBACK Worker(void *arg) ("\t\tWorker(0x%p): calling accept\n", me)); fd = PR_Accept(server->listener, &from, PR_INTERVAL_NO_TIMEOUT); - PR_Lock(server->ml); + PR_Lock(server->ml); pool->accepting -= 1; PR_NotifyCondVar(pool->acceptComplete); @@ -858,13 +870,15 @@ static void PR_CALLBACK Worker(void *arg) */ PRBool another = ((pool->workers < server->workers.minimum) || - ((0 == pool->accepting) - && (pool->workers < server->workers.maximum))) ? - PR_TRUE : PR_FALSE; + ((0 == pool->accepting) + && (pool->workers < server->workers.maximum))) ? + PR_TRUE : PR_FALSE; pool->active += 1; PR_Unlock(server->ml); - if (another) (void)CreateWorker(server, pool); + if (another) { + (void)CreateWorker(server, pool); + } rv = ProcessRequest(fd, server); if (PR_SUCCESS != rv) @@ -879,7 +893,7 @@ static void PR_CALLBACK Worker(void *arg) } exit: - PR_ClearInterrupt(); + PR_ClearInterrupt(); PR_Unlock(server->ml); if (NULL != fd) @@ -990,7 +1004,7 @@ static void PR_CALLBACK Server(void *arg) TEST_LOG( cltsrv_log_file, TEST_LOG_NOTICE, ("\tServer(0x%p): waiting for %u workers to exit\n", - me, server->pool.workers)); + me, server->pool.workers)); (void)PR_WaitCondVar(server->pool.exiting, PR_INTERVAL_NO_TIMEOUT); } @@ -1001,9 +1015,11 @@ static void PR_CALLBACK Server(void *arg) TEST_LOG( cltsrv_log_file, TEST_LOG_ALWAYS, ("\tServer(0x%p): stopped after %u operations and %u bytes\n", - me, server->operations, server->bytesTransferred)); + me, server->operations, server->bytesTransferred)); - if (NULL != server->listener) PR_Close(server->listener); + if (NULL != server->listener) { + PR_Close(server->listener); + } server->stopped = PR_IntervalNow(); } /* Server */ @@ -1011,10 +1027,12 @@ static void PR_CALLBACK Server(void *arg) 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"); + if (pthread_stats) { + PT_FPrintStats(debug_out, "\nPThread Statistics\n"); + } execution -= dally; } } /* WaitForCompletion */ @@ -1052,7 +1070,7 @@ int main(int argc, char **argv) CSClient_t *client; PRStatus rv, joinStatus; CSServer_t *server = NULL; - char *thread_type; + char *thread_type; PRUintn backlog = DEFAULT_BACKLOG; PRUintn clients = DEFAULT_CLIENTS; @@ -1079,11 +1097,9 @@ int main(int argc, char **argv) PLOptState *opt = PL_CreateOptState(argc, argv, "GX6b:a:c:w:W:e:s:T:vdhp"); #if defined(WIN32) - thread_provider = thread_win32; + thread_provider = thread_win32; #elif defined(_PR_PTHREADS) - thread_provider = thread_pthread; -#elif defined(IRIX) - thread_provider = thread_sproc; + thread_provider = thread_pthread; #else thread_provider = thread_nspr; #endif @@ -1092,70 +1108,95 @@ int main(int argc, char **argv) while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'G': /* use global threads */ - thread_scope = PR_GLOBAL_THREAD; - break; - case 'X': /* use XTP as transport */ - protocol = 36; - break; - case '6': /* Use IPv6 */ - domain = PR_AF_INET6; - break; - case 'a': /* the value for accepting */ - accepting = atoi(opt->value); - break; - case 'b': /* the value for backlock */ - backlog = atoi(opt->value); - break; - case 'T': /* the thread provider */ - if ('n' == *opt->value) thread_provider = thread_nspr; - else if ('p' == *opt->value) thread_provider = thread_pthread; - else if ('w' == *opt->value) thread_provider = thread_win32; - else {Help(); return 2; } - break; - case 'c': /* number of client threads */ - clients = atoi(opt->value); - break; - case 'w': /* minimum server worker threads */ - workersMin = atoi(opt->value); - break; - case 'W': /* maximum server worker threads */ - workersMax = atoi(opt->value); - break; - case 'e': /* program execution time in seconds */ - execution = atoi(opt->value); - break; - case 's': /* server's address */ - serverName = opt->value; - break; - case 'v': /* verbosity */ - verbosity = IncrementVerbosity(); - break; - case 'd': /* debug mode */ - debug_mode = PR_TRUE; - break; - case 'p': /* pthread mode */ - pthread_stats = PR_TRUE; - break; - case 'h': - default: - Help(); - return 2; + case 'G': /* use global threads */ + thread_scope = PR_GLOBAL_THREAD; + break; + case 'X': /* use XTP as transport */ + protocol = 36; + break; + case '6': /* Use IPv6 */ + domain = PR_AF_INET6; + break; + case 'a': /* the value for accepting */ + accepting = atoi(opt->value); + break; + case 'b': /* the value for backlock */ + backlog = atoi(opt->value); + break; + case 'T': /* the thread provider */ + if ('n' == *opt->value) { + thread_provider = thread_nspr; + } + else if ('p' == *opt->value) { + thread_provider = thread_pthread; + } + else if ('w' == *opt->value) { + thread_provider = thread_win32; + } + else { + Help(); + return 2; + } + break; + case 'c': /* number of client threads */ + clients = atoi(opt->value); + break; + case 'w': /* minimum server worker threads */ + workersMin = atoi(opt->value); + break; + case 'W': /* maximum server worker threads */ + workersMax = atoi(opt->value); + break; + case 'e': /* program execution time in seconds */ + execution = atoi(opt->value); + break; + case 's': /* server's address */ + serverName = opt->value; + break; + case 'v': /* verbosity */ + verbosity = IncrementVerbosity(); + break; + case 'd': /* debug mode */ + debug_mode = PR_TRUE; + break; + case 'p': /* pthread mode */ + pthread_stats = PR_TRUE; + break; + case 'h': + default: + Help(); + return 2; } } PL_DestroyOptState(opt); - if (0 != PL_strcmp(serverName, DEFAULT_SERVER)) serverIsLocal = PR_FALSE; - if (0 == execution) execution = DEFAULT_EXECUTION_TIME; - if (0 == workersMax) workersMax = DEFAULT_WORKERS_MAX; - if (0 == workersMin) workersMin = DEFAULT_WORKERS_MIN; - if (0 == accepting) accepting = ALLOWED_IN_ACCEPT; - if (0 == backlog) backlog = DEFAULT_BACKLOG; + if (0 != PL_strcmp(serverName, DEFAULT_SERVER)) { + serverIsLocal = PR_FALSE; + } + if (0 == execution) { + execution = DEFAULT_EXECUTION_TIME; + } + if (0 == workersMax) { + workersMax = DEFAULT_WORKERS_MAX; + } + if (0 == workersMin) { + workersMin = DEFAULT_WORKERS_MIN; + } + if (0 == accepting) { + accepting = ALLOWED_IN_ACCEPT; + } + if (0 == backlog) { + backlog = DEFAULT_BACKLOG; + } - if (workersMin > accepting) accepting = workersMin; + if (workersMin > accepting) { + accepting = workersMin; + } PR_STDIO_INIT(); TimeOfDayMessage("Client/Server started at", PR_GetCurrentThread()); @@ -1190,7 +1231,7 @@ int main(int argc, char **argv) ("main(0x%p): creating server thread\n", PR_GetCurrentThread())); rv = NewThread( - Server, server, PR_PRIORITY_HIGH, PR_JOINABLE_THREAD); + Server, server, PR_PRIORITY_HIGH, PR_JOINABLE_THREAD); TEST_ASSERT(PR_SUCCESS == rv); TEST_LOG( @@ -1198,14 +1239,15 @@ int main(int argc, char **argv) ("main(0x%p): waiting for server init\n", PR_GetCurrentThread())); PR_Lock(server->ml); - while (server->state == cs_init) + while (server->state == cs_init) { PR_WaitCondVar(server->stateChange, PR_INTERVAL_NO_TIMEOUT); + } PR_Unlock(server->ml); TEST_LOG( cltsrv_log_file, TEST_LOG_VERBOSE, ("main(0x%p): server init complete (port #%d)\n", - PR_GetCurrentThread(), server->port)); + PR_GetCurrentThread(), server->port)); } if (clients != 0) @@ -1218,8 +1260,8 @@ int main(int argc, char **argv) TEST_LOG( cltsrv_log_file, TEST_LOG_VERBOSE, ("main(0x%p): creating %d client threads\n", - PR_GetCurrentThread(), clients)); - + PR_GetCurrentThread(), clients)); + if (!serverIsLocal) { rv = PR_GetHostByName(serverName, buffer, BUFFER_SIZE, &host); @@ -1250,11 +1292,12 @@ int main(int argc, char **argv) cltsrv_log_file, TEST_LOG_INFO, ("main(0x%p): creating client threads\n", PR_GetCurrentThread())); rv = NewThread( - Client, &client[index], PR_PRIORITY_NORMAL, PR_JOINABLE_THREAD); + Client, &client[index], PR_PRIORITY_NORMAL, PR_JOINABLE_THREAD); TEST_ASSERT(PR_SUCCESS == rv); PR_Lock(client[index].ml); - while (cs_init == client[index].state) + while (cs_init == client[index].state) { PR_WaitCondVar(client[index].stateChange, PR_INTERVAL_NO_TIMEOUT); + } PR_Unlock(client[index].ml); } } @@ -1263,7 +1306,7 @@ int main(int argc, char **argv) TEST_LOG( cltsrv_log_file, TEST_LOG_ALWAYS, ("main(0x%p): waiting for execution interval (%d seconds)\n", - PR_GetCurrentThread(), execution)); + PR_GetCurrentThread(), execution)); WaitForCompletion(execution); @@ -1273,9 +1316,9 @@ int main(int argc, char **argv) { for (index = 0; index < clients; ++index) { - TEST_LOG(cltsrv_log_file, TEST_LOG_STATUS, - ("main(0x%p): notifying client(0x%p) to stop\n", - PR_GetCurrentThread(), client[index].thread)); + TEST_LOG(cltsrv_log_file, TEST_LOG_STATUS, + ("main(0x%p): notifying client(0x%p) to stop\n", + PR_GetCurrentThread(), client[index].thread)); PR_Lock(client[index].ml); if (cs_run == client[index].state) @@ -1288,12 +1331,12 @@ int main(int argc, char **argv) } PR_Unlock(client[index].ml); - TEST_LOG(cltsrv_log_file, TEST_LOG_VERBOSE, - ("main(0x%p): joining client(0x%p)\n", - PR_GetCurrentThread(), client[index].thread)); + TEST_LOG(cltsrv_log_file, TEST_LOG_VERBOSE, + ("main(0x%p): joining client(0x%p)\n", + PR_GetCurrentThread(), client[index].thread)); - joinStatus = JoinThread(client[index].thread); - TEST_ASSERT(PR_SUCCESS == joinStatus); + joinStatus = JoinThread(client[index].thread); + TEST_ASSERT(PR_SUCCESS == joinStatus); PR_DestroyCondVar(client[index].stateChange); PR_DestroyLock(client[index].ml); } @@ -1304,21 +1347,22 @@ int main(int argc, char **argv) { /* All clients joined - retrieve the server */ TEST_LOG( - cltsrv_log_file, TEST_LOG_NOTICE, + cltsrv_log_file, TEST_LOG_NOTICE, ("main(0x%p): notifying server(0x%p) to stop\n", - PR_GetCurrentThread(), server->thread)); + PR_GetCurrentThread(), server->thread)); PR_Lock(server->ml); server->state = cs_stop; PR_Interrupt(server->thread); - while (cs_exit != server->state) + while (cs_exit != server->state) { PR_WaitCondVar(server->stateChange, PR_INTERVAL_NO_TIMEOUT); + } PR_Unlock(server->ml); TEST_LOG( - cltsrv_log_file, TEST_LOG_NOTICE, + cltsrv_log_file, TEST_LOG_NOTICE, ("main(0x%p): joining server(0x%p)\n", - PR_GetCurrentThread(), server->thread)); + PR_GetCurrentThread(), server->thread)); joinStatus = JoinThread(server->thread); TEST_ASSERT(PR_SUCCESS == joinStatus); @@ -1330,19 +1374,22 @@ int main(int argc, char **argv) } TEST_LOG( - cltsrv_log_file, TEST_LOG_ALWAYS, + cltsrv_log_file, TEST_LOG_ALWAYS, ("main(0x%p): test complete\n", PR_GetCurrentThread())); - if (thread_provider == thread_win32) - thread_type = "\nWin32 Thread Statistics\n"; - else if (thread_provider == thread_pthread) - thread_type = "\npthread Statistics\n"; - else if (thread_provider == thread_sproc) - thread_type = "\nsproc Statistics\n"; + if (thread_provider == thread_win32) { + thread_type = "\nWin32 Thread Statistics\n"; + } + else if (thread_provider == thread_pthread) { + thread_type = "\npthread Statistics\n"; + } + else if (thread_provider == thread_sproc) { + thread_type = "\nsproc Statistics\n"; + } else { - PR_ASSERT(thread_provider == thread_nspr); - thread_type = "\nPRThread Statistics\nn"; - } + PR_ASSERT(thread_provider == thread_nspr); + thread_type = "\nPRThread Statistics\nn"; + } PT_FPrintStats(debug_out, thread_type); diff --git a/nsprpub/pr/tests/prpoll.c b/nsprpub/pr/tests/prpoll.c index d2c87081c..5c87a57d1 100644 --- a/nsprpub/pr/tests/prpoll.c +++ b/nsprpub/pr/tests/prpoll.c @@ -19,8 +19,8 @@ #include "private/pprio.h" -#define CLIENT_LOOPS 5 -#define BUF_SIZE 128 +#define CLIENT_LOOPS 5 +#define BUF_SIZE 128 #include <stdio.h> #include <string.h> @@ -51,11 +51,11 @@ clientThreadFunc(void *arg) PR_snprintf(buf, sizeof(buf), "%hu", port); for (i = 0; i < 5; i++) { - sock = PR_NewTCPSocket(); + sock = PR_NewTCPSocket(); PR_Connect(sock, &addr, PR_INTERVAL_NO_TIMEOUT); - PR_Write(sock, buf, sizeof(buf)); - PR_Close(sock); + PR_Write(sock, buf, sizeof(buf)); + PR_Close(sock); } } @@ -86,100 +86,100 @@ int main(int argc, char **argv) /* Create two listening sockets */ if ((listenSock1 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - exit(1); + fprintf(stderr, "Can't create a new TCP socket\n"); + exit(1); } addr.inet.family = PR_AF_INET; addr.inet.ip = PR_htonl(PR_INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - exit(1); + fprintf(stderr, "Can't bind socket\n"); + exit(1); } if (PR_GetSockName(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - exit(1); + fprintf(stderr, "PR_GetSockName failed\n"); + exit(1); } listenPort1 = PR_ntohs(addr.inet.port); if (PR_Listen(listenSock1, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - exit(1); + fprintf(stderr, "Can't listen on a socket\n"); + exit(1); } if ((listenSock2 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - exit(1); + fprintf(stderr, "Can't create a new TCP socket\n"); + exit(1); } addr.inet.family = PR_AF_INET; addr.inet.ip = PR_htonl(PR_INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - exit(1); + fprintf(stderr, "Can't bind socket\n"); + exit(1); } if (PR_GetSockName(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - exit(1); + fprintf(stderr, "PR_GetSockName failed\n"); + exit(1); } listenPort2 = PR_ntohs(addr.inet.port); if (PR_Listen(listenSock2, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - exit(1); + fprintf(stderr, "Can't listen on a socket\n"); + exit(1); } /* Set up the poll descriptor array */ pds = pds0; other_pds = pds1; memset(pds, 0, sizeof(pds)); - npds = 0; + npds = 0; pds[npds].fd = listenSock1; pds[npds].in_flags = PR_POLL_READ; - npds++; + npds++; pds[npds].fd = listenSock2; pds[npds].in_flags = PR_POLL_READ; - npds++; - - sd = socket(AF_INET, SOCK_STREAM, 0); - PR_ASSERT(sd >= 0); - memset((char *) &saddr, 0, sizeof(saddr)); - saddr.sin_family = AF_INET; - saddr.sin_addr.s_addr = htonl(INADDR_ANY); - saddr.sin_port = htons(0); - - rv = bind(sd, (struct sockaddr *)&saddr, sizeof(saddr)); - PR_ASSERT(rv == 0); - saddr_len = sizeof(saddr); - rv = getsockname(sd, (struct sockaddr *) &saddr, &saddr_len); - PR_ASSERT(rv == 0); + npds++; + + sd = socket(AF_INET, SOCK_STREAM, 0); + PR_ASSERT(sd >= 0); + memset((char *) &saddr, 0, sizeof(saddr)); + saddr.sin_family = AF_INET; + saddr.sin_addr.s_addr = htonl(INADDR_ANY); + saddr.sin_port = htons(0); + + rv = bind(sd, (struct sockaddr *)&saddr, sizeof(saddr)); + PR_ASSERT(rv == 0); + saddr_len = sizeof(saddr); + rv = getsockname(sd, (struct sockaddr *) &saddr, &saddr_len); + PR_ASSERT(rv == 0); listenPort3 = ntohs(saddr.sin_port); - rv = listen(sd, 5); - PR_ASSERT(rv == 0); + rv = listen(sd, 5); + PR_ASSERT(rv == 0); pds[npds].fd = socket_poll_fd = PR_CreateSocketPollFd(sd); - PR_ASSERT(pds[npds].fd); + PR_ASSERT(pds[npds].fd); pds[npds].in_flags = PR_POLL_READ; npds++; PR_snprintf(buf, sizeof(buf), - "The server thread is listening on ports %hu, %hu and %hu\n\n", - listenPort1, listenPort2, listenPort3); + "The server thread is listening on ports %hu, %hu and %hu\n\n", + listenPort1, listenPort2, listenPort3); printf("%s", buf); /* Testing timeout */ printf("PR_Poll should time out in 5 seconds\n"); retVal = PR_Poll(pds, npds, PR_SecondsToInterval(5)); if (retVal != 0) { - PR_snprintf(buf, sizeof(buf), - "PR_Poll should time out and return 0, but it returns %ld\n", - retVal); - fprintf(stderr, "%s", buf); - exit(1); + PR_snprintf(buf, sizeof(buf), + "PR_Poll should time out and return 0, but it returns %ld\n", + retVal); + fprintf(stderr, "%s", buf); + exit(1); } printf("PR_Poll timed out. Test passed.\n\n"); /* Testing bad fd */ printf("PR_Poll should detect a bad file descriptor\n"); if ((badFD = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a TCP socket\n"); - exit(1); + fprintf(stderr, "Can't create a TCP socket\n"); + exit(1); } pds[npds].fd = badFD; @@ -189,40 +189,40 @@ int main(int argc, char **argv) #if 0 retVal = PR_Poll(pds, npds, PR_INTERVAL_NO_TIMEOUT); if (retVal != 1 || (unsigned short) pds[2].out_flags != PR_POLL_NVAL) { - fprintf(stderr, "Failed to detect the bad fd: " - "PR_Poll returns %d, out_flags is 0x%hx\n", - retVal, pds[npds - 1].out_flags); - exit(1); + fprintf(stderr, "Failed to detect the bad fd: " + "PR_Poll returns %d, out_flags is 0x%hx\n", + retVal, pds[npds - 1].out_flags); + exit(1); } printf("PR_Poll detected the bad fd. Test passed.\n\n"); #endif npds--; clientThread = PR_CreateThread(PR_USER_THREAD, - clientThreadFunc, (void *) listenPort1, - PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, 0); + clientThreadFunc, (void *) listenPort1, + PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, 0); if (clientThread == NULL) { - fprintf(stderr, "can't create thread\n"); - exit(1); + fprintf(stderr, "can't create thread\n"); + exit(1); } clientThread = PR_CreateThread(PR_USER_THREAD, - clientThreadFunc, (void *) listenPort2, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, - PR_UNJOINABLE_THREAD, 0); + clientThreadFunc, (void *) listenPort2, + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, + PR_UNJOINABLE_THREAD, 0); if (clientThread == NULL) { - fprintf(stderr, "can't create thread\n"); - exit(1); + fprintf(stderr, "can't create thread\n"); + exit(1); } clientThread = PR_CreateThread(PR_USER_THREAD, - clientThreadFunc, (void *) listenPort3, - PR_PRIORITY_NORMAL, PR_GLOBAL_BOUND_THREAD, - PR_UNJOINABLE_THREAD, 0); + clientThreadFunc, (void *) listenPort3, + PR_PRIORITY_NORMAL, PR_GLOBAL_BOUND_THREAD, + PR_UNJOINABLE_THREAD, 0); if (clientThread == NULL) { - fprintf(stderr, "can't create thread\n"); - exit(1); + fprintf(stderr, "can't create thread\n"); + exit(1); } @@ -235,110 +235,110 @@ int main(int argc, char **argv) /* 30 events total */ i = 0; while (i < 30) { - PRPollDesc *tmp; - int nextIndex; - int nEvents = 0; - - retVal = PR_Poll(pds, npds, PR_INTERVAL_NO_TIMEOUT); - PR_ASSERT(retVal != 0); /* no timeout */ - if (retVal == -1) { - fprintf(stderr, "PR_Poll failed\n"); - exit(1); - } - - nextIndex = 3; - /* the three listening sockets */ - for (j = 0; j < 3; j++) { - other_pds[j] = pds[j]; - PR_ASSERT((pds[j].out_flags & PR_POLL_WRITE) == 0 - && (pds[j].out_flags & PR_POLL_EXCEPT) == 0); - if (pds[j].out_flags & PR_POLL_READ) { - PRFileDesc *sock; - - nEvents++; - if (j == 2) { - PROsfd newsd; - newsd = accept(PR_FileDesc2NativeHandle(pds[j].fd), NULL, 0); - if (newsd == -1) { - fprintf(stderr, "accept() failed\n"); - exit(1); - } - other_pds[nextIndex].fd = PR_CreateSocketPollFd(newsd); - PR_ASSERT(other_pds[nextIndex].fd); - other_pds[nextIndex].in_flags = PR_POLL_READ; - } else { - sock = PR_Accept(pds[j].fd, NULL, PR_INTERVAL_NO_TIMEOUT); - if (sock == NULL) { - fprintf(stderr, "PR_Accept() failed\n"); - exit(1); - } - other_pds[nextIndex].fd = sock; - other_pds[nextIndex].in_flags = PR_POLL_READ; - } - nextIndex++; - } else if (pds[j].out_flags & PR_POLL_ERR) { - fprintf(stderr, "PR_Poll() indicates that an fd has error\n"); - exit(1); - } else if (pds[j].out_flags & PR_POLL_NVAL) { - fprintf(stderr, "PR_Poll() indicates that fd %d is invalid\n", - PR_FileDesc2NativeHandle(pds[j].fd)); - exit(1); - } - } - - for (j = 3; j < npds; j++) { - PR_ASSERT((pds[j].out_flags & PR_POLL_WRITE) == 0 - && (pds[j].out_flags & PR_POLL_EXCEPT) == 0); - if (pds[j].out_flags & PR_POLL_READ) { - PRInt32 nBytes; - - nEvents++; - /* XXX: This call is a hack and should be fixed */ - if (PR_GetDescType(pds[j].fd) == (PRDescType) 0) { - nBytes = recv(PR_FileDesc2NativeHandle(pds[j].fd), buf, - sizeof(buf), 0); - if (nBytes == -1) { - fprintf(stderr, "recv() failed\n"); - exit(1); - } - printf("Server read %d bytes from native fd %d\n",nBytes, - PR_FileDesc2NativeHandle(pds[j].fd)); + PRPollDesc *tmp; + int nextIndex; + int nEvents = 0; + + retVal = PR_Poll(pds, npds, PR_INTERVAL_NO_TIMEOUT); + PR_ASSERT(retVal != 0); /* no timeout */ + if (retVal == -1) { + fprintf(stderr, "PR_Poll failed\n"); + exit(1); + } + + nextIndex = 3; + /* the three listening sockets */ + for (j = 0; j < 3; j++) { + other_pds[j] = pds[j]; + PR_ASSERT((pds[j].out_flags & PR_POLL_WRITE) == 0 + && (pds[j].out_flags & PR_POLL_EXCEPT) == 0); + if (pds[j].out_flags & PR_POLL_READ) { + PRFileDesc *sock; + + nEvents++; + if (j == 2) { + PROsfd newsd; + newsd = accept(PR_FileDesc2NativeHandle(pds[j].fd), NULL, 0); + if (newsd == -1) { + fprintf(stderr, "accept() failed\n"); + exit(1); + } + other_pds[nextIndex].fd = PR_CreateSocketPollFd(newsd); + PR_ASSERT(other_pds[nextIndex].fd); + other_pds[nextIndex].in_flags = PR_POLL_READ; + } else { + sock = PR_Accept(pds[j].fd, NULL, PR_INTERVAL_NO_TIMEOUT); + if (sock == NULL) { + fprintf(stderr, "PR_Accept() failed\n"); + exit(1); + } + other_pds[nextIndex].fd = sock; + other_pds[nextIndex].in_flags = PR_POLL_READ; + } + nextIndex++; + } else if (pds[j].out_flags & PR_POLL_ERR) { + fprintf(stderr, "PR_Poll() indicates that an fd has error\n"); + exit(1); + } else if (pds[j].out_flags & PR_POLL_NVAL) { + fprintf(stderr, "PR_Poll() indicates that fd %d is invalid\n", + PR_FileDesc2NativeHandle(pds[j].fd)); + exit(1); + } + } + + for (j = 3; j < npds; j++) { + PR_ASSERT((pds[j].out_flags & PR_POLL_WRITE) == 0 + && (pds[j].out_flags & PR_POLL_EXCEPT) == 0); + if (pds[j].out_flags & PR_POLL_READ) { + PRInt32 nBytes; + + nEvents++; + /* XXX: This call is a hack and should be fixed */ + if (PR_GetDescType(pds[j].fd) == (PRDescType) 0) { + nBytes = recv(PR_FileDesc2NativeHandle(pds[j].fd), buf, + sizeof(buf), 0); + if (nBytes == -1) { + fprintf(stderr, "recv() failed\n"); + exit(1); + } + printf("Server read %d bytes from native fd %d\n",nBytes, + PR_FileDesc2NativeHandle(pds[j].fd)); #ifdef WIN32 - closesocket((SOCKET)PR_FileDesc2NativeHandle(pds[j].fd)); + closesocket((SOCKET)PR_FileDesc2NativeHandle(pds[j].fd)); #else - close(PR_FileDesc2NativeHandle(pds[j].fd)); + close(PR_FileDesc2NativeHandle(pds[j].fd)); #endif - PR_DestroySocketPollFd(pds[j].fd); - } else { - nBytes = PR_Read(pds[j].fd, buf, sizeof(buf)); - if (nBytes == -1) { - fprintf(stderr, "PR_Read() failed\n"); - exit(1); - } - PR_Close(pds[j].fd); - } - /* Just to be safe */ - buf[BUF_SIZE - 1] = '\0'; - printf("The server received \"%s\" from a client\n", buf); - } else if (pds[j].out_flags & PR_POLL_ERR) { - fprintf(stderr, "PR_Poll() indicates that an fd has error\n"); - exit(1); - } else if (pds[j].out_flags & PR_POLL_NVAL) { - fprintf(stderr, "PR_Poll() indicates that an fd is invalid\n"); - exit(1); - } else { - other_pds[nextIndex] = pds[j]; - nextIndex++; - } - } - - PR_ASSERT(retVal == nEvents); - /* swap */ - tmp = pds; - pds = other_pds; - other_pds = tmp; - npds = nextIndex; - i += nEvents; + PR_DestroySocketPollFd(pds[j].fd); + } else { + nBytes = PR_Read(pds[j].fd, buf, sizeof(buf)); + if (nBytes == -1) { + fprintf(stderr, "PR_Read() failed\n"); + exit(1); + } + PR_Close(pds[j].fd); + } + /* Just to be safe */ + buf[BUF_SIZE - 1] = '\0'; + printf("The server received \"%s\" from a client\n", buf); + } else if (pds[j].out_flags & PR_POLL_ERR) { + fprintf(stderr, "PR_Poll() indicates that an fd has error\n"); + exit(1); + } else if (pds[j].out_flags & PR_POLL_NVAL) { + fprintf(stderr, "PR_Poll() indicates that an fd is invalid\n"); + exit(1); + } else { + other_pds[nextIndex] = pds[j]; + nextIndex++; + } + } + + PR_ASSERT(retVal == nEvents); + /* swap */ + tmp = pds; + pds = other_pds; + other_pds = tmp; + npds = nextIndex; + i += nEvents; } PR_DestroySocketPollFd(socket_poll_fd); diff --git a/nsprpub/pr/tests/prpollml.c b/nsprpub/pr/tests/prpollml.c index 6894c5257..118d3674d 100644 --- a/nsprpub/pr/tests/prpollml.c +++ b/nsprpub/pr/tests/prpollml.c @@ -15,14 +15,10 @@ #include <stdlib.h> #include <string.h> -#ifdef SYMBIAN -#define POLL_DESC_COUNT 128 -#else #define POLL_DESC_COUNT 256 /* This should be greater than the * STACK_POLL_DESC_COUNT macro in * ptio.c to cause syspoll_list to * be created. */ -#endif static PRPollDesc pd[POLL_DESC_COUNT]; @@ -38,8 +34,8 @@ static void Test(void) rv = PR_Poll(pd, i, timeout); if (rv != 0) { fprintf(stderr, - "PR_Poll should time out but returns %d (%d, %d)\n", - (int) rv, (int) PR_GetError(), (int) PR_GetOSError()); + "PR_Poll should time out but returns %d (%d, %d)\n", + (int) rv, (int) PR_GetError(), (int) PR_GetOSError()); exit(1); } } @@ -47,8 +43,8 @@ static void Test(void) for (i = POLL_DESC_COUNT; i >= 1; i--) { rv = PR_Poll(pd, i, timeout); if (rv != 0) { - fprintf(stderr, "PR_Poll should time out but returns %d\n", - (int) rv); + fprintf(stderr, "PR_Poll should time out but returns %d\n", + (int) rv); exit(1); } } @@ -74,22 +70,22 @@ int main(int argc, char **argv) sock = PR_NewTCPSocket(); if (sock == NULL) { fprintf(stderr, "PR_NewTCPSocket failed (%d, %d)\n", - (int) PR_GetError(), (int) PR_GetOSError()); + (int) PR_GetError(), (int) PR_GetOSError()); fprintf(stderr, "Ensure the per process file descriptor limit " - "is greater than %d.", POLL_DESC_COUNT); + "is greater than %d.", POLL_DESC_COUNT); exit(1); } if (PR_Bind(sock, &addr) == PR_FAILURE) { fprintf(stderr, "PR_Bind failed (%d, %d)\n", - (int) PR_GetError(), (int) PR_GetOSError()); + (int) PR_GetError(), (int) PR_GetOSError()); exit(1); } if (PR_Listen(sock, 5) == PR_FAILURE) { fprintf(stderr, "PR_Listen failed (%d, %d)\n", - (int) PR_GetError(), (int) PR_GetOSError()); + (int) PR_GetError(), (int) PR_GetOSError()); exit(1); } - + pd[i].fd = sock; pd[i].in_flags = PR_POLL_READ; } @@ -99,7 +95,7 @@ int main(int argc, char **argv) /* then run the test on all three kinds of threads */ thread = PR_CreateThread(PR_USER_THREAD, ThreadFunc, NULL, - PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); if (NULL == thread) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); @@ -109,7 +105,7 @@ int main(int argc, char **argv) exit(1); } thread = PR_CreateThread(PR_USER_THREAD, ThreadFunc, NULL, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); if (NULL == thread) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); @@ -119,7 +115,7 @@ int main(int argc, char **argv) exit(1); } thread = PR_CreateThread(PR_USER_THREAD, ThreadFunc, NULL, - PR_PRIORITY_NORMAL, PR_GLOBAL_BOUND_THREAD, PR_JOINABLE_THREAD, 0); + PR_PRIORITY_NORMAL, PR_GLOBAL_BOUND_THREAD, PR_JOINABLE_THREAD, 0); if (NULL == thread) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); diff --git a/nsprpub/pr/tests/prselect.c b/nsprpub/pr/tests/prselect.c index 15aa85580..2a81100e8 100644 --- a/nsprpub/pr/tests/prselect.c +++ b/nsprpub/pr/tests/prselect.c @@ -12,10 +12,10 @@ ** ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ***********************************************************************/ /*********************************************************************** @@ -40,26 +40,28 @@ /*********************************************************************** ** PRIVATE FUNCTION: Test_Result ** DESCRIPTION: Used in conjunction with the regress tool, prints out the -** status of the test case. +** status of the test case. ** INPUTS: PASS/FAIL ** OUTPUTS: None ** RETURN: None ** SIDE EFFECTS: -** +** ** RESTRICTIONS: ** None ** MEMORY: NA ** ALGORITHM: Determine what the status is and print accordingly. -** +** ***********************************************************************/ static Test_Result (int result) { - if (result == PASS) - printf ("PASS\n"); - else - printf ("FAIL\n"); + if (result == PASS) { + printf ("PASS\n"); + } + else { + printf ("FAIL\n"); + } } static void @@ -77,10 +79,10 @@ clientThreadFunc(void *arg) PR_snprintf(buf, sizeof(buf), "%hu", port); for (i = 0; i < 5; i++) { - sock = PR_NewTCPSocket(); + sock = PR_NewTCPSocket(); PR_Connect(sock, &addr, PR_INTERVAL_NO_TIMEOUT); - PR_Write(sock, buf, sizeof(buf)); - PR_Close(sock); + PR_Write(sock, buf, sizeof(buf)); + PR_Close(sock); } } @@ -98,91 +100,109 @@ int main(int argc, char **argv) PRInt32 retVal; PRIntn i, j; - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); if (debug_mode) { - printf("This program tests PR_Select with sockets. Timeout, error\n"); - printf("reporting, and normal operation are tested.\n\n"); - } + printf("This program tests PR_Select with sockets. Timeout, error\n"); + printf("reporting, and normal operation are tested.\n\n"); + } /* Create two listening sockets */ if ((listenSock1 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - if (!debug_mode) Test_Result(FAIL); - exit(1); + fprintf(stderr, "Can't create a new TCP socket\n"); + if (!debug_mode) { + Test_Result(FAIL); + } + exit(1); } addr.inet.family = AF_INET; addr.inet.ip = PR_htonl(INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - if (!debug_mode) Test_Result(FAIL); - exit(1); + fprintf(stderr, "Can't bind socket\n"); + if (!debug_mode) { + Test_Result(FAIL); + } + exit(1); } if (PR_GetSockName(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - if (!debug_mode) Test_Result(FAIL); - exit(1); + fprintf(stderr, "PR_GetSockName failed\n"); + if (!debug_mode) { + Test_Result(FAIL); + } + exit(1); } listenPort1 = PR_ntohs(addr.inet.port); if (PR_Listen(listenSock1, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - if (!debug_mode) Test_Result(FAIL); - exit(1); + fprintf(stderr, "Can't listen on a socket\n"); + if (!debug_mode) { + Test_Result(FAIL); + } + exit(1); } if ((listenSock2 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - if (!debug_mode) Test_Result(FAIL); - exit(1); + fprintf(stderr, "Can't create a new TCP socket\n"); + if (!debug_mode) { + Test_Result(FAIL); + } + exit(1); } addr.inet.family = AF_INET; addr.inet.ip = PR_htonl(INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - if (!debug_mode) Test_Result(FAIL); - exit(1); + fprintf(stderr, "Can't bind socket\n"); + if (!debug_mode) { + Test_Result(FAIL); + } + exit(1); } if (PR_GetSockName(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - if (!debug_mode) Test_Result(FAIL); - exit(1); + fprintf(stderr, "PR_GetSockName failed\n"); + if (!debug_mode) { + Test_Result(FAIL); + } + exit(1); } listenPort2 = PR_ntohs(addr.inet.port); if (PR_Listen(listenSock2, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - if (!debug_mode) Test_Result(FAIL); - exit(1); + fprintf(stderr, "Can't listen on a socket\n"); + if (!debug_mode) { + Test_Result(FAIL); + } + exit(1); } PR_snprintf(buf, sizeof(buf), - "The server thread is listening on ports %hu and %hu\n\n", - listenPort1, listenPort2); + "The server thread is listening on ports %hu and %hu\n\n", + listenPort1, listenPort2); printf("%s", buf); /* Set up the fd set */ @@ -191,29 +211,37 @@ int main(int argc, char **argv) PR_FD_SET(listenSock2, &readFdSet); /* Testing timeout */ - if (debug_mode) printf("PR_Select should time out in 5 seconds\n"); + if (debug_mode) { + printf("PR_Select should time out in 5 seconds\n"); + } retVal = PR_Select(0 /* unused */, &readFdSet, NULL, NULL, - PR_SecondsToInterval(5)); + PR_SecondsToInterval(5)); if (retVal != 0) { - PR_snprintf(buf, sizeof(buf), - "PR_Select should time out and return 0, but it returns %ld\n", - retVal); - fprintf(stderr, "%s", buf); - if (retVal == -1) { - fprintf(stderr, "Error %d, oserror %d\n", PR_GetError(), - PR_GetOSError()); - if (!debug_mode) Test_Result(FAIL); - } - exit(1); + PR_snprintf(buf, sizeof(buf), + "PR_Select should time out and return 0, but it returns %ld\n", + retVal); + fprintf(stderr, "%s", buf); + if (retVal == -1) { + fprintf(stderr, "Error %d, oserror %d\n", PR_GetError(), + PR_GetOSError()); + if (!debug_mode) { + Test_Result(FAIL); + } + } + exit(1); + } + if (debug_mode) { + printf("PR_Select timed out. Test passed.\n\n"); + } + else { + Test_Result(PASS); } - if (debug_mode) printf("PR_Select timed out. Test passed.\n\n"); - else Test_Result(PASS); /* Testing bad fd */ printf("PR_Select should detect a bad file descriptor\n"); if ((badFD = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a TCP socket\n"); - exit(1); + fprintf(stderr, "Can't create a TCP socket\n"); + exit(1); } PR_FD_SET(listenSock1, &readFdSet); @@ -221,35 +249,35 @@ int main(int argc, char **argv) PR_FD_SET(badFD, &readFdSet); PR_Close(badFD); /* make the fd bad */ retVal = PR_Select(0 /* unused */, &readFdSet, NULL, NULL, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); if (retVal != -1 || PR_GetError() != PR_BAD_DESCRIPTOR_ERROR) { - fprintf(stderr, "Failed to detect the bad fd: " - "PR_Select returns %d\n", retVal); - if (retVal == -1) { - fprintf(stderr, "Error %d, oserror %d\n", PR_GetError(), - PR_GetOSError()); - } - exit(1); + fprintf(stderr, "Failed to detect the bad fd: " + "PR_Select returns %d\n", retVal); + if (retVal == -1) { + fprintf(stderr, "Error %d, oserror %d\n", PR_GetError(), + PR_GetOSError()); + } + exit(1); } printf("PR_Select detected a bad fd. Test passed.\n\n"); PR_FD_CLR(badFD, &readFdSet); clientThread = PR_CreateThread(PR_USER_THREAD, - clientThreadFunc, (void *) listenPort1, - PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, 0); + clientThreadFunc, (void *) listenPort1, + PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, 0); if (clientThread == NULL) { - fprintf(stderr, "can't create thread\n"); - exit(1); + fprintf(stderr, "can't create thread\n"); + exit(1); } clientThread = PR_CreateThread(PR_USER_THREAD, - clientThreadFunc, (void *) listenPort2, - PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, 0); + clientThreadFunc, (void *) listenPort2, + PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, 0); if (clientThread == NULL) { - fprintf(stderr, "can't create thread\n"); - exit(1); + fprintf(stderr, "can't create thread\n"); + exit(1); } printf("Two client threads are created. Each of them will\n"); @@ -270,68 +298,68 @@ int main(int argc, char **argv) /* 20 events total */ i = 0; while (i < 20) { - PRFileDesc **tmp; - int nextIndex; - int nEvents = 0; - - retVal = PR_Select(0 /* unused */, &readFdSet, NULL, NULL, - PR_INTERVAL_NO_TIMEOUT); - PR_ASSERT(retVal != 0); /* no timeout */ - if (retVal == -1) { - fprintf(stderr, "PR_Select failed (%d, %d)\n", PR_GetError(), - PR_GetOSError()); - exit(1); - } - - nextIndex = 2; - /* the two listening sockets */ - for (j = 0; j < 2; j++) { - other_fds[j] = fds[j]; - if (PR_FD_ISSET(fds[j], &readFdSet)) { - PRFileDesc *sock; - - nEvents++; - sock = PR_Accept(fds[j], NULL, PR_INTERVAL_NO_TIMEOUT); - if (sock == NULL) { - fprintf(stderr, "PR_Accept() failed\n"); - exit(1); - } - other_fds[nextIndex] = sock; - PR_FD_SET(sock, &readFdSet); - nextIndex++; - } - PR_FD_SET(fds[j], &readFdSet); - } - - for (j = 2; j < nfds; j++) { - if (PR_FD_ISSET(fds[j], &readFdSet)) { - PRInt32 nBytes; - - PR_FD_CLR(fds[j], &readFdSet); - nEvents++; - nBytes = PR_Read(fds[j], buf, sizeof(buf)); - if (nBytes == -1) { - fprintf(stderr, "PR_Read() failed\n"); - exit(1); - } - /* Just to be safe */ - buf[127] = '\0'; - PR_Close(fds[j]); - printf("The server received \"%s\" from a client\n", buf); - } else { - PR_FD_SET(fds[j], &readFdSet); - other_fds[nextIndex] = fds[j]; - nextIndex++; - } - } - - PR_ASSERT(retVal == nEvents); - /* swap */ - tmp = fds; - fds = other_fds; - other_fds = tmp; - nfds = nextIndex; - i += nEvents; + PRFileDesc **tmp; + int nextIndex; + int nEvents = 0; + + retVal = PR_Select(0 /* unused */, &readFdSet, NULL, NULL, + PR_INTERVAL_NO_TIMEOUT); + PR_ASSERT(retVal != 0); /* no timeout */ + if (retVal == -1) { + fprintf(stderr, "PR_Select failed (%d, %d)\n", PR_GetError(), + PR_GetOSError()); + exit(1); + } + + nextIndex = 2; + /* the two listening sockets */ + for (j = 0; j < 2; j++) { + other_fds[j] = fds[j]; + if (PR_FD_ISSET(fds[j], &readFdSet)) { + PRFileDesc *sock; + + nEvents++; + sock = PR_Accept(fds[j], NULL, PR_INTERVAL_NO_TIMEOUT); + if (sock == NULL) { + fprintf(stderr, "PR_Accept() failed\n"); + exit(1); + } + other_fds[nextIndex] = sock; + PR_FD_SET(sock, &readFdSet); + nextIndex++; + } + PR_FD_SET(fds[j], &readFdSet); + } + + for (j = 2; j < nfds; j++) { + if (PR_FD_ISSET(fds[j], &readFdSet)) { + PRInt32 nBytes; + + PR_FD_CLR(fds[j], &readFdSet); + nEvents++; + nBytes = PR_Read(fds[j], buf, sizeof(buf)); + if (nBytes == -1) { + fprintf(stderr, "PR_Read() failed\n"); + exit(1); + } + /* Just to be safe */ + buf[127] = '\0'; + PR_Close(fds[j]); + printf("The server received \"%s\" from a client\n", buf); + } else { + PR_FD_SET(fds[j], &readFdSet); + other_fds[nextIndex] = fds[j]; + nextIndex++; + } + } + + PR_ASSERT(retVal == nEvents); + /* swap */ + tmp = fds; + fds = other_fds; + other_fds = tmp; + nfds = nextIndex; + i += nEvents; } printf("All tests finished\n"); diff --git a/nsprpub/pr/tests/randseed.c b/nsprpub/pr/tests/randseed.c index 45871777c..2ca14c7af 100644 --- a/nsprpub/pr/tests/randseed.c +++ b/nsprpub/pr/tests/randseed.c @@ -5,17 +5,17 @@ /* ** File: rngseed.c -** Description: +** Description: ** Test NSPR's Random Number Seed generator ** ** Initial test: Just make sure it outputs some data. -** +** ** ... more? ... check some iterations to ensure it is random (no dupes) ** ... more? ... histogram distribution of random numbers */ #include "plgetopt.h" -#include "nspr.h" +#include "nspr.h" #include "prrng.h" #include <stdio.h> #include <stdlib.h> @@ -55,22 +55,22 @@ static void PrintRand( void *buf, PRIntn size ) switch( size ) { case 1 : printf("%2.2X\n", *(rp++) ); - size -= 4; + size -= 4; break; case 2 : printf("%4.4X\n", *(rp++) ); - size -= 4; + size -= 4; break; case 3 : printf("%6.6X\n", *(rp++) ); - size -= 4; + size -= 4; break; default: while ( size >= 4) { PRIntn i = 3; do { printf("%8.8X ", *(rp++) ); - size -= 4; + size -= 4; } while( i-- ); i = 3; printf("\n"); @@ -90,26 +90,28 @@ int main(int argc, char **argv) PLOptStatus os; PLOptState *opt = PL_CreateOptState(argc, argv, "hdv"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug */ - debug = 1; - msgLevel = PR_LOG_ERROR; - break; - case 'v': /* verbose mode */ - msgLevel = PR_LOG_DEBUG; - break; - case 'h': /* help message */ - Help(); - break; - default: - break; + case 'd': /* debug */ + debug = 1; + msgLevel = PR_LOG_ERROR; + break; + case 'v': /* verbose mode */ + msgLevel = PR_LOG_DEBUG; + break; + case 'h': /* help message */ + Help(); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); } lm = PR_NewLogModule("Test"); /* Initialize logging */ @@ -121,10 +123,14 @@ int main(int argc, char **argv) failed_already = PR_TRUE; break; } - if (debug) PrintRand( buf, rSize ); + if (debug) { + PrintRand( buf, rSize ); + } } - if (debug) printf("%s\n", (failed_already)? "FAIL" : "PASS"); + if (debug) { + printf("%s\n", (failed_already)? "FAIL" : "PASS"); + } return( (failed_already == PR_TRUE )? 1 : 0 ); } /* main() */ /* end template.c */ diff --git a/nsprpub/pr/tests/ranfile.c b/nsprpub/pr/tests/ranfile.c index 08a4a98b8..a6dcc4ac4 100644 --- a/nsprpub/pr/tests/ranfile.c +++ b/nsprpub/pr/tests/ranfile.c @@ -12,12 +12,12 @@ ** Description: Test to hammer on various components of NSPR ** Modification History: ** 20-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ @@ -57,9 +57,9 @@ typedef struct Hammer_s { Problem problem; } Hammer_t; -#define DEFAULT_LIMIT 10 -#define DEFAULT_THREADS 2 -#define DEFAULT_LOOPS 1 +#define DEFAULT_LIMIT 10 +#define DEFAULT_THREADS 2 +#define DEFAULT_LOOPS 1 static PRInt32 pageSize = 1024; static const char* baseName = "./"; @@ -132,7 +132,9 @@ static void PR_CALLBACK Thread(void *arg) (void)sprintf(filename, "%ssg%04ld.dat", baseName, cd->id); - if (debug_mode) printf("Starting work on %s\n", filename); + if (debug_mode) { + printf("Starting work on %s\n", filename); + } while (PR_TRUE) { @@ -143,51 +145,75 @@ static void PR_CALLBACK Thread(void *arg) while (minor-- > 0) { cd->problem = sg_okay; - if (cd->action != sg_go) goto finished; + if (cd->action != sg_go) { + goto finished; + } cd->problem = sg_open; file = PR_Open(filename, PR_RDWR|PR_CREATE_FILE, 0666); - if (file == NULL) goto finished; + if (file == NULL) { + goto finished; + } for (index = 0; index < pages; index++) { cd->problem = sg_okay; - if (cd->action != sg_go) goto close; + if (cd->action != sg_go) { + goto close; + } cd->problem = sg_seek; bytes = PR_Seek(file, pageSize * index, PR_SEEK_SET); - if (bytes != pageSize * index) goto close; + if (bytes != pageSize * index) { + goto close; + } cd->problem = sg_write; bytes = PR_Write(file, &zero, sizeof(zero)); - if (bytes <= 0) goto close; + if (bytes <= 0) { + goto close; + } cd->writes += 1; } cd->problem = sg_close; rv = PR_Close(file); - if (rv != PR_SUCCESS) goto purge; + if (rv != PR_SUCCESS) { + goto purge; + } cd->problem = sg_okay; - if (cd->action != sg_go) goto purge; + if (cd->action != sg_go) { + goto purge; + } cd->problem = sg_open; file = PR_Open(filename, PR_RDWR, 0666); for (index = 0; index < pages; index++) { cd->problem = sg_okay; - if (cd->action != sg_go) goto close; + if (cd->action != sg_go) { + goto close; + } cd->problem = sg_seek; bytes = PR_Seek(file, pageSize * index, PR_SEEK_SET); - if (bytes != pageSize * index) goto close; + if (bytes != pageSize * index) { + goto close; + } cd->problem = sg_write; bytes = PR_Write(file, &zero, sizeof(zero)); - if (bytes <= 0) goto close; + if (bytes <= 0) { + goto close; + } cd->writes += 1; random = (random + 511) % pages; } cd->problem = sg_close; rv = PR_Close(file); - if (rv != PR_SUCCESS) goto purge; + if (rv != PR_SUCCESS) { + goto purge; + } cd->problem = sg_delete; rv = PR_Delete(filename); - if (rv != PR_SUCCESS) goto finished; - } + if (rv != PR_SUCCESS) { + goto finished; + } + } } close: @@ -200,7 +226,9 @@ finished: PR_NotifyCondVar(cd->cv); PR_Unlock(cd->ml); - if (debug_mode) printf("Ending work on %s\n", filename); + if (debug_mode) { + printf("Ending work on %s\n", filename); + } return; } /* Thread */ @@ -249,42 +277,44 @@ int main(int argc, char **argv) const char *where[] = {"okay", "open", "close", "delete", "write", "seek"}; - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "Gdl:t:i:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "Gdl:t:i:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'G': /* global threads */ - thread_scope = PR_GLOBAL_THREAD; - break; - case 'd': /* debug mode */ - debug_mode = 1; - break; - case 'l': /* limiting number */ - limit = atoi(opt->value); - break; - case 't': /* number of threads */ - threads = atoi(opt->value); - break; - case 'i': /* iteration counter */ - loops = atoi(opt->value); - break; - default: - break; + case 'G': /* global threads */ + thread_scope = PR_GLOBAL_THREAD; + break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + case 'l': /* limiting number */ + limit = atoi(opt->value); + break; + case 't': /* number of threads */ + threads = atoi(opt->value); + break; + case 'i': /* iteration counter */ + loops = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); @@ -293,18 +323,26 @@ int main(int argc, char **argv) ml = PR_NewLock(); cv = PR_NewCondVar(ml); - if (loops == 0) loops = DEFAULT_LOOPS; - if (limit == 0) limit = DEFAULT_LIMIT; - if (threads == 0) threads = DEFAULT_THREADS; + if (loops == 0) { + loops = DEFAULT_LOOPS; + } + if (limit == 0) { + limit = DEFAULT_LIMIT; + } + if (threads == 0) { + threads = DEFAULT_THREADS; + } if (debug_mode) printf( - "%s: Using loops = %d, threads = %d, limit = %d and %s threads\n", - programName, loops, threads, limit, - (thread_scope == PR_LOCAL_THREAD) ? "LOCAL" : "GLOBAL"); + "%s: Using loops = %d, threads = %d, limit = %d and %s threads\n", + programName, loops, threads, limit, + (thread_scope == PR_LOCAL_THREAD) ? "LOCAL" : "GLOBAL"); for (times = 0; times < loops; ++times) { - if (debug_mode) printf("%s: Setting concurrency level to %d\n", programName, times + 1); + if (debug_mode) { + printf("%s: Setting concurrency level to %d\n", programName, times + 1); + } PR_SetConcurrency(times + 1); for (active = 0; active < threads; active++) { @@ -317,9 +355,9 @@ int main(int argc, char **argv) hammer[active].limit = (RandomNum() % limit) + 1; hammer[active].timein = PR_IntervalNow(); hammer[active].thread = PR_CreateThread( - PR_USER_THREAD, Thread, &hammer[active], - PR_GetThreadPriority(PR_GetCurrentThread()), - thread_scope, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, Thread, &hammer[active], + PR_GetThreadPriority(PR_GetCurrentThread()), + thread_scope, PR_JOINABLE_THREAD, 0); PR_Lock(ml); PR_WaitCondVar(cv, interleave); /* start new ones slowly */ @@ -333,8 +371,9 @@ int main(int argc, char **argv) PR_Lock(ml); for (poll = 0; poll < threads; poll++) { - if (hammer[poll].action == sg_go) /* don't overwrite done */ - hammer[poll].action = sg_stop; /* ask him to stop */ + if (hammer[poll].action == sg_go) { /* don't overwrite done */ + hammer[poll].action = sg_stop; /* ask him to stop */ + } } PR_Unlock(ml); @@ -343,8 +382,9 @@ int main(int argc, char **argv) for (poll = 0; poll < threads; poll++) { PR_Lock(ml); - while (hammer[poll].action < sg_done) + while (hammer[poll].action < sg_done) { PR_WaitCondVar(cv, PR_INTERVAL_NO_TIMEOUT); + } PR_Unlock(ml); active -= 1; /* this is another one down */ @@ -353,38 +393,41 @@ int main(int argc, char **argv) if (hammer[poll].problem == sg_okay) { duration = PR_IntervalToMilliseconds( - PR_IntervalNow() - hammer[poll].timein); + PR_IntervalNow() - hammer[poll].timein); writes = hammer[poll].writes * 1000 / duration; - if (writes < writesMin) + if (writes < writesMin) { writesMin = writes; - if (writes > writesMax) + } + if (writes > writesMax) { writesMax = writes; + } writesTot += hammer[poll].writes; durationTot += duration; } - else - if (debug_mode) printf( + else if (debug_mode) printf( "%s: test failed %s after %ld seconds\n", programName, where[hammer[poll].problem], duration); - else failed_already=1; + else { + failed_already=1; + } } } } if (debug_mode) printf( - "%s: [%ld [%ld] %ld] writes/sec average\n", - programName, writesMin, writesTot * 1000 / durationTot, writesMax); + "%s: [%ld [%ld] %ld] writes/sec average\n", + programName, writesMin, writesTot * 1000 / durationTot, writesMax); PR_DestroyCondVar(cv); PR_DestroyLock(ml); - if (failed_already) - { - printf("FAIL\n"); - return 1; - } + if (failed_already) + { + printf("FAIL\n"); + return 1; + } else { printf("PASS\n"); - return 0; + return 0; } } /* main */ diff --git a/nsprpub/pr/tests/rmdir.c b/nsprpub/pr/tests/rmdir.c index e0c1eac8b..c1400d728 100644 --- a/nsprpub/pr/tests/rmdir.c +++ b/nsprpub/pr/tests/rmdir.c @@ -5,9 +5,9 @@ /* ** File: rmdir.c -** Description: Demonstrate bugzilla 80884. +** Description: Demonstrate bugzilla 80884. ** -** after fix to unix_errors.c, message should report correct +** after fix to unix_errors.c, message should report correct ** failure of PR_Rmdir(). ** ** @@ -24,7 +24,7 @@ #define FILENAME "file80883" PRBool failed_already = PR_FALSE; -PRBool debug_mode = PR_FALSE; +PRBool debug_mode = PR_FALSE; PRLogModuleInfo *lm; @@ -33,8 +33,8 @@ PRLogModuleInfo *lm; */ static void Help( void ) { fprintf(stderr, "template usage:\n" - "\t-d debug mode\n" - ); + "\t-d debug mode\n" + ); } /* --- end Help() */ int main(int argc, char **argv) @@ -46,7 +46,9 @@ int main(int argc, char **argv) /* parse command line options */ while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { case 'd': /* debug mode */ debug_mode = PR_TRUE; @@ -66,11 +68,11 @@ int main(int argc, char **argv) if (fd == 0) { PRErrorCode err = PR_GetError(); fprintf(stderr, "create file fails: %d: %s\n", err, - PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT)); + PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT)); failed_already = PR_TRUE; goto Finished; } - + PR_Close(fd); if (PR_RmDir( DIRNAME ) == PR_SUCCESS) { @@ -78,10 +80,10 @@ int main(int argc, char **argv) failed_already = PR_TRUE; goto Finished; } - + err = PR_GetError(); fprintf(stderr, "remove directory fails with: %d: %s\n", err, - PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT)); + PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT)); (void) PR_Delete( DIRNAME FILENAME); (void) PR_RmDir( DIRNAME ); @@ -89,7 +91,9 @@ int main(int argc, char **argv) return 0; Finished: - if ( debug_mode ) printf("%s\n", ( failed_already ) ? "FAILED" : "PASS" ); + if ( debug_mode ) { + printf("%s\n", ( failed_already ) ? "FAILED" : "PASS" ); + } return( (failed_already)? 1 : 0 ); } /* --- end main() */ /* --- end template.c */ diff --git a/nsprpub/pr/tests/runtests.sh b/nsprpub/pr/tests/runtests.sh index d021287b8..c570bf867 100755 --- a/nsprpub/pr/tests/runtests.sh +++ b/nsprpub/pr/tests/runtests.sh @@ -36,8 +36,6 @@ fi #dceemu - used to tests special functions in NSPR for DCE emulation #ipv6 - IPV6 not in use by NSPR clients #mbcs - tests use of multi-byte charset for filenames. See BugZilla #25140 -#sproc_ch - obsolete; sproc-based tests for Irix -#sproc_p - obsolete; sproc-based tests for Irix #io_timeoutk - obsolete; subsumed in io_timeout #io_timeoutu - obsolete; subsumed in io_timeout #prftest1 - obsolete; subsumed by prftest diff --git a/nsprpub/pr/tests/rwlockrank.c b/nsprpub/pr/tests/rwlockrank.c index 5872fa174..d77eb9680 100644 --- a/nsprpub/pr/tests/rwlockrank.c +++ b/nsprpub/pr/tests/rwlockrank.c @@ -64,13 +64,15 @@ int main(int argc, char **argv) PLOptState *opt = PL_CreateOptState(argc, argv, "d"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - _debug_on = 1; - break; - default: - break; + case 'd': /* debug mode */ + _debug_on = 1; + break; + default: + break; } } PL_DestroyOptState(opt); diff --git a/nsprpub/pr/tests/rwlocktest.c b/nsprpub/pr/tests/rwlocktest.c index d9368a4cd..396103c34 100644 --- a/nsprpub/pr/tests/rwlocktest.c +++ b/nsprpub/pr/tests/rwlocktest.c @@ -7,17 +7,17 @@ * * RWLock tests * - * Several threads are created to access and modify data arrays using - * PRRWLocks for synchronization. Two data arrays, array_A and array_B, are - * initialized with random data and a third array, array_C, is initialized - * with the sum of the first 2 arrays. + * Several threads are created to access and modify data arrays using + * PRRWLocks for synchronization. Two data arrays, array_A and array_B, are + * initialized with random data and a third array, array_C, is initialized + * with the sum of the first 2 arrays. + * + * Each one of the threads acquires a read lock to verify that the sum of + * the arrays A and B is equal to array C, and acquires a write lock to + * consistently update arrays A and B so that their is equal to array C. * - * Each one of the threads acquires a read lock to verify that the sum of - * the arrays A and B is equal to array C, and acquires a write lock to - * consistently update arrays A and B so that their is equal to array C. - * */ - + #include "nspr.h" #include "plgetopt.h" #include "prrwlock.h" @@ -29,181 +29,185 @@ static void update_array(void); static void check_array(void); typedef struct thread_args { - PRRWLock *rwlock; - PRInt32 loop_cnt; + PRRWLock *rwlock; + PRInt32 loop_cnt; } thread_args; PRFileDesc *output; PRFileDesc *errhandle; -#define DEFAULT_THREAD_CNT 4 -#define DEFAULT_LOOP_CNT 100 -#define TEST_ARRAY_SIZE 100 +#define DEFAULT_THREAD_CNT 4 +#define DEFAULT_LOOP_CNT 100 +#define TEST_ARRAY_SIZE 100 int main(int argc, char **argv) { PRInt32 cnt; - PRStatus rc; - PRInt32 i; + PRStatus rc; + PRInt32 i; - PRInt32 thread_cnt = DEFAULT_THREAD_CNT; - PRInt32 loop_cnt = DEFAULT_LOOP_CNT; - PRThread **threads; - thread_args *params; - PRRWLock *rwlock1; + PRInt32 thread_cnt = DEFAULT_THREAD_CNT; + PRInt32 loop_cnt = DEFAULT_LOOP_CNT; + PRThread **threads; + thread_args *params; + PRRWLock *rwlock1; - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "dt:c:"); + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "dt:c:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - _debug_on = 1; - break; - case 't': /* thread count */ - thread_cnt = atoi(opt->value); - break; - case 'c': /* loop count */ - loop_cnt = atoi(opt->value); - break; - default: - break; + case 'd': /* debug mode */ + _debug_on = 1; + break; + case 't': /* thread count */ + thread_cnt = atoi(opt->value); + break; + case 'c': /* loop count */ + loop_cnt = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); - PR_SetConcurrency(4); + PR_SetConcurrency(4); output = PR_GetSpecialFD(PR_StandardOutput); errhandle = PR_GetSpecialFD(PR_StandardError); - rwlock1 = PR_NewRWLock(0,"Lock 1"); - if (rwlock1 == NULL) { - PR_fprintf(errhandle, "PR_NewRWLock failed - error %d\n", - PR_GetError()); - return 1; - } - - threads = (PRThread**) PR_CALLOC(sizeof(PRThread*) * thread_cnt); - params = (thread_args *) PR_CALLOC(sizeof(thread_args) * thread_cnt); - - /* - * allocate and initialize data arrays - */ - array_A =(PRInt32 *) PR_MALLOC(sizeof(PRInt32) * TEST_ARRAY_SIZE); - array_B =(PRInt32 *) PR_MALLOC(sizeof(PRInt32) * TEST_ARRAY_SIZE); - array_C =(PRInt32 *) PR_MALLOC(sizeof(PRInt32) * TEST_ARRAY_SIZE); - cnt = 0; - for (i=0; i < TEST_ARRAY_SIZE;i++) { - array_A[i] = cnt++; - array_B[i] = cnt++; - array_C[i] = array_A[i] + array_B[i]; - } - - if (_debug_on) - PR_fprintf(output,"%s: thread_cnt = %d loop_cnt = %d\n", argv[0], - thread_cnt, loop_cnt); - for(cnt = 0; cnt < thread_cnt; cnt++) { - PRThreadScope scope; - - params[cnt].rwlock = rwlock1; - params[cnt].loop_cnt = loop_cnt; - - /* - * create LOCAL and GLOBAL threads alternately - */ - if (cnt & 1) - scope = PR_LOCAL_THREAD; - else - scope = PR_GLOBAL_THREAD; - - threads[cnt] = PR_CreateThread(PR_USER_THREAD, - rwtest, ¶ms[cnt], - PR_PRIORITY_NORMAL, - scope, - PR_JOINABLE_THREAD, - 0); - if (threads[cnt] == NULL) { - PR_fprintf(errhandle, "PR_CreateThread failed - error %d\n", - PR_GetError()); - PR_ProcessExit(2); - } - if (_debug_on) - PR_fprintf(output,"%s: created thread = %p\n", argv[0], - threads[cnt]); - } - - for(cnt = 0; cnt < thread_cnt; cnt++) { - rc = PR_JoinThread(threads[cnt]); - PR_ASSERT(rc == PR_SUCCESS); - - } - - PR_DELETE(threads); - PR_DELETE(params); - - PR_DELETE(array_A); - PR_DELETE(array_B); - PR_DELETE(array_C); - - PR_DestroyRWLock(rwlock1); - - - printf("PASS\n"); - return 0; + rwlock1 = PR_NewRWLock(0,"Lock 1"); + if (rwlock1 == NULL) { + PR_fprintf(errhandle, "PR_NewRWLock failed - error %d\n", + PR_GetError()); + return 1; + } + + threads = (PRThread**) PR_CALLOC(sizeof(PRThread*) * thread_cnt); + params = (thread_args *) PR_CALLOC(sizeof(thread_args) * thread_cnt); + + /* + * allocate and initialize data arrays + */ + array_A =(PRInt32 *) PR_MALLOC(sizeof(PRInt32) * TEST_ARRAY_SIZE); + array_B =(PRInt32 *) PR_MALLOC(sizeof(PRInt32) * TEST_ARRAY_SIZE); + array_C =(PRInt32 *) PR_MALLOC(sizeof(PRInt32) * TEST_ARRAY_SIZE); + cnt = 0; + for (i=0; i < TEST_ARRAY_SIZE; i++) { + array_A[i] = cnt++; + array_B[i] = cnt++; + array_C[i] = array_A[i] + array_B[i]; + } + + if (_debug_on) + PR_fprintf(output,"%s: thread_cnt = %d loop_cnt = %d\n", argv[0], + thread_cnt, loop_cnt); + for(cnt = 0; cnt < thread_cnt; cnt++) { + PRThreadScope scope; + + params[cnt].rwlock = rwlock1; + params[cnt].loop_cnt = loop_cnt; + + /* + * create LOCAL and GLOBAL threads alternately + */ + if (cnt & 1) { + scope = PR_LOCAL_THREAD; + } + else { + scope = PR_GLOBAL_THREAD; + } + + threads[cnt] = PR_CreateThread(PR_USER_THREAD, + rwtest, ¶ms[cnt], + PR_PRIORITY_NORMAL, + scope, + PR_JOINABLE_THREAD, + 0); + if (threads[cnt] == NULL) { + PR_fprintf(errhandle, "PR_CreateThread failed - error %d\n", + PR_GetError()); + PR_ProcessExit(2); + } + if (_debug_on) + PR_fprintf(output,"%s: created thread = %p\n", argv[0], + threads[cnt]); + } + + for(cnt = 0; cnt < thread_cnt; cnt++) { + rc = PR_JoinThread(threads[cnt]); + PR_ASSERT(rc == PR_SUCCESS); + + } + + PR_DELETE(threads); + PR_DELETE(params); + + PR_DELETE(array_A); + PR_DELETE(array_B); + PR_DELETE(array_C); + + PR_DestroyRWLock(rwlock1); + + + printf("PASS\n"); + return 0; } static void rwtest(void *args) { PRInt32 index; - thread_args *arg = (thread_args *) args; + thread_args *arg = (thread_args *) args; - for (index = 0; index < arg->loop_cnt; index++) { + for (index = 0; index < arg->loop_cnt; index++) { - /* - * verify sum, update arrays and verify sum again - */ + /* + * verify sum, update arrays and verify sum again + */ - PR_RWLock_Rlock(arg->rwlock); - check_array(); - PR_RWLock_Unlock(arg->rwlock); + PR_RWLock_Rlock(arg->rwlock); + check_array(); + PR_RWLock_Unlock(arg->rwlock); - PR_RWLock_Wlock(arg->rwlock); - update_array(); - PR_RWLock_Unlock(arg->rwlock); + PR_RWLock_Wlock(arg->rwlock); + update_array(); + PR_RWLock_Unlock(arg->rwlock); - PR_RWLock_Rlock(arg->rwlock); - check_array(); - PR_RWLock_Unlock(arg->rwlock); - } - if (_debug_on) - PR_fprintf(output, - "Thread[0x%x] lock = 0x%x exiting\n", - PR_GetCurrentThread(), arg->rwlock); + PR_RWLock_Rlock(arg->rwlock); + check_array(); + PR_RWLock_Unlock(arg->rwlock); + } + if (_debug_on) + PR_fprintf(output, + "Thread[0x%x] lock = 0x%x exiting\n", + PR_GetCurrentThread(), arg->rwlock); } static void check_array(void) { -PRInt32 i; + PRInt32 i; - for (i=0; i < TEST_ARRAY_SIZE;i++) - if (array_C[i] != (array_A[i] + array_B[i])) { - PR_fprintf(output, "Error - data check failed\n"); - PR_ProcessExit(1); - } + for (i=0; i < TEST_ARRAY_SIZE; i++) + if (array_C[i] != (array_A[i] + array_B[i])) { + PR_fprintf(output, "Error - data check failed\n"); + PR_ProcessExit(1); + } } static void update_array(void) { -PRInt32 i; + PRInt32 i; - for (i=0; i < TEST_ARRAY_SIZE;i++) { - array_A[i] += i; - array_B[i] -= i; - } + for (i=0; i < TEST_ARRAY_SIZE; i++) { + array_A[i] += i; + array_B[i] -= i; + } } diff --git a/nsprpub/pr/tests/sel_spd.c b/nsprpub/pr/tests/sel_spd.c index df5cd9c46..6c1704234 100644 --- a/nsprpub/pr/tests/sel_spd.c +++ b/nsprpub/pr/tests/sel_spd.c @@ -15,37 +15,23 @@ #include <stdio.h> #include <errno.h> #include <string.h> -#ifdef SYMBIAN -#include <getopt.h> -#endif #define PORT_BASE 19000 typedef struct timer_slot_t { - unsigned long d_connect; - unsigned long d_cl_data; - unsigned long d_sv_data; - unsigned long d_close; - unsigned long d_total; - unsigned long requests; + unsigned long d_connect; + unsigned long d_cl_data; + unsigned long d_sv_data; + unsigned long d_close; + unsigned long d_total; + unsigned long requests; } timer_slot_t; static long _iterations = 5; static long _client_data = 8192; -#ifdef SYMBIAN -/* - * Symbian OS does not scale well specially the requirement for thread stack - * space and buffer allocation space. It is easy to get into a fragmented - * memory and not be able to allocate thread stack or client/server data - * buffer. - */ -static long _server_data = (8*1024); -static long _threads_max = 10, _threads = 10; -#else static long _server_data = (128*1024); static long _threads_max = 10, _threads = 10; -#endif static int verbose=0; static PRMonitor *exit_cv; @@ -58,279 +44,286 @@ void tally_results(int); /* return the diff in microseconds */ unsigned long _delta(PRIntervalTime *start, PRIntervalTime *stop) { - /* - * Will C do the right thing with unsigned arithemtic? - */ - return PR_IntervalToMicroseconds(*stop - *start); + /* + * Will C do the right thing with unsigned arithemtic? + */ + return PR_IntervalToMicroseconds(*stop - *start); } int _readn(PRFileDesc *sock, char *buf, int len) { - int rem; - int bytes; + int rem; + int bytes; - for (rem=len; rem; rem -= bytes) { - bytes = PR_Recv(sock, buf+len-rem, rem, 0, PR_INTERVAL_NO_TIMEOUT); - if (bytes <= 0) + for (rem=len; rem; rem -= bytes) { + bytes = PR_Recv(sock, buf+len-rem, rem, 0, PR_INTERVAL_NO_TIMEOUT); + if (bytes <= 0) { return -1; - } - return len; + } + } + return len; } void _thread_exit(int id) { - PR_EnterMonitor(exit_cv); + PR_EnterMonitor(exit_cv); #ifdef DEBUG - fprintf(stdout, "Thread %d EXIT\n", id); + fprintf(stdout, "Thread %d EXIT\n", id); #endif - _thread_exit_count--; - if (_thread_exit_count == 0) { + _thread_exit_count--; + if (_thread_exit_count == 0) { #ifdef DEBUG - fprintf(stdout, "Thread %d EXIT triggered notify\n", id); + fprintf(stdout, "Thread %d EXIT triggered notify\n", id); #endif - PR_Notify(exit_cv); - } - PR_ExitMonitor(exit_cv); + PR_Notify(exit_cv); + } + PR_ExitMonitor(exit_cv); } void _server_thread(void *arg_id) { - void _client_thread(void *); - PRThread *thread; - int *id = (int *)arg_id; - PRFileDesc *sock; - PRSocketOptionData sockopt; - PRNetAddr sa; - PRFileDesc * newsock; - char *data_buffer = NULL; - int data_buffer_size; - int index; - PRIntervalTime start, - connect_done, - read_done, - write_done, - close_done; - + void _client_thread(void *); + int *id = (int *)arg_id; + PRFileDesc *sock; + PRSocketOptionData sockopt; + PRNetAddr sa; + PRFileDesc * newsock; + char *data_buffer = NULL; + int data_buffer_size; + int index; + PRIntervalTime start, + connect_done, + read_done, + write_done, + close_done; + #ifdef DEBUG - fprintf(stdout, "server thread %d alive\n", *id); + fprintf(stdout, "server thread %d alive\n", *id); #endif - data_buffer_size = (_client_data>_server_data?_client_data:_server_data); - - if ( (data_buffer = (char *)PR_Malloc(data_buffer_size * sizeof(char))) == NULL ) { - fprintf(stderr, "Error creating buffer in server thread %d\n", *id); - goto done; - } - - - if ( (sock = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Error creating socket in server thread %d\n", *id); - goto done; - } - - sockopt.option = PR_SockOpt_Reuseaddr; - sockopt.value.reuse_addr = PR_TRUE; - if ( PR_SetSocketOption(sock, &sockopt) == PR_FAILURE) { - fprintf(stderr, "Error setting socket option in server thread %d\n", *id); - goto done; - } - - memset(&sa, 0 , sizeof(sa)); - sa.inet.family = PR_AF_INET; - sa.inet.port = PR_htons(PORT_BASE + *id); - sa.inet.ip = PR_htonl(PR_INADDR_ANY); - - if ( PR_Bind(sock, &sa) < 0) { - fprintf(stderr, "Error binding socket in server thread %d errno = %d\n", *id, errno); - goto done; - } - - if ( PR_Listen(sock, 32) < 0 ) { - fprintf(stderr, "Error listening to socket in server thread %d\n", *id); - goto done; - } - - /* Tell the client to start */ - if ( (thread = PR_CreateThread(PR_USER_THREAD, - _client_thread, - id, - PR_PRIORITY_NORMAL, - scope2, - PR_UNJOINABLE_THREAD, - 0)) == NULL) - fprintf(stderr, "Error creating client thread %d\n", *id); - - for (index = 0; index< _iterations; index++) { + data_buffer_size = (_client_data>_server_data?_client_data:_server_data); + + if ( (data_buffer = (char *)PR_Malloc(data_buffer_size * sizeof(char))) == NULL ) { + fprintf(stderr, "Error creating buffer in server thread %d\n", *id); + goto done; + } + + + if ( (sock = PR_NewTCPSocket()) == NULL) { + fprintf(stderr, "Error creating socket in server thread %d\n", *id); + goto done; + } + + sockopt.option = PR_SockOpt_Reuseaddr; + sockopt.value.reuse_addr = PR_TRUE; + if ( PR_SetSocketOption(sock, &sockopt) == PR_FAILURE) { + fprintf(stderr, "Error setting socket option in server thread %d\n", *id); + goto done; + } + + memset(&sa, 0, sizeof(sa)); + sa.inet.family = PR_AF_INET; + sa.inet.port = PR_htons(PORT_BASE + *id); + sa.inet.ip = PR_htonl(PR_INADDR_ANY); + + if ( PR_Bind(sock, &sa) < 0) { + fprintf(stderr, "Error binding socket in server thread %d errno = %d\n", *id, errno); + goto done; + } + + if ( PR_Listen(sock, 32) < 0 ) { + fprintf(stderr, "Error listening to socket in server thread %d\n", *id); + goto done; + } + + /* Tell the client to start */ + if ( PR_CreateThread(PR_USER_THREAD, + _client_thread, + id, + PR_PRIORITY_NORMAL, + scope2, + PR_UNJOINABLE_THREAD, + 0) == NULL) { + fprintf(stderr, "Error creating client thread %d\n", *id); + } + + for (index = 0; index< _iterations; index++) { #ifdef DEBUG - fprintf(stdout, "server thread %d loop %d\n", *id, index); + fprintf(stdout, "server thread %d loop %d\n", *id, index); #endif - start = PR_IntervalNow(); + start = PR_IntervalNow(); - if ( (newsock = PR_Accept(sock, &sa, - PR_INTERVAL_NO_TIMEOUT)) == NULL) { - fprintf(stderr, "Error accepting connection %d in server thread %d\n", - index, *id); - goto done; - } + if ( (newsock = PR_Accept(sock, &sa, + PR_INTERVAL_NO_TIMEOUT)) == NULL) { + fprintf(stderr, "Error accepting connection %d in server thread %d\n", + index, *id); + goto done; + } #ifdef DEBUG - fprintf(stdout, "server thread %d got connection %d\n", *id, newsock); + fprintf(stdout, "server thread %d got connection %d\n", *id, newsock); #endif - connect_done = PR_IntervalNow(); - - if ( _readn(newsock, data_buffer, _client_data) < _client_data) { - fprintf(stderr, "Error reading client data for iteration %d in server thread %d\n", index, *id ); - goto done; - } + connect_done = PR_IntervalNow(); + + if ( _readn(newsock, data_buffer, _client_data) < _client_data) { + fprintf(stderr, "Error reading client data for iteration %d in server thread %d\n", index, *id ); + goto done; + } #ifdef DEBUG - fprintf(stdout, "server thread %d read %d bytes\n", *id, _client_data); + fprintf(stdout, "server thread %d read %d bytes\n", *id, _client_data); #endif - read_done = PR_IntervalNow(); + read_done = PR_IntervalNow(); - if ( PR_Send(newsock, data_buffer, _server_data, 0, - PR_INTERVAL_NO_TIMEOUT) < _server_data) { - fprintf(stderr, "Error sending client data for iteration %d in server thread %d\n", index, *id ); - goto done; - } + if ( PR_Send(newsock, data_buffer, _server_data, 0, + PR_INTERVAL_NO_TIMEOUT) < _server_data) { + fprintf(stderr, "Error sending client data for iteration %d in server thread %d\n", index, *id ); + goto done; + } #ifdef DEBUG - fprintf(stdout, "server thread %d write %d bytes\n", *id, _server_data); + fprintf(stdout, "server thread %d write %d bytes\n", *id, _server_data); #endif - write_done = PR_IntervalNow(); + write_done = PR_IntervalNow(); - PR_Close(newsock); + PR_Close(newsock); - close_done = PR_IntervalNow(); + close_done = PR_IntervalNow(); - timer_data[2*(*id)].d_connect += _delta(&start, &connect_done); - timer_data[2*(*id)].d_cl_data += _delta(&connect_done, &read_done); - timer_data[2*(*id)].d_sv_data += _delta(&read_done, &write_done); - timer_data[2*(*id)].d_close += _delta(&write_done, &close_done); - timer_data[2*(*id)].d_total += _delta(&start, &close_done); - timer_data[2*(*id)].requests++; + timer_data[2*(*id)].d_connect += _delta(&start, &connect_done); + timer_data[2*(*id)].d_cl_data += _delta(&connect_done, &read_done); + timer_data[2*(*id)].d_sv_data += _delta(&read_done, &write_done); + timer_data[2*(*id)].d_close += _delta(&write_done, &close_done); + timer_data[2*(*id)].d_total += _delta(&start, &close_done); + timer_data[2*(*id)].requests++; #ifdef DEBUG - fprintf(stdout, "server: %d %d %d %d %d\n", - _delta(&start, &connect_done), _delta(&connect_done, &read_done), - _delta(&read_done, &write_done), _delta(&write_done, &close_done), - _delta(&start, &close_done)); + fprintf(stdout, "server: %d %d %d %d %d\n", + _delta(&start, &connect_done), _delta(&connect_done, &read_done), + _delta(&read_done, &write_done), _delta(&write_done, &close_done), + _delta(&start, &close_done)); #endif - } + } done: - if (data_buffer != NULL) PR_Free (data_buffer); - if (sock) PR_Close(sock); - _thread_exit(*id); - return; + if (data_buffer != NULL) { + PR_Free (data_buffer); + } + if (sock) { + PR_Close(sock); + } + _thread_exit(*id); + return; } void _client_thread(void *arg_id) { - int *id = (int *)arg_id; - int index; - PRNetAddr sa; - PRFileDesc *sock_h; - char *data_buffer = NULL; - int data_buffer_size; - int bytes; - PRIntervalTime start, - connect_done, - read_done, - write_done, - close_done; - PRStatus rv; + int *id = (int *)arg_id; + int index; + PRNetAddr sa; + PRFileDesc *sock_h; + char *data_buffer = NULL; + int data_buffer_size; + int bytes; + PRIntervalTime start, + connect_done, + read_done, + write_done, + close_done; + PRStatus rv; #ifdef DEBUG - fprintf(stdout, "client thread %d alive\n", *id); + fprintf(stdout, "client thread %d alive\n", *id); #endif - data_buffer_size = (_client_data>_server_data?_client_data:_server_data); + data_buffer_size = (_client_data>_server_data?_client_data:_server_data); - if ( (data_buffer = (char *)PR_Malloc(data_buffer_size * sizeof(char))) == NULL) { - fprintf(stderr, "Error creating buffer in server thread %d\n", *id); - goto done; - } + if ( (data_buffer = (char *)PR_Malloc(data_buffer_size * sizeof(char))) == NULL) { + fprintf(stderr, "Error creating buffer in server thread %d\n", *id); + goto done; + } - memset(&sa, 0 , sizeof(sa)); - rv = PR_InitializeNetAddr(PR_IpAddrLoopback, PORT_BASE + *id, &sa); - PR_ASSERT(PR_SUCCESS == rv); - - for (index = 0; index< _iterations; index++) { + memset(&sa, 0, sizeof(sa)); + rv = PR_InitializeNetAddr(PR_IpAddrLoopback, PORT_BASE + *id, &sa); + PR_ASSERT(PR_SUCCESS == rv); + + for (index = 0; index< _iterations; index++) { #ifdef DEBUG - fprintf(stdout, "client thread %d loop %d\n", *id, index); + fprintf(stdout, "client thread %d loop %d\n", *id, index); #endif - start = PR_IntervalNow(); - if ( (sock_h = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Error creating socket %d in client thread %d\n", - index, *id); - goto done; - } + start = PR_IntervalNow(); + if ( (sock_h = PR_NewTCPSocket()) == NULL) { + fprintf(stderr, "Error creating socket %d in client thread %d\n", + index, *id); + goto done; + } #ifdef DEBUG - fprintf(stdout, "client thread %d socket created %d\n", *id, sock_h); + fprintf(stdout, "client thread %d socket created %d\n", *id, sock_h); #endif - if ( PR_Connect(sock_h, &sa, - PR_INTERVAL_NO_TIMEOUT) < 0) { - fprintf(stderr, "Error accepting connection %d in client thread %d\n", - index, *id); - goto done; - } + if ( PR_Connect(sock_h, &sa, + PR_INTERVAL_NO_TIMEOUT) < 0) { + fprintf(stderr, "Error accepting connection %d in client thread %d\n", + index, *id); + goto done; + } #ifdef DEBUG - fprintf(stdout, "client thread %d socket connected %d\n", *id, sock_h); + fprintf(stdout, "client thread %d socket connected %d\n", *id, sock_h); #endif - connect_done = PR_IntervalNow(); - if ( PR_Send(sock_h, data_buffer, _client_data, 0, - PR_INTERVAL_NO_TIMEOUT) < _client_data) { - fprintf(stderr, "Error sending client data for iteration %d in client thread %d\n", index, *id ); - goto done; - } + connect_done = PR_IntervalNow(); + if ( PR_Send(sock_h, data_buffer, _client_data, 0, + PR_INTERVAL_NO_TIMEOUT) < _client_data) { + fprintf(stderr, "Error sending client data for iteration %d in client thread %d\n", index, *id ); + goto done; + } #ifdef DEBUG - fprintf(stdout, "client thread %d socket wrote %d\n", *id, _client_data); + fprintf(stdout, "client thread %d socket wrote %d\n", *id, _client_data); #endif - write_done = PR_IntervalNow(); - if ( (bytes = _readn(sock_h, data_buffer, _server_data)) < _server_data) { - fprintf(stderr, "Error reading server data for iteration %d in client thread %d (read %d bytes)\n", index, *id, bytes ); - goto done; - } + write_done = PR_IntervalNow(); + if ( (bytes = _readn(sock_h, data_buffer, _server_data)) < _server_data) { + fprintf(stderr, "Error reading server data for iteration %d in client thread %d (read %d bytes)\n", index, *id, bytes ); + goto done; + } #ifdef DEBUG - fprintf(stdout, "client thread %d socket read %d\n", *id, _server_data); + fprintf(stdout, "client thread %d socket read %d\n", *id, _server_data); #endif - read_done = PR_IntervalNow(); - PR_Close(sock_h); - close_done = PR_IntervalNow(); - - timer_data[2*(*id)+1].d_connect += _delta(&start, &connect_done); - timer_data[2*(*id)+1].d_cl_data += _delta(&connect_done, &write_done); - timer_data[2*(*id)+1].d_sv_data += _delta(&write_done, &read_done); - timer_data[2*(*id)+1].d_close += _delta(&read_done, &close_done); - timer_data[2*(*id)+1].d_total += _delta(&start, &close_done); - timer_data[2*(*id)+1].requests++; - } + read_done = PR_IntervalNow(); + PR_Close(sock_h); + close_done = PR_IntervalNow(); + + timer_data[2*(*id)+1].d_connect += _delta(&start, &connect_done); + timer_data[2*(*id)+1].d_cl_data += _delta(&connect_done, &write_done); + timer_data[2*(*id)+1].d_sv_data += _delta(&write_done, &read_done); + timer_data[2*(*id)+1].d_close += _delta(&read_done, &close_done); + timer_data[2*(*id)+1].d_total += _delta(&start, &close_done); + timer_data[2*(*id)+1].requests++; + } done: - if (data_buffer != NULL) PR_Free (data_buffer); - _thread_exit(*id); + if (data_buffer != NULL) { + PR_Free (data_buffer); + } + _thread_exit(*id); - return; + return; } static @@ -338,31 +331,32 @@ void do_work(void) { int index; - _thread_exit_count = _threads * 2; - for (index=0; index<_threads; index++) { - PRThread *thread; - int *id = (int *)PR_Malloc(sizeof(int)); + _thread_exit_count = _threads * 2; + for (index=0; index<_threads; index++) { + int *id = (int *)PR_Malloc(sizeof(int)); + + *id = index; - *id = index; + if ( PR_CreateThread(PR_USER_THREAD, + _server_thread, + id, + PR_PRIORITY_NORMAL, + scope1, + PR_UNJOINABLE_THREAD, + 0) == NULL) { + fprintf(stderr, "Error creating server thread %d\n", index); + } + } - if ( (thread = PR_CreateThread(PR_USER_THREAD, - _server_thread, - id, - PR_PRIORITY_NORMAL, - scope1, - PR_UNJOINABLE_THREAD, - 0)) == NULL) - fprintf(stderr, "Error creating server thread %d\n", index); - } - - PR_EnterMonitor(exit_cv); - while (_thread_exit_count > 0) - PR_Wait(exit_cv, PR_INTERVAL_NO_TIMEOUT); - PR_ExitMonitor(exit_cv); + PR_EnterMonitor(exit_cv); + while (_thread_exit_count > 0) { + PR_Wait(exit_cv, PR_INTERVAL_NO_TIMEOUT); + } + PR_ExitMonitor(exit_cv); - fprintf(stdout, "TEST COMPLETE!\n"); + fprintf(stdout, "TEST COMPLETE!\n"); - tally_results(verbose); + tally_results(verbose); } @@ -414,47 +408,49 @@ static void Measure(void (*func)(void), const char *msg) int main(int argc, char **argv) { #if defined(XP_UNIX) || defined(XP_OS2) - int opt; - PR_IMPORT_DATA(char *) optarg; + int opt; + PR_IMPORT_DATA(char *) optarg; #endif #if defined(XP_UNIX) || defined(XP_OS2) - while ( (opt = getopt(argc, argv, "c:s:i:t:v")) != EOF) { - switch(opt) { - case 'i': - _iterations = atoi(optarg); - break; - case 't': - _threads_max = _threads = atoi(optarg); - break; - case 'c': - _client_data = atoi(optarg); - break; - case 's': - _server_data = atoi(optarg); - break; - case 'v': - verbose = 1; - break; - default: - break; - } - } + while ( (opt = getopt(argc, argv, "c:s:i:t:v")) != EOF) { + switch(opt) { + case 'i': + _iterations = atoi(optarg); + break; + case 't': + _threads_max = _threads = atoi(optarg); + break; + case 'c': + _client_data = atoi(optarg); + break; + case 's': + _server_data = atoi(optarg); + break; + case 'v': + verbose = 1; + break; + default: + break; + } + } #endif - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); + PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); - fprintf(stdout, "Running test for %d iterations with %d simultaneous threads.\n", - _iterations, _threads); - fprintf(stdout, "\tWill send %d bytes of client data and %d bytes of server data\n", - _client_data, _server_data); + fprintf(stdout, "Running test for %d iterations with %d simultaneous threads.\n", + _iterations, _threads); + fprintf(stdout, "\tWill send %d bytes of client data and %d bytes of server data\n", + _client_data, _server_data); - if ( (exit_cv = PR_NewMonitor()) == NULL) - fprintf(stderr, "Error creating monitor for exit cv\n"); - if ( (timer_data = (timer_slot_t *)PR_Malloc(2*_threads * sizeof(timer_slot_t))) == NULL) - fprintf(stderr, "error allocating thread time results array\n"); - memset(timer_data, 0 , 2*_threads*sizeof(timer_slot_t)); + if ( (exit_cv = PR_NewMonitor()) == NULL) { + fprintf(stderr, "Error creating monitor for exit cv\n"); + } + if ( (timer_data = (timer_slot_t *)PR_Malloc(2*_threads * sizeof(timer_slot_t))) == NULL) { + fprintf(stderr, "error allocating thread time results array\n"); + } + memset(timer_data, 0, 2*_threads*sizeof(timer_slot_t)); Measure(do_workUU, "select loop user/user"); Measure(do_workUK, "select loop user/kernel"); @@ -462,62 +458,62 @@ int main(int argc, char **argv) Measure(do_workKK, "select loop kernel/kernel"); - return 0; + return 0; } void tally_results(int verbose) { - int index; - unsigned long tot_connect = 0; - unsigned long tot_cl_data = 0; - unsigned long tot_sv_data = 0; - unsigned long tot_close = 0; - unsigned long tot_all = 0; - unsigned long tot_requests = 0; - - fprintf(stdout, "Server results:\n\n"); - for (index=0; index<_threads_max*2; index+=2) { - - if (verbose) - fprintf(stdout, "server thread %u\t%u\t%u\t%u\t%u\t%u\t%u\n", - index, timer_data[index].requests, timer_data[index].d_connect, - timer_data[index].d_cl_data, timer_data[index].d_sv_data, - timer_data[index].d_close, timer_data[index].d_total); - - tot_connect += timer_data[index].d_connect / _threads; - tot_cl_data += timer_data[index].d_cl_data / _threads; - tot_sv_data += timer_data[index].d_sv_data / _threads; - tot_close += timer_data[index].d_close / _threads; - tot_all += timer_data[index].d_total / _threads; - tot_requests += timer_data[index].requests / _threads; - } - fprintf(stdout, "----------\n"); - fprintf(stdout, "server per thread totals %u\t%u\t%u\t%u\t%u\n", - tot_requests, tot_connect, tot_cl_data, tot_sv_data, tot_close); - fprintf(stdout, "server per thread elapsed time %u\n", tot_all); - fprintf(stdout, "----------\n"); - - tot_connect = tot_cl_data = tot_sv_data = tot_close = tot_all = tot_requests = 0; - fprintf(stdout, "Client results:\n\n"); - for (index=1; index<_threads_max*2; index+=2) { - - if (verbose) - fprintf(stdout, "client thread %u\t%u\t%u\t%u\t%u\t%u\t%u\n", - index, timer_data[index].requests, timer_data[index].d_connect, - timer_data[index].d_cl_data, timer_data[index].d_sv_data, - timer_data[index].d_close, timer_data[index].d_total); - - tot_connect += timer_data[index].d_connect / _threads; - tot_cl_data += timer_data[index].d_cl_data / _threads; - tot_sv_data += timer_data[index].d_sv_data / _threads; - tot_close += timer_data[index].d_close / _threads; - tot_all += timer_data[index].d_total / _threads; - tot_requests += timer_data[index].requests / _threads; - } - fprintf(stdout, "----------\n"); - fprintf(stdout, "client per thread totals %u\t%u\t%u\t%u\t%u\n", - tot_requests, tot_connect, tot_cl_data, tot_sv_data, tot_close); - fprintf(stdout, "client per thread elapsed time %u\n", tot_all); + int index; + unsigned long tot_connect = 0; + unsigned long tot_cl_data = 0; + unsigned long tot_sv_data = 0; + unsigned long tot_close = 0; + unsigned long tot_all = 0; + unsigned long tot_requests = 0; + + fprintf(stdout, "Server results:\n\n"); + for (index=0; index<_threads_max*2; index+=2) { + + if (verbose) + fprintf(stdout, "server thread %u\t%u\t%u\t%u\t%u\t%u\t%u\n", + index, timer_data[index].requests, timer_data[index].d_connect, + timer_data[index].d_cl_data, timer_data[index].d_sv_data, + timer_data[index].d_close, timer_data[index].d_total); + + tot_connect += timer_data[index].d_connect / _threads; + tot_cl_data += timer_data[index].d_cl_data / _threads; + tot_sv_data += timer_data[index].d_sv_data / _threads; + tot_close += timer_data[index].d_close / _threads; + tot_all += timer_data[index].d_total / _threads; + tot_requests += timer_data[index].requests / _threads; + } + fprintf(stdout, "----------\n"); + fprintf(stdout, "server per thread totals %u\t%u\t%u\t%u\t%u\n", + tot_requests, tot_connect, tot_cl_data, tot_sv_data, tot_close); + fprintf(stdout, "server per thread elapsed time %u\n", tot_all); + fprintf(stdout, "----------\n"); + + tot_connect = tot_cl_data = tot_sv_data = tot_close = tot_all = tot_requests = 0; + fprintf(stdout, "Client results:\n\n"); + for (index=1; index<_threads_max*2; index+=2) { + + if (verbose) + fprintf(stdout, "client thread %u\t%u\t%u\t%u\t%u\t%u\t%u\n", + index, timer_data[index].requests, timer_data[index].d_connect, + timer_data[index].d_cl_data, timer_data[index].d_sv_data, + timer_data[index].d_close, timer_data[index].d_total); + + tot_connect += timer_data[index].d_connect / _threads; + tot_cl_data += timer_data[index].d_cl_data / _threads; + tot_sv_data += timer_data[index].d_sv_data / _threads; + tot_close += timer_data[index].d_close / _threads; + tot_all += timer_data[index].d_total / _threads; + tot_requests += timer_data[index].requests / _threads; + } + fprintf(stdout, "----------\n"); + fprintf(stdout, "client per thread totals %u\t%u\t%u\t%u\t%u\n", + tot_requests, tot_connect, tot_cl_data, tot_sv_data, tot_close); + fprintf(stdout, "client per thread elapsed time %u\n", tot_all); } diff --git a/nsprpub/pr/tests/selct_er.c b/nsprpub/pr/tests/selct_er.c index 85edb9897..0c5c46e08 100755 --- a/nsprpub/pr/tests/selct_er.c +++ b/nsprpub/pr/tests/selct_er.c @@ -12,23 +12,14 @@ ** ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ -#ifdef XP_BEOS -#include <stdio.h> -int main() -{ - printf( "This test is not ported to the BeOS\n" ); - return 0; -} -#else - /*********************************************************************** ** Includes ***********************************************************************/ @@ -57,92 +48,96 @@ int main(int argc, char **argv) char buf[128]; PRInt32 retVal; - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); if (debug_mode) { - printf("This program tests PR_Select with sockets. Error\n"); - printf("reporting operations are tested.\n\n"); - } + printf("This program tests PR_Select with sockets. Error\n"); + printf("reporting operations are tested.\n\n"); + } /* Create two listening sockets */ if ((listenSock1 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't create a new TCP socket\n"); + failed_already=1; + goto exit_now; } addr.inet.family = AF_INET; addr.inet.ip = PR_htonl(INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't bind socket\n"); + failed_already=1; + goto exit_now; } if (PR_GetSockName(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "PR_GetSockName failed\n"); + failed_already=1; + goto exit_now; } listenPort1 = PR_ntohs(addr.inet.port); if (PR_Listen(listenSock1, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't listen on a socket\n"); + failed_already=1; + goto exit_now; } if ((listenSock2 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't create a new TCP socket\n"); + failed_already=1; + goto exit_now; } addr.inet.family = AF_INET; addr.inet.ip = PR_htonl(INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't bind socket\n"); + failed_already=1; + goto exit_now; } if (PR_GetSockName(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "PR_GetSockName failed\n"); + failed_already=1; + goto exit_now; } listenPort2 = PR_ntohs(addr.inet.port); if (PR_Listen(listenSock2, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't listen on a socket\n"); + failed_already=1; + goto exit_now; } PR_snprintf(buf, sizeof(buf), - "The server thread is listening on ports %hu and %hu\n\n", - listenPort1, listenPort2); - if (debug_mode) printf("%s", buf); + "The server thread is listening on ports %hu and %hu\n\n", + listenPort1, listenPort2); + if (debug_mode) { + printf("%s", buf); + } /* Set up the fd set */ PR_FD_ZERO(&readFdSet); @@ -151,11 +146,13 @@ int main(int argc, char **argv) /* Testing bad fd */ - if (debug_mode) printf("PR_Select should detect a bad file descriptor\n"); + if (debug_mode) { + printf("PR_Select should detect a bad file descriptor\n"); + } if ((badFD = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a TCP socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't create a TCP socket\n"); + failed_already=1; + goto exit_now; } PR_FD_SET(badFD, &readFdSet); @@ -173,28 +170,31 @@ int main(int argc, char **argv) #endif retVal = PR_Select(0 /* unused */, &readFdSet, NULL, NULL, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); if (retVal != -1 || PR_GetError() != PR_BAD_DESCRIPTOR_ERROR) { - fprintf(stderr, "Failed to detect the bad fd: " - "PR_Select returns %d\n", retVal); - if (retVal == -1) { - fprintf(stderr, "Error %d, oserror %d\n", PR_GetError(), - PR_GetOSError()); - failed_already=1; - } - goto exit_now; - } - if (debug_mode) printf("PR_Select detected a bad fd. Test passed.\n\n"); - PR_FD_CLR(badFD, &readFdSet); - - PR_Cleanup(); - goto exit_now; + fprintf(stderr, "Failed to detect the bad fd: " + "PR_Select returns %d\n", retVal); + if (retVal == -1) { + fprintf(stderr, "Error %d, oserror %d\n", PR_GetError(), + PR_GetOSError()); + failed_already=1; + } + goto exit_now; + } + if (debug_mode) { + printf("PR_Select detected a bad fd. Test passed.\n\n"); + } + PR_FD_CLR(badFD, &readFdSet); + + PR_Cleanup(); + goto exit_now; exit_now: - if(failed_already) - return 1; - else - return 0; + if(failed_already) { + return 1; + } + else { + return 0; + } } -#endif /* XP_BEOS */ diff --git a/nsprpub/pr/tests/selct_nm.c b/nsprpub/pr/tests/selct_nm.c index 1b54c2afa..a698f0fa4 100644 --- a/nsprpub/pr/tests/selct_nm.c +++ b/nsprpub/pr/tests/selct_nm.c @@ -12,12 +12,12 @@ ** ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** @@ -57,10 +57,10 @@ clientThreadFunc(void *arg) PR_snprintf(buf, sizeof(buf), "%hu", addr.inet.port); for (i = 0; i < 5; i++) { - sock = PR_NewTCPSocket(); + sock = PR_NewTCPSocket(); PR_Connect(sock, &addr, PR_INTERVAL_NO_TIMEOUT); - PR_Write(sock, buf, sizeof(buf)); - PR_Close(sock); + PR_Write(sock, buf, sizeof(buf)); + PR_Close(sock); } } @@ -77,120 +77,124 @@ int main(int argc, char **argv) PRInt32 retVal; PRIntn i, j; - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); if (debug_mode) { - printf("This program tests PR_Select with sockets. \n"); - printf(" Normal operation are tested.\n\n"); - } + printf("This program tests PR_Select with sockets. \n"); + printf(" Normal operation are tested.\n\n"); + } /* Create two listening sockets */ if ((listenSock1 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't create a new TCP socket\n"); + failed_already=1; + goto exit_now; } addr.inet.family = PR_AF_INET; addr.inet.ip = PR_htonl(PR_INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't bind socket\n"); + failed_already=1; + goto exit_now; } if (PR_GetSockName(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "PR_GetSockName failed\n"); + failed_already=1; + goto exit_now; } listenPort1 = PR_ntohs(addr.inet.port); if (PR_Listen(listenSock1, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't listen on a socket\n"); + failed_already=1; + goto exit_now; } if ((listenSock2 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't create a new TCP socket\n"); + failed_already=1; + goto exit_now; } addr.inet.family = PR_AF_INET; addr.inet.ip = PR_htonl(PR_INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't bind socket\n"); + failed_already=1; + goto exit_now; } if (PR_GetSockName(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "PR_GetSockName failed\n"); + failed_already=1; + goto exit_now; } listenPort2 = PR_ntohs(addr.inet.port); if (PR_Listen(listenSock2, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); -failed_already=1; - goto exit_now; + fprintf(stderr, "Can't listen on a socket\n"); + failed_already=1; + goto exit_now; } PR_snprintf(buf, sizeof(buf), - "The server thread is listening on ports %hu and %hu\n\n", - listenPort1, listenPort2); - if (debug_mode) printf("%s", buf); + "The server thread is listening on ports %hu and %hu\n\n", + listenPort1, listenPort2); + if (debug_mode) { + printf("%s", buf); + } clientThread = PR_CreateThread(PR_USER_THREAD, - clientThreadFunc, (void *) listenPort1, - PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, 0); + clientThreadFunc, (void *) listenPort1, + PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, 0); if (clientThread == NULL) { - fprintf(stderr, "can't create thread\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "can't create thread\n"); + failed_already=1; + goto exit_now; } clientThread = PR_CreateThread(PR_USER_THREAD, - clientThreadFunc, (void *) listenPort2, - PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, 0); + clientThreadFunc, (void *) listenPort2, + PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, 0); if (clientThread == NULL) { - fprintf(stderr, "can't create thread\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "can't create thread\n"); + failed_already=1; + goto exit_now; } if (debug_mode) { - printf("Two client threads are created. Each of them will\n"); - printf("send data to one of the two ports the server is listening on.\n"); - printf("The data they send is the port number. Each of them send\n"); - printf("the data five times, so you should see ten lines below,\n"); - printf("interleaved in an arbitrary order.\n"); - } + printf("Two client threads are created. Each of them will\n"); + printf("send data to one of the two ports the server is listening on.\n"); + printf("The data they send is the port number. Each of them send\n"); + printf("the data five times, so you should see ten lines below,\n"); + printf("interleaved in an arbitrary order.\n"); + } /* set up the fd array */ fds = fds0; other_fds = fds1; @@ -205,80 +209,86 @@ failed_already=1; /* 20 events total */ i = 0; while (i < 20) { - PRFileDesc **tmp; - int nextIndex; - int nEvents = 0; + PRFileDesc **tmp; + int nextIndex; + int nEvents = 0; - retVal = PR_Select(0 /* unused */, &readFdSet, NULL, NULL, - PR_INTERVAL_NO_TIMEOUT); - PR_ASSERT(retVal != 0); /* no timeout */ - if (retVal == -1) { - fprintf(stderr, "PR_Select failed (%d, %d)\n", PR_GetError(), - PR_GetOSError()); - failed_already=1; - goto exit_now; - } + retVal = PR_Select(0 /* unused */, &readFdSet, NULL, NULL, + PR_INTERVAL_NO_TIMEOUT); + PR_ASSERT(retVal != 0); /* no timeout */ + if (retVal == -1) { + fprintf(stderr, "PR_Select failed (%d, %d)\n", PR_GetError(), + PR_GetOSError()); + failed_already=1; + goto exit_now; + } - nextIndex = 2; - /* the two listening sockets */ - for (j = 0; j < 2; j++) { - other_fds[j] = fds[j]; - if (PR_FD_ISSET(fds[j], &readFdSet)) { - PRFileDesc *sock; + nextIndex = 2; + /* the two listening sockets */ + for (j = 0; j < 2; j++) { + other_fds[j] = fds[j]; + if (PR_FD_ISSET(fds[j], &readFdSet)) { + PRFileDesc *sock; - nEvents++; - sock = PR_Accept(fds[j], NULL, PR_INTERVAL_NO_TIMEOUT); - if (sock == NULL) { - fprintf(stderr, "PR_Accept() failed\n"); - failed_already=1; - goto exit_now; - } - other_fds[nextIndex] = sock; - PR_FD_SET(sock, &readFdSet); - nextIndex++; - } - PR_FD_SET(fds[j], &readFdSet); - } + nEvents++; + sock = PR_Accept(fds[j], NULL, PR_INTERVAL_NO_TIMEOUT); + if (sock == NULL) { + fprintf(stderr, "PR_Accept() failed\n"); + failed_already=1; + goto exit_now; + } + other_fds[nextIndex] = sock; + PR_FD_SET(sock, &readFdSet); + nextIndex++; + } + PR_FD_SET(fds[j], &readFdSet); + } - for (j = 2; j < nfds; j++) { - if (PR_FD_ISSET(fds[j], &readFdSet)) { - PRInt32 nBytes; + for (j = 2; j < nfds; j++) { + if (PR_FD_ISSET(fds[j], &readFdSet)) { + PRInt32 nBytes; - PR_FD_CLR(fds[j], &readFdSet); - nEvents++; - nBytes = PR_Read(fds[j], buf, sizeof(buf)); - if (nBytes == -1) { - fprintf(stderr, "PR_Read() failed\n"); - failed_already=1; - goto exit_now; - } - /* Just to be safe */ - buf[127] = '\0'; - PR_Close(fds[j]); - if (debug_mode) printf("The server received \"%s\" from a client\n", buf); - } else { - PR_FD_SET(fds[j], &readFdSet); - other_fds[nextIndex] = fds[j]; - nextIndex++; - } - } + PR_FD_CLR(fds[j], &readFdSet); + nEvents++; + nBytes = PR_Read(fds[j], buf, sizeof(buf)); + if (nBytes == -1) { + fprintf(stderr, "PR_Read() failed\n"); + failed_already=1; + goto exit_now; + } + /* Just to be safe */ + buf[127] = '\0'; + PR_Close(fds[j]); + if (debug_mode) { + printf("The server received \"%s\" from a client\n", buf); + } + } else { + PR_FD_SET(fds[j], &readFdSet); + other_fds[nextIndex] = fds[j]; + nextIndex++; + } + } - PR_ASSERT(retVal == nEvents); - /* swap */ - tmp = fds; - fds = other_fds; - other_fds = tmp; - nfds = nextIndex; - i += nEvents; + PR_ASSERT(retVal == nEvents); + /* swap */ + tmp = fds; + fds = other_fds; + other_fds = tmp; + nfds = nextIndex; + i += nEvents; } - if (debug_mode) printf("Test passed\n"); + if (debug_mode) { + printf("Test passed\n"); + } PR_Cleanup(); - goto exit_now; + goto exit_now; exit_now: - if(failed_already) - return 1; - else - return 0; + if(failed_already) { + return 1; + } + else { + return 0; + } } diff --git a/nsprpub/pr/tests/selct_to.c b/nsprpub/pr/tests/selct_to.c index be0fb9e07..76ac99b2e 100644 --- a/nsprpub/pr/tests/selct_to.c +++ b/nsprpub/pr/tests/selct_to.c @@ -12,12 +12,12 @@ ** ** Modification History: ** 14-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** @@ -52,92 +52,96 @@ int main(int argc, char **argv) char buf[128]; PRInt32 retVal; - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); if (debug_mode) { - printf("This program tests PR_Select with sockets. Timeout \n"); - printf("operations are tested.\n\n"); - } + printf("This program tests PR_Select with sockets. Timeout \n"); + printf("operations are tested.\n\n"); + } /* Create two listening sockets */ if ((listenSock1 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't create a new TCP socket\n"); + failed_already=1; + goto exit_now; } addr.inet.family = PR_AF_INET; addr.inet.ip = PR_htonl(PR_INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't bind socket\n"); + failed_already=1; + goto exit_now; } if (PR_GetSockName(listenSock1, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "PR_GetSockName failed\n"); + failed_already=1; + goto exit_now; } listenPort1 = PR_ntohs(addr.inet.port); if (PR_Listen(listenSock1, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't listen on a socket\n"); + failed_already=1; + goto exit_now; } if ((listenSock2 = PR_NewTCPSocket()) == NULL) { - fprintf(stderr, "Can't create a new TCP socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't create a new TCP socket\n"); + failed_already=1; + goto exit_now; } addr.inet.family = PR_AF_INET; addr.inet.ip = PR_htonl(PR_INADDR_ANY); addr.inet.port = PR_htons(0); if (PR_Bind(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "Can't bind socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't bind socket\n"); + failed_already=1; + goto exit_now; } if (PR_GetSockName(listenSock2, &addr) == PR_FAILURE) { - fprintf(stderr, "PR_GetSockName failed\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "PR_GetSockName failed\n"); + failed_already=1; + goto exit_now; } listenPort2 = PR_ntohs(addr.inet.port); if (PR_Listen(listenSock2, 5) == PR_FAILURE) { - fprintf(stderr, "Can't listen on a socket\n"); - failed_already=1; - goto exit_now; + fprintf(stderr, "Can't listen on a socket\n"); + failed_already=1; + goto exit_now; } PR_snprintf(buf, sizeof(buf), - "The server thread is listening on ports %hu and %hu\n\n", - listenPort1, listenPort2); - if (debug_mode) printf("%s", buf); + "The server thread is listening on ports %hu and %hu\n\n", + listenPort1, listenPort2); + if (debug_mode) { + printf("%s", buf); + } /* Set up the fd set */ PR_FD_ZERO(&readFdSet); @@ -145,28 +149,34 @@ int main(int argc, char **argv) PR_FD_SET(listenSock2, &readFdSet); /* Testing timeout */ - if (debug_mode) printf("PR_Select should time out in 5 seconds\n"); + if (debug_mode) { + printf("PR_Select should time out in 5 seconds\n"); + } retVal = PR_Select(0 /* unused */, &readFdSet, NULL, NULL, - PR_SecondsToInterval(5)); + PR_SecondsToInterval(5)); if (retVal != 0) { - PR_snprintf(buf, sizeof(buf), - "PR_Select should time out and return 0, but it returns %ld\n", - retVal); - fprintf(stderr, "%s", buf); - if (retVal == -1) { - fprintf(stderr, "Error %d, oserror %d\n", PR_GetError(), - PR_GetOSError()); - failed_already=1; - } - goto exit_now; - } - if (debug_mode) printf("PR_Select timed out. Test passed.\n\n"); + PR_snprintf(buf, sizeof(buf), + "PR_Select should time out and return 0, but it returns %ld\n", + retVal); + fprintf(stderr, "%s", buf); + if (retVal == -1) { + fprintf(stderr, "Error %d, oserror %d\n", PR_GetError(), + PR_GetOSError()); + failed_already=1; + } + goto exit_now; + } + if (debug_mode) { + printf("PR_Select timed out. Test passed.\n\n"); + } PR_Cleanup(); exit_now: - if(failed_already) - return 1; - else - return 0; + if(failed_already) { + return 1; + } + else { + return 0; + } } diff --git a/nsprpub/pr/tests/select2.c b/nsprpub/pr/tests/select2.c index d82bb1ef9..da7360b02 100644 --- a/nsprpub/pr/tests/select2.c +++ b/nsprpub/pr/tests/select2.c @@ -11,10 +11,10 @@ ** ** Modification History: ** 20-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ***********************************************************************/ /*********************************************************************** @@ -40,34 +40,34 @@ PRInt32 count; /*********************************************************************** ** PRIVATE FUNCTION: Test_Result ** DESCRIPTION: Used in conjunction with the regress tool, prints out the -** status of the test case. +** status of the test case. ** INPUTS: PASS/FAIL ** OUTPUTS: None ** RETURN: None ** SIDE EFFECTS: -** +** ** RESTRICTIONS: ** None ** MEMORY: NA ** ALGORITHM: Determine what the status is and print accordingly. -** +** ***********************************************************************/ static void Test_Result (int result) { - switch (result) - { - case PASS: - printf ("PASS\n"); - break; - case FAIL: - printf ("FAIL\n"); - break; - default: - printf ("NOSTATUS\n"); - break; - } + switch (result) + { + case PASS: + printf ("PASS\n"); + break; + case FAIL: + printf ("FAIL\n"); + break; + default: + printf ("NOSTATUS\n"); + break; + } } static void EmptyPRSelect(void) @@ -75,8 +75,9 @@ static void EmptyPRSelect(void) PRInt32 index = count; PRInt32 rv; - for (; index--;) + for (; index--;) { rv = PR_Select(0, NULL, NULL, NULL, PR_INTERVAL_NO_WAIT); + } } static void EmptyNativeSelect(void) @@ -86,8 +87,9 @@ static void EmptyNativeSelect(void) struct timeval timeout; timeout.tv_sec = timeout.tv_usec = 0; - for (; index--;) + for (; index--;) { rv = select(0, NULL, NULL, NULL, &timeout); + } } static void PRSelectTest(void) @@ -96,7 +98,9 @@ static void PRSelectTest(void) PRNetAddr serverAddr; if ( (listenSocket = PR_NewTCPSocket()) == NULL) { - if (debug_mode) printf("\tServer error creating listen socket\n"); + if (debug_mode) { + printf("\tServer error creating listen socket\n"); + } return; } @@ -106,17 +110,23 @@ static void PRSelectTest(void) serverAddr.inet.ip = PR_htonl(INADDR_ANY); if ( PR_Bind(listenSocket, &serverAddr) == PR_FAILURE) { - if (debug_mode) printf("\tServer error binding to server address\n"); + if (debug_mode) { + printf("\tServer error binding to server address\n"); + } PR_Close(listenSocket); return; } if ( PR_Listen(listenSocket, 128) == PR_FAILURE) { - if (debug_mode) printf("\tServer error listening to server socket\n"); + if (debug_mode) { + printf("\tServer error listening to server socket\n"); + } PR_Close(listenSocket); return; } - if (debug_mode) printf("Listening on port %d\n", PORT); + if (debug_mode) { + printf("Listening on port %d\n", PORT); + } { PRFileDesc *newSock; @@ -129,40 +139,60 @@ static void PRSelectTest(void) loops++; - if (debug_mode) printf("Going into accept\n"); + if (debug_mode) { + printf("Going into accept\n"); + } - newSock = PR_Accept(listenSocket, - &rAddr, - PR_INTERVAL_NO_TIMEOUT); + newSock = PR_Accept(listenSocket, + &rAddr, + PR_INTERVAL_NO_TIMEOUT); - if (newSock) { - if (debug_mode) printf("Got connection!\n"); + if (newSock) { + if (debug_mode) { + printf("Got connection!\n"); + } } else { - if (debug_mode) printf("PR_Accept failed: error code %d\n", PR_GetError()); - else Test_Result (FAIL); + if (debug_mode) { + printf("PR_Accept failed: error code %d\n", PR_GetError()); + } + else { + Test_Result (FAIL); + } } PR_FD_ZERO(&rdset); PR_FD_SET(newSock, &rdset); - if (debug_mode) printf("Going into select \n"); + if (debug_mode) { + printf("Going into select \n"); + } rv = PR_Select(0, &rdset, 0, 0, PR_INTERVAL_NO_TIMEOUT); - if (debug_mode) printf("return from select is %d\n", rv); + if (debug_mode) { + printf("return from select is %d\n", rv); + } if (PR_FD_ISSET(newSock, &rdset)) { - if (debug_mode) printf("I can't believe it- the socket is ready okay!\n"); + if (debug_mode) { + printf("I can't believe it- the socket is ready okay!\n"); + } } else { - if (debug_mode) printf("Damn; the select test failed...\n"); - else Test_Result (FAIL); + if (debug_mode) { + printf("Damn; the select test failed...\n"); + } + else { + Test_Result (FAIL); + } } strcpy(buf, "XXXXXXXXXX"); bytesRead = PR_Recv(newSock, buf, 10, 0, PR_INTERVAL_NO_TIMEOUT); - buf[10] = '\0'; + buf[10] = '\0'; - if (debug_mode) printf("Recv completed with %d bytes, %s\n", bytesRead, buf); + if (debug_mode) { + printf("Recv completed with %d bytes, %s\n", bytesRead, buf); + } PR_Close(newSock); } @@ -177,7 +207,9 @@ static void NativeSelectTest(void) PRNetAddr serverAddr; if ( (listenSocket = PR_NewTCPSocket()) == NULL) { - if (debug_mode) printf("\tServer error creating listen socket\n"); + if (debug_mode) { + printf("\tServer error creating listen socket\n"); + } return; } @@ -187,17 +219,23 @@ static void NativeSelectTest(void) serverAddr.inet.ip = PR_htonl(INADDR_ANY); if ( PR_Bind(listenSocket, &serverAddr) == PR_FAILURE) { - if (debug_mode) printf("\tServer error binding to server address\n"); + if (debug_mode) { + printf("\tServer error binding to server address\n"); + } PR_Close(listenSocket); return; } if ( PR_Listen(listenSocket, 128) == PR_FAILURE) { - if (debug_mode) printf("\tServer error listening to server socket\n"); + if (debug_mode) { + printf("\tServer error listening to server socket\n"); + } PR_Close(listenSocket); return; } - if (debug_mode) printf("Listening on port %d\n", PORT); + if (debug_mode) { + printf("Listening on port %d\n", PORT); + } { PRIntn osfd; @@ -210,42 +248,61 @@ static void NativeSelectTest(void) loops++; - if (debug_mode) printf("Going into accept\n"); + if (debug_mode) { + printf("Going into accept\n"); + } newSock = PR_Accept(listenSocket, &rAddr, PR_INTERVAL_NO_TIMEOUT); - if (newSock) { - if (debug_mode) printf("Got connection!\n"); + if (newSock) { + if (debug_mode) { + printf("Got connection!\n"); + } } else { - if (debug_mode) printf("PR_Accept failed: error code %d\n", PR_GetError()); - else Test_Result (FAIL); + if (debug_mode) { + printf("PR_Accept failed: error code %d\n", PR_GetError()); + } + else { + Test_Result (FAIL); + } } osfd = PR_FileDesc2NativeHandle(newSock); FD_ZERO(&rdset); FD_SET(osfd, &rdset); - if (debug_mode) printf("Going into select \n"); + if (debug_mode) { + printf("Going into select \n"); + } timeout.tv_sec = 2; timeout.tv_usec = 0; rv = select(osfd + 1, &rdset, NULL, NULL, &timeout); - if (debug_mode) printf("return from select is %d\n", rv); + if (debug_mode) { + printf("return from select is %d\n", rv); + } if (FD_ISSET(osfd, &rdset)) { - if (debug_mode) + if (debug_mode) { printf("I can't believe it- the socket is ready okay!\n"); + } } else { - if (debug_mode) printf("Damn; the select test failed...\n"); - else Test_Result (FAIL); + if (debug_mode) { + printf("Damn; the select test failed...\n"); + } + else { + Test_Result (FAIL); + } } strcpy(buf, "XXXXXXXXXX"); bytesRead = PR_Recv(newSock, buf, 10, 0, PR_INTERVAL_NO_TIMEOUT); - buf[10] = '\0'; + buf[10] = '\0'; - if (debug_mode) printf("Recv completed with %d bytes, %s\n", bytesRead, buf); + if (debug_mode) { + printf("Recv completed with %d bytes, %s\n", bytesRead, buf); + } PR_Close(newSock); } @@ -269,43 +326,47 @@ static void Measure(void (*func)(void), const char *msg) d = (double)PR_IntervalToMicroseconds(stop - start); tot = PR_IntervalToMilliseconds(stop-start); - if (debug_mode) printf("%40s: %6.2f usec avg, %d msec total\n", msg, d / count, tot); + if (debug_mode) { + printf("%40s: %6.2f usec avg, %d msec total\n", msg, d / count, tot); + } } int main(int argc, char **argv) { - - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); if (argc > 2) { - count = atoi(argv[2]); + count = atoi(argv[2]); } else { - count = DEFAULT_COUNT; + count = DEFAULT_COUNT; } #if defined(XP_UNIX) @@ -315,7 +376,9 @@ int main(int argc, char **argv) Measure(EmptyNativeSelect, "time to call Empty select()"); Measure(PRSelectTest, "time to call 1 element PR_select()"); - if (!debug_mode) Test_Result (NOSTATUS); + if (!debug_mode) { + Test_Result (NOSTATUS); + } PR_Cleanup(); diff --git a/nsprpub/pr/tests/selintr.c b/nsprpub/pr/tests/selintr.c index 13621f74e..84513f688 100644 --- a/nsprpub/pr/tests/selintr.c +++ b/nsprpub/pr/tests/selintr.c @@ -29,9 +29,6 @@ int main() #include <sys/time.h> #include <stdio.h> -#ifdef SYMBIAN -#include <sys/select.h> -#endif int main(int argc, char **argv) { diff --git a/nsprpub/pr/tests/sem.c b/nsprpub/pr/tests/sem.c index ec7bb6e2c..80db76d2e 100644 --- a/nsprpub/pr/tests/sem.c +++ b/nsprpub/pr/tests/sem.c @@ -11,12 +11,12 @@ ** ** Modification History: ** 20-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** @@ -35,9 +35,9 @@ PRIntn failed_already=0; PRIntn debug_mode; -/* - Since we don't have stdin, stdout everywhere, we will fake - it with our in-memory buffers called stdin and stdout. +/* + Since we don't have stdin, stdout everywhere, we will fake + it with our in-memory buffers called stdin and stdout. */ #define SBSIZE 1024 @@ -54,156 +54,169 @@ static PRStatus finalResult = PR_SUCCESS; static size_t dread (PRUintn device, char *buf, size_t bufSize) { - PRUintn i; - - /* during first read call, initialize the stdinBuf buffer*/ - if (stdinBufIdx == 0) { - for (i=0; i<SBSIZE; i++) - stdinBuf[i] = i; - } - - /* now copy data from stdinBuf to the given buffer upto bufSize */ - for (i=0; i<bufSize; i++) { - if (stdinBufIdx == SBSIZE) - break; - buf[i] = stdinBuf[stdinBufIdx++]; - } - - return i; + PRUintn i; + + /* during first read call, initialize the stdinBuf buffer*/ + if (stdinBufIdx == 0) { + for (i=0; i<SBSIZE; i++) { + stdinBuf[i] = i; + } + } + + /* now copy data from stdinBuf to the given buffer upto bufSize */ + for (i=0; i<bufSize; i++) { + if (stdinBufIdx == SBSIZE) { + break; + } + buf[i] = stdinBuf[stdinBufIdx++]; + } + + return i; } static size_t dwrite (PRUintn device, char *buf, size_t bufSize) { - PRUintn i, j; - - /* copy data from the given buffer upto bufSize to stdoutBuf */ - for (i=0; i<bufSize; i++) { - if (stdoutBufIdx == SBSIZE) - break; - stdoutBuf[stdoutBufIdx++] = buf[i]; - } - - /* during last write call, compare the two buffers */ - if (stdoutBufIdx == SBSIZE) - for (j=0; j<SBSIZE; j++) - if (stdinBuf[j] != stdoutBuf[j]) { - if (debug_mode) printf("data mismatch for index= %d \n", j); - finalResult = PR_FAILURE; - } - - return i; + PRUintn i, j; + + /* copy data from the given buffer upto bufSize to stdoutBuf */ + for (i=0; i<bufSize; i++) { + if (stdoutBufIdx == SBSIZE) { + break; + } + stdoutBuf[stdoutBufIdx++] = buf[i]; + } + + /* during last write call, compare the two buffers */ + if (stdoutBufIdx == SBSIZE) + for (j=0; j<SBSIZE; j++) + if (stdinBuf[j] != stdoutBuf[j]) { + if (debug_mode) { + printf("data mismatch for index= %d \n", j); + } + finalResult = PR_FAILURE; + } + + return i; } /*------------------ Following is the real test program ---------*/ /* - Program to copy standard input to standard output. The program - uses two threads. One reads the input and puts the data in a - double buffer. The other reads the buffer contents and writes - it to standard output. + Program to copy standard input to standard output. The program + uses two threads. One reads the input and puts the data in a + double buffer. The other reads the buffer contents and writes + it to standard output. */ -PRSemaphore *emptyBufs; /* number of empty buffers */ -PRSemaphore *fullBufs; /* number of buffers that are full */ +PRSemaphore *emptyBufs; /* number of empty buffers */ +PRSemaphore *fullBufs; /* number of buffers that are full */ -#define BSIZE 100 +#define BSIZE 100 struct { - char data[BSIZE]; - PRUintn nbytes; /* number of bytes in this buffer */ + char data[BSIZE]; + PRUintn nbytes; /* number of bytes in this buffer */ } buf[2]; static void PR_CALLBACK reader(void *arg) { - PRUintn i = 0; - size_t nbytes; - - do { - (void) PR_WaitSem(emptyBufs); - nbytes = dread(0, buf[i].data, BSIZE); - buf[i].nbytes = nbytes; - PR_PostSem(fullBufs); - i = (i + 1) % 2; - } while (nbytes > 0); + PRUintn i = 0; + size_t nbytes; + + do { + (void) PR_WaitSem(emptyBufs); + nbytes = dread(0, buf[i].data, BSIZE); + buf[i].nbytes = nbytes; + PR_PostSem(fullBufs); + i = (i + 1) % 2; + } while (nbytes > 0); } static void writer(void) { - PRUintn i = 0; - size_t nbytes; - - do { - (void) PR_WaitSem(fullBufs); - nbytes = buf[i].nbytes; - if (nbytes > 0) { - nbytes = dwrite(1, buf[i].data, nbytes); - PR_PostSem(emptyBufs); - i = (i + 1) % 2; - } - } while (nbytes > 0); + PRUintn i = 0; + size_t nbytes; + + do { + (void) PR_WaitSem(fullBufs); + nbytes = buf[i].nbytes; + if (nbytes > 0) { + nbytes = dwrite(1, buf[i].data, nbytes); + PR_PostSem(emptyBufs); + i = (i + 1) % 2; + } + } while (nbytes > 0); } int main(int argc, char **argv) { - PRThread *r; + PRThread *r; PR_STDIO_INIT(); PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); { - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); - } + PL_DestroyOptState(opt); + } - /* main test */ + /* main test */ - emptyBufs = PR_NewSem(2); /* two empty buffers */ + emptyBufs = PR_NewSem(2); /* two empty buffers */ - fullBufs = PR_NewSem(0); /* zero full buffers */ + fullBufs = PR_NewSem(0); /* zero full buffers */ - /* create the reader thread */ - - r = PR_CreateThread(PR_USER_THREAD, - reader, 0, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, - 0); + /* create the reader thread */ - /* Do the writer operation in this thread */ - writer(); + r = PR_CreateThread(PR_USER_THREAD, + reader, 0, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, + 0); - PR_DestroySem(emptyBufs); - PR_DestroySem(fullBufs); + /* Do the writer operation in this thread */ + writer(); - if (finalResult == PR_SUCCESS) { - if (debug_mode) printf("sem Test Passed.\n"); - } - else{ - if (debug_mode) printf("sem Test Failed.\n"); - failed_already=1; - } + PR_DestroySem(emptyBufs); + PR_DestroySem(fullBufs); + + if (finalResult == PR_SUCCESS) { + if (debug_mode) { + printf("sem Test Passed.\n"); + } + } + else { + if (debug_mode) { + printf("sem Test Failed.\n"); + } + failed_already=1; + } PR_Cleanup(); - if(failed_already) - return 1; - else - return 0; + if(failed_already) { + return 1; + } + else { + return 0; + } } diff --git a/nsprpub/pr/tests/sema.c b/nsprpub/pr/tests/sema.c index 915fa30f8..76198eb04 100644 --- a/nsprpub/pr/tests/sema.c +++ b/nsprpub/pr/tests/sema.c @@ -31,7 +31,9 @@ void ThreadFunc(void *arg) exit(1); } if (counter == 2*i+1) { - if (debug_mode) printf("thread 2: counter = %d\n", counter); + if (debug_mode) { + printf("thread 2: counter = %d\n", counter); + } } else { fprintf(stderr, "thread 2: counter should be %d but is %d\n", 2*i+1, counter); @@ -61,7 +63,9 @@ int main(int argc, char **argv) PLOptState *opt = PL_CreateOptState(argc, argv, "dc:h"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { case 'd': /* debug mode */ debug_mode = PR_TRUE; @@ -98,7 +102,7 @@ int main(int argc, char **argv) exit(1); } thred = PR_CreateThread(PR_USER_THREAD, ThreadFunc, NULL, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); if (NULL == thred) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); @@ -113,7 +117,9 @@ int main(int argc, char **argv) exit(1); } if (counter == 2*i) { - if (debug_mode) printf("thread 1: counter = %d\n", counter); + if (debug_mode) { + printf("thread 1: counter = %d\n", counter); + } } else { fprintf(stderr, "thread 1: counter should be %d but is %d\n", 2*i, counter); diff --git a/nsprpub/pr/tests/semaerr.c b/nsprpub/pr/tests/semaerr.c index b27428f30..4e6a8ff27 100644 --- a/nsprpub/pr/tests/semaerr.c +++ b/nsprpub/pr/tests/semaerr.c @@ -8,15 +8,9 @@ #include <stdio.h> -#ifdef SYMBIAN -#define NO_SUCH_SEM_NAME "c:\\data\\nosuchsem.sem" -#define SEM_NAME1 "c:\\data\\foo.sem" -#define EXE_NAME "nspr_tests_semaerr1.exe" -#else #define NO_SUCH_SEM_NAME "/tmp/nosuchsem.sem" #define SEM_NAME1 "/tmp/foo.sem" #define EXE_NAME "semaerr1" -#endif #define SEM_MODE 0666 static PRBool debug_mode = PR_FALSE; @@ -39,7 +33,9 @@ int main(int argc, char **argv) PRInt32 exit_code; while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { case 'd': /* debug mode */ debug_mode = PR_TRUE; diff --git a/nsprpub/pr/tests/semaerr1.c b/nsprpub/pr/tests/semaerr1.c index fd1463dbc..b2e498723 100644 --- a/nsprpub/pr/tests/semaerr1.c +++ b/nsprpub/pr/tests/semaerr1.c @@ -8,13 +8,8 @@ #include <stdio.h> -#ifdef SYMBIAN -#define SEM_NAME1 "c:\\data\\foo.sem" -#define SEM_NAME2 "c:\\data\\bar.sem" -#else #define SEM_NAME1 "/tmp/foo.sem" #define SEM_NAME2 "/tmp/bar.sem" -#endif #define SEM_MODE 0666 static PRBool debug_mode = PR_FALSE; @@ -33,7 +28,9 @@ int main(int argc, char **argv) PRSem *sem; while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { case 'd': /* debug mode */ debug_mode = PR_TRUE; @@ -64,7 +61,7 @@ int main(int argc, char **argv) fprintf(stderr, "PR_DeleteSemaphore failed\n"); exit(1); } - + /* * Opening an existing semaphore with PR_SEM_CREATE|PR_SEM_EXCL. * should fail with PR_FILE_EXISTS_ERROR. diff --git a/nsprpub/pr/tests/semaping.c b/nsprpub/pr/tests/semaping.c index 007a5239c..2f31bd0bc 100644 --- a/nsprpub/pr/tests/semaping.c +++ b/nsprpub/pr/tests/semaping.c @@ -8,17 +8,10 @@ #include <stdio.h> -#ifdef SYMBIAN -#define SHM_NAME "c:\\data\\counter" -#define SEM_NAME1 "c:\\data\\foo.sem" -#define SEM_NAME2 "c:\\data\\bar.sem" -#define EXE_NAME "nspr_tests_semapong.exe" -#else #define SHM_NAME "/tmp/counter" #define SEM_NAME1 "/tmp/foo.sem" #define SEM_NAME2 "/tmp/bar.sem" #define EXE_NAME "semapong" -#endif #define SEM_MODE 0666 #define SHM_MODE 0666 #define ITERATIONS 1000 @@ -49,7 +42,9 @@ int main(int argc, char **argv) PLOptState *opt = PL_CreateOptState(argc, argv, "dc:h"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { case 'd': /* debug mode */ debug_mode = PR_TRUE; @@ -129,7 +124,9 @@ int main(int argc, char **argv) exit(1); } if (*counter_addr == 2*i) { - if (debug_mode) printf("process 1: counter = %d\n", *counter_addr); + if (debug_mode) { + printf("process 1: counter = %d\n", *counter_addr); + } } else { fprintf(stderr, "process 1: counter should be %d but is %d\n", 2*i, *counter_addr); diff --git a/nsprpub/pr/tests/semapong.c b/nsprpub/pr/tests/semapong.c index 16dea62ac..954f90f1d 100644 --- a/nsprpub/pr/tests/semapong.c +++ b/nsprpub/pr/tests/semapong.c @@ -8,15 +8,9 @@ #include <stdio.h> -#ifdef SYMBIAN -#define SHM_NAME "c:\\data\\counter" -#define SEM_NAME1 "c:\\data\\foo.sem" -#define SEM_NAME2 "c:\\data\\bar.sem" -#else #define SHM_NAME "/tmp/counter" #define SEM_NAME1 "/tmp/foo.sem" #define SEM_NAME2 "/tmp/bar.sem" -#endif #define ITERATIONS 1000 static PRBool debug_mode = PR_FALSE; @@ -40,7 +34,9 @@ int main(int argc, char **argv) PLOptState *opt = PL_CreateOptState(argc, argv, "dc:h"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { case 'd': /* debug mode */ debug_mode = PR_TRUE; @@ -90,7 +86,9 @@ int main(int argc, char **argv) exit(1); } if (*counter_addr == 2*i+1) { - if (debug_mode) printf("process 2: counter = %d\n", *counter_addr); + if (debug_mode) { + printf("process 2: counter = %d\n", *counter_addr); + } } else { fprintf(stderr, "process 2: counter should be %d but is %d\n", 2*i+1, *counter_addr); diff --git a/nsprpub/pr/tests/sendzlf.c b/nsprpub/pr/tests/sendzlf.c index 0f3df3f74..a65f6cd6b 100644 --- a/nsprpub/pr/tests/sendzlf.c +++ b/nsprpub/pr/tests/sendzlf.c @@ -4,7 +4,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* - * Test: sendzlf.c + * Test: sendzlf.c * * Description: send a zero-length file with PR_SendFile and * PR_TransmitFile. @@ -63,7 +63,7 @@ static void ClientThread(void *arg) exit(1); } if (memcmp(buf, HEADER_STR TRAILER_STR TRAILER_STR HEADER_STR HEADER_STR, - nexpected) != 0) { + nexpected) != 0) { fprintf(stderr, "wrong data is received\n"); exit(1); } @@ -84,7 +84,7 @@ static void ServerThread(void *arg) /* Create a zero-length file */ file = PR_Open(ZERO_LEN_FILE_NAME, - PR_CREATE_FILE|PR_TRUNCATE|PR_RDWR, 0666); + PR_CREATE_FILE|PR_TRUNCATE|PR_RDWR, 0666); if (NULL == file) { fprintf(stderr, "PR_Open failed\n"); exit(1); @@ -105,7 +105,7 @@ static void ServerThread(void *arg) } /* Send both header and trailer */ nbytes = PR_SendFile(acceptSock, &sfd, PR_TRANSMITFILE_KEEP_OPEN, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); if (HEADER_LEN+TRAILER_LEN != nbytes) { fprintf(stderr, "PR_SendFile should return %d but returned %d\n", HEADER_LEN+TRAILER_LEN, nbytes); @@ -114,7 +114,7 @@ static void ServerThread(void *arg) /* Trailer only, no header */ sfd.hlen = 0; nbytes = PR_SendFile(acceptSock, &sfd, PR_TRANSMITFILE_KEEP_OPEN, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); if (TRAILER_LEN != nbytes) { fprintf(stderr, "PR_SendFile should return %d but returned %d\n", TRAILER_LEN, nbytes); @@ -124,7 +124,7 @@ static void ServerThread(void *arg) sfd.hlen = HEADER_LEN; sfd.tlen = 0; nbytes = PR_SendFile(acceptSock, &sfd, PR_TRANSMITFILE_KEEP_OPEN, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); if (HEADER_LEN != nbytes) { fprintf(stderr, "PR_SendFile should return %d but returned %d\n", HEADER_LEN, nbytes); @@ -132,7 +132,7 @@ static void ServerThread(void *arg) } /* Try PR_TransmitFile */ nbytes = PR_TransmitFile(acceptSock, file, header, HEADER_LEN, - PR_TRANSMITFILE_KEEP_OPEN, PR_INTERVAL_NO_TIMEOUT); + PR_TRANSMITFILE_KEEP_OPEN, PR_INTERVAL_NO_TIMEOUT); if (HEADER_LEN != nbytes) { fprintf(stderr, "PR_TransmitFile should return %d but returned %d\n", HEADER_LEN, nbytes); @@ -184,15 +184,15 @@ int main(int argc, char **argv) } clientThread = PR_CreateThread(PR_USER_THREAD, - ClientThread, (void *) PR_ntohs(PR_NetAddrInetPort(&addr)), - PR_PRIORITY_NORMAL, scope, PR_JOINABLE_THREAD, 0); + ClientThread, (void *) PR_ntohs(PR_NetAddrInetPort(&addr)), + PR_PRIORITY_NORMAL, scope, PR_JOINABLE_THREAD, 0); if (NULL == clientThread) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); } serverThread = PR_CreateThread(PR_USER_THREAD, - ServerThread, listenSock, - PR_PRIORITY_NORMAL, scope, PR_JOINABLE_THREAD, 0); + ServerThread, listenSock, + PR_PRIORITY_NORMAL, scope, PR_JOINABLE_THREAD, 0); if (NULL == serverThread) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); diff --git a/nsprpub/pr/tests/server_test.c b/nsprpub/pr/tests/server_test.c index b794a7fe7..93ffe4aff 100644 --- a/nsprpub/pr/tests/server_test.c +++ b/nsprpub/pr/tests/server_test.c @@ -8,16 +8,16 @@ ** This server simulates a server running in loopback mode. ** ** The idea is that a single server is created. The server initially creates -** a number of worker threads. Then, with the server running, a number of +** a number of worker threads. Then, with the server running, a number of ** clients are created which start requesting service from the server. ** ** ** Modification History: ** 19-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ***********************************************************************/ /*********************************************************************** @@ -68,34 +68,34 @@ PRCondVar *ServerStateCV; /*********************************************************************** ** PRIVATE FUNCTION: Test_Result ** DESCRIPTION: Used in conjunction with the regress tool, prints out the -** status of the test case. +** status of the test case. ** INPUTS: PASS/FAIL ** OUTPUTS: None ** RETURN: None ** SIDE EFFECTS: -** +** ** RESTRICTIONS: ** None ** MEMORY: NA ** ALGORITHM: Determine what the status is and print accordingly. -** +** ***********************************************************************/ static void Test_Result (int result) { - switch (result) - { - case PASS: - printf ("PASS\n"); - break; - case FAIL: - printf ("FAIL\n"); - failed_already = 1; - break; - default: - break; - } + switch (result) + { + case PASS: + printf ("PASS\n"); + break; + case FAIL: + printf ("FAIL\n"); + failed_already = 1; + break; + default: + break; + } } static void do_work(void); @@ -108,7 +108,9 @@ SetServerState(char *waiter, PRInt32 state) ServerState = state; PR_NotifyCondVar(ServerStateCV); - if (debug_mode) DPRINTF("\t%s changed state to %d\n", waiter, state); + if (debug_mode) { + DPRINTF("\t%s changed state to %d\n", waiter, state); + } PR_Unlock(ServerStateCVLock); } @@ -120,14 +122,17 @@ WaitServerState(char *waiter, PRInt32 state) PR_Lock(ServerStateCVLock); - if (debug_mode) DPRINTF("\t%s waiting for state %d\n", waiter, state); + if (debug_mode) { + DPRINTF("\t%s waiting for state %d\n", waiter, state); + } - while(!(ServerState & state)) + while(!(ServerState & state)) { PR_WaitCondVar(ServerStateCV, PR_INTERVAL_NO_TIMEOUT); + } rv = ServerState; - if (debug_mode) DPRINTF("\t%s resuming from wait for state %d; state now %d\n", - waiter, state, ServerState); + if (debug_mode) DPRINTF("\t%s resuming from wait for state %d; state now %d\n", + waiter, state, ServerState); PR_Unlock(ServerStateCVLock); return rv; @@ -149,15 +154,21 @@ WorkerThreadFunc(void *_listenSock) char *sendBuf; if (debug_mode) DPRINTF("\tServer buffer is %d bytes; %d data, %d netaddrs\n", - _client_data+(2*sizeof(PRNetAddr))+32, _client_data, (2*sizeof(PRNetAddr))+32); + _client_data+(2*sizeof(PRNetAddr))+32, _client_data, (2*sizeof(PRNetAddr))+32); dataBuf = (char *)PR_MALLOC(_client_data + 2*sizeof(PRNetAddr) + 32); if (!dataBuf) - if (debug_mode) printf("\tServer could not malloc space!?\n"); + if (debug_mode) { + printf("\tServer could not malloc space!?\n"); + } sendBuf = (char *)PR_MALLOC(_server_data *sizeof(char)); if (!sendBuf) - if (debug_mode) printf("\tServer could not malloc space!?\n"); + if (debug_mode) { + printf("\tServer could not malloc space!?\n"); + } - if (debug_mode) DPRINTF("\tServer worker thread running\n"); + if (debug_mode) { + DPRINTF("\tServer worker thread running\n"); + } while(1) { PRInt32 bytesToRead = _client_data; @@ -168,9 +179,11 @@ WorkerThreadFunc(void *_listenSock) loops++; - if (debug_mode) DPRINTF("\tServer thread going into accept\n"); + if (debug_mode) { + DPRINTF("\tServer thread going into accept\n"); + } - bytesRead = PR_AcceptRead(listenSock, + bytesRead = PR_AcceptRead(listenSock, &newSock, &rAddr, dataBuf, @@ -178,66 +191,76 @@ WorkerThreadFunc(void *_listenSock) PR_INTERVAL_NO_TIMEOUT); if (bytesRead < 0) { - if (debug_mode) printf("\tServer error in accept (%d)\n", bytesRead); + if (debug_mode) { + printf("\tServer error in accept (%d)\n", bytesRead); + } continue; } - if (debug_mode) DPRINTF("\tServer accepted connection (%d bytes)\n", bytesRead); - + if (debug_mode) { + DPRINTF("\tServer accepted connection (%d bytes)\n", bytesRead); + } + PR_AtomicIncrement(&workerThreadsBusy); -#ifdef SYMBIAN - if (workerThreadsBusy == workerThreads && workerThreads<1) { -#else if (workerThreadsBusy == workerThreads) { -#endif PR_Lock(workerThreadsLock); if (workerThreadsBusy == workerThreads) { PRThread *WorkerThread; WorkerThread = PR_CreateThread( - PR_SYSTEM_THREAD, - WorkerThreadFunc, - listenSock, - PR_PRIORITY_NORMAL, - ServerScope, - PR_UNJOINABLE_THREAD, - THREAD_STACKSIZE); + PR_SYSTEM_THREAD, + WorkerThreadFunc, + listenSock, + PR_PRIORITY_NORMAL, + ServerScope, + PR_UNJOINABLE_THREAD, + THREAD_STACKSIZE); if (!WorkerThread) { - if (debug_mode) printf("Error creating client thread %d\n", workerThreads); + if (debug_mode) { + printf("Error creating client thread %d\n", workerThreads); + } } else { PR_AtomicIncrement(&workerThreads); - if (debug_mode) DPRINTF("\tServer creates worker (%d)\n", workerThreads); + if (debug_mode) { + DPRINTF("\tServer creates worker (%d)\n", workerThreads); + } } } PR_Unlock(workerThreadsLock); } - + bytesToRead -= bytesRead; while (bytesToRead) { - bytesRead = PR_Recv(newSock, - dataBuf, - bytesToRead, - 0, + bytesRead = PR_Recv(newSock, + dataBuf, + bytesToRead, + 0, PR_INTERVAL_NO_TIMEOUT); if (bytesRead < 0) { - if (debug_mode) printf("\tServer error receiving data (%d)\n", bytesRead); + if (debug_mode) { + printf("\tServer error receiving data (%d)\n", bytesRead); + } continue; } - if (debug_mode) DPRINTF("\tServer received %d bytes\n", bytesRead); + if (debug_mode) { + DPRINTF("\tServer received %d bytes\n", bytesRead); + } } bytesWritten = PR_Send(newSock, - sendBuf, - bytesToWrite, - 0, + sendBuf, + bytesToWrite, + 0, PR_INTERVAL_NO_TIMEOUT); if (bytesWritten != _server_data) { - if (debug_mode) printf("\tError sending data to client (%d, %d)\n", - bytesWritten, PR_GetOSError()); + if (debug_mode) printf("\tError sending data to client (%d, %d)\n", + bytesWritten, PR_GetOSError()); } else { - if (debug_mode) DPRINTF("\tServer sent %d bytes\n", bytesWritten); - } + if (debug_mode) { + DPRINTF("\tServer sent %d bytes\n", bytesWritten); + } + } PR_Close(newSock); PR_AtomicDecrement(&workerThreadsBusy); @@ -253,8 +276,12 @@ ServerSetup(void) PRThread *WorkerThread; if ((listenSocket = PR_NewTCPSocket()) == NULL) { - if (debug_mode) printf("\tServer error creating listen socket\n"); - else Test_Result(FAIL); + if (debug_mode) { + printf("\tServer error creating listen socket\n"); + } + else { + Test_Result(FAIL); + } return NULL; } @@ -262,8 +289,10 @@ ServerSetup(void) sockOpt.value.reuse_addr = PR_TRUE; if (PR_SetSocketOption(listenSocket, &sockOpt) != PR_SUCCESS) { if (debug_mode) printf("\tServer error setting socket option: OS error %d\n", - PR_GetOSError()); - else Test_Result(FAIL); + PR_GetOSError()); + else { + Test_Result(FAIL); + } PR_Close(listenSocket); return NULL; } @@ -275,15 +304,21 @@ ServerSetup(void) if (PR_Bind(listenSocket, &serverAddr) != PR_SUCCESS) { if (debug_mode) printf("\tServer error binding to server address: OS error %d\n", - PR_GetOSError()); - else Test_Result(FAIL); + PR_GetOSError()); + else { + Test_Result(FAIL); + } PR_Close(listenSocket); return NULL; } if (PR_Listen(listenSocket, 128) != PR_SUCCESS) { - if (debug_mode) printf("\tServer error listening to server socket\n"); - else Test_Result(FAIL); + if (debug_mode) { + printf("\tServer error listening to server socket\n"); + } + else { + Test_Result(FAIL); + } PR_Close(listenSocket); return NULL; @@ -296,21 +331,25 @@ ServerSetup(void) workerThreadsLock = PR_NewLock(); WorkerThread = PR_CreateThread( - PR_SYSTEM_THREAD, - WorkerThreadFunc, - listenSocket, - PR_PRIORITY_NORMAL, - ServerScope, - PR_UNJOINABLE_THREAD, - THREAD_STACKSIZE); + PR_SYSTEM_THREAD, + WorkerThreadFunc, + listenSocket, + PR_PRIORITY_NORMAL, + ServerScope, + PR_UNJOINABLE_THREAD, + THREAD_STACKSIZE); if (!WorkerThread) { - if (debug_mode) printf("error creating working thread\n"); + if (debug_mode) { + printf("error creating working thread\n"); + } PR_Close(listenSocket); return NULL; } PR_AtomicIncrement(&workerThreads); - if (debug_mode) DPRINTF("\tServer created primordial worker thread\n"); + if (debug_mode) { + DPRINTF("\tServer created primordial worker thread\n"); + } return listenSocket; } @@ -328,7 +367,9 @@ ServerThreadFunc(void *unused) SetServerState(SERVER, SERVER_STATE_DEAD); } else { - if (debug_mode) DPRINTF("\tServer up\n"); + if (debug_mode) { + DPRINTF("\tServer up\n"); + } /* Tell clients they can start now. */ SetServerState(SERVER, SERVER_STATE_READY); @@ -359,10 +400,14 @@ ClientThreadFunc(void *unused) sendBuf = (char *)PR_MALLOC(_client_data * sizeof(char)); if (!sendBuf) - if (debug_mode) printf("\tClient could not malloc space!?\n"); + if (debug_mode) { + printf("\tClient could not malloc space!?\n"); + } recvBuf = (char *)PR_MALLOC(_server_data * sizeof(char)); if (!recvBuf) - if (debug_mode) printf("\tClient could not malloc space!?\n"); + if (debug_mode) { + printf("\tClient could not malloc space!?\n"); + } memset(&serverAddr, 0, sizeof(PRNetAddr)); serverAddr.inet.family = PR_AF_INET; @@ -372,59 +417,75 @@ ClientThreadFunc(void *unused) while(numRequests > 0) { if ( (numRequests % 10) == 0 ) - if (debug_mode) printf("."); - if (debug_mode) DPRINTF("\tClient starting request %d\n", numRequests); + if (debug_mode) { + printf("."); + } + if (debug_mode) { + DPRINTF("\tClient starting request %d\n", numRequests); + } clientSocket = PR_NewTCPSocket(); if (!clientSocket) { if (debug_mode) printf("Client error creating socket: OS error %d\n", - PR_GetOSError()); + PR_GetOSError()); continue; } - if (debug_mode) DPRINTF("\tClient connecting\n"); + if (debug_mode) { + DPRINTF("\tClient connecting\n"); + } - rv = PR_Connect(clientSocket, + rv = PR_Connect(clientSocket, &serverAddr, PR_INTERVAL_NO_TIMEOUT); if (!clientSocket) { - if (debug_mode) printf("\tClient error connecting\n"); + if (debug_mode) { + printf("\tClient error connecting\n"); + } continue; } - if (debug_mode) DPRINTF("\tClient connected\n"); + if (debug_mode) { + DPRINTF("\tClient connected\n"); + } - rv = PR_Send(clientSocket, - sendBuf, - _client_data, - 0, + rv = PR_Send(clientSocket, + sendBuf, + _client_data, + 0, PR_INTERVAL_NO_TIMEOUT); if (rv != _client_data) { - if (debug_mode) printf("Client error sending data (%d)\n", rv); + if (debug_mode) { + printf("Client error sending data (%d)\n", rv); + } PR_Close(clientSocket); continue; } - if (debug_mode) DPRINTF("\tClient sent %d bytes\n", rv); + if (debug_mode) { + DPRINTF("\tClient sent %d bytes\n", rv); + } bytesNeeded = _server_data; while(bytesNeeded) { - rv = PR_Recv(clientSocket, - recvBuf, - bytesNeeded, - 0, + rv = PR_Recv(clientSocket, + recvBuf, + bytesNeeded, + 0, PR_INTERVAL_NO_TIMEOUT); if (rv <= 0) { - if (debug_mode) printf("Client error receiving data (%d) (%d/%d)\n", - rv, (_server_data - bytesNeeded), _server_data); + if (debug_mode) printf("Client error receiving data (%d) (%d/%d)\n", + rv, (_server_data - bytesNeeded), _server_data); break; } - if (debug_mode) DPRINTF("\tClient received %d bytes; need %d more\n", rv, bytesNeeded - rv); + if (debug_mode) { + DPRINTF("\tClient received %d bytes; need %d more\n", rv, bytesNeeded - rv); + } bytesNeeded -= rv; } PR_Close(clientSocket); - + PR_AtomicDecrement(&numRequests); } @@ -449,26 +510,30 @@ RunClients(void) for (index=0; index<_clients; index++) { PRThread *clientThread; - + clientThread = PR_CreateThread( - PR_USER_THREAD, - ClientThreadFunc, - NULL, - PR_PRIORITY_NORMAL, - ClientScope, - PR_UNJOINABLE_THREAD, - THREAD_STACKSIZE); + PR_USER_THREAD, + ClientThreadFunc, + NULL, + PR_PRIORITY_NORMAL, + ClientScope, + PR_UNJOINABLE_THREAD, + THREAD_STACKSIZE); if (!clientThread) { - if (debug_mode) printf("\terror creating client thread %d\n", index); - } else - if (debug_mode) DPRINTF("\tMain created client %d/%d\n", index+1, _clients); + if (debug_mode) { + printf("\terror creating client thread %d\n", index); + } + } else if (debug_mode) { + DPRINTF("\tMain created client %d/%d\n", index+1, _clients); + } } PR_EnterMonitor(clientMonitor); - while(numClients) + while(numClients) { PR_Wait(clientMonitor, PR_INTERVAL_NO_TIMEOUT); + } PR_ExitMonitor(clientMonitor); } @@ -482,15 +547,17 @@ void do_work() SetServerState(MAIN, SERVER_STATE_STARTUP); ServerThread = PR_CreateThread( - PR_USER_THREAD, - ServerThreadFunc, - NULL, - PR_PRIORITY_NORMAL, - ServerScope, - PR_JOINABLE_THREAD, - THREAD_STACKSIZE); + PR_USER_THREAD, + ServerThreadFunc, + NULL, + PR_PRIORITY_NORMAL, + ServerScope, + PR_JOINABLE_THREAD, + THREAD_STACKSIZE); if (!ServerThread) { - if (debug_mode) printf("error creating main server thread\n"); + if (debug_mode) { + printf("error creating main server thread\n"); + } return; } @@ -548,62 +615,64 @@ static void Measure(void (*func)(void), const char *msg) d = (double)PR_IntervalToMicroseconds(stop - start); - if (debug_mode) printf("\n%40s: %6.2f usec\n", msg, d / _iterations); + if (debug_mode) { + printf("\n%40s: %6.2f usec\n", msg, d / _iterations); + } } int main(int argc, char **argv) { - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); - /* main test */ -#ifndef SYMBIAN + /* main test */ if (debug_mode) { - printf("Enter number of iterations: \n"); - scanf("%d", &_iterations); - printf("Enter number of clients : \n"); - scanf("%d", &_clients); - printf("Enter size of client data : \n"); - scanf("%d", &_client_data); - printf("Enter size of server data : \n"); - scanf("%d", &_server_data); - } - else -#endif - { - - _iterations = 10; - _clients = 1; - _client_data = 10; - _server_data = 10; - } - + printf("Enter number of iterations: \n"); + scanf("%d", &_iterations); + printf("Enter number of clients : \n"); + scanf("%d", &_clients); + printf("Enter size of client data : \n"); + scanf("%d", &_client_data); + printf("Enter size of server data : \n"); + scanf("%d", &_server_data); + } + else + { + + _iterations = 10; + _clients = 1; + _client_data = 10; + _server_data = 10; + } + if (debug_mode) { - printf("\n\n%d iterations with %d client threads.\n", - _iterations, _clients); - printf("Sending %d bytes of client data and %d bytes of server data\n", - _client_data, _server_data); - } + printf("\n\n%d iterations with %d client threads.\n", + _iterations, _clients); + printf("Sending %d bytes of client data and %d bytes of server data\n", + _client_data, _server_data); + } PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); @@ -611,11 +680,11 @@ int main(int argc, char **argv) ServerStateCV = PR_NewCondVar(ServerStateCVLock); Measure(do_workUU, "server loop user/user"); - #if 0 +#if 0 Measure(do_workUK, "server loop user/kernel"); Measure(do_workKU, "server loop kernel/user"); Measure(do_workKK, "server loop kernel/kernel"); - #endif +#endif PR_Cleanup(); diff --git a/nsprpub/pr/tests/servr_kk.c b/nsprpub/pr/tests/servr_kk.c index 3e02027da..06f4fae11 100644 --- a/nsprpub/pr/tests/servr_kk.c +++ b/nsprpub/pr/tests/servr_kk.c @@ -8,18 +8,18 @@ ** This server simulates a server running in loopback mode. ** ** The idea is that a single server is created. The server initially creates -** a number of worker threads. Then, with the server running, a number of +** a number of worker threads. Then, with the server running, a number of ** clients are created which start requesting service from the server. ** ** ** Modification History: ** 19-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** @@ -72,7 +72,9 @@ SetServerState(char *waiter, PRInt32 state) ServerState = state; PR_NotifyCondVar(ServerStateCV); - if (debug_mode) DPRINTF("\t%s changed state to %d\n", waiter, state); + if (debug_mode) { + DPRINTF("\t%s changed state to %d\n", waiter, state); + } PR_Unlock(ServerStateCVLock); } @@ -84,14 +86,17 @@ WaitServerState(char *waiter, PRInt32 state) PR_Lock(ServerStateCVLock); - if (debug_mode) DPRINTF("\t%s waiting for state %d\n", waiter, state); + if (debug_mode) { + DPRINTF("\t%s waiting for state %d\n", waiter, state); + } - while(!(ServerState & state)) + while(!(ServerState & state)) { PR_WaitCondVar(ServerStateCV, PR_INTERVAL_NO_TIMEOUT); + } rv = ServerState; - if (debug_mode) DPRINTF("\t%s resuming from wait for state %d; state now %d\n", - waiter, state, ServerState); + if (debug_mode) DPRINTF("\t%s resuming from wait for state %d; state now %d\n", + waiter, state, ServerState); PR_Unlock(ServerStateCVLock); return rv; @@ -113,15 +118,21 @@ WorkerThreadFunc(void *_listenSock) char *sendBuf; if (debug_mode) DPRINTF("\tServer buffer is %d bytes; %d data, %d netaddrs\n", - _client_data+(2*sizeof(PRNetAddr))+32, _client_data, (2*sizeof(PRNetAddr))+32); + _client_data+(2*sizeof(PRNetAddr))+32, _client_data, (2*sizeof(PRNetAddr))+32); dataBuf = (char *)PR_MALLOC(_client_data + 2*sizeof(PRNetAddr) + 32); if (!dataBuf) - if (debug_mode) printf("\tServer could not malloc space!?\n"); + if (debug_mode) { + printf("\tServer could not malloc space!?\n"); + } sendBuf = (char *)PR_MALLOC(_server_data *sizeof(char)); if (!sendBuf) - if (debug_mode) printf("\tServer could not malloc space!?\n"); + if (debug_mode) { + printf("\tServer could not malloc space!?\n"); + } - if (debug_mode) DPRINTF("\tServer worker thread running\n"); + if (debug_mode) { + DPRINTF("\tServer worker thread running\n"); + } while(1) { PRInt32 bytesToRead = _client_data; @@ -132,9 +143,11 @@ WorkerThreadFunc(void *_listenSock) loops++; - if (debug_mode) DPRINTF("\tServer thread going into accept\n"); + if (debug_mode) { + DPRINTF("\tServer thread going into accept\n"); + } - bytesRead = PR_AcceptRead(listenSock, + bytesRead = PR_AcceptRead(listenSock, &newSock, &rAddr, dataBuf, @@ -142,65 +155,75 @@ WorkerThreadFunc(void *_listenSock) PR_INTERVAL_NO_TIMEOUT); if (bytesRead < 0) { - if (debug_mode) printf("\tServer error in accept (%d)\n", bytesRead); + if (debug_mode) { + printf("\tServer error in accept (%d)\n", bytesRead); + } continue; } - if (debug_mode) DPRINTF("\tServer accepted connection (%d bytes)\n", bytesRead); - + if (debug_mode) { + DPRINTF("\tServer accepted connection (%d bytes)\n", bytesRead); + } + PR_AtomicIncrement(&workerThreadsBusy); -#ifdef SYMBIAN - if (workerThreadsBusy == workerThreads && workerThreads<1) { -#else if (workerThreadsBusy == workerThreads) { -#endif PR_Lock(workerThreadsLock); if (workerThreadsBusy == workerThreads) { PRThread *WorkerThread; WorkerThread = PR_CreateThread( - PR_SYSTEM_THREAD, - WorkerThreadFunc, - listenSock, - PR_PRIORITY_NORMAL, - ServerScope, - PR_UNJOINABLE_THREAD, - THREAD_STACKSIZE); + PR_SYSTEM_THREAD, + WorkerThreadFunc, + listenSock, + PR_PRIORITY_NORMAL, + ServerScope, + PR_UNJOINABLE_THREAD, + THREAD_STACKSIZE); if (!WorkerThread) { - if (debug_mode) printf("Error creating client thread %d\n", workerThreads); + if (debug_mode) { + printf("Error creating client thread %d\n", workerThreads); + } } else { PR_AtomicIncrement(&workerThreads); - if (debug_mode) DPRINTF("\tServer creates worker (%d)\n", workerThreads); + if (debug_mode) { + DPRINTF("\tServer creates worker (%d)\n", workerThreads); + } } } PR_Unlock(workerThreadsLock); } - + bytesToRead -= bytesRead; while (bytesToRead) { - bytesRead = PR_Recv(newSock, - dataBuf, - bytesToRead, - 0, + bytesRead = PR_Recv(newSock, + dataBuf, + bytesToRead, + 0, PR_INTERVAL_NO_TIMEOUT); if (bytesRead < 0) { - if (debug_mode) printf("\tServer error receiving data (%d)\n", bytesRead); + if (debug_mode) { + printf("\tServer error receiving data (%d)\n", bytesRead); + } continue; } - if (debug_mode) DPRINTF("\tServer received %d bytes\n", bytesRead); + if (debug_mode) { + DPRINTF("\tServer received %d bytes\n", bytesRead); + } } bytesWritten = PR_Send(newSock, - sendBuf, - bytesToWrite, - 0, + sendBuf, + bytesToWrite, + 0, PR_INTERVAL_NO_TIMEOUT); if (bytesWritten != _server_data) { - if (debug_mode) printf("\tError sending data to client (%d, %d)\n", - bytesWritten, PR_GetOSError()); + if (debug_mode) printf("\tError sending data to client (%d, %d)\n", + bytesWritten, PR_GetOSError()); } else { - if (debug_mode) DPRINTF("\tServer sent %d bytes\n", bytesWritten); + if (debug_mode) { + DPRINTF("\tServer sent %d bytes\n", bytesWritten); + } } PR_Close(newSock); @@ -217,8 +240,12 @@ ServerSetup(void) PRThread *WorkerThread; if ( (listenSocket = PR_NewTCPSocket()) == NULL) { - if (debug_mode) printf("\tServer error creating listen socket\n"); - else failed_already=1; + if (debug_mode) { + printf("\tServer error creating listen socket\n"); + } + else { + failed_already=1; + } return NULL; } @@ -226,8 +253,10 @@ ServerSetup(void) sockOpt.value.reuse_addr = PR_TRUE; if ( PR_SetSocketOption(listenSocket, &sockOpt) == PR_FAILURE) { if (debug_mode) printf("\tServer error setting socket option: OS error %d\n", - PR_GetOSError()); - else failed_already=1; + PR_GetOSError()); + else { + failed_already=1; + } PR_Close(listenSocket); return NULL; } @@ -239,15 +268,21 @@ ServerSetup(void) if ( PR_Bind(listenSocket, &serverAddr) == PR_FAILURE) { if (debug_mode) printf("\tServer error binding to server address: OS error %d\n", - PR_GetOSError()); - else failed_already=1; + PR_GetOSError()); + else { + failed_already=1; + } PR_Close(listenSocket); return NULL; } if ( PR_Listen(listenSocket, 128) == PR_FAILURE) { - if (debug_mode) printf("\tServer error listening to server socket\n"); - else failed_already=1; + if (debug_mode) { + printf("\tServer error listening to server socket\n"); + } + else { + failed_already=1; + } PR_Close(listenSocket); return NULL; @@ -260,21 +295,25 @@ ServerSetup(void) workerThreadsLock = PR_NewLock(); WorkerThread = PR_CreateThread( - PR_SYSTEM_THREAD, - WorkerThreadFunc, - listenSocket, - PR_PRIORITY_NORMAL, - ServerScope, - PR_UNJOINABLE_THREAD, - THREAD_STACKSIZE); + PR_SYSTEM_THREAD, + WorkerThreadFunc, + listenSocket, + PR_PRIORITY_NORMAL, + ServerScope, + PR_UNJOINABLE_THREAD, + THREAD_STACKSIZE); if (!WorkerThread) { - if (debug_mode) printf("error creating working thread\n"); + if (debug_mode) { + printf("error creating working thread\n"); + } PR_Close(listenSocket); return NULL; } PR_AtomicIncrement(&workerThreads); - if (debug_mode) DPRINTF("\tServer created primordial worker thread\n"); + if (debug_mode) { + DPRINTF("\tServer created primordial worker thread\n"); + } return listenSocket; } @@ -292,7 +331,9 @@ ServerThreadFunc(void *unused) SetServerState(SERVER, SERVER_STATE_DEAD); } else { - if (debug_mode) DPRINTF("\tServer up\n"); + if (debug_mode) { + DPRINTF("\tServer up\n"); + } /* Tell clients they can start now. */ SetServerState(SERVER, SERVER_STATE_READY); @@ -323,10 +364,14 @@ ClientThreadFunc(void *unused) sendBuf = (char *)PR_MALLOC(_client_data * sizeof(char)); if (!sendBuf) - if (debug_mode) printf("\tClient could not malloc space!?\n"); + if (debug_mode) { + printf("\tClient could not malloc space!?\n"); + } recvBuf = (char *)PR_MALLOC(_server_data * sizeof(char)); if (!recvBuf) - if (debug_mode) printf("\tClient could not malloc space!?\n"); + if (debug_mode) { + printf("\tClient could not malloc space!?\n"); + } memset(&serverAddr, 0, sizeof(PRNetAddr)); serverAddr.inet.family = PR_AF_INET; @@ -336,59 +381,75 @@ ClientThreadFunc(void *unused) while(numRequests > 0) { if ( (numRequests % 10) == 0 ) - if (debug_mode) printf("."); - if (debug_mode) DPRINTF("\tClient starting request %d\n", numRequests); + if (debug_mode) { + printf("."); + } + if (debug_mode) { + DPRINTF("\tClient starting request %d\n", numRequests); + } clientSocket = PR_NewTCPSocket(); if (!clientSocket) { if (debug_mode) printf("Client error creating socket: OS error %d\n", - PR_GetOSError()); + PR_GetOSError()); continue; } - if (debug_mode) DPRINTF("\tClient connecting\n"); + if (debug_mode) { + DPRINTF("\tClient connecting\n"); + } - rv = PR_Connect(clientSocket, + rv = PR_Connect(clientSocket, &serverAddr, PR_INTERVAL_NO_TIMEOUT); if (!clientSocket) { - if (debug_mode) printf("\tClient error connecting\n"); + if (debug_mode) { + printf("\tClient error connecting\n"); + } continue; } - if (debug_mode) DPRINTF("\tClient connected\n"); + if (debug_mode) { + DPRINTF("\tClient connected\n"); + } - rv = PR_Send(clientSocket, - sendBuf, - _client_data, - 0, + rv = PR_Send(clientSocket, + sendBuf, + _client_data, + 0, PR_INTERVAL_NO_TIMEOUT); if (rv != _client_data) { - if (debug_mode) printf("Client error sending data (%d)\n", rv); + if (debug_mode) { + printf("Client error sending data (%d)\n", rv); + } PR_Close(clientSocket); continue; } - if (debug_mode) DPRINTF("\tClient sent %d bytes\n", rv); + if (debug_mode) { + DPRINTF("\tClient sent %d bytes\n", rv); + } bytesNeeded = _server_data; while(bytesNeeded) { - rv = PR_Recv(clientSocket, - recvBuf, - bytesNeeded, - 0, + rv = PR_Recv(clientSocket, + recvBuf, + bytesNeeded, + 0, PR_INTERVAL_NO_TIMEOUT); if (rv <= 0) { - if (debug_mode) printf("Client error receiving data (%d) (%d/%d)\n", - rv, (_server_data - bytesNeeded), _server_data); + if (debug_mode) printf("Client error receiving data (%d) (%d/%d)\n", + rv, (_server_data - bytesNeeded), _server_data); break; } - if (debug_mode) DPRINTF("\tClient received %d bytes; need %d more\n", rv, bytesNeeded - rv); + if (debug_mode) { + DPRINTF("\tClient received %d bytes; need %d more\n", rv, bytesNeeded - rv); + } bytesNeeded -= rv; } PR_Close(clientSocket); - + PR_AtomicDecrement(&numRequests); } @@ -413,26 +474,30 @@ RunClients(void) for (index=0; index<_clients; index++) { PRThread *clientThread; - + clientThread = PR_CreateThread( - PR_USER_THREAD, - ClientThreadFunc, - NULL, - PR_PRIORITY_NORMAL, - ClientScope, - PR_UNJOINABLE_THREAD, - THREAD_STACKSIZE); + PR_USER_THREAD, + ClientThreadFunc, + NULL, + PR_PRIORITY_NORMAL, + ClientScope, + PR_UNJOINABLE_THREAD, + THREAD_STACKSIZE); if (!clientThread) { - if (debug_mode) printf("\terror creating client thread %d\n", index); - } else - if (debug_mode) DPRINTF("\tMain created client %d/%d\n", index+1, _clients); + if (debug_mode) { + printf("\terror creating client thread %d\n", index); + } + } else if (debug_mode) { + DPRINTF("\tMain created client %d/%d\n", index+1, _clients); + } } PR_EnterMonitor(clientMonitor); - while(numClients) + while(numClients) { PR_Wait(clientMonitor, PR_INTERVAL_NO_TIMEOUT); + } PR_ExitMonitor(clientMonitor); } @@ -446,15 +511,17 @@ void do_work() SetServerState(MAIN, SERVER_STATE_STARTUP); ServerThread = PR_CreateThread( - PR_USER_THREAD, - ServerThreadFunc, - NULL, - PR_PRIORITY_NORMAL, - ServerScope, - PR_JOINABLE_THREAD, - THREAD_STACKSIZE); + PR_USER_THREAD, + ServerThreadFunc, + NULL, + PR_PRIORITY_NORMAL, + ServerScope, + PR_JOINABLE_THREAD, + THREAD_STACKSIZE); if (!ServerThread) { - if (debug_mode) printf("error creating main server thread\n"); + if (debug_mode) { + printf("error creating main server thread\n"); + } return; } @@ -512,61 +579,63 @@ static void Measure(void (*func)(void), const char *msg) d = (double)PR_IntervalToMicroseconds(stop - start); - if (debug_mode) printf("\n%40s: %6.2f usec\n", msg, d / _iterations); + if (debug_mode) { + printf("\n%40s: %6.2f usec\n", msg, d / _iterations); + } } int main(int argc, char **argv) { - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); - /* main test */ -#ifndef SYMBIAN + /* main test */ if (debug_mode) { - printf("Enter number of iterations: \n"); - scanf("%d", &_iterations); - printf("Enter number of clients : \n"); - scanf("%d", &_clients); - printf("Enter size of client data : \n"); - scanf("%d", &_client_data); - printf("Enter size of server data : \n"); - scanf("%d", &_server_data); - } - else -#endif - { - _iterations = 7; - _clients = 7; - _client_data = 100; - _server_data = 100; - } + printf("Enter number of iterations: \n"); + scanf("%d", &_iterations); + printf("Enter number of clients : \n"); + scanf("%d", &_clients); + printf("Enter size of client data : \n"); + scanf("%d", &_client_data); + printf("Enter size of server data : \n"); + scanf("%d", &_server_data); + } + else + { + _iterations = 7; + _clients = 7; + _client_data = 100; + _server_data = 100; + } if (debug_mode) { - printf("\n\n%d iterations with %d client threads.\n", - _iterations, _clients); - printf("Sending %d bytes of client data and %d bytes of server data\n", - _client_data, _server_data); - } + printf("\n\n%d iterations with %d client threads.\n", + _iterations, _clients); + printf("Sending %d bytes of client data and %d bytes of server data\n", + _client_data, _server_data); + } PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); @@ -578,11 +647,13 @@ int main(int argc, char **argv) Measure(do_workKK, "server loop kernel/kernel"); - PR_Cleanup(); + PR_Cleanup(); + + if(failed_already) { + return 1; + } + else { + return 0; + } - if(failed_already) - return 1; - else - return 0; - } diff --git a/nsprpub/pr/tests/servr_ku.c b/nsprpub/pr/tests/servr_ku.c index 1a54fc766..d0c446f52 100644 --- a/nsprpub/pr/tests/servr_ku.c +++ b/nsprpub/pr/tests/servr_ku.c @@ -8,18 +8,18 @@ ** This server simulates a server running in loopback mode. ** ** The idea is that a single server is created. The server initially creates -** a number of worker threads. Then, with the server running, a number of +** a number of worker threads. Then, with the server running, a number of ** clients are created which start requesting service from the server. ** ** ** Modification History: ** 19-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** @@ -73,7 +73,9 @@ SetServerState(char *waiter, PRInt32 state) ServerState = state; PR_NotifyCondVar(ServerStateCV); - if (debug_mode) DPRINTF("\t%s changed state to %d\n", waiter, state); + if (debug_mode) { + DPRINTF("\t%s changed state to %d\n", waiter, state); + } PR_Unlock(ServerStateCVLock); } @@ -85,14 +87,17 @@ WaitServerState(char *waiter, PRInt32 state) PR_Lock(ServerStateCVLock); - if (debug_mode) DPRINTF("\t%s waiting for state %d\n", waiter, state); + if (debug_mode) { + DPRINTF("\t%s waiting for state %d\n", waiter, state); + } - while(!(ServerState & state)) + while(!(ServerState & state)) { PR_WaitCondVar(ServerStateCV, PR_INTERVAL_NO_TIMEOUT); + } rv = ServerState; - if (debug_mode) DPRINTF("\t%s resuming from wait for state %d; state now %d\n", - waiter, state, ServerState); + if (debug_mode) DPRINTF("\t%s resuming from wait for state %d; state now %d\n", + waiter, state, ServerState); PR_Unlock(ServerStateCVLock); return rv; @@ -114,15 +119,21 @@ WorkerThreadFunc(void *_listenSock) char *sendBuf; if (debug_mode) DPRINTF("\tServer buffer is %d bytes; %d data, %d netaddrs\n", - _client_data+(2*sizeof(PRNetAddr))+32, _client_data, (2*sizeof(PRNetAddr))+32); + _client_data+(2*sizeof(PRNetAddr))+32, _client_data, (2*sizeof(PRNetAddr))+32); dataBuf = (char *)PR_MALLOC(_client_data + 2*sizeof(PRNetAddr) + 32); if (!dataBuf) - if (debug_mode) printf("\tServer could not malloc space!?\n"); + if (debug_mode) { + printf("\tServer could not malloc space!?\n"); + } sendBuf = (char *)PR_MALLOC(_server_data *sizeof(char)); if (!sendBuf) - if (debug_mode) printf("\tServer could not malloc space!?\n"); + if (debug_mode) { + printf("\tServer could not malloc space!?\n"); + } - if (debug_mode) DPRINTF("\tServer worker thread running\n"); + if (debug_mode) { + DPRINTF("\tServer worker thread running\n"); + } while(1) { PRInt32 bytesToRead = _client_data; @@ -133,9 +144,11 @@ WorkerThreadFunc(void *_listenSock) loops++; - if (debug_mode) DPRINTF("\tServer thread going into accept\n"); + if (debug_mode) { + DPRINTF("\tServer thread going into accept\n"); + } - bytesRead = PR_AcceptRead(listenSock, + bytesRead = PR_AcceptRead(listenSock, &newSock, &rAddr, dataBuf, @@ -143,65 +156,75 @@ WorkerThreadFunc(void *_listenSock) PR_INTERVAL_NO_TIMEOUT); if (bytesRead < 0) { - if (debug_mode) printf("\tServer error in accept (%d)\n", bytesRead); + if (debug_mode) { + printf("\tServer error in accept (%d)\n", bytesRead); + } continue; } - if (debug_mode) DPRINTF("\tServer accepted connection (%d bytes)\n", bytesRead); - + if (debug_mode) { + DPRINTF("\tServer accepted connection (%d bytes)\n", bytesRead); + } + PR_AtomicIncrement(&workerThreadsBusy); -#ifdef SYMBIAN - if (workerThreadsBusy == workerThreads && workerThreads<1) { -#else if (workerThreadsBusy == workerThreads) { -#endif PR_Lock(workerThreadsLock); if (workerThreadsBusy == workerThreads) { PRThread *WorkerThread; WorkerThread = PR_CreateThread( - PR_SYSTEM_THREAD, - WorkerThreadFunc, - listenSock, - PR_PRIORITY_NORMAL, - ServerScope, - PR_UNJOINABLE_THREAD, - THREAD_STACKSIZE); + PR_SYSTEM_THREAD, + WorkerThreadFunc, + listenSock, + PR_PRIORITY_NORMAL, + ServerScope, + PR_UNJOINABLE_THREAD, + THREAD_STACKSIZE); if (!WorkerThread) { - if (debug_mode) printf("Error creating client thread %d\n", workerThreads); + if (debug_mode) { + printf("Error creating client thread %d\n", workerThreads); + } } else { PR_AtomicIncrement(&workerThreads); - if (debug_mode) DPRINTF("\tServer creates worker (%d)\n", workerThreads); + if (debug_mode) { + DPRINTF("\tServer creates worker (%d)\n", workerThreads); + } } } PR_Unlock(workerThreadsLock); } - + bytesToRead -= bytesRead; while (bytesToRead) { - bytesRead = PR_Recv(newSock, - dataBuf, - bytesToRead, - 0, + bytesRead = PR_Recv(newSock, + dataBuf, + bytesToRead, + 0, PR_INTERVAL_NO_TIMEOUT); if (bytesRead < 0) { - if (debug_mode) printf("\tServer error receiving data (%d)\n", bytesRead); + if (debug_mode) { + printf("\tServer error receiving data (%d)\n", bytesRead); + } continue; } - if (debug_mode) DPRINTF("\tServer received %d bytes\n", bytesRead); + if (debug_mode) { + DPRINTF("\tServer received %d bytes\n", bytesRead); + } } bytesWritten = PR_Send(newSock, - sendBuf, - bytesToWrite, - 0, + sendBuf, + bytesToWrite, + 0, PR_INTERVAL_NO_TIMEOUT); if (bytesWritten != _server_data) { - if (debug_mode) printf("\tError sending data to client (%d, %d)\n", - bytesWritten, PR_GetOSError()); + if (debug_mode) printf("\tError sending data to client (%d, %d)\n", + bytesWritten, PR_GetOSError()); } else { - if (debug_mode) DPRINTF("\tServer sent %d bytes\n", bytesWritten); + if (debug_mode) { + DPRINTF("\tServer sent %d bytes\n", bytesWritten); + } } PR_Close(newSock); @@ -218,8 +241,12 @@ ServerSetup(void) PRThread *WorkerThread; if ( (listenSocket = PR_NewTCPSocket()) == NULL) { - if (debug_mode) printf("\tServer error creating listen socket\n"); - else failed_already=1; + if (debug_mode) { + printf("\tServer error creating listen socket\n"); + } + else { + failed_already=1; + } return NULL; } @@ -227,8 +254,10 @@ ServerSetup(void) sockOpt.value.reuse_addr = PR_TRUE; if ( PR_SetSocketOption(listenSocket, &sockOpt) == PR_FAILURE) { if (debug_mode) printf("\tServer error setting socket option: OS error %d\n", - PR_GetOSError()); - else failed_already=1; + PR_GetOSError()); + else { + failed_already=1; + } PR_Close(listenSocket); return NULL; } @@ -240,15 +269,21 @@ ServerSetup(void) if ( PR_Bind(listenSocket, &serverAddr) == PR_FAILURE) { if (debug_mode) printf("\tServer error binding to server address: OS error %d\n", - PR_GetOSError()); - else failed_already=1; + PR_GetOSError()); + else { + failed_already=1; + } PR_Close(listenSocket); return NULL; } if ( PR_Listen(listenSocket, 128) == PR_FAILURE) { - if (debug_mode) printf("\tServer error listening to server socket\n"); - else failed_already=1; + if (debug_mode) { + printf("\tServer error listening to server socket\n"); + } + else { + failed_already=1; + } PR_Close(listenSocket); return NULL; @@ -261,21 +296,25 @@ ServerSetup(void) workerThreadsLock = PR_NewLock(); WorkerThread = PR_CreateThread( - PR_SYSTEM_THREAD, - WorkerThreadFunc, - listenSocket, - PR_PRIORITY_NORMAL, - ServerScope, - PR_UNJOINABLE_THREAD, - THREAD_STACKSIZE); + PR_SYSTEM_THREAD, + WorkerThreadFunc, + listenSocket, + PR_PRIORITY_NORMAL, + ServerScope, + PR_UNJOINABLE_THREAD, + THREAD_STACKSIZE); if (!WorkerThread) { - if (debug_mode) printf("error creating working thread\n"); + if (debug_mode) { + printf("error creating working thread\n"); + } PR_Close(listenSocket); return NULL; } PR_AtomicIncrement(&workerThreads); - if (debug_mode) DPRINTF("\tServer created primordial worker thread\n"); + if (debug_mode) { + DPRINTF("\tServer created primordial worker thread\n"); + } return listenSocket; } @@ -293,7 +332,9 @@ ServerThreadFunc(void *unused) SetServerState(SERVER, SERVER_STATE_DEAD); } else { - if (debug_mode) DPRINTF("\tServer up\n"); + if (debug_mode) { + DPRINTF("\tServer up\n"); + } /* Tell clients they can start now. */ SetServerState(SERVER, SERVER_STATE_READY); @@ -324,10 +365,14 @@ ClientThreadFunc(void *unused) sendBuf = (char *)PR_MALLOC(_client_data * sizeof(char)); if (!sendBuf) - if (debug_mode) printf("\tClient could not malloc space!?\n"); + if (debug_mode) { + printf("\tClient could not malloc space!?\n"); + } recvBuf = (char *)PR_MALLOC(_server_data * sizeof(char)); if (!recvBuf) - if (debug_mode) printf("\tClient could not malloc space!?\n"); + if (debug_mode) { + printf("\tClient could not malloc space!?\n"); + } memset(&serverAddr, 0, sizeof(PRNetAddr)); serverAddr.inet.family = PR_AF_INET; @@ -337,59 +382,75 @@ ClientThreadFunc(void *unused) while(numRequests > 0) { if ( (numRequests % 10) == 0 ) - if (debug_mode) printf("."); - if (debug_mode) DPRINTF("\tClient starting request %d\n", numRequests); + if (debug_mode) { + printf("."); + } + if (debug_mode) { + DPRINTF("\tClient starting request %d\n", numRequests); + } clientSocket = PR_NewTCPSocket(); if (!clientSocket) { if (debug_mode) printf("Client error creating socket: OS error %d\n", - PR_GetOSError()); + PR_GetOSError()); continue; } - if (debug_mode) DPRINTF("\tClient connecting\n"); + if (debug_mode) { + DPRINTF("\tClient connecting\n"); + } - rv = PR_Connect(clientSocket, + rv = PR_Connect(clientSocket, &serverAddr, PR_INTERVAL_NO_TIMEOUT); if (!clientSocket) { - if (debug_mode) printf("\tClient error connecting\n"); + if (debug_mode) { + printf("\tClient error connecting\n"); + } continue; } - if (debug_mode) DPRINTF("\tClient connected\n"); + if (debug_mode) { + DPRINTF("\tClient connected\n"); + } - rv = PR_Send(clientSocket, - sendBuf, - _client_data, - 0, + rv = PR_Send(clientSocket, + sendBuf, + _client_data, + 0, PR_INTERVAL_NO_TIMEOUT); if (rv != _client_data) { - if (debug_mode) printf("Client error sending data (%d)\n", rv); + if (debug_mode) { + printf("Client error sending data (%d)\n", rv); + } PR_Close(clientSocket); continue; } - if (debug_mode) DPRINTF("\tClient sent %d bytes\n", rv); + if (debug_mode) { + DPRINTF("\tClient sent %d bytes\n", rv); + } bytesNeeded = _server_data; while(bytesNeeded) { - rv = PR_Recv(clientSocket, - recvBuf, - bytesNeeded, - 0, + rv = PR_Recv(clientSocket, + recvBuf, + bytesNeeded, + 0, PR_INTERVAL_NO_TIMEOUT); if (rv <= 0) { - if (debug_mode) printf("Client error receiving data (%d) (%d/%d)\n", - rv, (_server_data - bytesNeeded), _server_data); + if (debug_mode) printf("Client error receiving data (%d) (%d/%d)\n", + rv, (_server_data - bytesNeeded), _server_data); break; } - if (debug_mode) DPRINTF("\tClient received %d bytes; need %d more\n", rv, bytesNeeded - rv); + if (debug_mode) { + DPRINTF("\tClient received %d bytes; need %d more\n", rv, bytesNeeded - rv); + } bytesNeeded -= rv; } PR_Close(clientSocket); - + PR_AtomicDecrement(&numRequests); } @@ -414,26 +475,30 @@ RunClients(void) for (index=0; index<_clients; index++) { PRThread *clientThread; - + clientThread = PR_CreateThread( - PR_USER_THREAD, - ClientThreadFunc, - NULL, - PR_PRIORITY_NORMAL, - ClientScope, - PR_UNJOINABLE_THREAD, - THREAD_STACKSIZE); + PR_USER_THREAD, + ClientThreadFunc, + NULL, + PR_PRIORITY_NORMAL, + ClientScope, + PR_UNJOINABLE_THREAD, + THREAD_STACKSIZE); if (!clientThread) { - if (debug_mode) printf("\terror creating client thread %d\n", index); - } else - if (debug_mode) DPRINTF("\tMain created client %d/%d\n", index+1, _clients); + if (debug_mode) { + printf("\terror creating client thread %d\n", index); + } + } else if (debug_mode) { + DPRINTF("\tMain created client %d/%d\n", index+1, _clients); + } } PR_EnterMonitor(clientMonitor); - while(numClients) + while(numClients) { PR_Wait(clientMonitor, PR_INTERVAL_NO_TIMEOUT); + } PR_ExitMonitor(clientMonitor); } @@ -447,15 +512,17 @@ void do_work() SetServerState(MAIN, SERVER_STATE_STARTUP); ServerThread = PR_CreateThread( - PR_USER_THREAD, - ServerThreadFunc, - NULL, - PR_PRIORITY_NORMAL, - ServerScope, - PR_JOINABLE_THREAD, - THREAD_STACKSIZE); + PR_USER_THREAD, + ServerThreadFunc, + NULL, + PR_PRIORITY_NORMAL, + ServerScope, + PR_JOINABLE_THREAD, + THREAD_STACKSIZE); if (!ServerThread) { - if (debug_mode) printf("error creating main server thread\n"); + if (debug_mode) { + printf("error creating main server thread\n"); + } return; } @@ -494,61 +561,63 @@ static void Measure(void (*func)(void), const char *msg) d = (double)PR_IntervalToMicroseconds(stop - start); - if (debug_mode) printf("\n%40s: %6.2f usec\n", msg, d / _iterations); + if (debug_mode) { + printf("\n%40s: %6.2f usec\n", msg, d / _iterations); + } } int main(int argc, char **argv) { - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); - /* main test */ -#ifndef SYMBIAN + /* main test */ if (debug_mode) { - printf("Enter number of iterations: \n"); - scanf("%d", &_iterations); - printf("Enter number of clients : \n"); - scanf("%d", &_clients); - printf("Enter size of client data : \n"); - scanf("%d", &_client_data); - printf("Enter size of server data : \n"); - scanf("%d", &_server_data); - } - else -#endif - { - _iterations = 7; - _clients = 7; - _client_data = 100; - _server_data = 100; - } + printf("Enter number of iterations: \n"); + scanf("%d", &_iterations); + printf("Enter number of clients : \n"); + scanf("%d", &_clients); + printf("Enter size of client data : \n"); + scanf("%d", &_client_data); + printf("Enter size of server data : \n"); + scanf("%d", &_server_data); + } + else + { + _iterations = 7; + _clients = 7; + _client_data = 100; + _server_data = 100; + } if (debug_mode) { - printf("\n\n%d iterations with %d client threads.\n", - _iterations, _clients); - printf("Sending %d bytes of client data and %d bytes of server data\n", - _client_data, _server_data); - } + printf("\n\n%d iterations with %d client threads.\n", + _iterations, _clients); + printf("Sending %d bytes of client data and %d bytes of server data\n", + _client_data, _server_data); + } PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); @@ -560,9 +629,11 @@ int main(int argc, char **argv) Measure(do_workKU, "server loop kernel/user"); PR_Cleanup(); - if(failed_already) - return 1; - else - return 0; + if(failed_already) { + return 1; + } + else { + return 0; + } } diff --git a/nsprpub/pr/tests/servr_uk.c b/nsprpub/pr/tests/servr_uk.c index c61ad9886..bd97c8f35 100644 --- a/nsprpub/pr/tests/servr_uk.c +++ b/nsprpub/pr/tests/servr_uk.c @@ -8,18 +8,18 @@ ** This server simulates a server running in loopback mode. ** ** The idea is that a single server is created. The server initially creates -** a number of worker threads. Then, with the server running, a number of +** a number of worker threads. Then, with the server running, a number of ** clients are created which start requesting service from the server. ** ** ** Modification History: ** 19-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** @@ -75,7 +75,9 @@ SetServerState(char *waiter, PRInt32 state) ServerState = state; PR_NotifyCondVar(ServerStateCV); - if (debug_mode) DPRINTF("\t%s changed state to %d\n", waiter, state); + if (debug_mode) { + DPRINTF("\t%s changed state to %d\n", waiter, state); + } PR_Unlock(ServerStateCVLock); } @@ -87,14 +89,17 @@ WaitServerState(char *waiter, PRInt32 state) PR_Lock(ServerStateCVLock); - if (debug_mode) DPRINTF("\t%s waiting for state %d\n", waiter, state); + if (debug_mode) { + DPRINTF("\t%s waiting for state %d\n", waiter, state); + } - while(!(ServerState & state)) + while(!(ServerState & state)) { PR_WaitCondVar(ServerStateCV, PR_INTERVAL_NO_TIMEOUT); + } rv = ServerState; - if (debug_mode) DPRINTF("\t%s resuming from wait for state %d; state now %d\n", - waiter, state, ServerState); + if (debug_mode) DPRINTF("\t%s resuming from wait for state %d; state now %d\n", + waiter, state, ServerState); PR_Unlock(ServerStateCVLock); return rv; @@ -116,15 +121,21 @@ WorkerThreadFunc(void *_listenSock) char *sendBuf; if (debug_mode) DPRINTF("\tServer buffer is %d bytes; %d data, %d netaddrs\n", - _client_data+(2*sizeof(PRNetAddr))+32, _client_data, (2*sizeof(PRNetAddr))+32); + _client_data+(2*sizeof(PRNetAddr))+32, _client_data, (2*sizeof(PRNetAddr))+32); dataBuf = (char *)PR_MALLOC(_client_data + 2*sizeof(PRNetAddr) + 32); if (!dataBuf) - if (debug_mode) printf("\tServer could not malloc space!?\n"); + if (debug_mode) { + printf("\tServer could not malloc space!?\n"); + } sendBuf = (char *)PR_MALLOC(_server_data *sizeof(char)); if (!sendBuf) - if (debug_mode) printf("\tServer could not malloc space!?\n"); + if (debug_mode) { + printf("\tServer could not malloc space!?\n"); + } - if (debug_mode) DPRINTF("\tServer worker thread running\n"); + if (debug_mode) { + DPRINTF("\tServer worker thread running\n"); + } while(1) { PRInt32 bytesToRead = _client_data; @@ -135,9 +146,11 @@ WorkerThreadFunc(void *_listenSock) loops++; - if (debug_mode) DPRINTF("\tServer thread going into accept\n"); + if (debug_mode) { + DPRINTF("\tServer thread going into accept\n"); + } - bytesRead = PR_AcceptRead(listenSock, + bytesRead = PR_AcceptRead(listenSock, &newSock, &rAddr, dataBuf, @@ -145,65 +158,75 @@ WorkerThreadFunc(void *_listenSock) PR_INTERVAL_NO_TIMEOUT); if (bytesRead < 0) { - if (debug_mode) printf("\tServer error in accept (%d)\n", bytesRead); + if (debug_mode) { + printf("\tServer error in accept (%d)\n", bytesRead); + } continue; } - if (debug_mode) DPRINTF("\tServer accepted connection (%d bytes)\n", bytesRead); - + if (debug_mode) { + DPRINTF("\tServer accepted connection (%d bytes)\n", bytesRead); + } + PR_AtomicIncrement(&workerThreadsBusy); -#ifdef SYMBIAN - if (workerThreadsBusy == workerThreads && workerThreads<1) { -#else if (workerThreadsBusy == workerThreads) { -#endif PR_Lock(workerThreadsLock); if (workerThreadsBusy == workerThreads) { PRThread *WorkerThread; WorkerThread = PR_CreateThread( - PR_SYSTEM_THREAD, - WorkerThreadFunc, - listenSock, - PR_PRIORITY_NORMAL, - ServerScope, - PR_UNJOINABLE_THREAD, - THREAD_STACKSIZE); + PR_SYSTEM_THREAD, + WorkerThreadFunc, + listenSock, + PR_PRIORITY_NORMAL, + ServerScope, + PR_UNJOINABLE_THREAD, + THREAD_STACKSIZE); if (!WorkerThread) { - if (debug_mode) printf("Error creating client thread %d\n", workerThreads); + if (debug_mode) { + printf("Error creating client thread %d\n", workerThreads); + } } else { PR_AtomicIncrement(&workerThreads); - if (debug_mode) DPRINTF("\tServer creates worker (%d)\n", workerThreads); + if (debug_mode) { + DPRINTF("\tServer creates worker (%d)\n", workerThreads); + } } } PR_Unlock(workerThreadsLock); } - + bytesToRead -= bytesRead; while (bytesToRead) { - bytesRead = PR_Recv(newSock, - dataBuf, - bytesToRead, - 0, + bytesRead = PR_Recv(newSock, + dataBuf, + bytesToRead, + 0, PR_INTERVAL_NO_TIMEOUT); if (bytesRead < 0) { - if (debug_mode) printf("\tServer error receiving data (%d)\n", bytesRead); + if (debug_mode) { + printf("\tServer error receiving data (%d)\n", bytesRead); + } continue; } - if (debug_mode) DPRINTF("\tServer received %d bytes\n", bytesRead); + if (debug_mode) { + DPRINTF("\tServer received %d bytes\n", bytesRead); + } } bytesWritten = PR_Send(newSock, - sendBuf, - bytesToWrite, - 0, + sendBuf, + bytesToWrite, + 0, PR_INTERVAL_NO_TIMEOUT); if (bytesWritten != _server_data) { - if (debug_mode) printf("\tError sending data to client (%d, %d)\n", - bytesWritten, PR_GetOSError()); + if (debug_mode) printf("\tError sending data to client (%d, %d)\n", + bytesWritten, PR_GetOSError()); } else { - if (debug_mode) DPRINTF("\tServer sent %d bytes\n", bytesWritten); + if (debug_mode) { + DPRINTF("\tServer sent %d bytes\n", bytesWritten); + } } PR_Close(newSock); @@ -220,17 +243,22 @@ ServerSetup(void) PRThread *WorkerThread; if ( (listenSocket = PR_NewTCPSocket()) == NULL) { - if (debug_mode) printf("\tServer error creating listen socket\n"); - else - return NULL; + if (debug_mode) { + printf("\tServer error creating listen socket\n"); + } + else { + return NULL; + } } sockOpt.option = PR_SockOpt_Reuseaddr; sockOpt.value.reuse_addr = PR_TRUE; if ( PR_SetSocketOption(listenSocket, &sockOpt) == PR_FAILURE) { if (debug_mode) printf("\tServer error setting socket option: OS error %d\n", - PR_GetOSError()); - else failed_already=1; + PR_GetOSError()); + else { + failed_already=1; + } PR_Close(listenSocket); return NULL; } @@ -242,15 +270,21 @@ ServerSetup(void) if ( PR_Bind(listenSocket, &serverAddr) == PR_FAILURE) { if (debug_mode) printf("\tServer error binding to server address: OS error %d\n", - PR_GetOSError()); - else failed_already=1; + PR_GetOSError()); + else { + failed_already=1; + } PR_Close(listenSocket); return NULL; } if ( PR_Listen(listenSocket, 128) == PR_FAILURE) { - if (debug_mode) printf("\tServer error listening to server socket\n"); - else failed_already=1; + if (debug_mode) { + printf("\tServer error listening to server socket\n"); + } + else { + failed_already=1; + } PR_Close(listenSocket); return NULL; @@ -263,21 +297,25 @@ ServerSetup(void) workerThreadsLock = PR_NewLock(); WorkerThread = PR_CreateThread( - PR_SYSTEM_THREAD, - WorkerThreadFunc, - listenSocket, - PR_PRIORITY_NORMAL, - ServerScope, - PR_UNJOINABLE_THREAD, - THREAD_STACKSIZE); + PR_SYSTEM_THREAD, + WorkerThreadFunc, + listenSocket, + PR_PRIORITY_NORMAL, + ServerScope, + PR_UNJOINABLE_THREAD, + THREAD_STACKSIZE); if (!WorkerThread) { - if (debug_mode) printf("error creating working thread\n"); + if (debug_mode) { + printf("error creating working thread\n"); + } PR_Close(listenSocket); return NULL; } PR_AtomicIncrement(&workerThreads); - if (debug_mode) DPRINTF("\tServer created primordial worker thread\n"); + if (debug_mode) { + DPRINTF("\tServer created primordial worker thread\n"); + } return listenSocket; } @@ -295,7 +333,9 @@ ServerThreadFunc(void *unused) SetServerState(SERVER, SERVER_STATE_DEAD); } else { - if (debug_mode) DPRINTF("\tServer up\n"); + if (debug_mode) { + DPRINTF("\tServer up\n"); + } /* Tell clients they can start now. */ SetServerState(SERVER, SERVER_STATE_READY); @@ -326,10 +366,14 @@ ClientThreadFunc(void *unused) sendBuf = (char *)PR_MALLOC(_client_data * sizeof(char)); if (!sendBuf) - if (debug_mode) printf("\tClient could not malloc space!?\n"); + if (debug_mode) { + printf("\tClient could not malloc space!?\n"); + } recvBuf = (char *)PR_MALLOC(_server_data * sizeof(char)); if (!recvBuf) - if (debug_mode) printf("\tClient could not malloc space!?\n"); + if (debug_mode) { + printf("\tClient could not malloc space!?\n"); + } memset(&serverAddr, 0, sizeof(PRNetAddr)); serverAddr.inet.family = PR_AF_INET; @@ -339,59 +383,75 @@ ClientThreadFunc(void *unused) while(numRequests > 0) { if ( (numRequests % 10) == 0 ) - if (debug_mode) printf("."); - if (debug_mode) DPRINTF("\tClient starting request %d\n", numRequests); + if (debug_mode) { + printf("."); + } + if (debug_mode) { + DPRINTF("\tClient starting request %d\n", numRequests); + } clientSocket = PR_NewTCPSocket(); if (!clientSocket) { if (debug_mode) printf("Client error creating socket: OS error %d\n", - PR_GetOSError()); + PR_GetOSError()); continue; } - if (debug_mode) DPRINTF("\tClient connecting\n"); + if (debug_mode) { + DPRINTF("\tClient connecting\n"); + } - rv = PR_Connect(clientSocket, + rv = PR_Connect(clientSocket, &serverAddr, PR_INTERVAL_NO_TIMEOUT); if (!clientSocket) { - if (debug_mode) printf("\tClient error connecting\n"); + if (debug_mode) { + printf("\tClient error connecting\n"); + } continue; } - if (debug_mode) DPRINTF("\tClient connected\n"); + if (debug_mode) { + DPRINTF("\tClient connected\n"); + } - rv = PR_Send(clientSocket, - sendBuf, - _client_data, - 0, + rv = PR_Send(clientSocket, + sendBuf, + _client_data, + 0, PR_INTERVAL_NO_TIMEOUT); if (rv != _client_data) { - if (debug_mode) printf("Client error sending data (%d)\n", rv); + if (debug_mode) { + printf("Client error sending data (%d)\n", rv); + } PR_Close(clientSocket); continue; } - if (debug_mode) DPRINTF("\tClient sent %d bytes\n", rv); + if (debug_mode) { + DPRINTF("\tClient sent %d bytes\n", rv); + } bytesNeeded = _server_data; while(bytesNeeded) { - rv = PR_Recv(clientSocket, - recvBuf, - bytesNeeded, - 0, + rv = PR_Recv(clientSocket, + recvBuf, + bytesNeeded, + 0, PR_INTERVAL_NO_TIMEOUT); if (rv <= 0) { - if (debug_mode) printf("Client error receiving data (%d) (%d/%d)\n", - rv, (_server_data - bytesNeeded), _server_data); + if (debug_mode) printf("Client error receiving data (%d) (%d/%d)\n", + rv, (_server_data - bytesNeeded), _server_data); break; } - if (debug_mode) DPRINTF("\tClient received %d bytes; need %d more\n", rv, bytesNeeded - rv); + if (debug_mode) { + DPRINTF("\tClient received %d bytes; need %d more\n", rv, bytesNeeded - rv); + } bytesNeeded -= rv; } PR_Close(clientSocket); - + PR_AtomicDecrement(&numRequests); } @@ -416,26 +476,30 @@ RunClients(void) for (index=0; index<_clients; index++) { PRThread *clientThread; - + clientThread = PR_CreateThread( - PR_USER_THREAD, - ClientThreadFunc, - NULL, - PR_PRIORITY_NORMAL, - ClientScope, - PR_UNJOINABLE_THREAD, - THREAD_STACKSIZE); + PR_USER_THREAD, + ClientThreadFunc, + NULL, + PR_PRIORITY_NORMAL, + ClientScope, + PR_UNJOINABLE_THREAD, + THREAD_STACKSIZE); if (!clientThread) { - if (debug_mode) printf("\terror creating client thread %d\n", index); - } else - if (debug_mode) DPRINTF("\tMain created client %d/%d\n", index+1, _clients); + if (debug_mode) { + printf("\terror creating client thread %d\n", index); + } + } else if (debug_mode) { + DPRINTF("\tMain created client %d/%d\n", index+1, _clients); + } } PR_EnterMonitor(clientMonitor); - while(numClients) + while(numClients) { PR_Wait(clientMonitor, PR_INTERVAL_NO_TIMEOUT); + } PR_ExitMonitor(clientMonitor); } @@ -449,15 +513,17 @@ void do_work() SetServerState(MAIN, SERVER_STATE_STARTUP); ServerThread = PR_CreateThread( - PR_USER_THREAD, - ServerThreadFunc, - NULL, - PR_PRIORITY_NORMAL, - ServerScope, - PR_JOINABLE_THREAD, - THREAD_STACKSIZE); + PR_USER_THREAD, + ServerThreadFunc, + NULL, + PR_PRIORITY_NORMAL, + ServerScope, + PR_JOINABLE_THREAD, + THREAD_STACKSIZE); if (!ServerThread) { - if (debug_mode) printf("error creating main server thread\n"); + if (debug_mode) { + printf("error creating main server thread\n"); + } return; } @@ -496,61 +562,63 @@ static void Measure(void (*func)(void), const char *msg) d = (double)PR_IntervalToMicroseconds(stop - start); - if (debug_mode) printf("\n%40s: %6.2f usec\n", msg, d / _iterations); + if (debug_mode) { + printf("\n%40s: %6.2f usec\n", msg, d / _iterations); + } } int main(int argc, char **argv) { - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); - /* main test */ -#ifndef SYMBIAN + /* main test */ if (debug_mode) { - printf("Enter number of iterations: \n"); - scanf("%d", &_iterations); - printf("Enter number of clients : \n"); - scanf("%d", &_clients); - printf("Enter size of client data : \n"); - scanf("%d", &_client_data); - printf("Enter size of server data : \n"); - scanf("%d", &_server_data); - } - else -#endif - { - _iterations = 7; - _clients = 7; - _client_data = 100; - _server_data = 100; - } + printf("Enter number of iterations: \n"); + scanf("%d", &_iterations); + printf("Enter number of clients : \n"); + scanf("%d", &_clients); + printf("Enter size of client data : \n"); + scanf("%d", &_client_data); + printf("Enter size of server data : \n"); + scanf("%d", &_server_data); + } + else + { + _iterations = 7; + _clients = 7; + _client_data = 100; + _server_data = 100; + } if (debug_mode) { - printf("\n\n%d iterations with %d client threads.\n", - _iterations, _clients); - printf("Sending %d bytes of client data and %d bytes of server data\n", - _client_data, _server_data); - } + printf("\n\n%d iterations with %d client threads.\n", + _iterations, _clients); + printf("Sending %d bytes of client data and %d bytes of server data\n", + _client_data, _server_data); + } PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); @@ -563,8 +631,10 @@ int main(int argc, char **argv) PR_Cleanup(); - if(failed_already) - return 1; - else - return 0; + if(failed_already) { + return 1; + } + else { + return 0; + } } diff --git a/nsprpub/pr/tests/servr_uu.c b/nsprpub/pr/tests/servr_uu.c index 82cd7d9c2..8e77d8fa8 100644 --- a/nsprpub/pr/tests/servr_uu.c +++ b/nsprpub/pr/tests/servr_uu.c @@ -8,18 +8,18 @@ ** This server simulates a server running in loopback mode. ** ** The idea is that a single server is created. The server initially creates -** a number of worker threads. Then, with the server running, a number of +** a number of worker threads. Then, with the server running, a number of ** clients are created which start requesting service from the server. ** ** ** Modification History: ** 19-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. ***********************************************************************/ /*********************************************************************** @@ -73,7 +73,9 @@ SetServerState(char *waiter, PRInt32 state) ServerState = state; PR_NotifyCondVar(ServerStateCV); - if (debug_mode) DPRINTF("\t%s changed state to %d\n", waiter, state); + if (debug_mode) { + DPRINTF("\t%s changed state to %d\n", waiter, state); + } PR_Unlock(ServerStateCVLock); } @@ -85,14 +87,17 @@ WaitServerState(char *waiter, PRInt32 state) PR_Lock(ServerStateCVLock); - if (debug_mode) DPRINTF("\t%s waiting for state %d\n", waiter, state); + if (debug_mode) { + DPRINTF("\t%s waiting for state %d\n", waiter, state); + } - while(!(ServerState & state)) + while(!(ServerState & state)) { PR_WaitCondVar(ServerStateCV, PR_INTERVAL_NO_TIMEOUT); + } rv = ServerState; - if (debug_mode) DPRINTF("\t%s resuming from wait for state %d; state now %d\n", - waiter, state, ServerState); + if (debug_mode) DPRINTF("\t%s resuming from wait for state %d; state now %d\n", + waiter, state, ServerState); PR_Unlock(ServerStateCVLock); return rv; @@ -114,15 +119,21 @@ WorkerThreadFunc(void *_listenSock) char *sendBuf; if (debug_mode) DPRINTF("\tServer buffer is %d bytes; %d data, %d netaddrs\n", - _client_data+(2*sizeof(PRNetAddr))+32, _client_data, (2*sizeof(PRNetAddr))+32); + _client_data+(2*sizeof(PRNetAddr))+32, _client_data, (2*sizeof(PRNetAddr))+32); dataBuf = (char *)PR_MALLOC(_client_data + 2*sizeof(PRNetAddr) + 32); if (!dataBuf) - if (debug_mode) printf("\tServer could not malloc space!?\n"); + if (debug_mode) { + printf("\tServer could not malloc space!?\n"); + } sendBuf = (char *)PR_MALLOC(_server_data *sizeof(char)); if (!sendBuf) - if (debug_mode) printf("\tServer could not malloc space!?\n"); + if (debug_mode) { + printf("\tServer could not malloc space!?\n"); + } - if (debug_mode) DPRINTF("\tServer worker thread running\n"); + if (debug_mode) { + DPRINTF("\tServer worker thread running\n"); + } while(1) { PRInt32 bytesToRead = _client_data; @@ -133,9 +144,11 @@ WorkerThreadFunc(void *_listenSock) loops++; - if (debug_mode) DPRINTF("\tServer thread going into accept\n"); + if (debug_mode) { + DPRINTF("\tServer thread going into accept\n"); + } - bytesRead = PR_AcceptRead(listenSock, + bytesRead = PR_AcceptRead(listenSock, &newSock, &rAddr, dataBuf, @@ -143,67 +156,77 @@ WorkerThreadFunc(void *_listenSock) PR_INTERVAL_NO_TIMEOUT); if (bytesRead < 0) { - if (debug_mode) printf("\tServer error in accept (%d)\n", bytesRead); + if (debug_mode) { + printf("\tServer error in accept (%d)\n", bytesRead); + } continue; } - if (debug_mode) DPRINTF("\tServer accepted connection (%d bytes)\n", bytesRead); - + if (debug_mode) { + DPRINTF("\tServer accepted connection (%d bytes)\n", bytesRead); + } + PR_AtomicIncrement(&workerThreadsBusy); -#ifdef SYMBIAN - if (workerThreadsBusy == workerThreads && workerThreads<1) { -#else if (workerThreadsBusy == workerThreads) { -#endif PR_Lock(workerThreadsLock); if (workerThreadsBusy == workerThreads) { PRThread *WorkerThread; WorkerThread = PR_CreateThread( - PR_SYSTEM_THREAD, - WorkerThreadFunc, - listenSock, - PR_PRIORITY_NORMAL, - ServerScope, - PR_UNJOINABLE_THREAD, - THREAD_STACKSIZE); + PR_SYSTEM_THREAD, + WorkerThreadFunc, + listenSock, + PR_PRIORITY_NORMAL, + ServerScope, + PR_UNJOINABLE_THREAD, + THREAD_STACKSIZE); if (!WorkerThread) { - if (debug_mode) printf("Error creating client thread %d\n", workerThreads); + if (debug_mode) { + printf("Error creating client thread %d\n", workerThreads); + } } else { PR_AtomicIncrement(&workerThreads); - if (debug_mode) DPRINTF("\tServer creates worker (%d)\n", workerThreads); + if (debug_mode) { + DPRINTF("\tServer creates worker (%d)\n", workerThreads); + } } } PR_Unlock(workerThreadsLock); } - + bytesToRead -= bytesRead; while (bytesToRead) { - bytesRead = PR_Recv(newSock, - dataBuf, - bytesToRead, - 0, + bytesRead = PR_Recv(newSock, + dataBuf, + bytesToRead, + 0, PR_INTERVAL_NO_TIMEOUT); if (bytesRead < 0) { - if (debug_mode) printf("\tServer error receiving data (%d)\n", bytesRead); + if (debug_mode) { + printf("\tServer error receiving data (%d)\n", bytesRead); + } continue; } - if (debug_mode) DPRINTF("\tServer received %d bytes\n", bytesRead); + if (debug_mode) { + DPRINTF("\tServer received %d bytes\n", bytesRead); + } } bytesWritten = PR_Send(newSock, - sendBuf, - bytesToWrite, - 0, + sendBuf, + bytesToWrite, + 0, PR_INTERVAL_NO_TIMEOUT); if (bytesWritten != _server_data) { - if (debug_mode) printf("\tError sending data to client (%d, %d)\n", - bytesWritten, PR_GetOSError()); + if (debug_mode) printf("\tError sending data to client (%d, %d)\n", + bytesWritten, PR_GetOSError()); } else { - if (debug_mode) DPRINTF("\tServer sent %d bytes\n", bytesWritten); - } + if (debug_mode) { + DPRINTF("\tServer sent %d bytes\n", bytesWritten); + } + } PR_Close(newSock); PR_AtomicDecrement(&workerThreadsBusy); @@ -219,8 +242,12 @@ ServerSetup(void) PRThread *WorkerThread; if ( (listenSocket = PR_NewTCPSocket()) == NULL) { - if (debug_mode) printf("\tServer error creating listen socket\n"); - else failed_already=1; + if (debug_mode) { + printf("\tServer error creating listen socket\n"); + } + else { + failed_already=1; + } return NULL; } @@ -228,8 +255,10 @@ ServerSetup(void) sockOpt.value.reuse_addr = PR_TRUE; if ( PR_SetSocketOption(listenSocket, &sockOpt) == PR_FAILURE) { if (debug_mode) printf("\tServer error setting socket option: OS error %d\n", - PR_GetOSError()); - else failed_already=1; + PR_GetOSError()); + else { + failed_already=1; + } PR_Close(listenSocket); return NULL; } @@ -241,15 +270,21 @@ ServerSetup(void) if ( PR_Bind(listenSocket, &serverAddr) == PR_FAILURE) { if (debug_mode) printf("\tServer error binding to server address: OS error %d\n", - PR_GetOSError()); - else failed_already=1; + PR_GetOSError()); + else { + failed_already=1; + } PR_Close(listenSocket); return NULL; } if ( PR_Listen(listenSocket, 128) == PR_FAILURE) { - if (debug_mode) printf("\tServer error listening to server socket\n"); - else failed_already=1; + if (debug_mode) { + printf("\tServer error listening to server socket\n"); + } + else { + failed_already=1; + } PR_Close(listenSocket); return NULL; @@ -262,21 +297,25 @@ ServerSetup(void) workerThreadsLock = PR_NewLock(); WorkerThread = PR_CreateThread( - PR_SYSTEM_THREAD, - WorkerThreadFunc, - listenSocket, - PR_PRIORITY_NORMAL, - ServerScope, - PR_UNJOINABLE_THREAD, - THREAD_STACKSIZE); + PR_SYSTEM_THREAD, + WorkerThreadFunc, + listenSocket, + PR_PRIORITY_NORMAL, + ServerScope, + PR_UNJOINABLE_THREAD, + THREAD_STACKSIZE); if (!WorkerThread) { - if (debug_mode) printf("error creating working thread\n"); + if (debug_mode) { + printf("error creating working thread\n"); + } PR_Close(listenSocket); return NULL; } PR_AtomicIncrement(&workerThreads); - if (debug_mode) DPRINTF("\tServer created primordial worker thread\n"); + if (debug_mode) { + DPRINTF("\tServer created primordial worker thread\n"); + } return listenSocket; } @@ -294,7 +333,9 @@ ServerThreadFunc(void *unused) SetServerState(SERVER, SERVER_STATE_DEAD); } else { - if (debug_mode) DPRINTF("\tServer up\n"); + if (debug_mode) { + DPRINTF("\tServer up\n"); + } /* Tell clients they can start now. */ SetServerState(SERVER, SERVER_STATE_READY); @@ -325,10 +366,14 @@ ClientThreadFunc(void *unused) sendBuf = (char *)PR_MALLOC(_client_data * sizeof(char)); if (!sendBuf) - if (debug_mode) printf("\tClient could not malloc space!?\n"); + if (debug_mode) { + printf("\tClient could not malloc space!?\n"); + } recvBuf = (char *)PR_MALLOC(_server_data * sizeof(char)); if (!recvBuf) - if (debug_mode) printf("\tClient could not malloc space!?\n"); + if (debug_mode) { + printf("\tClient could not malloc space!?\n"); + } memset(&serverAddr, 0, sizeof(PRNetAddr)); serverAddr.inet.family = PR_AF_INET; @@ -338,59 +383,75 @@ ClientThreadFunc(void *unused) while(numRequests > 0) { if ( (numRequests % 10) == 0 ) - if (debug_mode) printf("."); - if (debug_mode) DPRINTF("\tClient starting request %d\n", numRequests); + if (debug_mode) { + printf("."); + } + if (debug_mode) { + DPRINTF("\tClient starting request %d\n", numRequests); + } clientSocket = PR_NewTCPSocket(); if (!clientSocket) { if (debug_mode) printf("Client error creating socket: OS error %d\n", - PR_GetOSError()); + PR_GetOSError()); continue; } - if (debug_mode) DPRINTF("\tClient connecting\n"); + if (debug_mode) { + DPRINTF("\tClient connecting\n"); + } - rv = PR_Connect(clientSocket, + rv = PR_Connect(clientSocket, &serverAddr, PR_INTERVAL_NO_TIMEOUT); if (!clientSocket) { - if (debug_mode) printf("\tClient error connecting\n"); + if (debug_mode) { + printf("\tClient error connecting\n"); + } continue; } - if (debug_mode) DPRINTF("\tClient connected\n"); + if (debug_mode) { + DPRINTF("\tClient connected\n"); + } - rv = PR_Send(clientSocket, - sendBuf, - _client_data, - 0, + rv = PR_Send(clientSocket, + sendBuf, + _client_data, + 0, PR_INTERVAL_NO_TIMEOUT); if (rv != _client_data) { - if (debug_mode) printf("Client error sending data (%d)\n", rv); + if (debug_mode) { + printf("Client error sending data (%d)\n", rv); + } PR_Close(clientSocket); continue; } - if (debug_mode) DPRINTF("\tClient sent %d bytes\n", rv); + if (debug_mode) { + DPRINTF("\tClient sent %d bytes\n", rv); + } bytesNeeded = _server_data; while(bytesNeeded) { - rv = PR_Recv(clientSocket, - recvBuf, - bytesNeeded, - 0, + rv = PR_Recv(clientSocket, + recvBuf, + bytesNeeded, + 0, PR_INTERVAL_NO_TIMEOUT); if (rv <= 0) { - if (debug_mode) printf("Client error receiving data (%d) (%d/%d)\n", - rv, (_server_data - bytesNeeded), _server_data); + if (debug_mode) printf("Client error receiving data (%d) (%d/%d)\n", + rv, (_server_data - bytesNeeded), _server_data); break; } - if (debug_mode) DPRINTF("\tClient received %d bytes; need %d more\n", rv, bytesNeeded - rv); + if (debug_mode) { + DPRINTF("\tClient received %d bytes; need %d more\n", rv, bytesNeeded - rv); + } bytesNeeded -= rv; } PR_Close(clientSocket); - + PR_AtomicDecrement(&numRequests); } @@ -415,26 +476,30 @@ RunClients(void) for (index=0; index<_clients; index++) { PRThread *clientThread; - + clientThread = PR_CreateThread( - PR_USER_THREAD, - ClientThreadFunc, - NULL, - PR_PRIORITY_NORMAL, - ClientScope, - PR_UNJOINABLE_THREAD, - THREAD_STACKSIZE); + PR_USER_THREAD, + ClientThreadFunc, + NULL, + PR_PRIORITY_NORMAL, + ClientScope, + PR_UNJOINABLE_THREAD, + THREAD_STACKSIZE); if (!clientThread) { - if (debug_mode) printf("\terror creating client thread %d\n", index); - } else - if (debug_mode) DPRINTF("\tMain created client %d/%d\n", index+1, _clients); + if (debug_mode) { + printf("\terror creating client thread %d\n", index); + } + } else if (debug_mode) { + DPRINTF("\tMain created client %d/%d\n", index+1, _clients); + } } PR_EnterMonitor(clientMonitor); - while(numClients) + while(numClients) { PR_Wait(clientMonitor, PR_INTERVAL_NO_TIMEOUT); + } PR_ExitMonitor(clientMonitor); } @@ -448,15 +513,17 @@ void do_work() SetServerState(MAIN, SERVER_STATE_STARTUP); ServerThread = PR_CreateThread( - PR_USER_THREAD, - ServerThreadFunc, - NULL, - PR_PRIORITY_NORMAL, - ServerScope, - PR_JOINABLE_THREAD, - THREAD_STACKSIZE); + PR_USER_THREAD, + ServerThreadFunc, + NULL, + PR_PRIORITY_NORMAL, + ServerScope, + PR_JOINABLE_THREAD, + THREAD_STACKSIZE); if (!ServerThread) { - if (debug_mode) printf("error creating main server thread\n"); + if (debug_mode) { + printf("error creating main server thread\n"); + } return; } @@ -494,61 +561,63 @@ static void Measure(void (*func)(void), const char *msg) d = (double)PR_IntervalToMicroseconds(stop - start); - if (debug_mode) printf("\n%40s: %6.2f usec\n", msg, d / _iterations); + if (debug_mode) { + printf("\n%40s: %6.2f usec\n", msg, d / _iterations); + } } int main(int argc, char **argv) { - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); - /* main test */ -#ifndef SYMBIAN + /* main test */ if (debug_mode) { - printf("Enter number of iterations: \n"); - scanf("%d", &_iterations); - printf("Enter number of clients : \n"); - scanf("%d", &_clients); - printf("Enter size of client data : \n"); - scanf("%d", &_client_data); - printf("Enter size of server data : \n"); - scanf("%d", &_server_data); - } - else -#endif - { - _iterations = 7; - _clients = 7; - _client_data = 100; - _server_data = 100; - } + printf("Enter number of iterations: \n"); + scanf("%d", &_iterations); + printf("Enter number of clients : \n"); + scanf("%d", &_clients); + printf("Enter size of client data : \n"); + scanf("%d", &_client_data); + printf("Enter size of server data : \n"); + scanf("%d", &_server_data); + } + else + { + _iterations = 7; + _clients = 7; + _client_data = 100; + _server_data = 100; + } if (debug_mode) { - printf("\n\n%d iterations with %d client threads.\n", - _iterations, _clients); - printf("Sending %d bytes of client data and %d bytes of server data\n", - _client_data, _server_data); - } + printf("\n\n%d iterations with %d client threads.\n", + _iterations, _clients); + printf("Sending %d bytes of client data and %d bytes of server data\n", + _client_data, _server_data); + } PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); @@ -560,10 +629,12 @@ int main(int argc, char **argv) Measure(do_workUU, "server loop user/user"); PR_Cleanup(); - - if(failed_already) - return 1; - else - return 0; - + + if(failed_already) { + return 1; + } + else { + return 0; + } + } diff --git a/nsprpub/pr/tests/short_thread.c b/nsprpub/pr/tests/short_thread.c index 87294014e..de069e896 100644 --- a/nsprpub/pr/tests/short_thread.c +++ b/nsprpub/pr/tests/short_thread.c @@ -19,40 +19,42 @@ static void housecleaning(void *cur_time); int main (int argc, char **argv) { - static PRIntervalTime thread_start_time; - static PRThread *housekeeping_tid = NULL; - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d"); - - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) - { - if (PL_OPT_BAD == os) continue; - switch (opt->option) - { - case 'd': /* debug mode */ - _debug_on = 1; - break; - default: - break; - } - } - PL_DestroyOptState(opt); - - if (( housekeeping_tid = - PR_CreateThread (PR_USER_THREAD, housecleaning, (void*)&thread_start_time, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, 0)) - == NULL ) { - fprintf(stderr, - "simple_test: Error - PR_CreateThread failed: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); - exit( 1 ); - } - PR_Cleanup(); - return(0); + static PRIntervalTime thread_start_time; + static PRThread *housekeeping_tid = NULL; + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d"); + + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + { + if (PL_OPT_BAD == os) { + continue; + } + switch (opt->option) + { + case 'd': /* debug mode */ + _debug_on = 1; + break; + default: + break; + } + } + PL_DestroyOptState(opt); + + if (( housekeeping_tid = + PR_CreateThread (PR_USER_THREAD, housecleaning, (void*)&thread_start_time, + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, 0)) + == NULL ) { + fprintf(stderr, + "simple_test: Error - PR_CreateThread failed: (%ld, %ld)\n", + PR_GetError(), PR_GetOSError()); + exit( 1 ); + } + PR_Cleanup(); + return(0); } static void -housecleaning (void *cur_time) +housecleaning (void *cur_time) { - DPRINTF(("Child Thread exiting\n")); + DPRINTF(("Child Thread exiting\n")); } diff --git a/nsprpub/pr/tests/sigpipe.c b/nsprpub/pr/tests/sigpipe.c index 0d37cbeab..02ba9114f 100644 --- a/nsprpub/pr/tests/sigpipe.c +++ b/nsprpub/pr/tests/sigpipe.c @@ -60,12 +60,7 @@ static void Test(void *arg) fprintf(stderr, "write to broken pipe should have failed with EPIPE but returned %d\n", rv); exit(1); } -#ifdef SYMBIAN - /* Have mercy on the unknown 142 errno, it seems ok */ - if (errno != EPIPE && errno != 142) { -#else if (errno != EPIPE) { -#endif fprintf(stderr, "write to broken pipe failed but with wrong errno: %d\n", errno); exit(1); } @@ -81,7 +76,7 @@ int main(int argc, char **argv) PR_SetError(0, 0); thread = PR_CreateThread(PR_USER_THREAD, Test, NULL, PR_PRIORITY_NORMAL, - PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); if (thread == NULL) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); diff --git a/nsprpub/pr/tests/sleep.c b/nsprpub/pr/tests/sleep.c index 43ef34cd8..3e00acab0 100644 --- a/nsprpub/pr/tests/sleep.c +++ b/nsprpub/pr/tests/sleep.c @@ -30,58 +30,66 @@ static void Other(void *unused) fprintf(stderr, "."); didit += 1; } - if (didit < 5) rv = 1; + if (didit < 5) { + rv = 1; + } } int main(int argc, char **argv) { PRUint32 elapsed; PRThread *thread; - struct timeval timein, timeout; + struct timeval timein, timeout; PRInt32 onePercent = 3000000UL / 100UL; - fprintf (stderr, "First sleep will sleep 3 seconds.\n"); - fprintf (stderr, " sleep 1 begin\n"); + fprintf (stderr, "First sleep will sleep 3 seconds.\n"); + fprintf (stderr, " sleep 1 begin\n"); (void)GTOD(&timein); - sleep (3); + sleep (3); (void)GTOD(&timeout); - fprintf (stderr, " sleep 1 end\n"); + fprintf (stderr, " sleep 1 end\n"); elapsed = 1000000UL * (timeout.tv_sec - timein.tv_sec); elapsed += (timeout.tv_usec - timein.tv_usec); fprintf(stderr, "elapsed %u usecs\n", elapsed); - if (labs(elapsed - 3000000UL) > onePercent) rv = 1; + if (labs(elapsed - 3000000UL) > onePercent) { + rv = 1; + } - PR_Init (PR_USER_THREAD, PR_PRIORITY_NORMAL, 100); + PR_Init (PR_USER_THREAD, PR_PRIORITY_NORMAL, 100); PR_STDIO_INIT(); - fprintf (stderr, "Second sleep should do the same (does it?).\n"); - fprintf (stderr, " sleep 2 begin\n"); + fprintf (stderr, "Second sleep should do the same (does it?).\n"); + fprintf (stderr, " sleep 2 begin\n"); (void)GTOD(&timein); - sleep (3); + sleep (3); (void)GTOD(&timeout); - fprintf (stderr, " sleep 2 end\n"); + fprintf (stderr, " sleep 2 end\n"); elapsed = 1000000UL * (timeout.tv_sec - timein.tv_sec); elapsed += (timeout.tv_usec - timein.tv_usec); fprintf(stderr, "elapsed %u usecs\n", elapsed); - if (labs(elapsed - 3000000UL) > onePercent) rv = 1; + if (labs(elapsed - 3000000UL) > onePercent) { + rv = 1; + } - fprintf (stderr, "What happens to other threads?\n"); - fprintf (stderr, "You should see dots every quarter second.\n"); - fprintf (stderr, "If you don't, you're probably running on classic NSPR.\n"); + fprintf (stderr, "What happens to other threads?\n"); + fprintf (stderr, "You should see dots every quarter second.\n"); + fprintf (stderr, "If you don't, you're probably running on classic NSPR.\n"); thread = PR_CreateThread( - PR_USER_THREAD, Other, NULL, PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); - fprintf (stderr, " sleep 2 begin\n"); + PR_USER_THREAD, Other, NULL, PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + fprintf (stderr, " sleep 2 begin\n"); (void)GTOD(&timein); - sleep (3); + sleep (3); (void)GTOD(&timeout); - fprintf (stderr, " sleep 2 end\n"); + fprintf (stderr, " sleep 2 end\n"); PR_Interrupt(thread); PR_JoinThread(thread); elapsed = 1000000UL * (timeout.tv_sec - timein.tv_sec); elapsed += (timeout.tv_usec - timein.tv_usec); fprintf(stderr, "elapsed %u usecs\n", elapsed); - if (labs(elapsed - 3000000UL) > onePercent) rv = 1; + if (labs(elapsed - 3000000UL) > onePercent) { + rv = 1; + } fprintf(stderr, "%s\n", (0 == rv) ? "PASSED" : "FAILED"); return rv; } @@ -90,7 +98,7 @@ int main(int argc, char **argv) PRIntn main() { - return 2; + return 2; } #endif /* defined(XP_UNIX) */ diff --git a/nsprpub/pr/tests/socket.c b/nsprpub/pr/tests/socket.c index 92f019d01..a4925350c 100644 --- a/nsprpub/pr/tests/socket.c +++ b/nsprpub/pr/tests/socket.c @@ -44,36 +44,32 @@ static int test_cancelio = 0; char *TEST_DIR = "prdir"; char *SMALL_FILE_NAME = "prsmallf"; char *LARGE_FILE_NAME = "prlargef"; -#elif defined(SYMBIAN) -char *TEST_DIR = "c:\\data\\prsocket"; -char *SMALL_FILE_NAME = "c:\\data\\prsocket\\small_file"; -char *LARGE_FILE_NAME = "c:\\data\\prsocket\\large_file"; #else char *TEST_DIR = "/tmp/prsocket_test_dir"; char *SMALL_FILE_NAME = "/tmp/prsocket_test_dir/small_file"; char *LARGE_FILE_NAME = "/tmp/prsocket_test_dir/large_file"; #endif -#define SMALL_FILE_SIZE (3 * 1024) /* 3 KB */ -#define SMALL_FILE_OFFSET_1 (512) -#define SMALL_FILE_LEN_1 (1 * 1024) /* 1 KB */ -#define SMALL_FILE_OFFSET_2 (75) -#define SMALL_FILE_LEN_2 (758) -#define SMALL_FILE_OFFSET_3 (1024) -#define SMALL_FILE_LEN_3 (SMALL_FILE_SIZE - SMALL_FILE_OFFSET_3) -#define SMALL_FILE_HEADER_SIZE (64) /* 64 bytes */ -#define SMALL_FILE_TRAILER_SIZE (128) /* 128 bytes */ - -#define LARGE_FILE_SIZE (3 * 1024 * 1024) /* 3 MB */ -#define LARGE_FILE_OFFSET_1 (0) -#define LARGE_FILE_LEN_1 (2 * 1024 * 1024) /* 2 MB */ -#define LARGE_FILE_OFFSET_2 (64) -#define LARGE_FILE_LEN_2 (1 * 1024 * 1024 + 75) -#define LARGE_FILE_OFFSET_3 (2 * 1024 * 1024 - 128) -#define LARGE_FILE_LEN_3 (LARGE_FILE_SIZE - LARGE_FILE_OFFSET_3) -#define LARGE_FILE_OFFSET_4 PR_GetPageSize() -#define LARGE_FILE_LEN_4 769 -#define LARGE_FILE_HEADER_SIZE (512) -#define LARGE_FILE_TRAILER_SIZE (64) +#define SMALL_FILE_SIZE (3 * 1024) /* 3 KB */ +#define SMALL_FILE_OFFSET_1 (512) +#define SMALL_FILE_LEN_1 (1 * 1024) /* 1 KB */ +#define SMALL_FILE_OFFSET_2 (75) +#define SMALL_FILE_LEN_2 (758) +#define SMALL_FILE_OFFSET_3 (1024) +#define SMALL_FILE_LEN_3 (SMALL_FILE_SIZE - SMALL_FILE_OFFSET_3) +#define SMALL_FILE_HEADER_SIZE (64) /* 64 bytes */ +#define SMALL_FILE_TRAILER_SIZE (128) /* 128 bytes */ + +#define LARGE_FILE_SIZE (3 * 1024 * 1024) /* 3 MB */ +#define LARGE_FILE_OFFSET_1 (0) +#define LARGE_FILE_LEN_1 (2 * 1024 * 1024) /* 2 MB */ +#define LARGE_FILE_OFFSET_2 (64) +#define LARGE_FILE_LEN_2 (1 * 1024 * 1024 + 75) +#define LARGE_FILE_OFFSET_3 (2 * 1024 * 1024 - 128) +#define LARGE_FILE_LEN_3 (LARGE_FILE_SIZE - LARGE_FILE_OFFSET_3) +#define LARGE_FILE_OFFSET_4 PR_GetPageSize() +#define LARGE_FILE_LEN_4 769 +#define LARGE_FILE_HEADER_SIZE (512) +#define LARGE_FILE_TRAILER_SIZE (64) #define BUF_DATA_SIZE (2 * 1024) #define TCP_MESG_SIZE 1024 @@ -82,14 +78,10 @@ char *LARGE_FILE_NAME = "/tmp/prsocket_test_dir/large_file"; * local host will not be lost */ #define UDP_DGRAM_SIZE 128 -#define NUM_TCP_CLIENTS 5 /* for a listen queue depth of 5 */ +#define NUM_TCP_CLIENTS 5 /* for a listen queue depth of 5 */ #define NUM_UDP_CLIENTS 10 -#ifdef SYMBIAN -#define NUM_TRANSMITFILE_CLIENTS 1 -#else #define NUM_TRANSMITFILE_CLIENTS 4 -#endif #define NUM_TCP_CONNECTIONS_PER_CLIENT 5 #define NUM_TCP_MESGS_PER_CONNECTION 10 @@ -149,7 +141,7 @@ typedef struct Client_Param { /* the sendfile method in emuSendFileMethods */ static PRInt32 PR_CALLBACK emu_SendFile(PRFileDesc *sd, PRSendFileData *sfd, - PRTransmitFileFlags flags, PRIntervalTime timeout) + PRTransmitFileFlags flags, PRIntervalTime timeout) { return PR_EmulateSendFile(sd, sfd, flags, timeout); } @@ -157,7 +149,7 @@ emu_SendFile(PRFileDesc *sd, PRSendFileData *sfd, /* the transmitfile method in emuSendFileMethods */ static PRInt32 PR_CALLBACK emu_TransmitFile(PRFileDesc *sd, PRFileDesc *fd, const void *headers, - PRInt32 hlen, PRTransmitFileFlags flags, PRIntervalTime timeout) + PRInt32 hlen, PRTransmitFileFlags flags, PRIntervalTime timeout) { PRSendFileData sfd; @@ -181,33 +173,35 @@ readn(PRFileDesc *sockfd, char *buf, int len) int rem; int bytes; int offset = 0; - int err; - PRIntervalTime timeout = PR_INTERVAL_NO_TIMEOUT; + int err; + PRIntervalTime timeout = PR_INTERVAL_NO_TIMEOUT; - if (test_cancelio) - timeout = PR_SecondsToInterval(2); + if (test_cancelio) { + timeout = PR_SecondsToInterval(2); + } for (rem=len; rem; offset += bytes, rem -= bytes) { DPRINTF(("thread = 0x%lx: calling PR_Recv, bytes = %d\n", - PR_GetCurrentThread(), rem)); + PR_GetCurrentThread(), rem)); retry: bytes = PR_Recv(sockfd, buf + offset, rem, 0, - timeout); + timeout); DPRINTF(("thread = 0x%lx: returning from PR_Recv, bytes = %d\n", - PR_GetCurrentThread(), bytes)); + PR_GetCurrentThread(), bytes)); if (bytes < 0) { #ifdef WINNT - printf("PR_Recv: error = %d oserr = %d\n",(err = PR_GetError()), - PR_GetOSError()); - if ((test_cancelio) && (err == PR_IO_TIMEOUT_ERROR)) { - if (PR_NT_CancelIo(sockfd) != PR_SUCCESS) - printf("PR_NT_CancelIO: error = %d\n",PR_GetError()); - timeout = PR_INTERVAL_NO_TIMEOUT; - goto retry; - } + printf("PR_Recv: error = %d oserr = %d\n",(err = PR_GetError()), + PR_GetOSError()); + if ((test_cancelio) && (err == PR_IO_TIMEOUT_ERROR)) { + if (PR_NT_CancelIo(sockfd) != PR_SUCCESS) { + printf("PR_NT_CancelIO: error = %d\n",PR_GetError()); + } + timeout = PR_INTERVAL_NO_TIMEOUT; + goto retry; + } #endif - return -1; - } + return -1; + } } return len; } @@ -225,13 +219,14 @@ writen(PRFileDesc *sockfd, char *buf, int len) for (rem=len; rem; offset += bytes, rem -= bytes) { DPRINTF(("thread = 0x%lx: calling PR_Send, bytes = %d\n", - PR_GetCurrentThread(), rem)); + PR_GetCurrentThread(), rem)); bytes = PR_Send(sockfd, buf + offset, rem, 0, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); DPRINTF(("thread = 0x%lx: returning from PR_Send, bytes = %d\n", - PR_GetCurrentThread(), bytes)); - if (bytes <= 0) + PR_GetCurrentThread(), bytes)); + if (bytes <= 0) { return -1; + } } return len; } @@ -270,7 +265,6 @@ Serve_Client(void *arg) goto exit; } /* Shutdown only RCV will cause error on Symbian OS */ -#if !defined(SYMBIAN) /* * shutdown reads, after the last read */ @@ -278,9 +272,8 @@ Serve_Client(void *arg) if (PR_Shutdown(sockfd, PR_SHUTDOWN_RCV) < 0) { fprintf(stderr,"prsocket_test: ERROR - PR_Shutdown\n"); } -#endif DPRINTF(("Serve_Client [0x%lx]: inbuf[0] = 0x%lx\n",PR_GetCurrentThread(), - (*((int *) in_buf->data)))); + (*((int *) in_buf->data)))); if (writen(sockfd, in_buf->data, bytes) < bytes) { fprintf(stderr,"prsocket_test: ERROR - Serve_Client:writen\n"); failed_already=1; @@ -303,59 +296,61 @@ exit: } PRThread* create_new_thread(PRThreadType type, - void (*start)(void *arg), - void *arg, - PRThreadPriority priority, - PRThreadScope scope, - PRThreadState state, - PRUint32 stackSize, PRInt32 index) + void (*start)(void *arg), + void *arg, + PRThreadPriority priority, + PRThreadScope scope, + PRThreadState state, + PRUint32 stackSize, PRInt32 index) { -PRInt32 native_thread = 0; + PRInt32 native_thread = 0; - PR_ASSERT(state == PR_UNJOINABLE_THREAD); + PR_ASSERT(state == PR_UNJOINABLE_THREAD); #if defined(_PR_PTHREADS) || defined(WIN32) - switch(index % 4) { - case 0: - scope = (PR_LOCAL_THREAD); - break; - case 1: - scope = (PR_GLOBAL_THREAD); - break; - case 2: - scope = (PR_GLOBAL_BOUND_THREAD); - break; - case 3: - native_thread = 1; - break; - default: - PR_NOT_REACHED("Invalid scope"); - break; - } - if (native_thread) { + switch(index % 4) { + case 0: + scope = (PR_LOCAL_THREAD); + break; + case 1: + scope = (PR_GLOBAL_THREAD); + break; + case 2: + scope = (PR_GLOBAL_BOUND_THREAD); + break; + case 3: + native_thread = 1; + break; + default: + PR_NOT_REACHED("Invalid scope"); + break; + } + if (native_thread) { #if defined(_PR_PTHREADS) - pthread_t tid; - if (!pthread_create(&tid, NULL, (void * (*)(void *)) start, arg)) - return((PRThread *) tid); - else - return (NULL); + pthread_t tid; + if (!pthread_create(&tid, NULL, (void * (*)(void *)) start, arg)) { + return((PRThread *) tid); + } + else { + return (NULL); + } #else - HANDLE thandle; - unsigned tid; - - thandle = (HANDLE) _beginthreadex( - NULL, - stackSize, - (unsigned (__stdcall *)(void *))start, - arg, - STACK_SIZE_PARAM_IS_A_RESERVATION, - &tid); - return((PRThread *) thandle); + HANDLE thandle; + unsigned tid; + + thandle = (HANDLE) _beginthreadex( + NULL, + stackSize, + (unsigned (__stdcall *)(void *))start, + arg, + STACK_SIZE_PARAM_IS_A_RESERVATION, + &tid); + return((PRThread *) thandle); #endif - } else { - return(PR_CreateThread(type,start,arg,priority,scope,state,stackSize)); - } + } else { + return(PR_CreateThread(type,start,arg,priority,scope,state,stackSize)); + } #else - return(PR_CreateThread(type,start,arg,priority,scope,state,stackSize)); + return(PR_CreateThread(type,start,arg,priority,scope,state,stackSize)); #endif } @@ -377,28 +372,29 @@ TCP_Server(void *arg) /* * Create a tcp socket */ - if ((sockfd = PR_OpenTCPSocket(server_domain)) == NULL) { + if ((sockfd = PR_OpenTCPSocket(server_domain)) == NULL) { fprintf(stderr,"prsocket_test: PR_NewTCPSocket failed\n"); goto exit; } - memset(&netaddr, 0 , sizeof(netaddr)); - - if (PR_SetNetAddr(PR_IpAddrAny, server_domain, TCP_SERVER_PORT, - &netaddr) == PR_FAILURE) { + memset(&netaddr, 0, sizeof(netaddr)); + + if (PR_SetNetAddr(PR_IpAddrAny, server_domain, TCP_SERVER_PORT, + &netaddr) == PR_FAILURE) { fprintf(stderr,"prsocket_test: PR_SetNetAddr failed\n"); goto exit; - } + } /* * try a few times to bind server's address, if addresses are in * use */ i = 0; - + while (PR_Bind(sockfd, &netaddr) < 0) { if (PR_GetError() == PR_ADDRESS_IN_USE_ERROR) { netaddr.inet.port += 2; - if (i++ < SERVER_MAX_BIND_COUNT) + if (i++ < SERVER_MAX_BIND_COUNT) { continue; + } } fprintf(stderr,"prsocket_test: ERROR - PR_Bind failed\n"); perror("PR_Bind"); @@ -419,16 +415,16 @@ TCP_Server(void *arg) } DPRINTF(("TCP_Server: PR_BIND netaddr.inet.ip = 0x%lx, netaddr.inet.port = %d\n", - netaddr.inet.ip, netaddr.inet.port)); - if (PR_SetNetAddr(PR_IpAddrLoopback, client_domain, - PR_ntohs(PR_NetAddrInetPort(&netaddr)), - &tcp_server_addr) == PR_FAILURE) { + netaddr.inet.ip, netaddr.inet.port)); + if (PR_SetNetAddr(PR_IpAddrLoopback, client_domain, + PR_ntohs(PR_NetAddrInetPort(&netaddr)), + &tcp_server_addr) == PR_FAILURE) { fprintf(stderr,"prsocket_test: PR_SetNetAddr failed\n"); goto exit; - } - if ((client_domain == PR_AF_INET6) && (server_domain == PR_AF_INET)) - PR_ConvertIPv4AddrToIPv6(PR_htonl(INADDR_LOOPBACK), - &tcp_server_addr.ipv6.ip); + } + if ((client_domain == PR_AF_INET6) && (server_domain == PR_AF_INET)) + PR_ConvertIPv4AddrToIPv6(PR_htonl(INADDR_LOOPBACK), + &tcp_server_addr.ipv6.ip); /* * Wake up parent thread because server address is bound and made @@ -440,13 +436,13 @@ TCP_Server(void *arg) /* test both null and non-null 'addr' argument to PR_Accept */ PRNetAddr *addrp = (i%2 ? &netaddr: NULL); - DPRINTF(("TCP_Server: Accepting connection\n")); + DPRINTF(("TCP_Server: Accepting connection\n")); if ((newsockfd = PR_Accept(sockfd, addrp, - PR_INTERVAL_NO_TIMEOUT)) == NULL) { + PR_INTERVAL_NO_TIMEOUT)) == NULL) { fprintf(stderr,"prsocket_test: ERROR - PR_Accept failed\n"); goto exit; } - DPRINTF(("TCP_Server: Accepted connection\n")); + DPRINTF(("TCP_Server: Accepted connection\n")); scp = PR_NEW(Serve_Client_Param); if (scp == NULL) { fprintf(stderr,"prsocket_test: PR_NEW failed\n"); @@ -460,11 +456,11 @@ TCP_Server(void *arg) scp->datalen = sp->datalen; t = create_new_thread(PR_USER_THREAD, - Serve_Client, (void *)scp, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, - 0, i); + Serve_Client, (void *)scp, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, + 0, i); if (t == NULL) { fprintf(stderr,"prsocket_test: PR_CreateThread failed\n"); failed_already=1; @@ -509,18 +505,18 @@ UDP_Server(void *arg) /* * Create a udp socket */ - if ((sockfd = PR_OpenUDPSocket(server_domain)) == NULL) { + if ((sockfd = PR_OpenUDPSocket(server_domain)) == NULL) { fprintf(stderr,"prsocket_test: PR_NewUDPSocket failed\n"); failed_already=1; return; } - memset(&netaddr, 0 , sizeof(netaddr)); - if (PR_SetNetAddr(PR_IpAddrAny, server_domain, UDP_SERVER_PORT, - &netaddr) == PR_FAILURE) { + memset(&netaddr, 0, sizeof(netaddr)); + if (PR_SetNetAddr(PR_IpAddrAny, server_domain, UDP_SERVER_PORT, + &netaddr) == PR_FAILURE) { fprintf(stderr,"prsocket_test: PR_SetNetAddr failed\n"); failed_already=1; return; - } + } /* * try a few times to bind server's address, if addresses are in * use @@ -529,8 +525,9 @@ UDP_Server(void *arg) while (PR_Bind(sockfd, &netaddr) < 0) { if (PR_GetError() == PR_ADDRESS_IN_USE_ERROR) { netaddr.inet.port += 2; - if (i++ < SERVER_MAX_BIND_COUNT) + if (i++ < SERVER_MAX_BIND_COUNT) { continue; + } } fprintf(stderr,"prsocket_test: ERROR - PR_Bind failed\n"); perror("PR_Bind"); @@ -545,24 +542,24 @@ UDP_Server(void *arg) } DPRINTF(("PR_Bind: UDP Server netaddr.inet.ip = 0x%lx, netaddr.inet.port = %d\n", - netaddr.inet.ip, netaddr.inet.port)); + netaddr.inet.ip, netaddr.inet.port)); /* * We can't use the IP address returned by PR_GetSockName in * netaddr.inet.ip because netaddr.inet.ip is returned * as 0 (= PR_INADDR_ANY). */ - if (PR_SetNetAddr(PR_IpAddrLoopback, client_domain, - PR_ntohs(PR_NetAddrInetPort(&netaddr)), - &udp_server_addr) == PR_FAILURE) { + if (PR_SetNetAddr(PR_IpAddrLoopback, client_domain, + PR_ntohs(PR_NetAddrInetPort(&netaddr)), + &udp_server_addr) == PR_FAILURE) { fprintf(stderr,"prsocket_test: PR_SetNetAddr failed\n"); failed_already=1; return; - } - if ((client_domain == PR_AF_INET6) && (server_domain == PR_AF_INET)) - PR_ConvertIPv4AddrToIPv6(PR_htonl(INADDR_LOOPBACK), - &udp_server_addr.ipv6.ip); - + } + if ((client_domain == PR_AF_INET6) && (server_domain == PR_AF_INET)) + PR_ConvertIPv4AddrToIPv6(PR_htonl(INADDR_LOOPBACK), + &udp_server_addr.ipv6.ip); + /* * Wake up parent thread because server address is bound and made * available in the global variable 'udp_server_addr' @@ -580,22 +577,22 @@ UDP_Server(void *arg) * Receive datagrams from clients and send them back, unmodified, to the * clients */ - memset(&netaddr, 0 , sizeof(netaddr)); + memset(&netaddr, 0, sizeof(netaddr)); for (i = 0; i < (num_udp_clients * num_udp_datagrams_per_client); i++) { DPRINTF(("UDP_Server: calling PR_RecvFrom client - ip = 0x%lx, port = %d bytes = %d inbuf = 0x%lx, inbuf[0] = 0x%lx\n", - netaddr.inet.ip, netaddr.inet.port, bytes, in_buf->data, - in_buf->data[0])); + netaddr.inet.ip, netaddr.inet.port, bytes, in_buf->data, + in_buf->data[0])); rv = PR_RecvFrom(sockfd, in_buf->data, bytes, 0, &netaddr, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); DPRINTF(("UDP_Server: PR_RecvFrom client - ip = 0x%lx, port = %d bytes = %d inbuf = 0x%lx, inbuf[0] = 0x%lx\n", - netaddr.inet.ip, netaddr.inet.port, rv, in_buf->data, - in_buf->data[0])); + netaddr.inet.ip, netaddr.inet.port, rv, in_buf->data, + in_buf->data[0])); if (rv != bytes) { return; } rv = PR_SendTo(sockfd, in_buf->data, bytes, 0, &netaddr, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); if (rv != bytes) { return; } @@ -653,9 +650,9 @@ TCP_Client(void *arg) failed_already=1; return; } - if (PR_Connect(sockfd, &netaddr,PR_INTERVAL_NO_TIMEOUT) < 0){ - fprintf(stderr, "PR_Connect failed: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); + if (PR_Connect(sockfd, &netaddr,PR_INTERVAL_NO_TIMEOUT) < 0) { + fprintf(stderr, "PR_Connect failed: (%ld, %ld)\n", + PR_GetError(), PR_GetOSError()); failed_already=1; return; } @@ -668,8 +665,9 @@ TCP_Client(void *arg) * write to server */ #ifdef WINNT - if (test_cancelio && (j == 0)) - PR_Sleep(PR_SecondsToInterval(12)); + if (test_cancelio && (j == 0)) { + PR_Sleep(PR_SecondsToInterval(12)); + } #endif if (writen(sockfd, out_buf->data, bytes) < bytes) { fprintf(stderr,"prsocket_test: ERROR - TCP_Client:writen\n"); @@ -677,7 +675,7 @@ TCP_Client(void *arg) return; } DPRINTF(("TCP Client [0x%lx]: out_buf = 0x%lx out_buf[0] = 0x%lx\n", - PR_GetCurrentThread(), out_buf, (*((int *) out_buf->data)))); + PR_GetCurrentThread(), out_buf, (*((int *) out_buf->data)))); if (readn(sockfd, in_buf->data, bytes) < bytes) { fprintf(stderr,"prsocket_test: ERROR - TCP_Client:readn\n"); failed_already=1; @@ -697,9 +695,6 @@ TCP_Client(void *arg) */ if (PR_Shutdown(sockfd, PR_SHUTDOWN_BOTH) < 0) { fprintf(stderr,"prsocket_test: ERROR - PR_Shutdown\n"); -#if defined(SYMBIAN) - if (EPIPE != errno) -#endif failed_already=1; } PR_Close(sockfd); @@ -722,7 +717,7 @@ TCP_Client(void *arg) /* * UDP_Client * Client Thread - * Create a socket and bind an address + * Create a socket and bind an address * Communicate with the server at the address specified in the argument. * Fill in a buffer, write data to server, read it back and check * for data corruption. @@ -761,13 +756,13 @@ UDP_Client(void *arg) * bind an address for the client, let the system chose the port * number */ - memset(&netaddr, 0 , sizeof(netaddr)); - if (PR_SetNetAddr(PR_IpAddrAny, client_domain, 0, - &netaddr) == PR_FAILURE) { + memset(&netaddr, 0, sizeof(netaddr)); + if (PR_SetNetAddr(PR_IpAddrAny, client_domain, 0, + &netaddr) == PR_FAILURE) { fprintf(stderr,"prsocket_test: PR_SetNetAddr failed\n"); failed_already=1; return; - } + } if (PR_Bind(sockfd, &netaddr) < 0) { fprintf(stderr,"prsocket_test: ERROR - PR_Bind failed\n"); perror("PR_Bind"); @@ -781,12 +776,12 @@ UDP_Client(void *arg) } DPRINTF(("PR_Bind: UDP Client netaddr.inet.ip = 0x%lx, netaddr.inet.port = %d\n", - netaddr.inet.ip, netaddr.inet.port)); + netaddr.inet.ip, netaddr.inet.port)); netaddr = cp->server_addr; if (cp->udp_connect) { - if (PR_Connect(sockfd, &netaddr,PR_INTERVAL_NO_TIMEOUT) < 0){ + if (PR_Connect(sockfd, &netaddr,PR_INTERVAL_NO_TIMEOUT) < 0) { fprintf(stderr,"prsocket_test: PR_Connect failed\n"); failed_already=1; return; @@ -798,33 +793,33 @@ UDP_Client(void *arg) * fill in random data */ DPRINTF(("UDP_Client [0x%lx]: out_buf = 0x%lx bytes = 0x%lx\n", - PR_GetCurrentThread(), out_buf->data, bytes)); + PR_GetCurrentThread(), out_buf->data, bytes)); memset(out_buf->data, ((PRInt32) (&netaddr)) + i, bytes); /* * write to server */ if (cp->udp_connect) rv = PR_Send(sockfd, out_buf->data, bytes, 0, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); else rv = PR_SendTo(sockfd, out_buf->data, bytes, 0, &netaddr, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); if (rv != bytes) { return; } DPRINTF(("UDP_Client [0x%lx]: out_buf = 0x%lx out_buf[0] = 0x%lx\n", - PR_GetCurrentThread(), out_buf, (*((int *) out_buf->data)))); + PR_GetCurrentThread(), out_buf, (*((int *) out_buf->data)))); if (cp->udp_connect) rv = PR_Recv(sockfd, in_buf->data, bytes, 0, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); else rv = PR_RecvFrom(sockfd, in_buf->data, bytes, 0, &netaddr, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); if (rv != bytes) { return; } DPRINTF(("UDP_Client [0x%lx]: in_buf = 0x%lx in_buf[0] = 0x%lx\n", - PR_GetCurrentThread(), in_buf, (*((int *) in_buf->data)))); + PR_GetCurrentThread(), in_buf, (*((int *) in_buf->data)))); /* * verify the data read */ @@ -853,7 +848,7 @@ UDP_Client(void *arg) /* * TCP_Socket_Client_Server_Test - concurrent server test - * + * * One server and several clients are started * Each client connects to the server and sends a chunk of data * For each connection, server starts another thread to read the data @@ -905,11 +900,11 @@ TCP_Socket_Client_Server_Test(void) sparamp->exit_counter = &thread_count; sparamp->datalen = datalen; t = PR_CreateThread(PR_USER_THREAD, - TCP_Server, (void *)sparamp, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, - 0); + TCP_Server, (void *)sparamp, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, + 0); if (t == NULL) { fprintf(stderr,"prsocket_test: PR_CreateThread failed\n"); failed_already=1; @@ -939,11 +934,11 @@ TCP_Socket_Client_Server_Test(void) cparamp->datalen = datalen; for (i = 0; i < num_tcp_clients; i++) { t = create_new_thread(PR_USER_THREAD, - TCP_Client, (void *) cparamp, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, - 0, i); + TCP_Client, (void *) cparamp, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, + 0, i); if (t == NULL) { fprintf(stderr,"prsocket_test: PR_CreateThread failed\n"); failed_already=1; @@ -960,16 +955,16 @@ TCP_Socket_Client_Server_Test(void) PR_ExitMonitor(mon2); printf("%30s","TCP_Socket_Client_Server_Test:"); printf("%2ld Server %2ld Clients %2ld connections_per_client\n",1l, - num_tcp_clients, num_tcp_connections_per_client); + num_tcp_clients, num_tcp_connections_per_client); printf("%30s %2ld messages_per_connection %4ld bytes_per_message\n",":", - num_tcp_mesgs_per_connection, tcp_mesg_size); + num_tcp_mesgs_per_connection, tcp_mesg_size); return 0; } /* * UDP_Socket_Client_Server_Test - iterative server test - * + * * One server and several clients are started * Each client connects to the server and sends a chunk of data * For each connection, server starts another thread to read the data @@ -1023,11 +1018,11 @@ UDP_Socket_Client_Server_Test(void) sparamp->datalen = datalen; DPRINTF(("Creating UDP server")); t = PR_CreateThread(PR_USER_THREAD, - UDP_Server, (void *)sparamp, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, - 0); + UDP_Server, (void *)sparamp, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, + 0); if (t == NULL) { fprintf(stderr,"prsocket_test: PR_CreateThread failed\n"); failed_already=1; @@ -1059,17 +1054,19 @@ UDP_Socket_Client_Server_Test(void) * Cause every other client thread to connect udp sockets */ cparamp->udp_connect = udp_connect; - if (udp_connect) + if (udp_connect) { udp_connect = 0; - else + } + else { udp_connect = 1; + } DPRINTF(("Creating UDP client %d\n", i)); t = PR_CreateThread(PR_USER_THREAD, - UDP_Client, (void *) cparamp, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, - 0); + UDP_Client, (void *) cparamp, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, + 0); if (t == NULL) { fprintf(stderr,"prsocket_test: PR_CreateThread failed\n"); failed_already=1; @@ -1086,7 +1083,7 @@ UDP_Socket_Client_Server_Test(void) printf("%30s","UDP_Socket_Client_Server_Test: "); printf("%2ld Server %2ld Clients\n",1l, num_udp_clients); printf("%30s %2ld datagrams_per_client %4ld bytes_per_datagram\n",":", - num_udp_datagrams_per_client, udp_datagram_size); + num_udp_datagrams_per_client, udp_datagram_size); return 0; } @@ -1105,17 +1102,17 @@ TransmitFile_Client(void *arg) union PRNetAddr netaddr; char *small_buf, *large_buf; Client_Param *cp = (Client_Param *) arg; - PRInt32 rlen; + PRInt32 rlen; small_buf = (char*)PR_Malloc(SMALL_FILE_SIZE + SMALL_FILE_HEADER_SIZE + - SMALL_FILE_TRAILER_SIZE); + SMALL_FILE_TRAILER_SIZE); if (small_buf == NULL) { fprintf(stderr,"prsocket_test: failed to alloc buffer\n"); failed_already=1; return; } large_buf = (char*)PR_Malloc(LARGE_FILE_SIZE + LARGE_FILE_HEADER_SIZE + - LARGE_FILE_TRAILER_SIZE); + LARGE_FILE_TRAILER_SIZE); if (large_buf == NULL) { fprintf(stderr,"prsocket_test: failed to alloc buffer\n"); failed_already=1; @@ -1131,7 +1128,7 @@ TransmitFile_Client(void *arg) return; } - if (PR_Connect(sockfd, &netaddr,PR_INTERVAL_NO_TIMEOUT) < 0){ + if (PR_Connect(sockfd, &netaddr,PR_INTERVAL_NO_TIMEOUT) < 0) { fprintf(stderr,"prsocket_test: PR_Connect failed\n"); failed_already=1; return; @@ -1142,22 +1139,22 @@ TransmitFile_Client(void *arg) if (readn(sockfd, small_buf, SMALL_FILE_SIZE + SMALL_FILE_HEADER_SIZE) != (SMALL_FILE_SIZE + SMALL_FILE_HEADER_SIZE)) { fprintf(stderr, - "prsocket_test: TransmitFile_Client failed to receive file\n"); + "prsocket_test: TransmitFile_Client failed to receive file\n"); failed_already=1; return; } -#if defined(XP_UNIX) && !defined(SYMBIAN) +#if defined(XP_UNIX) /* File transmission test can not be done because of large file's size */ - if (memcmp(small_file_header, small_buf, SMALL_FILE_HEADER_SIZE) != 0){ + if (memcmp(small_file_header, small_buf, SMALL_FILE_HEADER_SIZE) != 0) { fprintf(stderr, - "prsocket_test: TransmitFile_Client ERROR - small file header data corruption\n"); + "prsocket_test: TransmitFile_Client ERROR - small file header data corruption\n"); failed_already=1; return; } if (memcmp(small_file_addr, small_buf + SMALL_FILE_HEADER_SIZE, - SMALL_FILE_SIZE) != 0) { + SMALL_FILE_SIZE) != 0) { fprintf(stderr, - "prsocket_test: TransmitFile_Client ERROR - small file data corruption\n"); + "prsocket_test: TransmitFile_Client ERROR - small file data corruption\n"); failed_already=1; return; } @@ -1167,263 +1164,263 @@ TransmitFile_Client(void *arg) */ if (readn(sockfd, large_buf, LARGE_FILE_SIZE) != LARGE_FILE_SIZE) { fprintf(stderr, - "prsocket_test: TransmitFile_Client failed to receive file\n"); + "prsocket_test: TransmitFile_Client failed to receive file\n"); failed_already=1; return; } -#if defined(XP_UNIX) && !defined(SYMBIAN) +#if defined(XP_UNIX) if (memcmp(large_file_addr, large_buf, LARGE_FILE_SIZE) != 0) { fprintf(stderr, - "prsocket_test: TransmitFile_Client ERROR - large file data corruption\n"); + "prsocket_test: TransmitFile_Client ERROR - large file data corruption\n"); failed_already=1; } #endif - /* - * receive data from PR_SendFile - */ - /* - * case 1: small file with header and trailer - */ + /* + * receive data from PR_SendFile + */ + /* + * case 1: small file with header and trailer + */ rlen = SMALL_FILE_SIZE + SMALL_FILE_HEADER_SIZE + - SMALL_FILE_TRAILER_SIZE; + SMALL_FILE_TRAILER_SIZE; if (readn(sockfd, small_buf, rlen) != rlen) { fprintf(stderr, - "prsocket_test: SendFile_Client failed to receive file\n"); + "prsocket_test: SendFile_Client failed to receive file\n"); failed_already=1; return; } -#if defined(XP_UNIX) && !defined(SYMBIAN) - if (memcmp(small_file_header, small_buf, SMALL_FILE_HEADER_SIZE) != 0){ +#if defined(XP_UNIX) + if (memcmp(small_file_header, small_buf, SMALL_FILE_HEADER_SIZE) != 0) { fprintf(stderr, - "SendFile 1. ERROR - small file header corruption\n"); + "SendFile 1. ERROR - small file header corruption\n"); failed_already=1; return; } if (memcmp(small_file_addr, small_buf + SMALL_FILE_HEADER_SIZE, - SMALL_FILE_SIZE) != 0) { + SMALL_FILE_SIZE) != 0) { fprintf(stderr, - "SendFile 1. ERROR - small file data corruption\n"); + "SendFile 1. ERROR - small file data corruption\n"); failed_already=1; return; } if (memcmp(small_file_trailer, - small_buf + SMALL_FILE_HEADER_SIZE + SMALL_FILE_SIZE, - SMALL_FILE_TRAILER_SIZE) != 0) { + small_buf + SMALL_FILE_HEADER_SIZE + SMALL_FILE_SIZE, + SMALL_FILE_TRAILER_SIZE) != 0) { fprintf(stderr, - "SendFile 1. ERROR - small file trailer corruption\n"); + "SendFile 1. ERROR - small file trailer corruption\n"); failed_already=1; return; } #endif - /* - * case 2: partial large file at zero offset, file with header and trailer - */ + /* + * case 2: partial large file at zero offset, file with header and trailer + */ rlen = LARGE_FILE_LEN_1 + LARGE_FILE_HEADER_SIZE + - LARGE_FILE_TRAILER_SIZE; + LARGE_FILE_TRAILER_SIZE; if (readn(sockfd, large_buf, rlen) != rlen) { fprintf(stderr, - "prsocket_test: SendFile_Client failed to receive file\n"); + "prsocket_test: SendFile_Client failed to receive file\n"); failed_already=1; return; } -#if defined(XP_UNIX) && !defined(SYMBIAN) - if (memcmp(large_file_header, large_buf, LARGE_FILE_HEADER_SIZE) != 0){ +#if defined(XP_UNIX) + if (memcmp(large_file_header, large_buf, LARGE_FILE_HEADER_SIZE) != 0) { fprintf(stderr, - "SendFile 2. ERROR - large file header corruption\n"); + "SendFile 2. ERROR - large file header corruption\n"); failed_already=1; return; } if (memcmp(large_file_addr, large_buf + LARGE_FILE_HEADER_SIZE, - LARGE_FILE_LEN_1) != 0) { + LARGE_FILE_LEN_1) != 0) { fprintf(stderr, - "SendFile 2. ERROR - large file data corruption\n"); + "SendFile 2. ERROR - large file data corruption\n"); failed_already=1; return; } if (memcmp(large_file_trailer, - large_buf + LARGE_FILE_HEADER_SIZE + LARGE_FILE_LEN_1, - LARGE_FILE_TRAILER_SIZE) != 0) { + large_buf + LARGE_FILE_HEADER_SIZE + LARGE_FILE_LEN_1, + LARGE_FILE_TRAILER_SIZE) != 0) { fprintf(stderr, - "SendFile 2. ERROR - large file trailer corruption\n"); + "SendFile 2. ERROR - large file trailer corruption\n"); failed_already=1; return; } #endif - /* - * case 3: partial small file at non-zero offset, with header - */ + /* + * case 3: partial small file at non-zero offset, with header + */ rlen = SMALL_FILE_LEN_1 + SMALL_FILE_HEADER_SIZE; if (readn(sockfd, small_buf, rlen) != rlen) { fprintf(stderr, - "prsocket_test: SendFile_Client failed to receive file\n"); + "prsocket_test: SendFile_Client failed to receive file\n"); failed_already=1; return; } -#if defined(XP_UNIX) && !defined(SYMBIAN) - if (memcmp(small_file_header, small_buf, SMALL_FILE_HEADER_SIZE) != 0){ +#if defined(XP_UNIX) + if (memcmp(small_file_header, small_buf, SMALL_FILE_HEADER_SIZE) != 0) { fprintf(stderr, - "SendFile 3. ERROR - small file header corruption\n"); + "SendFile 3. ERROR - small file header corruption\n"); failed_already=1; return; } if (memcmp((char *) small_file_addr + SMALL_FILE_OFFSET_1, - small_buf + SMALL_FILE_HEADER_SIZE, SMALL_FILE_LEN_1) != 0) { + small_buf + SMALL_FILE_HEADER_SIZE, SMALL_FILE_LEN_1) != 0) { fprintf(stderr, - "SendFile 3. ERROR - small file data corruption\n"); + "SendFile 3. ERROR - small file data corruption\n"); failed_already=1; return; } #endif - /* - * case 4: partial small file at non-zero offset, with trailer - */ + /* + * case 4: partial small file at non-zero offset, with trailer + */ rlen = SMALL_FILE_LEN_2 + SMALL_FILE_TRAILER_SIZE; if (readn(sockfd, small_buf, rlen) != rlen) { fprintf(stderr, - "prsocket_test: SendFile_Client failed to receive file\n"); + "prsocket_test: SendFile_Client failed to receive file\n"); failed_already=1; return; } -#if defined(XP_UNIX) && !defined(SYMBIAN) +#if defined(XP_UNIX) if (memcmp((char *) small_file_addr + SMALL_FILE_OFFSET_2, small_buf, - SMALL_FILE_LEN_2) != 0) { + SMALL_FILE_LEN_2) != 0) { fprintf(stderr, - "SendFile 4. ERROR - small file data corruption\n"); + "SendFile 4. ERROR - small file data corruption\n"); failed_already=1; return; } if (memcmp(small_file_trailer, small_buf + SMALL_FILE_LEN_2, - SMALL_FILE_TRAILER_SIZE) != 0) { + SMALL_FILE_TRAILER_SIZE) != 0) { fprintf(stderr, - "SendFile 4. ERROR - small file trailer corruption\n"); + "SendFile 4. ERROR - small file trailer corruption\n"); failed_already=1; return; } #endif - /* - * case 5: partial large file at non-zero offset, file with header - */ + /* + * case 5: partial large file at non-zero offset, file with header + */ rlen = LARGE_FILE_LEN_2 + LARGE_FILE_HEADER_SIZE; if (readn(sockfd, large_buf, rlen) != rlen) { fprintf(stderr, - "prsocket_test: SendFile_Client failed to receive file\n"); + "prsocket_test: SendFile_Client failed to receive file\n"); failed_already=1; return; } -#if defined(XP_UNIX) && !defined(SYMBIAN) - if (memcmp(large_file_header, large_buf, LARGE_FILE_HEADER_SIZE) != 0){ +#if defined(XP_UNIX) + if (memcmp(large_file_header, large_buf, LARGE_FILE_HEADER_SIZE) != 0) { fprintf(stderr, - "SendFile 5. ERROR - large file header corruption\n"); + "SendFile 5. ERROR - large file header corruption\n"); failed_already=1; return; } if (memcmp((char *)large_file_addr + LARGE_FILE_OFFSET_2, - large_buf + LARGE_FILE_HEADER_SIZE, - LARGE_FILE_LEN_2) != 0) { + large_buf + LARGE_FILE_HEADER_SIZE, + LARGE_FILE_LEN_2) != 0) { fprintf(stderr, - "SendFile 5. ERROR - large file data corruption\n"); + "SendFile 5. ERROR - large file data corruption\n"); failed_already=1; return; } #endif - /* - * case 6: partial small file at non-zero offset, with header - */ + /* + * case 6: partial small file at non-zero offset, with header + */ rlen = SMALL_FILE_LEN_3 + SMALL_FILE_HEADER_SIZE; if (readn(sockfd, small_buf, rlen) != rlen) { fprintf(stderr, - "prsocket_test: SendFile_Client failed to receive file\n"); + "prsocket_test: SendFile_Client failed to receive file\n"); failed_already=1; return; } -#if defined(XP_UNIX) && !defined(SYMBIAN) - if (memcmp(small_file_header, small_buf, SMALL_FILE_HEADER_SIZE) != 0){ +#if defined(XP_UNIX) + if (memcmp(small_file_header, small_buf, SMALL_FILE_HEADER_SIZE) != 0) { fprintf(stderr, - "SendFile 6. ERROR - small file header corruption\n"); + "SendFile 6. ERROR - small file header corruption\n"); return; } if (memcmp((char *) small_file_addr + SMALL_FILE_OFFSET_3, - small_buf + SMALL_FILE_HEADER_SIZE, SMALL_FILE_LEN_3) != 0) { + small_buf + SMALL_FILE_HEADER_SIZE, SMALL_FILE_LEN_3) != 0) { #if 0 - char *i, *j; - int k; - - i = (char *) small_file_addr + SMALL_FILE_OFFSET_3; - j = small_buf + SMALL_FILE_HEADER_SIZE; - k = SMALL_FILE_LEN_3; - while (k-- > 0) { - if (*i++ != *j++) - printf("i = %d j = %d\n", - (int) (i - ((char *) small_file_addr + SMALL_FILE_OFFSET_3)), - (int) (j - (small_buf + SMALL_FILE_HEADER_SIZE))); - } + char *i, *j; + int k; + + i = (char *) small_file_addr + SMALL_FILE_OFFSET_3; + j = small_buf + SMALL_FILE_HEADER_SIZE; + k = SMALL_FILE_LEN_3; + while (k-- > 0) { + if (*i++ != *j++) + printf("i = %d j = %d\n", + (int) (i - ((char *) small_file_addr + SMALL_FILE_OFFSET_3)), + (int) (j - (small_buf + SMALL_FILE_HEADER_SIZE))); + } #endif fprintf(stderr, - "SendFile 6. ERROR - small file data corruption\n"); + "SendFile 6. ERROR - small file data corruption\n"); failed_already=1; return; } #endif - /* - * case 7: partial large file at non-zero offset, with header - */ + /* + * case 7: partial large file at non-zero offset, with header + */ rlen = LARGE_FILE_LEN_3 + LARGE_FILE_HEADER_SIZE; if (readn(sockfd, large_buf, rlen) != rlen) { fprintf(stderr, - "prsocket_test: SendFile_Client failed to receive file\n"); + "prsocket_test: SendFile_Client failed to receive file\n"); failed_already=1; return; } -#if defined(XP_UNIX) && !defined(SYMBIAN) - if (memcmp(large_file_header, large_buf, LARGE_FILE_HEADER_SIZE) != 0){ +#if defined(XP_UNIX) + if (memcmp(large_file_header, large_buf, LARGE_FILE_HEADER_SIZE) != 0) { fprintf(stderr, - "SendFile 7. ERROR - large file header corruption\n"); + "SendFile 7. ERROR - large file header corruption\n"); failed_already=1; return; } if (memcmp((char *)large_file_addr + LARGE_FILE_OFFSET_3, - large_buf + LARGE_FILE_HEADER_SIZE, - LARGE_FILE_LEN_3) != 0) { + large_buf + LARGE_FILE_HEADER_SIZE, + LARGE_FILE_LEN_3) != 0) { fprintf(stderr, - "SendFile 7. ERROR - large file data corruption\n"); + "SendFile 7. ERROR - large file data corruption\n"); failed_already=1; return; } #endif - /* - * case 8: partial large file at non-zero, page-aligned offset, with - * header and trailer - */ + /* + * case 8: partial large file at non-zero, page-aligned offset, with + * header and trailer + */ rlen = LARGE_FILE_LEN_4 + LARGE_FILE_HEADER_SIZE + - LARGE_FILE_TRAILER_SIZE; + LARGE_FILE_TRAILER_SIZE; if (readn(sockfd, large_buf, rlen) != rlen) { fprintf(stderr, - "prsocket_test: SendFile_Client failed to receive file\n"); + "prsocket_test: SendFile_Client failed to receive file\n"); failed_already=1; return; } -#if defined(XP_UNIX) && !defined(SYMBIAN) - if (memcmp(large_file_header, large_buf, LARGE_FILE_HEADER_SIZE) != 0){ +#if defined(XP_UNIX) + if (memcmp(large_file_header, large_buf, LARGE_FILE_HEADER_SIZE) != 0) { fprintf(stderr, - "SendFile 2. ERROR - large file header corruption\n"); + "SendFile 2. ERROR - large file header corruption\n"); failed_already=1; return; } if (memcmp((char *)large_file_addr + LARGE_FILE_OFFSET_4, - large_buf + LARGE_FILE_HEADER_SIZE, - LARGE_FILE_LEN_4) != 0) { + large_buf + LARGE_FILE_HEADER_SIZE, + LARGE_FILE_LEN_4) != 0) { fprintf(stderr, - "SendFile 2. ERROR - large file data corruption\n"); + "SendFile 2. ERROR - large file data corruption\n"); failed_already=1; return; } if (memcmp(large_file_trailer, - large_buf + LARGE_FILE_HEADER_SIZE + LARGE_FILE_LEN_4, - LARGE_FILE_TRAILER_SIZE) != 0) { + large_buf + LARGE_FILE_HEADER_SIZE + LARGE_FILE_LEN_4, + LARGE_FILE_TRAILER_SIZE) != 0) { fprintf(stderr, - "SendFile 2. ERROR - large file trailer corruption\n"); + "SendFile 2. ERROR - large file trailer corruption\n"); failed_already=1; return; } @@ -1458,15 +1455,15 @@ Serve_TransmitFile_Client(void *arg) PRInt32 bytes; PRFileDesc *local_small_file_fd=NULL; PRFileDesc *local_large_file_fd=NULL; - PRSendFileData sfd; - PRInt32 slen; + PRSendFileData sfd; + PRInt32 slen; sockfd = scp->sockfd; local_small_file_fd = PR_Open(SMALL_FILE_NAME, PR_RDONLY,0); if (local_small_file_fd == NULL) { fprintf(stderr,"prsocket_test failed to open file for transmitting %s\n", - SMALL_FILE_NAME); + SMALL_FILE_NAME); failed_already=1; goto done; } @@ -1474,218 +1471,220 @@ Serve_TransmitFile_Client(void *arg) if (local_large_file_fd == NULL) { fprintf(stderr,"prsocket_test failed to open file for transmitting %s\n", - LARGE_FILE_NAME); + LARGE_FILE_NAME); failed_already=1; goto done; } bytes = PR_TransmitFile(sockfd, local_small_file_fd, small_file_header, - SMALL_FILE_HEADER_SIZE, PR_TRANSMITFILE_KEEP_OPEN, - PR_INTERVAL_NO_TIMEOUT); + SMALL_FILE_HEADER_SIZE, PR_TRANSMITFILE_KEEP_OPEN, + PR_INTERVAL_NO_TIMEOUT); if (bytes != (SMALL_FILE_SIZE+ SMALL_FILE_HEADER_SIZE)) { fprintf(stderr, - "prsocet_test: PR_TransmitFile failed: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); + "prsocet_test: PR_TransmitFile failed: (%ld, %ld)\n", + PR_GetError(), PR_GetOSError()); failed_already=1; } bytes = PR_TransmitFile(sockfd, local_large_file_fd, NULL, 0, - PR_TRANSMITFILE_KEEP_OPEN, PR_INTERVAL_NO_TIMEOUT); + PR_TRANSMITFILE_KEEP_OPEN, PR_INTERVAL_NO_TIMEOUT); if (bytes != LARGE_FILE_SIZE) { fprintf(stderr, - "prsocket_test: PR_TransmitFile failed: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); + "prsocket_test: PR_TransmitFile failed: (%ld, %ld)\n", + PR_GetError(), PR_GetOSError()); failed_already=1; } - /* - * PR_SendFile test cases - */ + /* + * PR_SendFile test cases + */ - /* - * case 1: small file with header and trailer - */ - sfd.fd = local_small_file_fd; - sfd.file_offset = 0; - sfd.file_nbytes = 0; - sfd.header = small_file_header; - sfd.hlen = SMALL_FILE_HEADER_SIZE; - sfd.trailer = small_file_trailer; - sfd.tlen = SMALL_FILE_TRAILER_SIZE; + /* + * case 1: small file with header and trailer + */ + sfd.fd = local_small_file_fd; + sfd.file_offset = 0; + sfd.file_nbytes = 0; + sfd.header = small_file_header; + sfd.hlen = SMALL_FILE_HEADER_SIZE; + sfd.trailer = small_file_trailer; + sfd.tlen = SMALL_FILE_TRAILER_SIZE; bytes = PR_SendFile(sockfd, &sfd, PR_TRANSMITFILE_KEEP_OPEN, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); slen = SMALL_FILE_SIZE+ SMALL_FILE_HEADER_SIZE + - SMALL_FILE_TRAILER_SIZE; + SMALL_FILE_TRAILER_SIZE; if (bytes != slen) { fprintf(stderr, - "socket: Error - 1. PR_SendFile send_size = %d, bytes sent = %d\n", - slen, bytes); + "socket: Error - 1. PR_SendFile send_size = %d, bytes sent = %d\n", + slen, bytes); fprintf(stderr, - "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); + "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", + PR_GetError(), PR_GetOSError()); failed_already=1; } - /* - * case 2: partial large file at zero offset, file with header and trailer - */ - sfd.fd = local_large_file_fd; - sfd.file_offset = 0; - sfd.file_nbytes = LARGE_FILE_LEN_1; - sfd.header = large_file_header; - sfd.hlen = LARGE_FILE_HEADER_SIZE; - sfd.trailer = large_file_trailer; - sfd.tlen = LARGE_FILE_TRAILER_SIZE; + /* + * case 2: partial large file at zero offset, file with header and trailer + */ + sfd.fd = local_large_file_fd; + sfd.file_offset = 0; + sfd.file_nbytes = LARGE_FILE_LEN_1; + sfd.header = large_file_header; + sfd.hlen = LARGE_FILE_HEADER_SIZE; + sfd.trailer = large_file_trailer; + sfd.tlen = LARGE_FILE_TRAILER_SIZE; bytes = PR_SendFile(sockfd, &sfd, PR_TRANSMITFILE_KEEP_OPEN, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); slen = LARGE_FILE_LEN_1 + LARGE_FILE_HEADER_SIZE + - LARGE_FILE_TRAILER_SIZE; + LARGE_FILE_TRAILER_SIZE; if (bytes != slen) { fprintf(stderr, - "socket: Error - 2. PR_SendFile send_size = %d, bytes sent = %d\n", - slen, bytes); + "socket: Error - 2. PR_SendFile send_size = %d, bytes sent = %d\n", + slen, bytes); fprintf(stderr, - "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - } - /* - * case 3: partial small file at non-zero offset, with header - */ - sfd.fd = local_small_file_fd; - sfd.file_offset = SMALL_FILE_OFFSET_1; - sfd.file_nbytes = SMALL_FILE_LEN_1; - sfd.header = small_file_header; - sfd.hlen = SMALL_FILE_HEADER_SIZE; - sfd.trailer = NULL; - sfd.tlen = 0; + "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + } + /* + * case 3: partial small file at non-zero offset, with header + */ + sfd.fd = local_small_file_fd; + sfd.file_offset = SMALL_FILE_OFFSET_1; + sfd.file_nbytes = SMALL_FILE_LEN_1; + sfd.header = small_file_header; + sfd.hlen = SMALL_FILE_HEADER_SIZE; + sfd.trailer = NULL; + sfd.tlen = 0; bytes = PR_SendFile(sockfd, &sfd, PR_TRANSMITFILE_KEEP_OPEN, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); slen = SMALL_FILE_LEN_1 + SMALL_FILE_HEADER_SIZE; if (bytes != slen) { fprintf(stderr, - "socket: Error - 3. PR_SendFile send_size = %d, bytes sent = %d\n", - slen, bytes); + "socket: Error - 3. PR_SendFile send_size = %d, bytes sent = %d\n", + slen, bytes); fprintf(stderr, - "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - } - /* - * case 4: partial small file at non-zero offset, with trailer - */ - sfd.fd = local_small_file_fd; - sfd.file_offset = SMALL_FILE_OFFSET_2; - sfd.file_nbytes = SMALL_FILE_LEN_2; - sfd.header = NULL; - sfd.hlen = 0; - sfd.trailer = small_file_trailer; - sfd.tlen = SMALL_FILE_TRAILER_SIZE; + "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + } + /* + * case 4: partial small file at non-zero offset, with trailer + */ + sfd.fd = local_small_file_fd; + sfd.file_offset = SMALL_FILE_OFFSET_2; + sfd.file_nbytes = SMALL_FILE_LEN_2; + sfd.header = NULL; + sfd.hlen = 0; + sfd.trailer = small_file_trailer; + sfd.tlen = SMALL_FILE_TRAILER_SIZE; bytes = PR_SendFile(sockfd, &sfd, PR_TRANSMITFILE_KEEP_OPEN, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); slen = SMALL_FILE_LEN_2 + SMALL_FILE_TRAILER_SIZE; if (bytes != slen) { fprintf(stderr, - "socket: Error - 4. PR_SendFile send_size = %d, bytes sent = %d\n", - slen, bytes); + "socket: Error - 4. PR_SendFile send_size = %d, bytes sent = %d\n", + slen, bytes); fprintf(stderr, - "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - } - /* - * case 5: partial large file at non-zero offset, file with header - */ - sfd.fd = local_large_file_fd; - sfd.file_offset = LARGE_FILE_OFFSET_2; - sfd.file_nbytes = LARGE_FILE_LEN_2; - sfd.header = large_file_header; - sfd.hlen = LARGE_FILE_HEADER_SIZE; - sfd.trailer = NULL; - sfd.tlen = 0; + "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + } + /* + * case 5: partial large file at non-zero offset, file with header + */ + sfd.fd = local_large_file_fd; + sfd.file_offset = LARGE_FILE_OFFSET_2; + sfd.file_nbytes = LARGE_FILE_LEN_2; + sfd.header = large_file_header; + sfd.hlen = LARGE_FILE_HEADER_SIZE; + sfd.trailer = NULL; + sfd.tlen = 0; bytes = PR_SendFile(sockfd, &sfd, PR_TRANSMITFILE_KEEP_OPEN, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); slen = LARGE_FILE_LEN_2 + LARGE_FILE_HEADER_SIZE; if (bytes != slen) { fprintf(stderr, - "socket: Error - 5. PR_SendFile send_size = %d, bytes sent = %d\n", - slen, bytes); + "socket: Error - 5. PR_SendFile send_size = %d, bytes sent = %d\n", + slen, bytes); fprintf(stderr, - "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - } - /* - * case 6: partial small file from non-zero offset till end of file, with header - */ - sfd.fd = local_small_file_fd; - sfd.file_offset = SMALL_FILE_OFFSET_3; - sfd.file_nbytes = 0; /* data from offset to end-of-file */ - sfd.header = small_file_header; - sfd.hlen = SMALL_FILE_HEADER_SIZE; - sfd.trailer = NULL; - sfd.tlen = 0; + "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + } + /* + * case 6: partial small file from non-zero offset till end of file, with header + */ + sfd.fd = local_small_file_fd; + sfd.file_offset = SMALL_FILE_OFFSET_3; + sfd.file_nbytes = 0; /* data from offset to end-of-file */ + sfd.header = small_file_header; + sfd.hlen = SMALL_FILE_HEADER_SIZE; + sfd.trailer = NULL; + sfd.tlen = 0; bytes = PR_SendFile(sockfd, &sfd, PR_TRANSMITFILE_KEEP_OPEN, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); slen = SMALL_FILE_LEN_3 + SMALL_FILE_HEADER_SIZE; if (bytes != slen) { fprintf(stderr, - "socket: Error - 6. PR_SendFile send_size = %d, bytes sent = %d\n", - slen, bytes); + "socket: Error - 6. PR_SendFile send_size = %d, bytes sent = %d\n", + slen, bytes); fprintf(stderr, - "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - } - /* - * case 7: partial large file at non-zero offset till end-of-file, with header - */ - sfd.fd = local_large_file_fd; - sfd.file_offset = LARGE_FILE_OFFSET_3; - sfd.file_nbytes = 0; /* data until end-of-file */ - sfd.header = large_file_header; - sfd.hlen = LARGE_FILE_HEADER_SIZE; - sfd.trailer = NULL; - sfd.tlen = 0; + "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + } + /* + * case 7: partial large file at non-zero offset till end-of-file, with header + */ + sfd.fd = local_large_file_fd; + sfd.file_offset = LARGE_FILE_OFFSET_3; + sfd.file_nbytes = 0; /* data until end-of-file */ + sfd.header = large_file_header; + sfd.hlen = LARGE_FILE_HEADER_SIZE; + sfd.trailer = NULL; + sfd.tlen = 0; bytes = PR_SendFile(sockfd, &sfd, PR_TRANSMITFILE_KEEP_OPEN, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); slen = LARGE_FILE_LEN_3 + LARGE_FILE_HEADER_SIZE; if (bytes != slen) { fprintf(stderr, - "socket: Error - 7. PR_SendFile send_size = %d, bytes sent = %d\n", - slen, bytes); + "socket: Error - 7. PR_SendFile send_size = %d, bytes sent = %d\n", + slen, bytes); fprintf(stderr, - "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); - failed_already=1; - } - /* - * case 8: partial large file at non-zero page-aligned offset, - * with header and trailer - */ - sfd.fd = local_large_file_fd; - sfd.file_offset = LARGE_FILE_OFFSET_4; - sfd.file_nbytes = LARGE_FILE_LEN_4; - sfd.header = large_file_header; - sfd.hlen = LARGE_FILE_HEADER_SIZE; - sfd.trailer = large_file_trailer; - sfd.tlen = LARGE_FILE_TRAILER_SIZE; + "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", + PR_GetError(), PR_GetOSError()); + failed_already=1; + } + /* + * case 8: partial large file at non-zero page-aligned offset, + * with header and trailer + */ + sfd.fd = local_large_file_fd; + sfd.file_offset = LARGE_FILE_OFFSET_4; + sfd.file_nbytes = LARGE_FILE_LEN_4; + sfd.header = large_file_header; + sfd.hlen = LARGE_FILE_HEADER_SIZE; + sfd.trailer = large_file_trailer; + sfd.tlen = LARGE_FILE_TRAILER_SIZE; bytes = PR_SendFile(sockfd, &sfd, PR_TRANSMITFILE_CLOSE_SOCKET, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); slen = LARGE_FILE_LEN_4 + LARGE_FILE_HEADER_SIZE + - LARGE_FILE_TRAILER_SIZE; + LARGE_FILE_TRAILER_SIZE; if (bytes != slen) { fprintf(stderr, - "socket: Error - 2. PR_SendFile send_size = %d, bytes sent = %d\n", - slen, bytes); + "socket: Error - 2. PR_SendFile send_size = %d, bytes sent = %d\n", + slen, bytes); fprintf(stderr, - "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); + "prsocket_test: PR_SendFile failed: (%ld, %ld)\n", + PR_GetError(), PR_GetOSError()); failed_already=1; } done: - if (local_small_file_fd != NULL) + if (local_small_file_fd != NULL) { PR_Close(local_small_file_fd); - if (local_large_file_fd != NULL) + } + if (local_large_file_fd != NULL) { PR_Close(local_large_file_fd); + } } /* @@ -1718,7 +1717,7 @@ TransmitFile_Server(void *arg) failed_already=1; goto exit; } - memset(&netaddr, 0 , sizeof(netaddr)); + memset(&netaddr, 0, sizeof(netaddr)); netaddr.inet.family = PR_AF_INET; netaddr.inet.port = PR_htons(TCP_SERVER_PORT); netaddr.inet.ip = PR_htonl(PR_INADDR_ANY); @@ -1730,8 +1729,9 @@ TransmitFile_Server(void *arg) while (PR_Bind(sockfd, &netaddr) < 0) { if (PR_GetError() == PR_ADDRESS_IN_USE_ERROR) { netaddr.inet.port += 2; - if (i++ < SERVER_MAX_BIND_COUNT) + if (i++ < SERVER_MAX_BIND_COUNT) { continue; + } } fprintf(stderr,"prsocket_test: ERROR - PR_Bind failed\n"); failed_already=1; @@ -1747,13 +1747,13 @@ TransmitFile_Server(void *arg) if (PR_GetSockName(sockfd, &netaddr) < 0) { fprintf(stderr, - "prsocket_test: ERROR - PR_GetSockName failed\n"); + "prsocket_test: ERROR - PR_GetSockName failed\n"); failed_already=1; goto exit; } DPRINTF(("TCP_Server: PR_BIND netaddr.inet.ip = 0x%lx, netaddr.inet.port = %d\n", - netaddr.inet.ip, netaddr.inet.port)); + netaddr.inet.ip, netaddr.inet.port)); tcp_server_addr.inet.family = netaddr.inet.family; tcp_server_addr.inet.port = netaddr.inet.port; tcp_server_addr.inet.ip = netaddr.inet.ip; @@ -1769,26 +1769,26 @@ TransmitFile_Server(void *arg) PRNetAddr *addrp = (i%2 ? &netaddr: NULL); if ((newsockfd = PR_Accept(sockfd, addrp, - PR_INTERVAL_NO_TIMEOUT)) == NULL) { + PR_INTERVAL_NO_TIMEOUT)) == NULL) { fprintf(stderr, - "prsocket_test: ERROR - PR_Accept failed\n"); + "prsocket_test: ERROR - PR_Accept failed\n"); failed_already=1; goto exit; } /* test both regular and emulated PR_SendFile */ if (i%2) { PRFileDesc *layer = PR_CreateIOLayerStub( - emuSendFileIdentity, &emuSendFileMethods); + emuSendFileIdentity, &emuSendFileMethods); if (layer == NULL) { fprintf(stderr, - "prsocket_test: ERROR - PR_CreateIOLayerStub failed\n"); + "prsocket_test: ERROR - PR_CreateIOLayerStub failed\n"); failed_already=1; goto exit; } if (PR_PushIOLayer(newsockfd, PR_TOP_IO_LAYER, layer) - == PR_FAILURE) { + == PR_FAILURE) { fprintf(stderr, - "prsocket_test: ERROR - PR_PushIOLayer failed\n"); + "prsocket_test: ERROR - PR_PushIOLayer failed\n"); failed_already=1; goto exit; } @@ -1807,14 +1807,14 @@ TransmitFile_Server(void *arg) scp->datalen = sp->datalen; t[i] = PR_CreateThread(PR_USER_THREAD, - Serve_TransmitFile_Client, (void *)scp, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_JOINABLE_THREAD, - 0); + Serve_TransmitFile_Client, (void *)scp, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_JOINABLE_THREAD, + 0); if (t[i] == NULL) { fprintf(stderr, - "prsocket_test: PR_CreateThread failed\n"); + "prsocket_test: PR_CreateThread failed\n"); failed_already=1; goto exit; } @@ -1850,8 +1850,8 @@ exit: } /* - * Socket_Misc_Test - test miscellaneous functions - * + * Socket_Misc_Test - test miscellaneous functions + * */ static PRInt32 Socket_Misc_Test(void) @@ -1865,9 +1865,9 @@ Socket_Misc_Test(void) PRInt32 datalen; /* - * We deliberately pick a buffer size that is not a nice multiple - * of 1024. - */ + * We deliberately pick a buffer size that is not a nice multiple + * of 1024. + */ #define TRANSMITFILE_BUF_SIZE (4 * 1024 - 11) typedef struct { @@ -1888,7 +1888,7 @@ Socket_Misc_Test(void) if (small_file_fd == NULL) { fprintf(stderr,"prsocket_test failed to create/open file %s\n", - SMALL_FILE_NAME); + SMALL_FILE_NAME); failed_already=1; rv = -1; goto done; @@ -1909,12 +1909,12 @@ Socket_Misc_Test(void) count = 0; do { len = (SMALL_FILE_SIZE - count) > TRANSMITFILE_BUF_SIZE ? - TRANSMITFILE_BUF_SIZE : (SMALL_FILE_SIZE - count); + TRANSMITFILE_BUF_SIZE : (SMALL_FILE_SIZE - count); bytes = PR_Write(small_file_fd, buf->data, len); if (bytes <= 0) { fprintf(stderr, - "prsocket_test failed to write to file %s\n", - SMALL_FILE_NAME); + "prsocket_test failed to write to file %s\n", + SMALL_FILE_NAME); failed_already=1; rv = -1; goto done; @@ -1926,10 +1926,10 @@ Socket_Misc_Test(void) * map the small file; used in checking for data corruption */ small_file_addr = mmap(0, SMALL_FILE_SIZE, PROT_READ, - MAP_SHARED, small_file_fd->secret->md.osfd, 0); + MAP_SHARED, small_file_fd->secret->md.osfd, 0); if (small_file_addr == (void *) -1) { fprintf(stderr,"prsocket_test failed to mmap file %s\n", - SMALL_FILE_NAME); + SMALL_FILE_NAME); failed_already=1; rv = -1; goto done; @@ -1946,7 +1946,7 @@ Socket_Misc_Test(void) goto done; } memset(small_file_header, (int) PR_IntervalNow(), - SMALL_FILE_HEADER_SIZE); + SMALL_FILE_HEADER_SIZE); /* * trailer for small file */ @@ -1958,7 +1958,7 @@ Socket_Misc_Test(void) goto done; } memset(small_file_trailer, (int) PR_IntervalNow(), - SMALL_FILE_TRAILER_SIZE); + SMALL_FILE_TRAILER_SIZE); /* * setup large file */ @@ -1966,7 +1966,7 @@ Socket_Misc_Test(void) if (large_file_fd == NULL) { fprintf(stderr,"prsocket_test failed to create/open file %s\n", - LARGE_FILE_NAME); + LARGE_FILE_NAME); failed_already=1; rv = -1; goto done; @@ -1980,28 +1980,28 @@ Socket_Misc_Test(void) count = 0; do { len = (LARGE_FILE_SIZE - count) > TRANSMITFILE_BUF_SIZE ? - TRANSMITFILE_BUF_SIZE : (LARGE_FILE_SIZE - count); + TRANSMITFILE_BUF_SIZE : (LARGE_FILE_SIZE - count); bytes = PR_Write(large_file_fd, buf->data, len); if (bytes <= 0) { fprintf(stderr, - "prsocket_test failed to write to file %s: (%ld, %ld)\n", - LARGE_FILE_NAME, - PR_GetError(), PR_GetOSError()); + "prsocket_test failed to write to file %s: (%ld, %ld)\n", + LARGE_FILE_NAME, + PR_GetError(), PR_GetOSError()); failed_already=1; rv = -1; goto done; } count += bytes; } while (count < LARGE_FILE_SIZE); -#if defined(XP_UNIX) && !defined(SYMBIAN) +#if defined(XP_UNIX) /* * map the large file; used in checking for data corruption */ large_file_addr = mmap(0, LARGE_FILE_SIZE, PROT_READ, - MAP_SHARED, large_file_fd->secret->md.osfd, 0); + MAP_SHARED, large_file_fd->secret->md.osfd, 0); if (large_file_addr == (void *) -1) { fprintf(stderr,"prsocket_test failed to mmap file %s\n", - LARGE_FILE_NAME); + LARGE_FILE_NAME); failed_already=1; rv = -1; goto done; @@ -2018,7 +2018,7 @@ Socket_Misc_Test(void) goto done; } memset(large_file_header, (int) PR_IntervalNow(), - LARGE_FILE_HEADER_SIZE); + LARGE_FILE_HEADER_SIZE); /* * trailer for large file */ @@ -2030,7 +2030,7 @@ Socket_Misc_Test(void) goto done; } memset(large_file_trailer, (int) PR_IntervalNow(), - LARGE_FILE_TRAILER_SIZE); + LARGE_FILE_TRAILER_SIZE); datalen = tcp_mesg_size; thread_count = 0; @@ -2065,11 +2065,11 @@ Socket_Misc_Test(void) sparamp->exit_counter = &thread_count; sparamp->datalen = datalen; t = PR_CreateThread(PR_USER_THREAD, - TransmitFile_Server, (void *)sparamp, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, - 0); + TransmitFile_Server, (void *)sparamp, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, + 0); if (t == NULL) { fprintf(stderr,"prsocket_test: PR_CreateThread failed\n"); failed_already=1; @@ -2102,11 +2102,11 @@ Socket_Misc_Test(void) cparamp->datalen = datalen; for (i = 0; i < num_transmitfile_clients; i++) { t = create_new_thread(PR_USER_THREAD, - TransmitFile_Client, (void *) cparamp, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, - 0, i); + TransmitFile_Client, (void *) cparamp, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, + 0, i); if (t == NULL) { fprintf(stderr,"prsocket_test: PR_CreateThread failed\n"); rv = -1; @@ -2126,7 +2126,7 @@ done: if (buf) { PR_DELETE(buf); } -#if defined(XP_UNIX) && !defined(SYMBIAN) +#if defined(XP_UNIX) munmap((char*)small_file_addr, SMALL_FILE_SIZE); munmap((char*)large_file_addr, LARGE_FILE_SIZE); #endif @@ -2134,24 +2134,24 @@ done: PR_Close(large_file_fd); if ((PR_Delete(SMALL_FILE_NAME)) == PR_FAILURE) { fprintf(stderr,"prsocket_test: failed to unlink file %s\n", - SMALL_FILE_NAME); + SMALL_FILE_NAME); failed_already=1; } if ((PR_Delete(LARGE_FILE_NAME)) == PR_FAILURE) { fprintf(stderr,"prsocket_test: failed to unlink file %s\n", - LARGE_FILE_NAME); + LARGE_FILE_NAME); failed_already=1; } if ((PR_RmDir(TEST_DIR)) == PR_FAILURE) { fprintf(stderr,"prsocket_test failed to rmdir %s: (%ld, %ld)\n", - TEST_DIR, PR_GetError(), PR_GetOSError()); + TEST_DIR, PR_GetError(), PR_GetOSError()); failed_already=1; } printf("%-29s%s","Socket_Misc_Test",":"); printf("%2d Server %2d Clients\n",1, num_transmitfile_clients); printf("%30s Sizes of Transmitted Files - %4d KB, %2d MB \n",":", - SMALL_FILE_SIZE/1024, LARGE_FILE_SIZE/(1024 * 1024)); + SMALL_FILE_SIZE/1024, LARGE_FILE_SIZE/(1024 * 1024)); return rv; @@ -2172,14 +2172,16 @@ int main(int argc, char **argv) PLOptState *opt = PL_CreateOptState(argc, argv, "d"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - _debug_on = 1; - break; - default: - break; + case 'd': /* debug mode */ + _debug_on = 1; + break; + default: + break; } } PL_DestroyOptState(opt); @@ -2197,112 +2199,69 @@ int main(int argc, char **argv) /* * run client-server test with TCP, Ipv4-Ipv4 */ - printf("TCP Client/Server Test - IPv4/Ipv4\n"); + printf("TCP Client/Server Test - IPv4/Ipv4\n"); if (TCP_Socket_Client_Server_Test() < 0) { printf("TCP_Socket_Client_Server_Test failed\n"); goto done; - } else + } else { printf("TCP_Socket_Client_Server_Test Passed\n"); + } /* * client-server test, Ipv6-Ipv4 */ - client_domain = PR_AF_INET6; - printf("TCP Client/Server Test - IPv6/Ipv4\n"); + client_domain = PR_AF_INET6; + printf("TCP Client/Server Test - IPv6/Ipv4\n"); if (TCP_Socket_Client_Server_Test() < 0) { printf("TCP_Socket_Client_Server_Test failed\n"); goto done; - } else + } else { printf("TCP_Socket_Client_Server_Test Passed\n"); + } /* * client-server test, Ipv4-Ipv6 */ - client_domain = PR_AF_INET; - server_domain = PR_AF_INET6; - printf("TCP Client/Server Test - IPv4/Ipv6\n"); + client_domain = PR_AF_INET; + server_domain = PR_AF_INET6; + printf("TCP Client/Server Test - IPv4/Ipv6\n"); if (TCP_Socket_Client_Server_Test() < 0) { printf("TCP_Socket_Client_Server_Test failed\n"); goto done; - } else + } else { printf("TCP_Socket_Client_Server_Test Passed\n"); + } /* * client-server test, Ipv6-Ipv6 */ - client_domain = PR_AF_INET6; - server_domain = PR_AF_INET6; - printf("TCP Client/Server Test - IPv6/Ipv6\n"); + client_domain = PR_AF_INET6; + server_domain = PR_AF_INET6; + printf("TCP Client/Server Test - IPv6/Ipv6\n"); if (TCP_Socket_Client_Server_Test() < 0) { printf("TCP_Socket_Client_Server_Test failed\n"); goto done; - } else + } else { printf("TCP_Socket_Client_Server_Test Passed\n"); - test_cancelio = 0; - -#if defined(SYMBIAN) && !defined(__WINSCW__) - /* UDP tests only run on Symbian devices but not emulator */ - /* - * run client-server test with UDP, IPv4/IPv4 - */ - printf("UDP Client/Server Test - IPv4/Ipv4\n"); - client_domain = PR_AF_INET; - server_domain = PR_AF_INET; - if (UDP_Socket_Client_Server_Test() < 0) { - printf("UDP_Socket_Client_Server_Test failed\n"); - goto done; - } else - printf("UDP_Socket_Client_Server_Test Passed\n"); - /* - * run client-server test with UDP, IPv6/IPv4 - */ - printf("UDP Client/Server Test - IPv6/Ipv4\n"); - client_domain = PR_AF_INET6; - server_domain = PR_AF_INET; - if (UDP_Socket_Client_Server_Test() < 0) { - printf("UDP_Socket_Client_Server_Test failed\n"); - goto done; - } else - printf("UDP_Socket_Client_Server_Test Passed\n"); - /* - * run client-server test with UDP,IPv4-IPv6 - */ - printf("UDP Client/Server Test - IPv4/Ipv6\n"); - client_domain = PR_AF_INET; - server_domain = PR_AF_INET6; - if (UDP_Socket_Client_Server_Test() < 0) { - printf("UDP_Socket_Client_Server_Test failed\n"); - goto done; - } else - printf("UDP_Socket_Client_Server_Test Passed\n"); - /* - * run client-server test with UDP,IPv6-IPv6 - */ - printf("UDP Client/Server Test - IPv6/Ipv6\n"); - client_domain = PR_AF_INET6; - server_domain = PR_AF_INET6; - if (UDP_Socket_Client_Server_Test() < 0) { - printf("UDP_Socket_Client_Server_Test failed\n"); - goto done; - } else - printf("UDP_Socket_Client_Server_Test Passed\n"); -#endif - + } + test_cancelio = 0; + /* * Misc socket tests - including transmitfile, etc. */ - /* File transmission test can not be done in Symbian OS because of + /* File transmission test can not be done in Symbian OS because of * large file's size and the incomplete mmap() implementation. */ -#if !defined(WIN16) && !defined(SYMBIAN) +#if !defined(WIN16) /* -** The 'transmit file' test does not run because -** transmit file is not implemented in NSPR yet. -** -*/ + ** The 'transmit file' test does not run because + ** transmit file is not implemented in NSPR yet. + ** + */ if (Socket_Misc_Test() < 0) { printf("Socket_Misc_Test failed\n"); failed_already=1; goto done; - } else + } else { printf("Socket_Misc_Test passed\n"); + } /* * run client-server test with TCP again to test @@ -2311,12 +2270,17 @@ int main(int argc, char **argv) if (TCP_Socket_Client_Server_Test() < 0) { printf("TCP_Socket_Client_Server_Test failed\n"); goto done; - } else + } else { printf("TCP_Socket_Client_Server_Test Passed\n"); + } #endif done: PR_Cleanup(); - if (failed_already) return 1; - else return 0; + if (failed_already) { + return 1; + } + else { + return 0; + } } diff --git a/nsprpub/pr/tests/sockopt.c b/nsprpub/pr/tests/sockopt.c index b9b2f6dd3..540a19b90 100644 --- a/nsprpub/pr/tests/sockopt.c +++ b/nsprpub/pr/tests/sockopt.c @@ -20,7 +20,9 @@ static PRBool failed = PR_FALSE; static void Failed(const char *msg1, const char *msg2) { - if (NULL != msg1) PR_fprintf(err, "%s ", msg1); + if (NULL != msg1) { + PR_fprintf(err, "%s ", msg1); + } PL_FPrintError(err, msg2); failed = PR_TRUE; } /* Failed */ @@ -65,8 +67,12 @@ int main(int argc, char **argv) err = PR_GetSpecialFD(PR_StandardError); PR_STDIO_INIT(); - if (NULL == udp) Failed("PR_NewUDPSocket()", NULL); - else if (NULL == tcp) Failed("PR_NewTCPSocket()", NULL); + if (NULL == udp) { + Failed("PR_NewUDPSocket()", NULL); + } + else if (NULL == tcp) { + Failed("PR_NewTCPSocket()", NULL); + } else { PRSockOption option; @@ -74,9 +80,13 @@ int main(int argc, char **argv) PRNetAddr addr; rv = PR_InitializeNetAddr(PR_IpAddrAny, 0, &addr); - if (PR_FAILURE == rv) Failed("PR_InitializeNetAddr()", NULL); + if (PR_FAILURE == rv) { + Failed("PR_InitializeNetAddr()", NULL); + } rv = PR_Bind(udp, &addr); - if (PR_FAILURE == rv) Failed("PR_Bind()", NULL); + if (PR_FAILURE == rv) { + Failed("PR_Bind()", NULL); + } for(option = PR_SockOpt_Linger; option < PR_SockOpt_Last; Incr(&option)) { PRSocketOptionData data; @@ -86,55 +96,49 @@ int main(int argc, char **argv) { case PR_SockOpt_Nonblocking: data.value.non_blocking = PR_TRUE; - break; -#ifndef SYMBIAN + break; case PR_SockOpt_Linger: data.value.linger.polarity = PR_TRUE; - data.value.linger.linger = PR_SecondsToInterval(2); - break; -#endif + data.value.linger.linger = PR_SecondsToInterval(2); + break; case PR_SockOpt_Reuseaddr: - data.value.reuse_addr = PR_TRUE; - break; - case PR_SockOpt_Keepalive: - data.value.keep_alive = PR_TRUE; - break; + data.value.reuse_addr = PR_TRUE; + break; + case PR_SockOpt_Keepalive: + data.value.keep_alive = PR_TRUE; + break; case PR_SockOpt_RecvBufferSize: - data.value.recv_buffer_size = segment; - break; - case PR_SockOpt_SendBufferSize: - data.value.send_buffer_size = segment; - break; -#ifndef SYMBIAN + data.value.recv_buffer_size = segment; + break; + case PR_SockOpt_SendBufferSize: + data.value.send_buffer_size = segment; + break; case PR_SockOpt_IpTimeToLive: - data.value.ip_ttl = 64; - break; + data.value.ip_ttl = 64; + break; case PR_SockOpt_IpTypeOfService: - data.value.tos = 0; - break; + data.value.tos = 0; + break; case PR_SockOpt_McastTimeToLive: - fd = udp; - data.value.mcast_ttl = 4; - break; + fd = udp; + data.value.mcast_ttl = 4; + break; case PR_SockOpt_McastLoopback: - fd = udp; - data.value.mcast_loopback = PR_TRUE; - break; -#endif + fd = udp; + data.value.mcast_loopback = PR_TRUE; + break; case PR_SockOpt_NoDelay: - data.value.no_delay = PR_TRUE; - break; + data.value.no_delay = PR_TRUE; + break; #ifndef WIN32 case PR_SockOpt_MaxSegment: - data.value.max_segment = segment; - break; + data.value.max_segment = segment; + break; #endif -#ifndef SYMBIAN case PR_SockOpt_Broadcast: - fd = udp; - data.value.broadcast = PR_TRUE; - break; -#endif + fd = udp; + data.value.broadcast = PR_TRUE; + break; #ifdef SO_REUSEPORT case PR_SockOpt_Reuseport: data.value.reuse_port = PR_TRUE; @@ -143,22 +147,25 @@ int main(int argc, char **argv) default: continue; } - /* - * TCP_MAXSEG can only be read, not set - */ + /* + * TCP_MAXSEG can only be read, not set + */ if (option != PR_SockOpt_MaxSegment) { #ifdef WIN32 - if (option != PR_SockOpt_McastLoopback) + if (option != PR_SockOpt_McastLoopback) #endif - { - rv = PR_SetSocketOption(fd, &data); - if (PR_FAILURE == rv) - Failed("PR_SetSocketOption()", tag[option]); - } - } + { + rv = PR_SetSocketOption(fd, &data); + if (PR_FAILURE == rv) { + Failed("PR_SetSocketOption()", tag[option]); + } + } + } rv = PR_GetSocketOption(fd, &data); - if (PR_FAILURE == rv) Failed("PR_GetSocketOption()", tag[option]); + if (PR_FAILURE == rv) { + Failed("PR_GetSocketOption()", tag[option]); + } } PR_Close(udp); PR_Close(tcp); diff --git a/nsprpub/pr/tests/sprintf.c b/nsprpub/pr/tests/sprintf.c index 014392c03..51db026d1 100644 --- a/nsprpub/pr/tests/sprintf.c +++ b/nsprpub/pr/tests/sprintf.c @@ -4,16 +4,16 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* - * File: sprintf.c + * File: sprintf.c * Description: * This is a test program for the PR_snprintf() functions defined * in prprf.c. This test program is based on ns/nspr/tests/sprintf.c, * revision 1.10. * Modification History: - * 20-May-1997 AGarcia replaced printf statment to return PASS\n. This is to be used by the - * regress tool parsing routine. + * 20-May-1997 AGarcia replaced printf statment to return PASS\n. This is to be used by the + * regress tool parsing routine. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to - * recognize the return code from tha main program. + * recognize the return code from tha main program. */ #include "prinit.h" @@ -46,60 +46,66 @@ static void test_i(char *pattern, int i) /* compare results */ if ((strncmp(s, buf, sizeof(buf)) != 0) || - (strncmp(s, sbuf, sizeof(sbuf)) != 0)) { - fprintf(stderr, - "pattern='%s' i=%d\nPR_smprintf='%s'\nPR_snprintf='%s'\n sprintf='%s'\n", - pattern, i, s, buf, sbuf); - PR_smprintf_free(s); - exit(-1); + (strncmp(s, sbuf, sizeof(sbuf)) != 0)) { + fprintf(stderr, + "pattern='%s' i=%d\nPR_smprintf='%s'\nPR_snprintf='%s'\n sprintf='%s'\n", + pattern, i, s, buf, sbuf); + PR_smprintf_free(s); + exit(-1); } - PR_smprintf_free(s); + PR_smprintf_free(s); } static void TestI(void) { static int nums[] = { - 0, 1, -1, 10, -10, - 32767, -32768, + 0, 1, -1, 10, -10, + 32767, -32768, }; static char *signs[] = { - "", - "0", "-", "+", " ", - "0-", "0+", "0 ", "-0", "-+", "- ", - "+0", "+-", "+ ", " 0", " -", " +", - "0-+", "0- ", "0+-", "0+ ", "0 -", "0 +", - "-0+", "-0 ", "-+0", "-+ ", "- 0", "- +", - "+0-", "+0 ", "+-0", "+- ", "+ 0", "+ -", - " 0-", " 0+", " -0", " -+", " +0", " +-", - "0-+ ", "0- +", "0+- ", "0+ -", "0 -+", "0 +-", - "-0+ ", "-0 +", "-+0 ", "-+ 0", "- 0+", "- +0", - "+0- ", "+0 -", "+-0 ", "+- 0", "+ 0-", "+ -0", - " 0-+", " 0+-", " -0+", " -+0", " +0-", " +-0", + "", + "0", "-", "+", " ", + "0-", "0+", "0 ", "-0", "-+", "- ", + "+0", "+-", "+ ", " 0", " -", " +", + "0-+", "0- ", "0+-", "0+ ", "0 -", "0 +", + "-0+", "-0 ", "-+0", "-+ ", "- 0", "- +", + "+0-", "+0 ", "+-0", "+- ", "+ 0", "+ -", + " 0-", " 0+", " -0", " -+", " +0", " +-", + "0-+ ", "0- +", "0+- ", "0+ -", "0 -+", "0 +-", + "-0+ ", "-0 +", "-+0 ", "-+ 0", "- 0+", "- +0", + "+0- ", "+0 -", "+-0 ", "+- 0", "+ 0-", "+ -0", + " 0-+", " 0+-", " -0+", " -+0", " +0-", " +-0", }; static char *precs[] = { - "", "3", "5", "43", - "7.3", "7.5", "7.11", "7.43", + "", "3", "5", "43", + "7.3", "7.5", "7.11", "7.43", }; static char *formats[] = { - "d", "o", "x", "u", - "hd", "ho", "hx", "hu" + "d", "o", "x", "u", + "hd", "ho", "hx", "hu" }; int f, s, n, p; char fmt[20]; for (f = 0; f < PR_ARRAY_SIZE(formats); f++) { - for (s = 0; s < PR_ARRAY_SIZE(signs); s++) { - for (p = 0; p < PR_ARRAY_SIZE(precs); p++) { - fmt[0] = '%'; - fmt[1] = 0; - if (signs[s]) strcat(fmt, signs[s]); - if (precs[p]) strcat(fmt, precs[p]); - if (formats[f]) strcat(fmt, formats[f]); - for (n = 0; n < PR_ARRAY_SIZE(nums); n++) { - test_i(fmt, nums[n]); - } - } - } + for (s = 0; s < PR_ARRAY_SIZE(signs); s++) { + for (p = 0; p < PR_ARRAY_SIZE(precs); p++) { + fmt[0] = '%'; + fmt[1] = 0; + if (signs[s]) { + strcat(fmt, signs[s]); + } + if (precs[p]) { + strcat(fmt, precs[p]); + } + if (formats[f]) { + strcat(fmt, formats[f]); + } + for (n = 0; n < PR_ARRAY_SIZE(nums); n++) { + test_i(fmt, nums[n]); + } + } + } } } @@ -124,47 +130,47 @@ static void test_l(char *pattern, char *spattern, PRInt32 l) /* compare results */ if ((strncmp(s, buf, sizeof(buf)) != 0) || - (strncmp(s, sbuf, sizeof(sbuf)) != 0)) { - fprintf(stderr, - "pattern='%s' l=%ld\nPR_smprintf='%s'\nPR_snprintf='%s'\n sprintf='%s'\n", - pattern, l, s, buf, sbuf); - PR_smprintf_free(s); - exit(-1); + (strncmp(s, sbuf, sizeof(sbuf)) != 0)) { + fprintf(stderr, + "pattern='%s' l=%ld\nPR_smprintf='%s'\nPR_snprintf='%s'\n sprintf='%s'\n", + pattern, l, s, buf, sbuf); + PR_smprintf_free(s); + exit(-1); } - PR_smprintf_free(s); + PR_smprintf_free(s); } static void TestL(void) { static PRInt32 nums[] = { - 0, - 1, - -1, - 10, - -10, - 32767, - -32768, - PR_INT32(0x7fffffff), /* 2147483647L */ - -1 - PR_INT32(0x7fffffff) /* -2147483648L */ + 0, + 1, + -1, + 10, + -10, + 32767, + -32768, + PR_INT32(0x7fffffff), /* 2147483647L */ + -1 - PR_INT32(0x7fffffff) /* -2147483648L */ }; static char *signs[] = { - "", - "0", "-", "+", " ", - "0-", "0+", "0 ", "-0", "-+", "- ", - "+0", "+-", "+ ", " 0", " -", " +", - "0-+", "0- ", "0+-", "0+ ", "0 -", "0 +", - "-0+", "-0 ", "-+0", "-+ ", "- 0", "- +", - "+0-", "+0 ", "+-0", "+- ", "+ 0", "+ -", - " 0-", " 0+", " -0", " -+", " +0", " +-", - "0-+ ", "0- +", "0+- ", "0+ -", "0 -+", "0 +-", - "-0+ ", "-0 +", "-+0 ", "-+ 0", "- 0+", "- +0", - "+0- ", "+0 -", "+-0 ", "+- 0", "+ 0-", "+ -0", - " 0-+", " 0+-", " -0+", " -+0", " +0-", " +-0", + "", + "0", "-", "+", " ", + "0-", "0+", "0 ", "-0", "-+", "- ", + "+0", "+-", "+ ", " 0", " -", " +", + "0-+", "0- ", "0+-", "0+ ", "0 -", "0 +", + "-0+", "-0 ", "-+0", "-+ ", "- 0", "- +", + "+0-", "+0 ", "+-0", "+- ", "+ 0", "+ -", + " 0-", " 0+", " -0", " -+", " +0", " +-", + "0-+ ", "0- +", "0+- ", "0+ -", "0 -+", "0 +-", + "-0+ ", "-0 +", "-+0 ", "-+ 0", "- 0+", "- +0", + "+0- ", "+0 -", "+-0 ", "+- 0", "+ 0-", "+ -0", + " 0-+", " 0+-", " -0+", " -+0", " +0-", " +-0", }; static char *precs[] = { - "", "3", "5", "43", - ".3", ".43", - "7.3", "7.5", "7.11", "7.43", + "", "3", "5", "43", + ".3", ".43", + "7.3", "7.5", "7.11", "7.43", }; static char *formats[] = { "ld", "lo", "lx", "lu" }; @@ -180,20 +186,28 @@ static void TestL(void) char fmt[40], sfmt[40]; for (f = 0; f < PR_ARRAY_SIZE(formats); f++) { - for (s = 0; s < PR_ARRAY_SIZE(signs); s++) { - for (p = 0; p < PR_ARRAY_SIZE(precs); p++) { - fmt[0] = '%'; - fmt[1] = 0; - if (signs[s]) strcat(fmt, signs[s]); - if (precs[p]) strcat(fmt, precs[p]); - strcpy(sfmt, fmt); - if (formats[f]) strcat(fmt, formats[f]); - if (sformats[f]) strcat(sfmt, sformats[f]); - for (n = 0; n < PR_ARRAY_SIZE(nums); n++) { - test_l(fmt, sfmt, nums[n]); - } - } - } + for (s = 0; s < PR_ARRAY_SIZE(signs); s++) { + for (p = 0; p < PR_ARRAY_SIZE(precs); p++) { + fmt[0] = '%'; + fmt[1] = 0; + if (signs[s]) { + strcat(fmt, signs[s]); + } + if (precs[p]) { + strcat(fmt, precs[p]); + } + strcpy(sfmt, fmt); + if (formats[f]) { + strcat(fmt, formats[f]); + } + if (sformats[f]) { + strcat(sfmt, sformats[f]); + } + for (n = 0; n < PR_ARRAY_SIZE(nums); n++) { + test_l(fmt, sfmt, nums[n]); + } + } + } } } @@ -219,7 +233,7 @@ static void test_ll(char *pattern, char *spattern, PRInt64 l) /* compare results */ if ((strncmp(s, buf, sizeof(buf)) != 0) || - (strncmp(s, sbuf, sizeof(sbuf)) != 0)) { + (strncmp(s, sbuf, sizeof(sbuf)) != 0)) { #if PR_BYTES_PER_LONG == 8 #define FORMAT_SPEC "%ld" #elif defined(WIN16) @@ -229,73 +243,73 @@ static void test_ll(char *pattern, char *spattern, PRInt64 l) #else #define FORMAT_SPEC "%lld" #endif - fprintf(stderr, - "pattern='%s' ll=" FORMAT_SPEC "\nPR_smprintf='%s'\nPR_snprintf='%s'\n sprintf='%s'\n", - pattern, l, s, buf, sbuf); - printf("FAIL\n"); - PR_smprintf_free(s); - exit(-1); + fprintf(stderr, + "pattern='%s' ll=" FORMAT_SPEC "\nPR_smprintf='%s'\nPR_snprintf='%s'\n sprintf='%s'\n", + pattern, l, s, buf, sbuf); + printf("FAIL\n"); + PR_smprintf_free(s); + exit(-1); } - PR_smprintf_free(s); + PR_smprintf_free(s); #else /* compare results */ if ((strncmp(s, buf, sizeof(buf)) != 0)) { - fprintf(stderr, - "pattern='%s'\nPR_smprintf='%s'\nPR_snprintf='%s'\n sprintf='%s'\n", - pattern, s, buf, sbuf); - printf("FAIL\n"); - PR_smprintf_free(s); + fprintf(stderr, + "pattern='%s'\nPR_smprintf='%s'\nPR_snprintf='%s'\n sprintf='%s'\n", + pattern, s, buf, sbuf); + printf("FAIL\n"); + PR_smprintf_free(s); exit(-1); } - PR_smprintf_free(s); + PR_smprintf_free(s); #endif } static void TestLL(void) { static PRInt64 nums[] = { - LL_INIT(0, 0), - LL_INIT(0, 1), - LL_INIT(0xffffffff, 0xffffffff), /* -1 */ - LL_INIT(0, 10), - LL_INIT(0xffffffff, 0xfffffff6), /* -10 */ - LL_INIT(0, 32767), - LL_INIT(0xffffffff, 0xffff8000), /* -32768 */ - LL_INIT(0, 0x7fffffff), /* 2147483647 */ - LL_INIT(0xffffffff, 0x80000000), /* -2147483648 */ - LL_INIT(0x7fffffff, 0xffffffff), /* 9223372036854775807 */ - LL_INIT(0x80000000, 0), /* -9223372036854775808 */ - PR_INT64(0), - PR_INT64(1), - PR_INT64(-1), - PR_INT64(10), - PR_INT64(-10), - PR_INT64(32767), - PR_INT64(-32768), - PR_INT64(2147483647), - PR_INT64(-2147483648), - PR_INT64(9223372036854775807), - PR_INT64(-9223372036854775808) + LL_INIT(0, 0), + LL_INIT(0, 1), + LL_INIT(0xffffffff, 0xffffffff), /* -1 */ + LL_INIT(0, 10), + LL_INIT(0xffffffff, 0xfffffff6), /* -10 */ + LL_INIT(0, 32767), + LL_INIT(0xffffffff, 0xffff8000), /* -32768 */ + LL_INIT(0, 0x7fffffff), /* 2147483647 */ + LL_INIT(0xffffffff, 0x80000000), /* -2147483648 */ + LL_INIT(0x7fffffff, 0xffffffff), /* 9223372036854775807 */ + LL_INIT(0x80000000, 0), /* -9223372036854775808 */ + PR_INT64(0), + PR_INT64(1), + PR_INT64(-1), + PR_INT64(10), + PR_INT64(-10), + PR_INT64(32767), + PR_INT64(-32768), + PR_INT64(2147483647), + PR_INT64(-2147483648), + PR_INT64(9223372036854775807), + PR_INT64(-9223372036854775808) }; static char *signs[] = { - "", - "0", "-", "+", " ", - "0-", "0+", "0 ", "-0", "-+", "- ", - "+0", "+-", "+ ", " 0", " -", " +", - "0-+", "0- ", "0+-", "0+ ", "0 -", "0 +", - "-0+", "-0 ", "-+0", "-+ ", "- 0", "- +", - "+0-", "+0 ", "+-0", "+- ", "+ 0", "+ -", - " 0-", " 0+", " -0", " -+", " +0", " +-", - "0-+ ", "0- +", "0+- ", "0+ -", "0 -+", "0 +-", - "-0+ ", "-0 +", "-+0 ", "-+ 0", "- 0+", "- +0", - "+0- ", "+0 -", "+-0 ", "+- 0", "+ 0-", "+ -0", - " 0-+", " 0+-", " -0+", " -+0", " +0-", " +-0", + "", + "0", "-", "+", " ", + "0-", "0+", "0 ", "-0", "-+", "- ", + "+0", "+-", "+ ", " 0", " -", " +", + "0-+", "0- ", "0+-", "0+ ", "0 -", "0 +", + "-0+", "-0 ", "-+0", "-+ ", "- 0", "- +", + "+0-", "+0 ", "+-0", "+- ", "+ 0", "+ -", + " 0-", " 0+", " -0", " -+", " +0", " +-", + "0-+ ", "0- +", "0+- ", "0+ -", "0 -+", "0 +-", + "-0+ ", "-0 +", "-+0 ", "-+ 0", "- 0+", "- +0", + "+0- ", "+0 -", "+-0 ", "+- 0", "+ 0-", "+ -0", + " 0-+", " 0+-", " -0+", " -+0", " +0-", " +-0", }; static char *precs[] = { - "", "3", "5", "43", - ".3", ".43", - "7.3", "7.5", "7.11", "7.43", + "", "3", "5", "43", + ".3", ".43", + "7.3", "7.5", "7.11", "7.43", }; static char *formats[] = { "lld", "llo", "llx", "llu" }; @@ -314,20 +328,28 @@ static void TestLL(void) char fmt[40], sfmt[40]; for (f = 0; f < PR_ARRAY_SIZE(formats); f++) { - for (s = 0; s < PR_ARRAY_SIZE(signs); s++) { - for (p = 0; p < PR_ARRAY_SIZE(precs); p++) { - fmt[0] = '%'; - fmt[1] = 0; - if (signs[s]) strcat(fmt, signs[s]); - if (precs[p]) strcat(fmt, precs[p]); - strcpy(sfmt, fmt); - if (formats[f]) strcat(fmt, formats[f]); - if (sformats[f]) strcat(sfmt, sformats[f]); - for (n = 0; n < PR_ARRAY_SIZE(nums); n++) { - test_ll(fmt, sfmt, nums[n]); - } - } - } + for (s = 0; s < PR_ARRAY_SIZE(signs); s++) { + for (p = 0; p < PR_ARRAY_SIZE(precs); p++) { + fmt[0] = '%'; + fmt[1] = 0; + if (signs[s]) { + strcat(fmt, signs[s]); + } + if (precs[p]) { + strcat(fmt, precs[p]); + } + strcpy(sfmt, fmt); + if (formats[f]) { + strcat(fmt, formats[f]); + } + if (sformats[f]) { + strcat(sfmt, sformats[f]); + } + for (n = 0; n < PR_ARRAY_SIZE(nums); n++) { + test_ll(fmt, sfmt, nums[n]); + } + } + } } } @@ -356,64 +378,70 @@ static void test_s(char *pattern, char *ss) sprintf(sbuf, pattern, ss); for (n = 0; n < 8; n++) { - PR_ASSERT(before[n] == 0xBB); - PR_ASSERT(after[n] == 0xAA); + PR_ASSERT(before[n] == 0xBB); + PR_ASSERT(after[n] == 0xAA); } /* compare results */ if ((strncmp(s, buf, sizeof(buf)) != 0) || - (strncmp(s, sbuf, sizeof(sbuf)) != 0)) { - fprintf(stderr, - "pattern='%s' ss=%.20s\nPR_smprintf='%s'\nPR_snprintf='%s'\n sprintf='%s'\n", - pattern, ss, s, buf, sbuf); - printf("FAIL\n"); - PR_smprintf_free(s); - exit(-1); + (strncmp(s, sbuf, sizeof(sbuf)) != 0)) { + fprintf(stderr, + "pattern='%s' ss=%.20s\nPR_smprintf='%s'\nPR_snprintf='%s'\n sprintf='%s'\n", + pattern, ss, s, buf, sbuf); + printf("FAIL\n"); + PR_smprintf_free(s); + exit(-1); } - PR_smprintf_free(s); + PR_smprintf_free(s); } static void TestS(void) { static char *strs[] = { - "", - "a", - "abc", - "abcde", - "abcdefABCDEF", - "abcdefghijklmnopqrstuvwxyz0123456789!@#$" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$" - "abcdefghijklmnopqrstuvwxyz0123456789!@#$", + "", + "a", + "abc", + "abcde", + "abcdefABCDEF", + "abcdefghijklmnopqrstuvwxyz0123456789!@#$" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$" + "abcdefghijklmnopqrstuvwxyz0123456789!@#$", }; /* '0' is not relevant to printing strings */ static char *signs[] = { - "", - "-", "+", " ", - "-+", "- ", "+-", "+ ", " -", " +", - "-+ ", "- +", "+- ", "+ -", " -+", " +-", + "", + "-", "+", " ", + "-+", "- ", "+-", "+ ", " -", " +", + "-+ ", "- +", "+- ", "+ -", " -+", " +-", }; static char *precs[] = { - "", "3", "5", "43", - ".3", ".43", - "7.3", "7.5", "7.11", "7.43", + "", "3", "5", "43", + ".3", ".43", + "7.3", "7.5", "7.11", "7.43", }; static char *formats[] = { "s" }; int f, s, n, p; char fmt[40]; for (f = 0; f < PR_ARRAY_SIZE(formats); f++) { - for (s = 0; s < PR_ARRAY_SIZE(signs); s++) { - for (p = 0; p < PR_ARRAY_SIZE(precs); p++) { - fmt[0] = '%'; - fmt[1] = 0; - if (signs[s]) strcat(fmt+strlen(fmt), signs[s]); - if (precs[p]) strcat(fmt+strlen(fmt), precs[p]); - if (formats[f]) strcat(fmt+strlen(fmt), formats[f]); - for (n = 0; n < PR_ARRAY_SIZE(strs); n++) { - test_s(fmt, strs[n]); - } - } - } + for (s = 0; s < PR_ARRAY_SIZE(signs); s++) { + for (p = 0; p < PR_ARRAY_SIZE(precs); p++) { + fmt[0] = '%'; + fmt[1] = 0; + if (signs[s]) { + strcat(fmt+strlen(fmt), signs[s]); + } + if (precs[p]) { + strcat(fmt+strlen(fmt), precs[p]); + } + if (formats[f]) { + strcat(fmt+strlen(fmt), formats[f]); + } + for (n = 0; n < PR_ARRAY_SIZE(strs); n++) { + test_s(fmt, strs[n]); + } + } + } } } diff --git a/nsprpub/pr/tests/sproc_ch.c b/nsprpub/pr/tests/sproc_ch.c deleted file mode 100644 index 0264b4ce9..000000000 --- a/nsprpub/pr/tests/sproc_ch.c +++ /dev/null @@ -1,87 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Test sproc_ch.c - * - * The purpose of this test and the sproc_p.c test is to test the shutdown - * of all the IRIX sprocs in a program when one of them dies due to an error. - * - * There are three sprocs in this test: the parent, the child, and the - * grandchild. The parent and child sprocs never stop on their own. - * The grandchild sproc gets a segmentation fault and dies. You should - * You should use "ps" to see if the parent and child sprocs are killed - * after the grandchild dies. - */ - -#include "prinit.h" -#include <stdio.h> - -#if !defined(IRIX) - -int main(int argc, char **argv) -{ - printf("This test applies to IRIX only.\n"); - return 0; -} - -#else /* IRIX */ - -#include "prthread.h" -#include <sys/types.h> -#include <unistd.h> - -void SegFault(void *unused) -{ - int *p = 0; - - printf("The grandchild sproc has pid %d.\n", getpid()); - printf("The grandchild sproc will get a segmentation fault and die.\n"); - printf("The parent and child sprocs should be killed after the " - "grandchild sproc dies.\n"); - printf("Use 'ps' to make sure this is so.\n"); - fflush(stdout); - /* Force a segmentation fault */ - *p = 0; -} - -void NeverStops(void *unused) -{ - int i = 0; - - printf("The child sproc has pid %d.\n", getpid()); - printf("The child sproc won't stop on its own.\n"); - fflush(stdout); - - /* create the grandchild sproc */ - PR_CreateThread(PR_USER_THREAD, SegFault, NULL, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, 0); - - while (1) { - i++; - } -} - -int main() -{ - int i= 0; - - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); - - printf("The parent sproc has pid %d.\n", getpid()); - printf("The parent sproc won't stop on its own.\n"); - fflush(stdout); - - /* create the child sproc */ - PR_CreateThread(PR_USER_THREAD, NeverStops, NULL, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, 0); - - while (1) { - i++; - } - return 0; -} - -#endif /* IRIX */ diff --git a/nsprpub/pr/tests/sproc_p.c b/nsprpub/pr/tests/sproc_p.c deleted file mode 100644 index 8911f1f5b..000000000 --- a/nsprpub/pr/tests/sproc_p.c +++ /dev/null @@ -1,69 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Test sproc_p.c - * - * The purpose of this test and the sproc_ch.c test is to test the shutdown - * of all the IRIX sprocs in a program when one of them dies due to an error. - * - * In this test, the parent sproc gets a segmentation fault and dies. - * The child sproc never stops on its own. You should use "ps" to see if - * the child sproc is killed after the parent dies. - */ - -#include "prinit.h" -#include <stdio.h> - -#if !defined(IRIX) - -int main(int argc, char **argv) -{ - printf("This test applies to IRIX only.\n"); - return 0; -} - -#else /* IRIX */ - -#include "prthread.h" -#include <sys/types.h> -#include <unistd.h> - -void NeverStops(void *unused) -{ - int i = 0; - - printf("The child sproc has pid %d.\n", getpid()); - printf("The child sproc won't stop on its own.\n"); - fflush(stdout); - - /* I never stop */ - while (1) { - i++; - } -} - -int main() -{ - int *p = 0; - - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); - - printf("The parent sproc has pid %d.\n", getpid()); - printf("The parent sproc will first create a child sproc.\n"); - printf("Then the parent sproc will get a segmentation fault and die.\n"); - printf("The child sproc should be killed after the parent sproc dies.\n"); - printf("Use 'ps' to make sure this is so.\n"); - fflush(stdout); - - PR_CreateThread(PR_USER_THREAD, NeverStops, NULL, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, 0); - - /* Force a segmentation fault */ - *p = 0; - return 0; -} - -#endif /* IRIX */ diff --git a/nsprpub/pr/tests/stack.c b/nsprpub/pr/tests/stack.c index 182191ad5..5526a2744 100644 --- a/nsprpub/pr/tests/stack.c +++ b/nsprpub/pr/tests/stack.c @@ -7,29 +7,29 @@ /* * * Test atomic stack operations - * - * Two stacks are created and threads add data items (each containing - * one of the first n integers) to the first stack, remove data items - * from the first stack and add them to the second stack. The primordial - * thread compares the sum of the first n integers to the sum of the - * integers in the data items in the second stack. The test succeeds if - * they are equal. + * + * Two stacks are created and threads add data items (each containing + * one of the first n integers) to the first stack, remove data items + * from the first stack and add them to the second stack. The primordial + * thread compares the sum of the first n integers to the sum of the + * integers in the data items in the second stack. The test succeeds if + * they are equal. */ - + #include "nspr.h" #include "plgetopt.h" typedef struct _DataRecord { - PRInt32 data; - PRStackElem link; + PRInt32 data; + PRStackElem link; } DataRecord; #define RECORD_LINK_PTR(lp) ((DataRecord*) ((char*) (lp) - offsetof(DataRecord,link))) -#define MAX_THREAD_CNT 100 -#define DEFAULT_THREAD_CNT 4 -#define DEFAULT_DATA_CNT 100 -#define DEFAULT_LOOP_CNT 10000 +#define MAX_THREAD_CNT 100 +#define DEFAULT_THREAD_CNT 4 +#define DEFAULT_DATA_CNT 100 +#define DEFAULT_LOOP_CNT 10000 /* * sum of the first n numbers using the formula n*(n+1)/2 @@ -37,11 +37,11 @@ typedef struct _DataRecord { #define SUM_OF_NUMBERS(n) ((n & 1) ? (((n + 1)/2) * n) : ((n/2) * (n+1))) typedef struct stack_data { - PRStack *list1; - PRStack *list2; - PRInt32 initial_data_value; - PRInt32 data_cnt; - PRInt32 loops; + PRStack *list1; + PRStack *list2; + PRInt32 initial_data_value; + PRInt32 data_cnt; + PRInt32 loops; } stack_data; static void stackop(void *arg); @@ -53,228 +53,230 @@ PRFileDesc *errhandle; int main(int argc, char **argv) { -#if !(defined(SYMBIAN) && defined(__WINS__)) PRInt32 rv, cnt, sum; - DataRecord *Item; - PRStack *list1, *list2; - PRStackElem *node; - PRStatus rc; + DataRecord *Item; + PRStack *list1, *list2; + PRStackElem *node; + PRStatus rc; - PRInt32 thread_cnt = DEFAULT_THREAD_CNT; - PRInt32 data_cnt = DEFAULT_DATA_CNT; - PRInt32 loops = DEFAULT_LOOP_CNT; - PRThread **threads; - stack_data *thread_args; + PRInt32 thread_cnt = DEFAULT_THREAD_CNT; + PRInt32 data_cnt = DEFAULT_DATA_CNT; + PRInt32 loops = DEFAULT_LOOP_CNT; + PRThread **threads; + stack_data *thread_args; - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "dt:c:l:"); + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "dt:c:l:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - _debug_on = 1; - break; - case 't': /* thread count */ - thread_cnt = atoi(opt->value); - break; - case 'c': /* data count */ - data_cnt = atoi(opt->value); - break; - case 'l': /* loop count */ - loops = atoi(opt->value); - break; - default: - break; + case 'd': /* debug mode */ + _debug_on = 1; + break; + case 't': /* thread count */ + thread_cnt = atoi(opt->value); + break; + case 'c': /* data count */ + data_cnt = atoi(opt->value); + break; + case 'l': /* loop count */ + loops = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); - PR_SetConcurrency(4); + PR_SetConcurrency(4); output = PR_GetSpecialFD(PR_StandardOutput); errhandle = PR_GetSpecialFD(PR_StandardError); - list1 = PR_CreateStack("Stack_1"); - if (list1 == NULL) { - PR_fprintf(errhandle, "PR_CreateStack failed - error %d\n", - PR_GetError()); - return 1; - } - - list2 = PR_CreateStack("Stack_2"); - if (list2 == NULL) { - PR_fprintf(errhandle, "PR_CreateStack failed - error %d\n", - PR_GetError()); - return 1; - } - - - threads = (PRThread**) PR_CALLOC(sizeof(PRThread*) * thread_cnt); - thread_args = (stack_data *) PR_CALLOC(sizeof(stack_data) * thread_cnt); - - if (_debug_on) - PR_fprintf(output,"%s: thread_cnt = %d data_cnt = %d\n", argv[0], - thread_cnt, data_cnt); - for(cnt = 0; cnt < thread_cnt; cnt++) { - PRThreadScope scope; - - thread_args[cnt].list1 = list1; - thread_args[cnt].list2 = list2; - thread_args[cnt].loops = loops; - thread_args[cnt].data_cnt = data_cnt; - thread_args[cnt].initial_data_value = 1 + cnt * data_cnt; - - if (cnt & 1) - scope = PR_GLOBAL_THREAD; - else - scope = PR_LOCAL_THREAD; - - - threads[cnt] = PR_CreateThread(PR_USER_THREAD, - stackop, &thread_args[cnt], - PR_PRIORITY_NORMAL, - scope, - PR_JOINABLE_THREAD, - 0); - if (threads[cnt] == NULL) { - PR_fprintf(errhandle, "PR_CreateThread failed - error %d\n", - PR_GetError()); - PR_ProcessExit(2); - } - if (_debug_on) - PR_fprintf(output,"%s: created thread = 0x%x\n", argv[0], - threads[cnt]); - } - - for(cnt = 0; cnt < thread_cnt; cnt++) { - rc = PR_JoinThread(threads[cnt]); - PR_ASSERT(rc == PR_SUCCESS); - } - - node = PR_StackPop(list1); - /* - * list1 should be empty - */ - if (node != NULL) { - PR_fprintf(errhandle, "Error - Stack 1 not empty\n"); - PR_ASSERT(node == NULL); - PR_ProcessExit(4); - } - - cnt = data_cnt * thread_cnt; - sum = 0; - while (cnt-- > 0) { - node = PR_StackPop(list2); - /* - * There should be at least 'cnt' number of records - */ - if (node == NULL) { - PR_fprintf(errhandle, "Error - PR_StackPop returned NULL\n"); - PR_ProcessExit(3); - } - Item = RECORD_LINK_PTR(node); - sum += Item->data; - } - node = PR_StackPop(list2); - /* - * there should be exactly 'cnt' number of records - */ - if (node != NULL) { - PR_fprintf(errhandle, "Error - Stack 2 not empty\n"); - PR_ASSERT(node == NULL); - PR_ProcessExit(4); - } - PR_DELETE(threads); - PR_DELETE(thread_args); - - PR_DestroyStack(list1); - PR_DestroyStack(list2); - - if (sum == SUM_OF_NUMBERS(data_cnt * thread_cnt)) { - PR_fprintf(output, "%s successful\n", argv[0]); - PR_fprintf(output, "\t\tsum = 0x%x, expected = 0x%x\n", sum, - SUM_OF_NUMBERS(thread_cnt * data_cnt)); - return 0; - } else { - PR_fprintf(output, "%s failed: sum = 0x%x, expected = 0x%x\n", - argv[0], sum, - SUM_OF_NUMBERS(data_cnt * thread_cnt)); - return 2; - } -#endif + list1 = PR_CreateStack("Stack_1"); + if (list1 == NULL) { + PR_fprintf(errhandle, "PR_CreateStack failed - error %d\n", + PR_GetError()); + return 1; + } + + list2 = PR_CreateStack("Stack_2"); + if (list2 == NULL) { + PR_fprintf(errhandle, "PR_CreateStack failed - error %d\n", + PR_GetError()); + return 1; + } + + + threads = (PRThread**) PR_CALLOC(sizeof(PRThread*) * thread_cnt); + thread_args = (stack_data *) PR_CALLOC(sizeof(stack_data) * thread_cnt); + + if (_debug_on) + PR_fprintf(output,"%s: thread_cnt = %d data_cnt = %d\n", argv[0], + thread_cnt, data_cnt); + for(cnt = 0; cnt < thread_cnt; cnt++) { + PRThreadScope scope; + + thread_args[cnt].list1 = list1; + thread_args[cnt].list2 = list2; + thread_args[cnt].loops = loops; + thread_args[cnt].data_cnt = data_cnt; + thread_args[cnt].initial_data_value = 1 + cnt * data_cnt; + + if (cnt & 1) { + scope = PR_GLOBAL_THREAD; + } + else { + scope = PR_LOCAL_THREAD; + } + + + threads[cnt] = PR_CreateThread(PR_USER_THREAD, + stackop, &thread_args[cnt], + PR_PRIORITY_NORMAL, + scope, + PR_JOINABLE_THREAD, + 0); + if (threads[cnt] == NULL) { + PR_fprintf(errhandle, "PR_CreateThread failed - error %d\n", + PR_GetError()); + PR_ProcessExit(2); + } + if (_debug_on) + PR_fprintf(output,"%s: created thread = 0x%x\n", argv[0], + threads[cnt]); + } + + for(cnt = 0; cnt < thread_cnt; cnt++) { + rc = PR_JoinThread(threads[cnt]); + PR_ASSERT(rc == PR_SUCCESS); + } + + node = PR_StackPop(list1); + /* + * list1 should be empty + */ + if (node != NULL) { + PR_fprintf(errhandle, "Error - Stack 1 not empty\n"); + PR_ASSERT(node == NULL); + PR_ProcessExit(4); + } + + cnt = data_cnt * thread_cnt; + sum = 0; + while (cnt-- > 0) { + node = PR_StackPop(list2); + /* + * There should be at least 'cnt' number of records + */ + if (node == NULL) { + PR_fprintf(errhandle, "Error - PR_StackPop returned NULL\n"); + PR_ProcessExit(3); + } + Item = RECORD_LINK_PTR(node); + sum += Item->data; + } + node = PR_StackPop(list2); + /* + * there should be exactly 'cnt' number of records + */ + if (node != NULL) { + PR_fprintf(errhandle, "Error - Stack 2 not empty\n"); + PR_ASSERT(node == NULL); + PR_ProcessExit(4); + } + PR_DELETE(threads); + PR_DELETE(thread_args); + + PR_DestroyStack(list1); + PR_DestroyStack(list2); + + if (sum == SUM_OF_NUMBERS(data_cnt * thread_cnt)) { + PR_fprintf(output, "%s successful\n", argv[0]); + PR_fprintf(output, "\t\tsum = 0x%x, expected = 0x%x\n", sum, + SUM_OF_NUMBERS(thread_cnt * data_cnt)); + return 0; + } else { + PR_fprintf(output, "%s failed: sum = 0x%x, expected = 0x%x\n", + argv[0], sum, + SUM_OF_NUMBERS(data_cnt * thread_cnt)); + return 2; + } } static void stackop(void *thread_arg) { PRInt32 val, cnt, index, loops; - DataRecord *Items, *Item; - PRStack *list1, *list2; - PRStackElem *node; - stack_data *arg = (stack_data *) thread_arg; - - val = arg->initial_data_value; - cnt = arg->data_cnt; - loops = arg->loops; - list1 = arg->list1; - list2 = arg->list2; - - /* - * allocate memory for the data records - */ - Items = (DataRecord *) PR_CALLOC(sizeof(DataRecord) * cnt); - PR_ASSERT(Items != NULL); - index = 0; - - if (_debug_on) - PR_fprintf(output, - "Thread[0x%x] init_val = %d cnt = %d data1 = 0x%x datan = 0x%x\n", - PR_GetCurrentThread(), val, cnt, &Items[0], &Items[cnt-1]); - - - /* - * add the data records to list1 - */ - while (cnt-- > 0) { - Items[index].data = val++; - PR_StackPush(list1, &Items[index].link); - index++; - } - - /* - * pop data records from list1 and add them back to list1 - * generates contention for the stack accesses - */ - while (loops-- > 0) { - cnt = arg->data_cnt; - while (cnt-- > 0) { - node = PR_StackPop(list1); - if (node == NULL) { - PR_fprintf(errhandle, "Error - PR_StackPop returned NULL\n"); - PR_ASSERT(node != NULL); - PR_ProcessExit(3); - } - PR_StackPush(list1, node); - } - } - /* - * remove the data records from list1 and add them to list2 - */ - cnt = arg->data_cnt; - while (cnt-- > 0) { - node = PR_StackPop(list1); - if (node == NULL) { - PR_fprintf(errhandle, "Error - PR_StackPop returned NULL\n"); - PR_ASSERT(node != NULL); - PR_ProcessExit(3); - } - PR_StackPush(list2, node); - } - if (_debug_on) - PR_fprintf(output, - "Thread[0x%x] init_val = %d cnt = %d exiting\n", - PR_GetCurrentThread(), val, cnt); + DataRecord *Items, *Item; + PRStack *list1, *list2; + PRStackElem *node; + stack_data *arg = (stack_data *) thread_arg; + + val = arg->initial_data_value; + cnt = arg->data_cnt; + loops = arg->loops; + list1 = arg->list1; + list2 = arg->list2; + + /* + * allocate memory for the data records + */ + Items = (DataRecord *) PR_CALLOC(sizeof(DataRecord) * cnt); + PR_ASSERT(Items != NULL); + index = 0; + + if (_debug_on) + PR_fprintf(output, + "Thread[0x%x] init_val = %d cnt = %d data1 = 0x%x datan = 0x%x\n", + PR_GetCurrentThread(), val, cnt, &Items[0], &Items[cnt-1]); + + + /* + * add the data records to list1 + */ + while (cnt-- > 0) { + Items[index].data = val++; + PR_StackPush(list1, &Items[index].link); + index++; + } + + /* + * pop data records from list1 and add them back to list1 + * generates contention for the stack accesses + */ + while (loops-- > 0) { + cnt = arg->data_cnt; + while (cnt-- > 0) { + node = PR_StackPop(list1); + if (node == NULL) { + PR_fprintf(errhandle, "Error - PR_StackPop returned NULL\n"); + PR_ASSERT(node != NULL); + PR_ProcessExit(3); + } + PR_StackPush(list1, node); + } + } + /* + * remove the data records from list1 and add them to list2 + */ + cnt = arg->data_cnt; + while (cnt-- > 0) { + node = PR_StackPop(list1); + if (node == NULL) { + PR_fprintf(errhandle, "Error - PR_StackPop returned NULL\n"); + PR_ASSERT(node != NULL); + PR_ProcessExit(3); + } + PR_StackPush(list2, node); + } + if (_debug_on) + PR_fprintf(output, + "Thread[0x%x] init_val = %d cnt = %d exiting\n", + PR_GetCurrentThread(), val, cnt); } diff --git a/nsprpub/pr/tests/stat.c b/nsprpub/pr/tests/stat.c index c570056f8..1f870a0d4 100644 --- a/nsprpub/pr/tests/stat.c +++ b/nsprpub/pr/tests/stat.c @@ -4,7 +4,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* - * Program to test different ways to get file info; right now it + * Program to test different ways to get file info; right now it * only works for solaris and OS/2. * */ @@ -35,9 +35,9 @@ static void statPRStat(void) { PRFileInfo finfo; PRInt32 index = count; - - for (;index--;) { - PR_GetFileInfo(filename, &finfo); + + for (; index--;) { + PR_GetFileInfo(filename, &finfo); } } @@ -45,8 +45,8 @@ static void statStat(void) { struct stat finfo; PRInt32 index = count; - - for (;index--;) { + + for (; index--;) { stat(filename, &finfo); } } @@ -75,9 +75,9 @@ int main(int argc, char **argv) PR_STDIO_INIT(); if (argc > 1) { - count = atoi(argv[1]); + count = atoi(argv[1]); } else { - count = DEFAULT_COUNT; + count = DEFAULT_COUNT; } Measure(statPRStat, "time to call PR_GetFileInfo()"); diff --git a/nsprpub/pr/tests/stdio.c b/nsprpub/pr/tests/stdio.c index 8e2b85608..d8a12389b 100644 --- a/nsprpub/pr/tests/stdio.c +++ b/nsprpub/pr/tests/stdio.c @@ -8,9 +8,9 @@ * Description: testing the "special" fds * Modification History: * 20-May-1997 AGarcia - Replace Test succeeded status with PASS. This is used by the - * regress tool parsing code. + * regress tool parsing code. ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to -** recognize the return code from tha main program. +** recognize the return code from tha main program. */ @@ -29,12 +29,12 @@ static PRIntn PR_CALLBACK stdio(PRIntn argc, char **argv) PRFileDesc *err = PR_GetSpecialFD(PR_StandardError); rv = PR_Write( - out, "This to standard out\n", - strlen("This to standard out\n")); + out, "This to standard out\n", + strlen("This to standard out\n")); PR_ASSERT((PRInt32)strlen("This to standard out\n") == rv); rv = PR_Write( - err, "This to standard err\n", - strlen("This to standard err\n")); + err, "This to standard err\n", + strlen("This to standard err\n")); PR_ASSERT((PRInt32)strlen("This to standard err\n") == rv); return 0; diff --git a/nsprpub/pr/tests/strod.c b/nsprpub/pr/tests/strod.c index 3d1503e00..014192fa6 100644 --- a/nsprpub/pr/tests/strod.c +++ b/nsprpub/pr/tests/strod.c @@ -31,21 +31,23 @@ static PRIntn PR_CALLBACK RealMain(PRIntn argc, char **argv) while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'n': /* number to translate */ - number = opt->value; - break; - case 'l': /* number of times to run the tests */ - loops = atoi(opt->value); - break; - case 'h': /* user wants some guidance */ - Help(); /* so give him an earful */ - return 2; /* but not a lot else */ - break; - default: - break; + case 'n': /* number to translate */ + number = opt->value; + break; + case 'l': /* number of times to run the tests */ + loops = atoi(opt->value); + break; + case 'h': /* user wants some guidance */ + Help(); /* so give him an earful */ + return 2; /* but not a lot else */ + break; + default: + break; } } PL_DestroyOptState(opt); @@ -67,7 +69,7 @@ static PRIntn PR_CALLBACK RealMain(PRIntn argc, char **argv) int main(int argc, char **argv) { PRIntn rv; - + PR_STDIO_INIT(); rv = PR_Initialize(RealMain, argc, argv, 0); return rv; diff --git a/nsprpub/pr/tests/suspend.c b/nsprpub/pr/tests/suspend.c index 7dfe28c66..1976b9d8c 100644 --- a/nsprpub/pr/tests/suspend.c +++ b/nsprpub/pr/tests/suspend.c @@ -3,15 +3,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifdef XP_BEOS -#include <stdio.h> -int main() -{ - printf( "This test is not ported to the BeOS\n" ); - return 0; -} -#else - #include "nspr.h" #include "prpriv.h" #include "prinrval.h" @@ -42,21 +33,21 @@ Level_1_Thread(void *arg) PRThread *thr; thr = PR_CreateThreadGCAble(PR_USER_THREAD, - Level_2_Thread, - NULL, - PR_PRIORITY_HIGH, - scope, - PR_JOINABLE_THREAD, - 0); + Level_2_Thread, + NULL, + PR_PRIORITY_HIGH, + scope, + PR_JOINABLE_THREAD, + 0); if (!thr) { printf("Could not create thread!\n"); } else { printf("Level_1_Thread[0x%lx] created %15s thread 0x%lx\n", - PR_GetCurrentThread(), - (scope == PR_GLOBAL_THREAD) ? - "PR_GLOBAL_THREAD" : "PR_LOCAL_THREAD", - thr); + PR_GetCurrentThread(), + (scope == PR_GLOBAL_THREAD) ? + "PR_GLOBAL_THREAD" : "PR_LOCAL_THREAD", + thr); PR_JoinThread(thr); } PR_EnterMonitor(mon); @@ -72,13 +63,13 @@ static PRStatus PR_CALLBACK print_thread(PRThread *thread, int i, void *arg) PRWord *registers; printf( - "\nprint_thread[0x%lx]: %-20s - i = %ld\n",thread, + "\nprint_thread[0x%lx]: %-20s - i = %ld\n",thread, (PR_GLOBAL_THREAD == PR_GetThreadScope(thread)) ? "PR_GLOBAL_THREAD" : "PR_LOCAL_THREAD", i); registers = PR_GetGCRegisters(thread, 0, (int *)&words); if (registers) printf("Registers R0 = 0x%x R1 = 0x%x R2 = 0x%x R3 = 0x%x\n", - registers[0],registers[1],registers[2],registers[3]); + registers[0],registers[1],registers[2],registers[3]); printf("Stack Pointer = 0x%lx\n", PR_GetSP(thread)); return PR_SUCCESS; } @@ -97,21 +88,21 @@ static void Level_0_Thread(PRThreadScope scope1, PRThreadScope scope2) alive = count; for (n=0; n<count; n++) { thr = PR_CreateThreadGCAble(PR_USER_THREAD, - Level_1_Thread, - (void *)scope2, - PR_PRIORITY_NORMAL, - scope1, - PR_UNJOINABLE_THREAD, - 0); + Level_1_Thread, + (void *)scope2, + PR_PRIORITY_NORMAL, + scope1, + PR_UNJOINABLE_THREAD, + 0); if (!thr) { printf("Could not create thread!\n"); alive--; } printf("Level_0_Thread[0x%lx] created %15s thread 0x%lx\n", - PR_GetCurrentThread(), - (scope1 == PR_GLOBAL_THREAD) ? - "PR_GLOBAL_THREAD" : "PR_LOCAL_THREAD", - thr); + PR_GetCurrentThread(), + (scope1 == PR_GLOBAL_THREAD) ? + "PR_GLOBAL_THREAD" : "PR_LOCAL_THREAD", + thr); PR_Sleep(0); } @@ -120,7 +111,7 @@ static void Level_0_Thread(PRThreadScope scope1, PRThreadScope scope2) registers = PR_GetGCRegisters(me, 1, (int *)&words); if (registers) printf("My Registers: R0 = 0x%x R1 = 0x%x R2 = 0x%x R3 = 0x%x\n", - registers[0],registers[1],registers[2],registers[3]); + registers[0],registers[1],registers[2],registers[3]); printf("My Stack Pointer = 0x%lx\n", PR_GetSP(me)); PR_ResumeAll(); @@ -184,4 +175,3 @@ int main(int argc, char **argv) return 0; } -#endif /* XP_BEOS */ diff --git a/nsprpub/pr/tests/switch.c b/nsprpub/pr/tests/switch.c index 43c5ce562..43db7888f 100644 --- a/nsprpub/pr/tests/switch.c +++ b/nsprpub/pr/tests/switch.c @@ -45,11 +45,11 @@ static void Help(void) debug_out = PR_STDOUT; PR_fprintf( - debug_out, "Usage: >./switch [-c n] [-t n] [-d] [-v] [-G] [-C n]\n"); + debug_out, "Usage: >./switch [-c n] [-t n] [-d] [-v] [-G] [-C n]\n"); PR_fprintf( - debug_out, "-c n\tloops at thread level (default: %d)\n", DEFAULT_LOOPS); + debug_out, "-c n\tloops at thread level (default: %d)\n", DEFAULT_LOOPS); PR_fprintf( - debug_out, "-t n\tnumber of threads (default: %d)\n", DEFAULT_THREADS); + debug_out, "-t n\tnumber of threads (default: %d)\n", DEFAULT_THREADS); PR_fprintf(debug_out, "-d\tturn on debugging output (default: FALSE)\n"); PR_fprintf(debug_out, "-v\tturn on verbose output (default: FALSE)\n"); PR_fprintf(debug_out, "-G\tglobal threads only (default: FALSE)\n"); @@ -63,9 +63,12 @@ static void PR_CALLBACK Notified(void *arg) while (PR_SUCCESS == status) { PR_Lock(shared->ml); - while (shared->twiddle && (PR_SUCCESS == status)) + while (shared->twiddle && (PR_SUCCESS == status)) { status = PR_WaitCondVar(shared->cv, PR_INTERVAL_NO_TIMEOUT); - if (verbosity) PR_fprintf(debug_out, "+"); + } + if (verbosity) { + PR_fprintf(debug_out, "+"); + } shared->twiddle = PR_TRUE; shared->next->twiddle = PR_FALSE; PR_NotifyCondVar(shared->next->cv); @@ -76,7 +79,7 @@ static void PR_CALLBACK Notified(void *arg) static Shared home; PRIntn PR_CALLBACK Switch(PRIntn argc, char **argv) { - PLOptStatus os; + PLOptStatus os; PRStatus status; PRBool help = PR_FALSE; PRUintn concurrency = 1; @@ -85,52 +88,56 @@ PRIntn PR_CALLBACK Switch(PRIntn argc, char **argv) PRThreadScope thread_scope = PR_LOCAL_THREAD; PRUintn thread_count, inner_count, loop_count, average; PRUintn thread_limit = DEFAULT_THREADS, loop_limit = DEFAULT_LOOPS; - PLOptState *opt = PL_CreateOptState(argc, argv, "hdvc:t:C:G"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + PLOptState *opt = PL_CreateOptState(argc, argv, "hdvc:t:C:G"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'v': /* verbose mode */ - verbosity = PR_TRUE; - case 'd': /* debug mode */ - debug_mode = PR_TRUE; - break; - case 'c': /* loop counter */ - loop_limit = atoi(opt->value); - break; - case 't': /* thread limit */ - thread_limit = atoi(opt->value); - break; - case 'C': /* Concurrency limit */ - concurrency = atoi(opt->value); - break; - case 'G': /* global threads only */ - thread_scope = PR_GLOBAL_THREAD; - break; - case 'h': /* help message */ - Help(); - help = PR_TRUE; - break; - default: - break; + case 'v': /* verbose mode */ + verbosity = PR_TRUE; + case 'd': /* debug mode */ + debug_mode = PR_TRUE; + break; + case 'c': /* loop counter */ + loop_limit = atoi(opt->value); + break; + case 't': /* thread limit */ + thread_limit = atoi(opt->value); + break; + case 'C': /* Concurrency limit */ + concurrency = atoi(opt->value); + break; + case 'G': /* global threads only */ + thread_scope = PR_GLOBAL_THREAD; + break; + case 'h': /* help message */ + Help(); + help = PR_TRUE; + break; + default: + break; } } - PL_DestroyOptState(opt); - - if (help) return -1; - - if (PR_TRUE == debug_mode) - { - debug_out = PR_STDOUT; - PR_fprintf(debug_out, "Test parameters\n"); - PR_fprintf(debug_out, "\tThreads involved: %d\n", thread_limit); - PR_fprintf(debug_out, "\tIteration limit: %d\n", loop_limit); - PR_fprintf(debug_out, "\tConcurrency: %d\n", concurrency); - PR_fprintf( - debug_out, "\tThread type: %s\n", - (PR_GLOBAL_THREAD == thread_scope) ? "GLOBAL" : "LOCAL"); - } + PL_DestroyOptState(opt); + + if (help) { + return -1; + } + + if (PR_TRUE == debug_mode) + { + debug_out = PR_STDOUT; + PR_fprintf(debug_out, "Test parameters\n"); + PR_fprintf(debug_out, "\tThreads involved: %d\n", thread_limit); + PR_fprintf(debug_out, "\tIteration limit: %d\n", loop_limit); + PR_fprintf(debug_out, "\tConcurrency: %d\n", concurrency); + PR_fprintf( + debug_out, "\tThread type: %s\n", + (PR_GLOBAL_THREAD == thread_scope) ? "GLOBAL" : "LOCAL"); + } PR_SetConcurrency(concurrency); @@ -153,70 +160,78 @@ PRIntn PR_CALLBACK Switch(PRIntn argc, char **argv) link = shared; shared->thread = PR_CreateThread( - PR_USER_THREAD, Notified, shared, - PR_PRIORITY_HIGH, thread_scope, - PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, Notified, shared, + PR_PRIORITY_HIGH, thread_scope, + PR_JOINABLE_THREAD, 0); PR_ASSERT(shared->thread != NULL); - if (NULL == shared->thread) + if (NULL == shared->thread) { failed = PR_TRUE; - } + } + } for (loop_count = 1; loop_count <= loop_limit; ++loop_count) { - timein = PR_IntervalNow(); - for (inner_count = 0; inner_count < INNER_LOOPS; ++inner_count) - { - PR_Lock(home.ml); - home.twiddle = PR_TRUE; - shared->twiddle = PR_FALSE; - PR_NotifyCondVar(shared->cv); - while (home.twiddle) + timein = PR_IntervalNow(); + for (inner_count = 0; inner_count < INNER_LOOPS; ++inner_count) + { + PR_Lock(home.ml); + home.twiddle = PR_TRUE; + shared->twiddle = PR_FALSE; + PR_NotifyCondVar(shared->cv); + while (home.twiddle) { - status = PR_WaitCondVar(home.cv, PR_INTERVAL_NO_TIMEOUT); - if (PR_FAILURE == status) - failed = PR_TRUE; + status = PR_WaitCondVar(home.cv, PR_INTERVAL_NO_TIMEOUT); + if (PR_FAILURE == status) { + failed = PR_TRUE; + } } - PR_Unlock(home.ml); - } - timeout += (PR_IntervalNow() - timein); - } - - if (debug_mode) - { - average = PR_IntervalToMicroseconds(timeout) - / (INNER_LOOPS * loop_limit * thread_count); - PR_fprintf( - debug_out, "Average switch times %d usecs for %d threads\n", + PR_Unlock(home.ml); + } + timeout += (PR_IntervalNow() - timein); + } + + if (debug_mode) + { + average = PR_IntervalToMicroseconds(timeout) + / (INNER_LOOPS * loop_limit * thread_count); + PR_fprintf( + debug_out, "Average switch times %d usecs for %d threads\n", average, thread_limit); - } + } link = shared; for (thread_count = 1; thread_count <= thread_limit; ++thread_count) { - if (&home == link) break; + if (&home == link) { + break; + } status = PR_Interrupt(link->thread); - if (PR_SUCCESS != status) + if (PR_SUCCESS != status) { failed = PR_TRUE; - if (debug_mode) - PL_FPrintError(debug_out, "Failed to interrupt"); + if (debug_mode) { + PL_FPrintError(debug_out, "Failed to interrupt"); + } } - link = link->next; + link = link->next; } for (thread_count = 1; thread_count <= thread_limit; ++thread_count) { link = shared->next; status = PR_JoinThread(shared->thread); - if (PR_SUCCESS != status) - { + if (PR_SUCCESS != status) + { failed = PR_TRUE; - if (debug_mode) - PL_FPrintError(debug_out, "Failed to join"); + if (debug_mode) { + PL_FPrintError(debug_out, "Failed to join"); + } } PR_DestroyCondVar(shared->cv); PR_DELETE(shared); - if (&home == link) break; + if (&home == link) { + break; + } shared = link; } PR_DestroyCondVar(home.cv); diff --git a/nsprpub/pr/tests/system.c b/nsprpub/pr/tests/system.c index 60d318ed8..85b5e2e50 100644 --- a/nsprpub/pr/tests/system.c +++ b/nsprpub/pr/tests/system.c @@ -35,8 +35,12 @@ int main(int argc, char **argv) for (cmd = PR_SI_HOSTNAME; cmd <= PR_SI_ARCHITECTURE; Incr(&cmd)) { rv = PR_GetSystemInfo(cmd, info, SYS_INFO_BUFFER_LENGTH); - if (PR_SUCCESS == rv) PR_fprintf(output, "%s: %s\n", tag[cmd], info); - else PL_FPrintError(output, tag[cmd]); + if (PR_SUCCESS == rv) { + PR_fprintf(output, "%s: %s\n", tag[cmd], info); + } + else { + PL_FPrintError(output, tag[cmd]); + } } PR_DELETE(info); diff --git a/nsprpub/pr/tests/testbit.c b/nsprpub/pr/tests/testbit.c index 0987f5f05..889c637e2 100644 --- a/nsprpub/pr/tests/testbit.c +++ b/nsprpub/pr/tests/testbit.c @@ -24,74 +24,88 @@ int main(int argc, char **argv) /* ** Test bitmap things. */ - if ( PR_TEST_BIT( myMap, 0 )) + if ( PR_TEST_BIT( myMap, 0 )) { ErrorReport("Test 0.0: Failed\n"); + } - if ( PR_TEST_BIT( myMap, 31 )) + if ( PR_TEST_BIT( myMap, 31 )) { ErrorReport("Test 0.1: Failed\n"); + } - if ( PR_TEST_BIT( myMap, 128 )) + if ( PR_TEST_BIT( myMap, 128 )) { ErrorReport("Test 0.2: Failed\n"); + } - if ( PR_TEST_BIT( myMap, 129 )) + if ( PR_TEST_BIT( myMap, 129 )) { ErrorReport("Test 0.3: Failed\n"); + } PR_SET_BIT( myMap, 0 ); - if ( !PR_TEST_BIT( myMap, 0 )) + if ( !PR_TEST_BIT( myMap, 0 )) { ErrorReport("Test 1.0: Failed\n"); + } PR_CLEAR_BIT( myMap, 0 ); - if ( PR_TEST_BIT( myMap, 0 )) + if ( PR_TEST_BIT( myMap, 0 )) { ErrorReport("Test 1.0.1: Failed\n"); + } PR_SET_BIT( myMap, 31 ); - if ( !PR_TEST_BIT( myMap, 31 )) + if ( !PR_TEST_BIT( myMap, 31 )) { ErrorReport("Test 1.1: Failed\n"); + } PR_CLEAR_BIT( myMap, 31 ); - if ( PR_TEST_BIT( myMap, 31 )) + if ( PR_TEST_BIT( myMap, 31 )) { ErrorReport("Test 1.1.1: Failed\n"); + } PR_SET_BIT( myMap, 128 ); - if ( !PR_TEST_BIT( myMap, 128 )) + if ( !PR_TEST_BIT( myMap, 128 )) { ErrorReport("Test 1.2: Failed\n"); + } PR_CLEAR_BIT( myMap, 128 ); - if ( PR_TEST_BIT( myMap, 128 )) + if ( PR_TEST_BIT( myMap, 128 )) { ErrorReport("Test 1.2.1: Failed\n"); + } PR_SET_BIT( myMap, 129 ); - if ( !PR_TEST_BIT( myMap, 129 )) + if ( !PR_TEST_BIT( myMap, 129 )) { ErrorReport("Test 1.3: Failed\n"); + } PR_CLEAR_BIT( myMap, 129 ); - if ( PR_TEST_BIT( myMap, 129 )) + if ( PR_TEST_BIT( myMap, 129 )) { ErrorReport("Test 1.3.1: Failed\n"); + } /* ** Test Ceiling and Floor functions and macros */ - if ((rc = PR_CeilingLog2(32)) != 5 ) + if ((rc = PR_CeilingLog2(32)) != 5 ) { ErrorReport("Test 10.0: Failed\n"); + } - if ((rc = PR_FloorLog2(32)) != 5 ) + if ((rc = PR_FloorLog2(32)) != 5 ) { ErrorReport("Test 10.1: Failed\n"); + } /* ** Evaluate results and exit */ if (failed) - { + { printf("FAILED\n"); return(1); - } + } else - { + { printf("PASSED\n"); return(0); - } + } } /* end main() */ /* end testbit.c */ diff --git a/nsprpub/pr/tests/testfile.c b/nsprpub/pr/tests/testfile.c index 1191bfe94..99cf94ddd 100644 --- a/nsprpub/pr/tests/testfile.c +++ b/nsprpub/pr/tests/testfile.c @@ -16,9 +16,6 @@ #if defined(_PR_PTHREADS) #include <pthread.h> #endif -#ifdef SYMBIAN -#include <getopt.h> -#endif #if defined(XP_OS2) #define INCL_DOSFILEMGR @@ -45,24 +42,24 @@ PRInt32 count; int thread_count; #ifdef WIN16 -#define BUF_DATA_SIZE 256 * 120 +#define BUF_DATA_SIZE 256 * 120 #else -#define BUF_DATA_SIZE 256 * 1024 +#define BUF_DATA_SIZE 256 * 1024 #endif -#define NUM_RDWR_THREADS 10 -#define NUM_DIRTEST_THREADS 4 +#define NUM_RDWR_THREADS 10 +#define NUM_DIRTEST_THREADS 4 #define CHUNK_SIZE 512 typedef struct buffer { - char data[BUF_DATA_SIZE]; + char data[BUF_DATA_SIZE]; } buffer; typedef struct File_Rdwr_Param { - char *pathname; - char *buf; - int offset; - int len; + char *pathname; + char *buf; + int offset; + int len; } File_Rdwr_Param; #ifdef XP_PC @@ -74,11 +71,7 @@ char *TEST_DIR = "C:\\temp\\prdir"; char *FILE_NAME = "pr_testfile"; char *HIDDEN_FILE_NAME = "hidden_pr_testfile"; #else -#ifdef SYMBIAN -char *TEST_DIR = "c:\\data\\testfile_dir"; -#else char *TEST_DIR = "/tmp/testfile_dir"; -#endif char *FILE_NAME = "pr_testfile"; char *HIDDEN_FILE_NAME = ".hidden_pr_testfile"; #endif @@ -87,800 +80,805 @@ char pathname[256], renamename[256]; #ifdef WINCE WCHAR wPathname[256]; #endif -#define TMPDIR_LEN 64 +#define TMPDIR_LEN 64 char testdir[TMPDIR_LEN]; static PRInt32 PR_CALLBACK DirTest(void *argunused); PRInt32 dirtest_failed = 0; PRThread* create_new_thread(PRThreadType type, - void (*start)(void *arg), - void *arg, - PRThreadPriority priority, - PRThreadScope scope, - PRThreadState state, - PRUint32 stackSize, PRInt32 index) + void (*start)(void *arg), + void *arg, + PRThreadPriority priority, + PRThreadScope scope, + PRThreadState state, + PRUint32 stackSize, PRInt32 index) { -PRInt32 native_thread = 0; + PRInt32 native_thread = 0; - PR_ASSERT(state == PR_UNJOINABLE_THREAD); + PR_ASSERT(state == PR_UNJOINABLE_THREAD); #if defined(_PR_PTHREADS) || defined(WIN32) || defined(XP_OS2) - switch(index % 4) { - case 0: - scope = (PR_LOCAL_THREAD); - break; - case 1: - scope = (PR_GLOBAL_THREAD); - break; - case 2: - scope = (PR_GLOBAL_BOUND_THREAD); - break; - case 3: - native_thread = 1; - break; - default: - PR_NOT_REACHED("Invalid scope"); - break; - } - if (native_thread) { + switch(index % 4) { + case 0: + scope = (PR_LOCAL_THREAD); + break; + case 1: + scope = (PR_GLOBAL_THREAD); + break; + case 2: + scope = (PR_GLOBAL_BOUND_THREAD); + break; + case 3: + native_thread = 1; + break; + default: + PR_NOT_REACHED("Invalid scope"); + break; + } + if (native_thread) { #if defined(_PR_PTHREADS) - pthread_t tid; - if (!pthread_create(&tid, NULL, start, arg)) - return((PRThread *) tid); - else - return (NULL); + pthread_t tid; + if (!pthread_create(&tid, NULL, start, arg)) { + return((PRThread *) tid); + } + else { + return (NULL); + } #elif defined(XP_OS2) TID tid; tid = (TID)_beginthread((void(* _Optlink)(void*))start, NULL, 32768, arg); if (tid == -1) { - printf("_beginthread failed. errno %d\n", errno); - return (NULL); + printf("_beginthread failed. errno %d\n", errno); + return (NULL); + } + else { + return((PRThread *) tid); } - else - return((PRThread *) tid); #else - HANDLE thandle; - unsigned tid; - - thandle = (HANDLE) _beginthreadex( - NULL, - stackSize, - (unsigned (__stdcall *)(void *))start, - arg, - STACK_SIZE_PARAM_IS_A_RESERVATION, - &tid); - return((PRThread *) thandle); + HANDLE thandle; + unsigned tid; + + thandle = (HANDLE) _beginthreadex( + NULL, + stackSize, + (unsigned (__stdcall *)(void *))start, + arg, + STACK_SIZE_PARAM_IS_A_RESERVATION, + &tid); + return((PRThread *) thandle); #endif - } else { - return(PR_CreateThread(type,start,arg,priority,scope,state,stackSize)); - } + } else { + return(PR_CreateThread(type,start,arg,priority,scope,state,stackSize)); + } #else - return(PR_CreateThread(type,start,arg,priority,scope,state,stackSize)); + return(PR_CreateThread(type,start,arg,priority,scope,state,stackSize)); #endif } static void PR_CALLBACK File_Write(void *arg) { -PRFileDesc *fd_file; -File_Rdwr_Param *fp = (File_Rdwr_Param *) arg; -char *name, *buf; -int offset, len; - - setbuf(stdout, NULL); - name = fp->pathname; - buf = fp->buf; - offset = fp->offset; - len = fp->len; - - fd_file = PR_Open(name, PR_RDWR | PR_CREATE_FILE, 0777); - if (fd_file == NULL) { - printf("testfile failed to create/open file %s\n",name); - return; - } - if (PR_Seek(fd_file, offset, PR_SEEK_SET) < 0) { - printf("testfile failed to seek in file %s\n",name); - return; - } - if ((PR_Write(fd_file, buf, len)) < 0) { - printf("testfile failed to write to file %s\n",name); - return; - } - DPRINTF(("Write out_buf[0] = 0x%x\n",(*((int *) buf)))); - PR_Close(fd_file); - PR_DELETE(fp); - - PR_EnterMonitor(mon); - --thread_count; - PR_Notify(mon); - PR_ExitMonitor(mon); + PRFileDesc *fd_file; + File_Rdwr_Param *fp = (File_Rdwr_Param *) arg; + char *name, *buf; + int offset, len; + + setbuf(stdout, NULL); + name = fp->pathname; + buf = fp->buf; + offset = fp->offset; + len = fp->len; + + fd_file = PR_Open(name, PR_RDWR | PR_CREATE_FILE, 0777); + if (fd_file == NULL) { + printf("testfile failed to create/open file %s\n",name); + return; + } + if (PR_Seek(fd_file, offset, PR_SEEK_SET) < 0) { + printf("testfile failed to seek in file %s\n",name); + return; + } + if ((PR_Write(fd_file, buf, len)) < 0) { + printf("testfile failed to write to file %s\n",name); + return; + } + DPRINTF(("Write out_buf[0] = 0x%x\n",(*((int *) buf)))); + PR_Close(fd_file); + PR_DELETE(fp); + + PR_EnterMonitor(mon); + --thread_count; + PR_Notify(mon); + PR_ExitMonitor(mon); } static void PR_CALLBACK File_Read(void *arg) { -PRFileDesc *fd_file; -File_Rdwr_Param *fp = (File_Rdwr_Param *) arg; -char *name, *buf; -int offset, len; - - setbuf(stdout, NULL); - name = fp->pathname; - buf = fp->buf; - offset = fp->offset; - len = fp->len; - - fd_file = PR_Open(name, PR_RDONLY, 0); - if (fd_file == NULL) { - printf("testfile failed to open file %s\n",name); - return; - } - if (PR_Seek(fd_file, offset, PR_SEEK_SET) < 0) { - printf("testfile failed to seek in file %s\n",name); - return; - } - if ((PR_Read(fd_file, buf, len)) < 0) { - printf("testfile failed to read to file %s\n",name); - return; - } - DPRINTF(("Read in_buf[0] = 0x%x\n",(*((int *) buf)))); - PR_Close(fd_file); - PR_DELETE(fp); - - PR_EnterMonitor(mon); - --thread_count; - PR_Notify(mon); - PR_ExitMonitor(mon); + PRFileDesc *fd_file; + File_Rdwr_Param *fp = (File_Rdwr_Param *) arg; + char *name, *buf; + int offset, len; + + setbuf(stdout, NULL); + name = fp->pathname; + buf = fp->buf; + offset = fp->offset; + len = fp->len; + + fd_file = PR_Open(name, PR_RDONLY, 0); + if (fd_file == NULL) { + printf("testfile failed to open file %s\n",name); + return; + } + if (PR_Seek(fd_file, offset, PR_SEEK_SET) < 0) { + printf("testfile failed to seek in file %s\n",name); + return; + } + if ((PR_Read(fd_file, buf, len)) < 0) { + printf("testfile failed to read to file %s\n",name); + return; + } + DPRINTF(("Read in_buf[0] = 0x%x\n",(*((int *) buf)))); + PR_Close(fd_file); + PR_DELETE(fp); + + PR_EnterMonitor(mon); + --thread_count; + PR_Notify(mon); + PR_ExitMonitor(mon); } static PRInt32 Misc_File_Tests(char *pathname) { -PRFileDesc *fd_file; -int len, rv = 0; -PRFileInfo file_info, file_info1; -char tmpname[1024]; - - setbuf(stdout, NULL); - /* - * Test PR_Available, PR_Seek, PR_GetFileInfo, PR_Rename, PR_Access - */ - - fd_file = PR_Open(pathname, PR_RDWR | PR_CREATE_FILE, 0777); - - if (fd_file == NULL) { - printf("testfile failed to create/open file %s\n",pathname); - return -1; - } - if (PR_GetOpenFileInfo(fd_file, &file_info) < 0) { - printf("testfile PR_GetFileInfo failed on file %s\n",pathname); - rv = -1; - goto cleanup; - } - if (PR_Access(pathname, PR_ACCESS_EXISTS) != 0) { - printf("testfile PR_Access failed on file %s\n",pathname); - rv = -1; - goto cleanup; - } - if (PR_Access(pathname, PR_ACCESS_WRITE_OK) != 0) { - printf("testfile PR_Access failed on file %s\n",pathname); - rv = -1; - goto cleanup; - } - if (PR_Access(pathname, PR_ACCESS_READ_OK) != 0) { - printf("testfile PR_Access failed on file %s\n",pathname); - rv = -1; - goto cleanup; - } - - - if (PR_GetFileInfo(pathname, &file_info) < 0) { - printf("testfile PR_GetFileInfo failed on file %s\n",pathname); - rv = -1; - goto cleanup; - } - if (file_info.type != PR_FILE_FILE) { - printf( - "testfile: Error - PR_GetFileInfo returned incorrect type for file %s\n", - pathname); - rv = -1; - goto cleanup; - } - if (file_info.size != 0) { - printf( - "testfile PR_GetFileInfo returned incorrect size (%d should be 0) for file %s\n", - file_info.size, pathname); - rv = -1; - goto cleanup; - } - file_info1 = file_info; - - len = PR_Available(fd_file); - if (len < 0) { - printf("testfile PR_Available failed on file %s\n",pathname); - rv = -1; - goto cleanup; - } else if (len != 0) { - printf( - "testfile PR_Available failed: expected/returned = %d/%d bytes\n", - 0, len); - rv = -1; - goto cleanup; - } - if (PR_GetOpenFileInfo(fd_file, &file_info) < 0) { - printf("testfile PR_GetFileInfo failed on file %s\n",pathname); - goto cleanup; - } - if (LL_NE(file_info.creationTime , file_info1.creationTime)) { - printf( - "testfile PR_GetFileInfo returned incorrect status-change time: %s\n", - pathname); - printf("ft = %lld, ft1 = %lld\n",file_info.creationTime, - file_info1.creationTime); - rv = -1; - goto cleanup; - } - len = PR_Write(fd_file, out_buf->data, CHUNK_SIZE); - if (len < 0) { - printf("testfile failed to write to file %s\n",pathname); - rv = -1; - goto cleanup; - } - if (PR_GetOpenFileInfo(fd_file, &file_info) < 0) { - printf("testfile PR_GetFileInfo failed on file %s\n",pathname); - goto cleanup; - } - if (file_info.size != CHUNK_SIZE) { - printf( - "testfile PR_GetFileInfo returned incorrect size (%d should be %d) for file %s\n", - file_info.size, CHUNK_SIZE, pathname); - rv = -1; - goto cleanup; - } - if (LL_CMP(file_info.modifyTime, < , file_info1.modifyTime)) { - printf( - "testfile PR_GetFileInfo returned incorrect modify time: %s\n", - pathname); - printf("ft = %lld, ft1 = %lld\n",file_info.modifyTime, - file_info1.modifyTime); - rv = -1; - goto cleanup; - } - - len = PR_Available(fd_file); - if (len < 0) { - printf("testfile PR_Available failed on file %s\n",pathname); - rv = -1; - goto cleanup; - } else if (len != 0) { - printf( - "testfile PR_Available failed: expected/returned = %d/%d bytes\n", - 0, len); - rv = -1; - goto cleanup; - } - - PR_Seek(fd_file, 0, PR_SEEK_SET); - len = PR_Available(fd_file); - if (len < 0) { - printf("testfile PR_Available failed on file %s\n",pathname); - rv = -1; - goto cleanup; - } else if (len != CHUNK_SIZE) { - printf( - "testfile PR_Available failed: expected/returned = %d/%d bytes\n", - CHUNK_SIZE, len); - rv = -1; - goto cleanup; - } + PRFileDesc *fd_file; + int len, rv = 0; + PRFileInfo file_info, file_info1; + char tmpname[1024]; + + setbuf(stdout, NULL); + /* + * Test PR_Available, PR_Seek, PR_GetFileInfo, PR_Rename, PR_Access + */ + + fd_file = PR_Open(pathname, PR_RDWR | PR_CREATE_FILE, 0777); + + if (fd_file == NULL) { + printf("testfile failed to create/open file %s\n",pathname); + return -1; + } + if (PR_GetOpenFileInfo(fd_file, &file_info) < 0) { + printf("testfile PR_GetFileInfo failed on file %s\n",pathname); + rv = -1; + goto cleanup; + } + if (PR_Access(pathname, PR_ACCESS_EXISTS) != 0) { + printf("testfile PR_Access failed on file %s\n",pathname); + rv = -1; + goto cleanup; + } + if (PR_Access(pathname, PR_ACCESS_WRITE_OK) != 0) { + printf("testfile PR_Access failed on file %s\n",pathname); + rv = -1; + goto cleanup; + } + if (PR_Access(pathname, PR_ACCESS_READ_OK) != 0) { + printf("testfile PR_Access failed on file %s\n",pathname); + rv = -1; + goto cleanup; + } + + + if (PR_GetFileInfo(pathname, &file_info) < 0) { + printf("testfile PR_GetFileInfo failed on file %s\n",pathname); + rv = -1; + goto cleanup; + } + if (file_info.type != PR_FILE_FILE) { + printf( + "testfile: Error - PR_GetFileInfo returned incorrect type for file %s\n", + pathname); + rv = -1; + goto cleanup; + } + if (file_info.size != 0) { + printf( + "testfile PR_GetFileInfo returned incorrect size (%d should be 0) for file %s\n", + file_info.size, pathname); + rv = -1; + goto cleanup; + } + file_info1 = file_info; + + len = PR_Available(fd_file); + if (len < 0) { + printf("testfile PR_Available failed on file %s\n",pathname); + rv = -1; + goto cleanup; + } else if (len != 0) { + printf( + "testfile PR_Available failed: expected/returned = %d/%d bytes\n", + 0, len); + rv = -1; + goto cleanup; + } + if (PR_GetOpenFileInfo(fd_file, &file_info) < 0) { + printf("testfile PR_GetFileInfo failed on file %s\n",pathname); + goto cleanup; + } + if (LL_NE(file_info.creationTime, file_info1.creationTime)) { + printf( + "testfile PR_GetFileInfo returned incorrect status-change time: %s\n", + pathname); + printf("ft = %lld, ft1 = %lld\n",file_info.creationTime, + file_info1.creationTime); + rv = -1; + goto cleanup; + } + len = PR_Write(fd_file, out_buf->data, CHUNK_SIZE); + if (len < 0) { + printf("testfile failed to write to file %s\n",pathname); + rv = -1; + goto cleanup; + } + if (PR_GetOpenFileInfo(fd_file, &file_info) < 0) { + printf("testfile PR_GetFileInfo failed on file %s\n",pathname); + goto cleanup; + } + if (file_info.size != CHUNK_SIZE) { + printf( + "testfile PR_GetFileInfo returned incorrect size (%d should be %d) for file %s\n", + file_info.size, CHUNK_SIZE, pathname); + rv = -1; + goto cleanup; + } + if (LL_CMP(file_info.modifyTime, <, file_info1.modifyTime)) { + printf( + "testfile PR_GetFileInfo returned incorrect modify time: %s\n", + pathname); + printf("ft = %lld, ft1 = %lld\n",file_info.modifyTime, + file_info1.modifyTime); + rv = -1; + goto cleanup; + } + + len = PR_Available(fd_file); + if (len < 0) { + printf("testfile PR_Available failed on file %s\n",pathname); + rv = -1; + goto cleanup; + } else if (len != 0) { + printf( + "testfile PR_Available failed: expected/returned = %d/%d bytes\n", + 0, len); + rv = -1; + goto cleanup; + } + + PR_Seek(fd_file, 0, PR_SEEK_SET); + len = PR_Available(fd_file); + if (len < 0) { + printf("testfile PR_Available failed on file %s\n",pathname); + rv = -1; + goto cleanup; + } else if (len != CHUNK_SIZE) { + printf( + "testfile PR_Available failed: expected/returned = %d/%d bytes\n", + CHUNK_SIZE, len); + rv = -1; + goto cleanup; + } PR_Close(fd_file); - strcpy(tmpname,pathname); - strcat(tmpname,".RENAMED"); - if (PR_FAILURE == PR_Rename(pathname, tmpname)) { - printf("testfile failed to rename file %s\n",pathname); - rv = -1; - goto cleanup; - } + strcpy(tmpname,pathname); + strcat(tmpname,".RENAMED"); + if (PR_FAILURE == PR_Rename(pathname, tmpname)) { + printf("testfile failed to rename file %s\n",pathname); + rv = -1; + goto cleanup; + } - fd_file = PR_Open(pathname, PR_RDWR | PR_CREATE_FILE, 0777); - len = PR_Write(fd_file, out_buf->data, CHUNK_SIZE); + fd_file = PR_Open(pathname, PR_RDWR | PR_CREATE_FILE, 0777); + len = PR_Write(fd_file, out_buf->data, CHUNK_SIZE); PR_Close(fd_file); - if (PR_SUCCESS == PR_Rename(pathname, tmpname)) { - printf("testfile renamed to existing file %s\n",pathname); - } + if (PR_SUCCESS == PR_Rename(pathname, tmpname)) { + printf("testfile renamed to existing file %s\n",pathname); + } - if ((PR_Delete(tmpname)) < 0) { - printf("testfile failed to unlink file %s\n",tmpname); - rv = -1; - } + if ((PR_Delete(tmpname)) < 0) { + printf("testfile failed to unlink file %s\n",tmpname); + rv = -1; + } cleanup: - if ((PR_Delete(pathname)) < 0) { - printf("testfile failed to unlink file %s\n",pathname); - rv = -1; - } - return rv; + if ((PR_Delete(pathname)) < 0) { + printf("testfile failed to unlink file %s\n",pathname); + rv = -1; + } + return rv; } static PRInt32 PR_CALLBACK FileTest(void) { -PRDir *fd_dir; -int i, offset, len, rv = 0; -PRThread *t; -PRThreadScope scope = PR_GLOBAL_THREAD; -File_Rdwr_Param *fparamp; - - /* - * Create Test dir - */ - if ((PR_MkDir(TEST_DIR, 0777)) < 0) { - printf("testfile failed to create dir %s\n",TEST_DIR); - return -1; - } - fd_dir = PR_OpenDir(TEST_DIR); - if (fd_dir == NULL) { - printf("testfile failed to open dir %s\n",TEST_DIR); - rv = -1; - goto cleanup; - } + PRDir *fd_dir; + int i, offset, len, rv = 0; + PRThread *t; + PRThreadScope scope = PR_GLOBAL_THREAD; + File_Rdwr_Param *fparamp; + + /* + * Create Test dir + */ + if ((PR_MkDir(TEST_DIR, 0777)) < 0) { + printf("testfile failed to create dir %s\n",TEST_DIR); + return -1; + } + fd_dir = PR_OpenDir(TEST_DIR); + if (fd_dir == NULL) { + printf("testfile failed to open dir %s\n",TEST_DIR); + rv = -1; + goto cleanup; + } PR_CloseDir(fd_dir); - strcat(pathname, TEST_DIR); - strcat(pathname, "/"); - strcat(pathname, FILE_NAME); - - in_buf = PR_NEW(buffer); - if (in_buf == NULL) { - printf( - "testfile failed to alloc buffer struct\n"); - rv = -1; - goto cleanup; - } - out_buf = PR_NEW(buffer); - if (out_buf == NULL) { - printf( - "testfile failed to alloc buffer struct\n"); - rv = -1; - goto cleanup; - } - - /* - * Start a bunch of writer threads - */ - offset = 0; - len = CHUNK_SIZE; - PR_EnterMonitor(mon); - for (i = 0; i < NUM_RDWR_THREADS; i++) { - fparamp = PR_NEW(File_Rdwr_Param); - if (fparamp == NULL) { - printf( - "testfile failed to alloc File_Rdwr_Param struct\n"); - rv = -1; - goto cleanup; - } - fparamp->pathname = pathname; - fparamp->buf = out_buf->data + offset; - fparamp->offset = offset; - fparamp->len = len; - memset(fparamp->buf, i, len); - - t = create_new_thread(PR_USER_THREAD, - File_Write, (void *)fparamp, - PR_PRIORITY_NORMAL, - scope, - PR_UNJOINABLE_THREAD, - 0, i); - offset += len; - } - thread_count = i; - /* Wait for writer threads to exit */ - while (thread_count) { - PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT); - } - PR_ExitMonitor(mon); - - - /* - * Start a bunch of reader threads - */ - offset = 0; - len = CHUNK_SIZE; - PR_EnterMonitor(mon); - for (i = 0; i < NUM_RDWR_THREADS; i++) { - fparamp = PR_NEW(File_Rdwr_Param); - if (fparamp == NULL) { - printf( - "testfile failed to alloc File_Rdwr_Param struct\n"); - rv = -1; - goto cleanup; - } - fparamp->pathname = pathname; - fparamp->buf = in_buf->data + offset; - fparamp->offset = offset; - fparamp->len = len; - - t = create_new_thread(PR_USER_THREAD, - File_Read, (void *)fparamp, - PR_PRIORITY_NORMAL, - scope, - PR_UNJOINABLE_THREAD, - 0, i); - offset += len; - if ((offset + len) > BUF_DATA_SIZE) - break; - } - thread_count = i; - - /* Wait for reader threads to exit */ - while (thread_count) { - PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT); - } - PR_ExitMonitor(mon); - - if (memcmp(in_buf->data, out_buf->data, offset) != 0) { - printf("File Test failed: file data corrupted\n"); - rv = -1; - goto cleanup; - } - - if ((PR_Delete(pathname)) < 0) { - printf("testfile failed to unlink file %s\n",pathname); - rv = -1; - goto cleanup; - } - - /* - * Test PR_Available, PR_Seek, PR_GetFileInfo, PR_Rename, PR_Access - */ - if (Misc_File_Tests(pathname) < 0) { - rv = -1; - } + strcat(pathname, TEST_DIR); + strcat(pathname, "/"); + strcat(pathname, FILE_NAME); + + in_buf = PR_NEW(buffer); + if (in_buf == NULL) { + printf( + "testfile failed to alloc buffer struct\n"); + rv = -1; + goto cleanup; + } + out_buf = PR_NEW(buffer); + if (out_buf == NULL) { + printf( + "testfile failed to alloc buffer struct\n"); + rv = -1; + goto cleanup; + } + + /* + * Start a bunch of writer threads + */ + offset = 0; + len = CHUNK_SIZE; + PR_EnterMonitor(mon); + for (i = 0; i < NUM_RDWR_THREADS; i++) { + fparamp = PR_NEW(File_Rdwr_Param); + if (fparamp == NULL) { + printf( + "testfile failed to alloc File_Rdwr_Param struct\n"); + rv = -1; + goto cleanup; + } + fparamp->pathname = pathname; + fparamp->buf = out_buf->data + offset; + fparamp->offset = offset; + fparamp->len = len; + memset(fparamp->buf, i, len); + + t = create_new_thread(PR_USER_THREAD, + File_Write, (void *)fparamp, + PR_PRIORITY_NORMAL, + scope, + PR_UNJOINABLE_THREAD, + 0, i); + offset += len; + } + thread_count = i; + /* Wait for writer threads to exit */ + while (thread_count) { + PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT); + } + PR_ExitMonitor(mon); + + + /* + * Start a bunch of reader threads + */ + offset = 0; + len = CHUNK_SIZE; + PR_EnterMonitor(mon); + for (i = 0; i < NUM_RDWR_THREADS; i++) { + fparamp = PR_NEW(File_Rdwr_Param); + if (fparamp == NULL) { + printf( + "testfile failed to alloc File_Rdwr_Param struct\n"); + rv = -1; + goto cleanup; + } + fparamp->pathname = pathname; + fparamp->buf = in_buf->data + offset; + fparamp->offset = offset; + fparamp->len = len; + + t = create_new_thread(PR_USER_THREAD, + File_Read, (void *)fparamp, + PR_PRIORITY_NORMAL, + scope, + PR_UNJOINABLE_THREAD, + 0, i); + offset += len; + if ((offset + len) > BUF_DATA_SIZE) { + break; + } + } + thread_count = i; + + /* Wait for reader threads to exit */ + while (thread_count) { + PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT); + } + PR_ExitMonitor(mon); + + if (memcmp(in_buf->data, out_buf->data, offset) != 0) { + printf("File Test failed: file data corrupted\n"); + rv = -1; + goto cleanup; + } + + if ((PR_Delete(pathname)) < 0) { + printf("testfile failed to unlink file %s\n",pathname); + rv = -1; + goto cleanup; + } + + /* + * Test PR_Available, PR_Seek, PR_GetFileInfo, PR_Rename, PR_Access + */ + if (Misc_File_Tests(pathname) < 0) { + rv = -1; + } cleanup: - if ((PR_RmDir(TEST_DIR)) < 0) { - printf("testfile failed to rmdir %s\n", TEST_DIR); - rv = -1; - } - return rv; + if ((PR_RmDir(TEST_DIR)) < 0) { + printf("testfile failed to rmdir %s\n", TEST_DIR); + rv = -1; + } + return rv; } struct dirtest_arg { - PRMonitor *mon; - PRInt32 done; + PRMonitor *mon; + PRInt32 done; }; static PRInt32 RunDirTest(void) { -int i; -PRThread *t; -PRMonitor *mon; -struct dirtest_arg thrarg; - - mon = PR_NewMonitor(); - if (!mon) { - printf("RunDirTest: Error - failed to create monitor\n"); - dirtest_failed = 1; - return -1; - } - thrarg.mon = mon; - - for (i = 0; i < NUM_DIRTEST_THREADS; i++) { - - thrarg.done= 0; - t = create_new_thread(PR_USER_THREAD, - DirTest, &thrarg, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, - 0, i); - if (!t) { - printf("RunDirTest: Error - failed to create thread\n"); - dirtest_failed = 1; - return -1; - } - PR_EnterMonitor(mon); - while (!thrarg.done) - PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT); - PR_ExitMonitor(mon); - - } - PR_DestroyMonitor(mon); - return 0; + int i; + PRThread *t; + PRMonitor *mon; + struct dirtest_arg thrarg; + + mon = PR_NewMonitor(); + if (!mon) { + printf("RunDirTest: Error - failed to create monitor\n"); + dirtest_failed = 1; + return -1; + } + thrarg.mon = mon; + + for (i = 0; i < NUM_DIRTEST_THREADS; i++) { + + thrarg.done= 0; + t = create_new_thread(PR_USER_THREAD, + DirTest, &thrarg, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, + 0, i); + if (!t) { + printf("RunDirTest: Error - failed to create thread\n"); + dirtest_failed = 1; + return -1; + } + PR_EnterMonitor(mon); + while (!thrarg.done) { + PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT); + } + PR_ExitMonitor(mon); + + } + PR_DestroyMonitor(mon); + return 0; } static PRInt32 PR_CALLBACK DirTest(void *arg) { -struct dirtest_arg *tinfo = (struct dirtest_arg *) arg; -PRFileDesc *fd_file; -PRDir *fd_dir; -int i; -int path_len; -PRDirEntry *dirEntry; -PRFileInfo info; -PRInt32 num_files = 0; + struct dirtest_arg *tinfo = (struct dirtest_arg *) arg; + PRFileDesc *fd_file; + PRDir *fd_dir; + int i; + int path_len; + PRDirEntry *dirEntry; + PRFileInfo info; + PRInt32 num_files = 0; #if defined(XP_PC) && defined(WIN32) -HANDLE hfile; + HANDLE hfile; #endif #define FILES_IN_DIR 20 - /* - * Create Test dir - */ - DPRINTF(("Creating test dir %s\n",TEST_DIR)); - if ((PR_MkDir(TEST_DIR, 0777)) < 0) { - printf( - "testfile failed to create dir %s [%d, %d]\n", - TEST_DIR, PR_GetError(), PR_GetOSError()); - return -1; - } - fd_dir = PR_OpenDir(TEST_DIR); - if (fd_dir == NULL) { - printf( - "testfile failed to open dirctory %s [%d, %d]\n", - TEST_DIR, PR_GetError(), PR_GetOSError()); - return -1; - } - - strcpy(pathname, TEST_DIR); - strcat(pathname, "/"); - strcat(pathname, FILE_NAME); - path_len = strlen(pathname); - - for (i = 0; i < FILES_IN_DIR; i++) { - - sprintf(pathname + path_len,"%d%s",i,""); - - DPRINTF(("Creating test file %s\n",pathname)); - - fd_file = PR_Open(pathname, PR_RDWR | PR_CREATE_FILE, 0777); - - if (fd_file == NULL) { - printf( - "testfile failed to create/open file %s [%d, %d]\n", - pathname, PR_GetError(), PR_GetOSError()); - return -1; - } + /* + * Create Test dir + */ + DPRINTF(("Creating test dir %s\n",TEST_DIR)); + if ((PR_MkDir(TEST_DIR, 0777)) < 0) { + printf( + "testfile failed to create dir %s [%d, %d]\n", + TEST_DIR, PR_GetError(), PR_GetOSError()); + return -1; + } + fd_dir = PR_OpenDir(TEST_DIR); + if (fd_dir == NULL) { + printf( + "testfile failed to open dirctory %s [%d, %d]\n", + TEST_DIR, PR_GetError(), PR_GetOSError()); + return -1; + } + + strcpy(pathname, TEST_DIR); + strcat(pathname, "/"); + strcat(pathname, FILE_NAME); + path_len = strlen(pathname); + + for (i = 0; i < FILES_IN_DIR; i++) { + + sprintf(pathname + path_len,"%d%s",i,""); + + DPRINTF(("Creating test file %s\n",pathname)); + + fd_file = PR_Open(pathname, PR_RDWR | PR_CREATE_FILE, 0777); + + if (fd_file == NULL) { + printf( + "testfile failed to create/open file %s [%d, %d]\n", + pathname, PR_GetError(), PR_GetOSError()); + return -1; + } PR_Close(fd_file); - } -#if defined(XP_UNIX) || (defined(XP_PC) && defined(WIN32)) || defined(XP_OS2) || defined(XP_BEOS) - /* - * Create a hidden file - a platform-dependent operation - */ - strcpy(pathname, TEST_DIR); - strcat(pathname, "/"); - strcat(pathname, HIDDEN_FILE_NAME); -#if defined(XP_UNIX) || defined(XP_BEOS) - DPRINTF(("Creating hidden test file %s\n",pathname)); - fd_file = PR_Open(pathname, PR_RDWR | PR_CREATE_FILE, 0777); - - if (fd_file == NULL) { - printf( - "testfile failed to create/open hidden file %s [%d, %d]\n", - pathname, PR_GetError(), PR_GetOSError()); - return -1; - } + } +#if defined(XP_UNIX) || (defined(XP_PC) && defined(WIN32)) || defined(XP_OS2) + /* + * Create a hidden file - a platform-dependent operation + */ + strcpy(pathname, TEST_DIR); + strcat(pathname, "/"); + strcat(pathname, HIDDEN_FILE_NAME); +#if defined(XP_UNIX) + DPRINTF(("Creating hidden test file %s\n",pathname)); + fd_file = PR_Open(pathname, PR_RDWR | PR_CREATE_FILE, 0777); + + if (fd_file == NULL) { + printf( + "testfile failed to create/open hidden file %s [%d, %d]\n", + pathname, PR_GetError(), PR_GetOSError()); + return -1; + } PR_Close(fd_file); #elif defined(WINCE) - DPRINTF(("Creating hidden test file %s\n",pathname)); - MultiByteToWideChar(CP_ACP, 0, pathname, -1, wPathname, 256); - hfile = CreateFile(wPathname, GENERIC_READ, - FILE_SHARE_READ|FILE_SHARE_WRITE, - NULL, - CREATE_NEW, - FILE_ATTRIBUTE_HIDDEN, - NULL); - if (hfile == INVALID_HANDLE_VALUE) { - printf("testfile failed to create/open hidden file %s [0, %d]\n", - pathname, GetLastError()); - return -1; - } - CloseHandle(hfile); - + DPRINTF(("Creating hidden test file %s\n",pathname)); + MultiByteToWideChar(CP_ACP, 0, pathname, -1, wPathname, 256); + hfile = CreateFile(wPathname, GENERIC_READ, + FILE_SHARE_READ|FILE_SHARE_WRITE, + NULL, + CREATE_NEW, + FILE_ATTRIBUTE_HIDDEN, + NULL); + if (hfile == INVALID_HANDLE_VALUE) { + printf("testfile failed to create/open hidden file %s [0, %d]\n", + pathname, GetLastError()); + return -1; + } + CloseHandle(hfile); + #elif defined(XP_PC) && defined(WIN32) - DPRINTF(("Creating hidden test file %s\n",pathname)); - hfile = CreateFile(pathname, GENERIC_READ, - FILE_SHARE_READ|FILE_SHARE_WRITE, - NULL, - CREATE_NEW, - FILE_ATTRIBUTE_HIDDEN, - NULL); - if (hfile == INVALID_HANDLE_VALUE) { - printf("testfile failed to create/open hidden file %s [0, %d]\n", - pathname, GetLastError()); - return -1; - } - CloseHandle(hfile); - + DPRINTF(("Creating hidden test file %s\n",pathname)); + hfile = CreateFile(pathname, GENERIC_READ, + FILE_SHARE_READ|FILE_SHARE_WRITE, + NULL, + CREATE_NEW, + FILE_ATTRIBUTE_HIDDEN, + NULL); + if (hfile == INVALID_HANDLE_VALUE) { + printf("testfile failed to create/open hidden file %s [0, %d]\n", + pathname, GetLastError()); + return -1; + } + CloseHandle(hfile); + #elif defined(OS2) - DPRINTF(("Creating hidden test file %s\n",pathname)); - fd_file = PR_Open(pathname, PR_RDWR | PR_CREATE_FILE, (int)FILE_HIDDEN); - - if (fd_file == NULL) { - printf("testfile failed to create/open hidden file %s [%d, %d]\n", - pathname, PR_GetError(), PR_GetOSError()); - return -1; - } - PR_Close(fd_file); -#endif /* XP_UNIX */ - -#endif /* XP_UNIX || (XP_PC && WIN32) */ - - - if (PR_FAILURE == PR_CloseDir(fd_dir)) - { - printf( - "testfile failed to close dirctory %s [%d, %d]\n", - TEST_DIR, PR_GetError(), PR_GetOSError()); - return -1; - } - fd_dir = PR_OpenDir(TEST_DIR); - if (fd_dir == NULL) { - printf( - "testfile failed to reopen dirctory %s [%d, %d]\n", - TEST_DIR, PR_GetError(), PR_GetOSError()); - return -1; - } - - /* - * List all files, including hidden files - */ - DPRINTF(("Listing all files in directory %s\n",TEST_DIR)); -#if defined(XP_UNIX) || (defined(XP_PC) && defined(WIN32)) || defined(XP_OS2) || defined(XP_BEOS) - num_files = FILES_IN_DIR + 1; + DPRINTF(("Creating hidden test file %s\n",pathname)); + fd_file = PR_Open(pathname, PR_RDWR | PR_CREATE_FILE, (int)FILE_HIDDEN); + + if (fd_file == NULL) { + printf("testfile failed to create/open hidden file %s [%d, %d]\n", + pathname, PR_GetError(), PR_GetOSError()); + return -1; + } + PR_Close(fd_file); +#endif /* XP_UNIX */ + +#endif /* XP_UNIX || (XP_PC && WIN32) */ + + + if (PR_FAILURE == PR_CloseDir(fd_dir)) + { + printf( + "testfile failed to close dirctory %s [%d, %d]\n", + TEST_DIR, PR_GetError(), PR_GetOSError()); + return -1; + } + fd_dir = PR_OpenDir(TEST_DIR); + if (fd_dir == NULL) { + printf( + "testfile failed to reopen dirctory %s [%d, %d]\n", + TEST_DIR, PR_GetError(), PR_GetOSError()); + return -1; + } + + /* + * List all files, including hidden files + */ + DPRINTF(("Listing all files in directory %s\n",TEST_DIR)); +#if defined(XP_UNIX) || (defined(XP_PC) && defined(WIN32)) || defined(XP_OS2) + num_files = FILES_IN_DIR + 1; #else - num_files = FILES_IN_DIR; + num_files = FILES_IN_DIR; #endif - while ((dirEntry = PR_ReadDir(fd_dir, PR_SKIP_BOTH)) != NULL) { - num_files--; - strcpy(pathname, TEST_DIR); - strcat(pathname, "/"); - strcat(pathname, dirEntry->name); - DPRINTF(("\t%s\n",dirEntry->name)); - - if ((PR_GetFileInfo(pathname, &info)) < 0) { - printf( - "testfile failed to GetFileInfo file %s [%d, %d]\n", - pathname, PR_GetError(), PR_GetOSError()); - return -1; - } - - if (info.type != PR_FILE_FILE) { - printf( - "testfile incorrect fileinfo for file %s [%d, %d]\n", - pathname, PR_GetError(), PR_GetOSError()); - return -1; - } - } - if (num_files != 0) - { - printf( - "testfile failed to find all files in directory %s [%d, %d]\n", - TEST_DIR, PR_GetError(), PR_GetOSError()); - return -1; - } + while ((dirEntry = PR_ReadDir(fd_dir, PR_SKIP_BOTH)) != NULL) { + num_files--; + strcpy(pathname, TEST_DIR); + strcat(pathname, "/"); + strcat(pathname, dirEntry->name); + DPRINTF(("\t%s\n",dirEntry->name)); + + if ((PR_GetFileInfo(pathname, &info)) < 0) { + printf( + "testfile failed to GetFileInfo file %s [%d, %d]\n", + pathname, PR_GetError(), PR_GetOSError()); + return -1; + } + + if (info.type != PR_FILE_FILE) { + printf( + "testfile incorrect fileinfo for file %s [%d, %d]\n", + pathname, PR_GetError(), PR_GetOSError()); + return -1; + } + } + if (num_files != 0) + { + printf( + "testfile failed to find all files in directory %s [%d, %d]\n", + TEST_DIR, PR_GetError(), PR_GetOSError()); + return -1; + } PR_CloseDir(fd_dir); -#if defined(XP_UNIX) || (defined(XP_PC) && defined(WIN32)) || defined(XP_OS2) || defined(XP_BEOS) - - /* - * List all files, except hidden files - */ - - fd_dir = PR_OpenDir(TEST_DIR); - if (fd_dir == NULL) { - printf( - "testfile failed to reopen dirctory %s [%d, %d]\n", - TEST_DIR, PR_GetError(), PR_GetOSError()); - return -1; - } - - DPRINTF(("Listing non-hidden files in directory %s\n",TEST_DIR)); - while ((dirEntry = PR_ReadDir(fd_dir, PR_SKIP_HIDDEN)) != NULL) { - DPRINTF(("\t%s\n",dirEntry->name)); - if (!strcmp(HIDDEN_FILE_NAME, dirEntry->name)) { - printf("testfile found hidden file %s\n", pathname); - return -1; - } - - } - /* - * Delete hidden file - */ - strcpy(pathname, TEST_DIR); - strcat(pathname, "/"); - strcat(pathname, HIDDEN_FILE_NAME); - if (PR_FAILURE == PR_Delete(pathname)) { - printf( - "testfile failed to delete hidden file %s [%d, %d]\n", - pathname, PR_GetError(), PR_GetOSError()); - return -1; - } +#if defined(XP_UNIX) || (defined(XP_PC) && defined(WIN32)) || defined(XP_OS2) + + /* + * List all files, except hidden files + */ + + fd_dir = PR_OpenDir(TEST_DIR); + if (fd_dir == NULL) { + printf( + "testfile failed to reopen dirctory %s [%d, %d]\n", + TEST_DIR, PR_GetError(), PR_GetOSError()); + return -1; + } + + DPRINTF(("Listing non-hidden files in directory %s\n",TEST_DIR)); + while ((dirEntry = PR_ReadDir(fd_dir, PR_SKIP_HIDDEN)) != NULL) { + DPRINTF(("\t%s\n",dirEntry->name)); + if (!strcmp(HIDDEN_FILE_NAME, dirEntry->name)) { + printf("testfile found hidden file %s\n", pathname); + return -1; + } + + } + /* + * Delete hidden file + */ + strcpy(pathname, TEST_DIR); + strcat(pathname, "/"); + strcat(pathname, HIDDEN_FILE_NAME); + if (PR_FAILURE == PR_Delete(pathname)) { + printf( + "testfile failed to delete hidden file %s [%d, %d]\n", + pathname, PR_GetError(), PR_GetOSError()); + return -1; + } PR_CloseDir(fd_dir); -#endif /* XP_UNIX || (XP_PC && WIN32) */ - - strcpy(renamename, TEST_DIR); - strcat(renamename, ".RENAMED"); - if (PR_FAILURE == PR_Rename(TEST_DIR, renamename)) { - printf( - "testfile failed to rename directory %s [%d, %d]\n", - TEST_DIR, PR_GetError(), PR_GetOSError()); - return -1; - } - - if (PR_FAILURE == PR_MkDir(TEST_DIR, 0777)) { - printf( - "testfile failed to recreate dir %s [%d, %d]\n", - TEST_DIR, PR_GetError(), PR_GetOSError()); - return -1; - } - if (PR_SUCCESS == PR_Rename(renamename, TEST_DIR)) { - printf( - "testfile renamed directory to existing name %s\n", - renamename); - return -1; - } - - if (PR_FAILURE == PR_RmDir(TEST_DIR)) { - printf( - "testfile failed to rmdir %s [%d, %d]\n", - TEST_DIR, PR_GetError(), PR_GetOSError()); - return -1; - } - - if (PR_FAILURE == PR_Rename(renamename, TEST_DIR)) { - printf( - "testfile failed to rename directory %s [%d, %d]\n", - renamename, PR_GetError(), PR_GetOSError()); - return -1; - } - fd_dir = PR_OpenDir(TEST_DIR); - if (fd_dir == NULL) { - printf( - "testfile failed to reopen directory %s [%d, %d]\n", - TEST_DIR, PR_GetError(), PR_GetOSError()); - return -1; - } - - strcpy(pathname, TEST_DIR); - strcat(pathname, "/"); - strcat(pathname, FILE_NAME); - path_len = strlen(pathname); - - for (i = 0; i < FILES_IN_DIR; i++) { - - sprintf(pathname + path_len,"%d%s",i,""); - - if (PR_FAILURE == PR_Delete(pathname)) { - printf( - "testfile failed to delete file %s [%d, %d]\n", - pathname, PR_GetError(), PR_GetOSError()); - return -1; - } - } +#endif /* XP_UNIX || (XP_PC && WIN32) */ + + strcpy(renamename, TEST_DIR); + strcat(renamename, ".RENAMED"); + if (PR_FAILURE == PR_Rename(TEST_DIR, renamename)) { + printf( + "testfile failed to rename directory %s [%d, %d]\n", + TEST_DIR, PR_GetError(), PR_GetOSError()); + return -1; + } + + if (PR_FAILURE == PR_MkDir(TEST_DIR, 0777)) { + printf( + "testfile failed to recreate dir %s [%d, %d]\n", + TEST_DIR, PR_GetError(), PR_GetOSError()); + return -1; + } + if (PR_SUCCESS == PR_Rename(renamename, TEST_DIR)) { + printf( + "testfile renamed directory to existing name %s\n", + renamename); + return -1; + } + + if (PR_FAILURE == PR_RmDir(TEST_DIR)) { + printf( + "testfile failed to rmdir %s [%d, %d]\n", + TEST_DIR, PR_GetError(), PR_GetOSError()); + return -1; + } + + if (PR_FAILURE == PR_Rename(renamename, TEST_DIR)) { + printf( + "testfile failed to rename directory %s [%d, %d]\n", + renamename, PR_GetError(), PR_GetOSError()); + return -1; + } + fd_dir = PR_OpenDir(TEST_DIR); + if (fd_dir == NULL) { + printf( + "testfile failed to reopen directory %s [%d, %d]\n", + TEST_DIR, PR_GetError(), PR_GetOSError()); + return -1; + } + + strcpy(pathname, TEST_DIR); + strcat(pathname, "/"); + strcat(pathname, FILE_NAME); + path_len = strlen(pathname); + + for (i = 0; i < FILES_IN_DIR; i++) { + + sprintf(pathname + path_len,"%d%s",i,""); + + if (PR_FAILURE == PR_Delete(pathname)) { + printf( + "testfile failed to delete file %s [%d, %d]\n", + pathname, PR_GetError(), PR_GetOSError()); + return -1; + } + } PR_CloseDir(fd_dir); - if (PR_FAILURE == PR_RmDir(TEST_DIR)) { - printf( - "testfile failed to rmdir %s [%d, %d]\n", - TEST_DIR, PR_GetError(), PR_GetOSError()); - return -1; - } - PR_EnterMonitor(tinfo->mon); - tinfo->done = 1; - PR_Notify(tinfo->mon); - PR_ExitMonitor(tinfo->mon); - - return 0; + if (PR_FAILURE == PR_RmDir(TEST_DIR)) { + printf( + "testfile failed to rmdir %s [%d, %d]\n", + TEST_DIR, PR_GetError(), PR_GetOSError()); + return -1; + } + PR_EnterMonitor(tinfo->mon); + tinfo->done = 1; + PR_Notify(tinfo->mon); + PR_ExitMonitor(tinfo->mon); + + return 0; } /************************************************************************/ @@ -891,32 +889,32 @@ HANDLE hfile; int main(int argc, char **argv) { #ifdef WIN32 - PRUint32 len; + PRUint32 len; #endif #if defined(XP_UNIX) || defined(XP_OS2) - int opt; - extern char *optarg; - extern int optind; + int opt; + extern char *optarg; + extern int optind; #endif #if defined(XP_UNIX) || defined(XP_OS2) - while ((opt = getopt(argc, argv, "d")) != EOF) { - switch(opt) { - case 'd': - _debug_on = 1; - break; - default: - break; - } + while ((opt = getopt(argc, argv, "d")) != EOF) { + switch(opt) { + case 'd': + _debug_on = 1; + break; + default: + break; } + } #endif - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); + PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); - mon = PR_NewMonitor(); - if (mon == NULL) { - printf("testfile: PR_NewMonitor failed\n"); - exit(2); - } + mon = PR_NewMonitor(); + if (mon == NULL) { + printf("testfile: PR_NewMonitor failed\n"); + exit(2); + } #ifdef WIN32 #ifdef WINCE @@ -927,35 +925,35 @@ int main(int argc, char **argv) /* * enough space for prdir */ - WideCharToMultiByte(CP_ACP, 0, tdir, -1, testdir, TMPDIR_LEN, 0, 0); + WideCharToMultiByte(CP_ACP, 0, tdir, -1, testdir, TMPDIR_LEN, 0, 0); } } #else - len = GetTempPath(TMPDIR_LEN, testdir); + len = GetTempPath(TMPDIR_LEN, testdir); #endif /* WINCE */ - if ((len > 0) && (len < (TMPDIR_LEN - 6))) { - /* - * enough space for prdir - */ - strcpy((testdir + len),"prdir"); - TEST_DIR = testdir; - printf("TEST_DIR = %s\n",TEST_DIR); - } + if ((len > 0) && (len < (TMPDIR_LEN - 6))) { + /* + * enough space for prdir + */ + strcpy((testdir + len),"prdir"); + TEST_DIR = testdir; + printf("TEST_DIR = %s\n",TEST_DIR); + } #endif /* WIN32 */ - if (FileTest() < 0) { - printf("File Test failed\n"); - exit(2); - } - printf("File Test passed\n"); - if ((RunDirTest() < 0) || dirtest_failed) { - printf("Dir Test failed\n"); - exit(2); - } - printf("Dir Test passed\n"); - - PR_DestroyMonitor(mon); - PR_Cleanup(); + if (FileTest() < 0) { + printf("File Test failed\n"); + exit(2); + } + printf("File Test passed\n"); + if ((RunDirTest() < 0) || dirtest_failed) { + printf("Dir Test failed\n"); + exit(2); + } + printf("Dir Test passed\n"); + + PR_DestroyMonitor(mon); + PR_Cleanup(); return 0; } diff --git a/nsprpub/pr/tests/threads.c b/nsprpub/pr/tests/threads.c index 1b9b133d9..4a28dc6e5 100644 --- a/nsprpub/pr/tests/threads.c +++ b/nsprpub/pr/tests/threads.c @@ -16,7 +16,7 @@ PRInt32 count, iterations, alive; PRBool debug_mode = PR_FALSE, passed = PR_TRUE; -void +void PR_CALLBACK ReallyDumbThread(void *arg) { @@ -42,7 +42,7 @@ DumbThread(void *arg) if (!thr) { if (debug_mode) { printf("Could not create really dumb thread (%d, %d)!\n", - PR_GetError(), PR_GetOSError()); + PR_GetError(), PR_GetOSError()); } passed = PR_FALSE; } else { @@ -65,8 +65,8 @@ static void CreateThreads(PRThreadScope scope1, PRThreadScope scope2) alive = count; for (n=0; n<count; n++) { thr = PR_CreateThread(PR_USER_THREAD, - DumbThread, - (void *)scope2, + DumbThread, + (void *)scope2, PR_PRIORITY_NORMAL, scope1, PR_UNJOINABLE_THREAD, @@ -74,12 +74,12 @@ static void CreateThreads(PRThreadScope scope1, PRThreadScope scope2) if (!thr) { if (debug_mode) { printf("Could not create dumb thread (%d, %d)!\n", - PR_GetError(), PR_GetOSError()); + PR_GetError(), PR_GetOSError()); } passed = PR_FALSE; alive--; } - + PR_Sleep(0); } @@ -90,7 +90,7 @@ static void CreateThreads(PRThreadScope scope1, PRThreadScope scope2) } PR_ExitMonitor(mon); - PR_DestroyMonitor(mon); + PR_DestroyMonitor(mon); } static void CreateThreadsUU(void) @@ -137,37 +137,43 @@ int main(int argc, char **argv) PR_STDIO_INIT(); PR_Init(PR_USER_THREAD, PR_PRIORITY_HIGH, 0); - + { - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "dc:i:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "dc:i:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = PR_TRUE; - break; - case 'c': /* loop counter */ - count = atoi(opt->value); - break; - case 'i': /* loop counter */ - iterations = atoi(opt->value); - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = PR_TRUE; + break; + case 'c': /* loop counter */ + count = atoi(opt->value); + break; + case 'i': /* loop counter */ + iterations = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); } - if (0 == count) count = 50; - if (0 == iterations) iterations = 10; + if (0 == count) { + count = 50; + } + if (0 == iterations) { + iterations = 10; + } if (debug_mode) { - printf("\ + printf("\ ** Tests lots of thread creations. \n\ ** Create %ld native threads %ld times. \n\ ** Create %ld user threads %ld times \n", iterations,count,iterations,count); @@ -180,7 +186,9 @@ int main(int argc, char **argv) Measure(CreateThreadsKK, "Create native/native threads"); } - if (debug_mode) printf("\nNow switch to recycling threads \n\n"); + if (debug_mode) { + printf("\nNow switch to recycling threads \n\n"); + } PR_SetThreadRecycleMode(1); for (index=0; index<iterations; index++) { diff --git a/nsprpub/pr/tests/thrpool_client.c b/nsprpub/pr/tests/thrpool_client.c index 7f3df3271..2c01a3c51 100644 --- a/nsprpub/pr/tests/thrpool_client.c +++ b/nsprpub/pr/tests/thrpool_client.c @@ -43,7 +43,7 @@ static char *program_name = NULL; #define BUF_DATA_SIZE (2 * 1024) #define TCP_MESG_SIZE 1024 -#define NUM_TCP_CLIENTS 10 /* for a listen queue depth of 5 */ +#define NUM_TCP_CLIENTS 10 /* for a listen queue depth of 5 */ #define NUM_TCP_CONNECTIONS_PER_CLIENT 10 #define NUM_TCP_MESGS_PER_CONNECTION 10 @@ -79,18 +79,18 @@ readn(PRFileDesc *sockfd, char *buf, int len) int rem; int bytes; int offset = 0; - PRIntervalTime timeout = PR_INTERVAL_NO_TIMEOUT; + PRIntervalTime timeout = PR_INTERVAL_NO_TIMEOUT; for (rem=len; rem; offset += bytes, rem -= bytes) { DPRINTF(("thread = 0x%lx: calling PR_Recv, bytes = %d\n", - PR_GetCurrentThread(), rem)); + PR_GetCurrentThread(), rem)); bytes = PR_Recv(sockfd, buf + offset, rem, 0, - timeout); + timeout); DPRINTF(("thread = 0x%lx: returning from PR_Recv, bytes = %d\n", - PR_GetCurrentThread(), bytes)); + PR_GetCurrentThread(), bytes)); if (bytes < 0) { - return -1; - } + return -1; + } } return len; } @@ -108,13 +108,14 @@ writen(PRFileDesc *sockfd, char *buf, int len) for (rem=len; rem; offset += bytes, rem -= bytes) { DPRINTF(("thread = 0x%lx: calling PR_Send, bytes = %d\n", - PR_GetCurrentThread(), rem)); + PR_GetCurrentThread(), rem)); bytes = PR_Send(sockfd, buf + offset, rem, 0, - PR_INTERVAL_NO_TIMEOUT); + PR_INTERVAL_NO_TIMEOUT); DPRINTF(("thread = 0x%lx: returning from PR_Send, bytes = %d\n", - PR_GetCurrentThread(), bytes)); - if (bytes <= 0) + PR_GetCurrentThread(), bytes)); + if (bytes <= 0) { return -1; + } } return len; } @@ -163,9 +164,9 @@ TCP_Client(void *arg) } DPRINTF(("TCP client connecting to server:%d\n", server_port)); - if (PR_Connect(sockfd, &netaddr,PR_INTERVAL_NO_TIMEOUT) < 0){ - fprintf(stderr, "PR_Connect failed: (%ld, %ld)\n", - PR_GetError(), PR_GetOSError()); + if (PR_Connect(sockfd, &netaddr,PR_INTERVAL_NO_TIMEOUT) < 0) { + fprintf(stderr, "PR_Connect failed: (%ld, %ld)\n", + PR_GetError(), PR_GetOSError()); failed_already=1; return; } @@ -182,10 +183,10 @@ TCP_Client(void *arg) failed_already=1; return; } - /* + /* DPRINTF(("TCP Client [0x%lx]: out_buf = 0x%lx out_buf[0] = 0x%lx\n", PR_GetCurrentThread(), out_buf, (*((int *) out_buf->data)))); - */ + */ if (readn(sockfd, in_buf->data, bytes) < bytes) { fprintf(stderr,"%s: ERROR - TCP_Client:readn\n", program_name); failed_already=1; @@ -226,7 +227,7 @@ TCP_Client(void *arg) /* * TCP_Socket_Client_Server_Test - concurrent server test - * + * * Each client connects to the server and sends a chunk of data * For each connection, server reads the data * from the client and sends it back to the client, unmodified. @@ -243,7 +244,7 @@ TCP_Socket_Client_Server_Test(void) PRMonitor *mon2; PRInt32 datalen; PRInt32 connections = 0; - PRThread *thr; + PRThread *thr; datalen = tcp_mesg_size; connections = 0; @@ -271,16 +272,16 @@ TCP_Socket_Client_Server_Test(void) cparamp->exit_counter = &connections; cparamp->datalen = datalen; for (i = 0; i < num_tcp_clients; i++) { - thr = PR_CreateThread(PR_USER_THREAD, TCP_Client, (void *)cparamp, - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, 0); + thr = PR_CreateThread(PR_USER_THREAD, TCP_Client, (void *)cparamp, + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, 0); if (NULL == thr) { fprintf(stderr,"%s: PR_CreateThread failed\n", program_name); failed_already=1; return -1; } - PR_EnterMonitor(mon2); + PR_EnterMonitor(mon2); connections++; - PR_ExitMonitor(mon2); + PR_ExitMonitor(mon2); DPRINTF(("Created TCP client = 0x%lx\n", thr)); } /* Wait for client jobs to exit */ @@ -292,9 +293,9 @@ TCP_Socket_Client_Server_Test(void) PR_ExitMonitor(mon2); printf("%30s","TCP_Socket_Client_Server_Test:"); printf("%2ld Server %2ld Clients %2ld connections_per_client\n",1l, - num_tcp_clients, num_tcp_connections_per_client); + num_tcp_clients, num_tcp_connections_per_client); printf("%30s %2ld messages_per_connection %4ld bytes_per_message\n",":", - num_tcp_mesgs_per_connection, tcp_mesg_size); + num_tcp_mesgs_per_connection, tcp_mesg_size); PR_DELETE(cparamp); return 0; @@ -309,22 +310,24 @@ int main(int argc, char **argv) */ PLOptStatus os; PLOptState *opt; - program_name = argv[0]; + program_name = argv[0]; opt = PL_CreateOptState(argc, argv, "dp:"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - _debug_on = 1; - break; - case 'p': - server_port = atoi(opt->value); - break; - default: - break; + case 'd': /* debug mode */ + _debug_on = 1; + break; + case 'p': + server_port = atoi(opt->value); + break; + default: + break; } } PL_DestroyOptState(opt); @@ -334,11 +337,13 @@ int main(int argc, char **argv) PR_SetConcurrency(4); - TCP_Socket_Client_Server_Test(); + TCP_Socket_Client_Server_Test(); PR_Cleanup(); - if (failed_already) - return 1; - else - return 0; + if (failed_already) { + return 1; + } + else { + return 0; + } } diff --git a/nsprpub/pr/tests/thrpool_server.c b/nsprpub/pr/tests/thrpool_server.c index ef09f23b5..ecae117a8 100644 --- a/nsprpub/pr/tests/thrpool_server.c +++ b/nsprpub/pr/tests/thrpool_server.c @@ -26,7 +26,7 @@ #endif /* for getcwd */ -#if defined(XP_UNIX) || defined (XP_OS2) || defined(XP_BEOS) +#if defined(XP_UNIX) || defined (XP_OS2) #include <unistd.h> #elif defined(XP_PC) #include <direct.h> @@ -51,13 +51,13 @@ static void serve_client_write(void *arg); #define BUF_DATA_SIZE (2 * 1024) #define TCP_MESG_SIZE 1024 -#define NUM_TCP_CLIENTS 10 /* for a listen queue depth of 5 */ +#define NUM_TCP_CLIENTS 10 /* for a listen queue depth of 5 */ #define NUM_TCP_CONNECTIONS_PER_CLIENT 10 #define NUM_TCP_MESGS_PER_CONNECTION 10 -#define TCP_SERVER_PORT 10000 -#define SERVER_MAX_BIND_COUNT 100 +#define TCP_SERVER_PORT 10000 +#define SERVER_MAX_BIND_COUNT 100 #ifdef WINCE char *getcwd(char *buf, size_t size) @@ -66,7 +66,7 @@ char *getcwd(char *buf, size_t size) _wgetcwd(wpath, MAX_PATH); WideCharToMultiByte(CP_ACP, 0, wpath, -1, buf, size, 0, 0); } - + #define perror(s) #endif @@ -85,12 +85,12 @@ typedef struct buffer { typedef struct Server_Param { PRJobIoDesc iod; /* socket to read from/write to */ - PRInt32 datalen; /* bytes of data transfered in each read/write */ - PRNetAddr netaddr; - PRMonitor *exit_mon; /* monitor to signal on exit */ - PRInt32 *job_counterp; /* counter to decrement, before exit */ - PRInt32 conn_counter; /* counter to decrement, before exit */ - PRThreadPool *tp; + PRInt32 datalen; /* bytes of data transfered in each read/write */ + PRNetAddr netaddr; + PRMonitor *exit_mon; /* monitor to signal on exit */ + PRInt32 *job_counterp; /* counter to decrement, before exit */ + PRInt32 conn_counter; /* counter to decrement, before exit */ + PRThreadPool *tp; } Server_Param; typedef struct Serve_Client_Param { @@ -98,60 +98,60 @@ typedef struct Serve_Client_Param { PRInt32 datalen; /* bytes of data transfered in each read/write */ PRMonitor *exit_mon; /* monitor to signal on exit */ PRInt32 *job_counterp; /* counter to decrement, before exit */ - PRThreadPool *tp; + PRThreadPool *tp; } Serve_Client_Param; typedef struct Session { PRJobIoDesc iod; /* socket to read from/write to */ - buffer *in_buf; - PRInt32 bytes; - PRInt32 msg_num; - PRInt32 bytes_read; + buffer *in_buf; + PRInt32 bytes; + PRInt32 msg_num; + PRInt32 bytes_read; PRMonitor *exit_mon; /* monitor to signal on exit */ PRInt32 *job_counterp; /* counter to decrement, before exit */ - PRThreadPool *tp; + PRThreadPool *tp; } Session; static void serve_client_read(void *arg) { - Session *sp = (Session *) arg; + Session *sp = (Session *) arg; int rem; int bytes; int offset; - PRFileDesc *sockfd; - char *buf; - PRJob *jobp; + PRFileDesc *sockfd; + char *buf; + PRJob *jobp; - PRIntervalTime timeout = PR_INTERVAL_NO_TIMEOUT; + PRIntervalTime timeout = PR_INTERVAL_NO_TIMEOUT; - sockfd = sp->iod.socket; - buf = sp->in_buf->data; + 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); + 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; } @@ -159,35 +159,35 @@ serve_client_read(void *arg) static void serve_client_write(void *arg) { - Session *sp = (Session *) arg; + Session *sp = (Session *) arg; int bytes; - PRFileDesc *sockfd; - char *buf; - PRJob *jobp; + PRFileDesc *sockfd; + char *buf; + PRJob *jobp; - sockfd = sp->iod.socket; - buf = sp->in_buf->data; + sockfd = sp->iod.socket; + buf = sp->in_buf->data; PR_ASSERT(sp->msg_num < num_tcp_mesgs_per_connection); - bytes = PR_Send(sockfd, buf, sp->bytes, 0, PR_INTERVAL_NO_TIMEOUT); - PR_ASSERT(bytes == sp->bytes); + bytes = PR_Send(sockfd, buf, sp->bytes, 0, PR_INTERVAL_NO_TIMEOUT); + PR_ASSERT(bytes == sp->bytes); - if (bytes < 0) { - return; - } - DPRINTF(("serve_client: write complete, msg(%d) \n", sp->msg_num)); + if (bytes < 0) { + return; + } + DPRINTF(("serve_client: write complete, msg(%d) \n", sp->msg_num)); sp->msg_num++; if (sp->msg_num < num_tcp_mesgs_per_connection) { - sp->bytes_read = 0; - sp->iod.timeout = PR_SecondsToInterval(60); - jobp = PR_QueueJob_Read(sp->tp, &sp->iod, serve_client_read, sp, - PR_FALSE); - PR_ASSERT(NULL != jobp); - return; - } - - DPRINTF(("serve_client: read/write complete, msg(%d) \n", sp->msg_num)); + sp->bytes_read = 0; + sp->iod.timeout = PR_SecondsToInterval(60); + jobp = PR_QueueJob_Read(sp->tp, &sp->iod, serve_client_read, sp, + PR_FALSE); + PR_ASSERT(NULL != jobp); + return; + } + + DPRINTF(("serve_client: read/write complete, msg(%d) \n", sp->msg_num)); if (PR_Shutdown(sockfd, PR_SHUTDOWN_BOTH) < 0) { fprintf(stderr,"%s: ERROR - PR_Shutdown\n", program_name); } @@ -215,11 +215,11 @@ Serve_Client(void *arg) { Serve_Client_Param *scp = (Serve_Client_Param *) arg; buffer *in_buf; - Session *sp; - PRJob *jobp; + Session *sp; + PRJob *jobp; - sp = PR_NEW(Session); - sp->iod = scp->iod; + sp = PR_NEW(Session); + sp->iod = scp->iod; in_buf = PR_NEW(buffer); if (in_buf == NULL) { @@ -228,19 +228,19 @@ Serve_Client(void *arg) 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->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); + 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 @@ -249,32 +249,32 @@ print_stats(void *arg) Server_Param *sp = (Server_Param *) arg; PRThreadPool *tp = sp->tp; PRInt32 counter; - PRJob *jobp; + PRJob *jobp; - PR_EnterMonitor(sp->exit_mon); - counter = (*sp->job_counterp); - PR_ExitMonitor(sp->exit_mon); + PR_EnterMonitor(sp->exit_mon); + counter = (*sp->job_counterp); + PR_ExitMonitor(sp->exit_mon); - printf("PRINT_STATS: #client connections = %d\n",counter); + printf("PRINT_STATS: #client connections = %d\n",counter); - jobp = PR_QueueJob_Timer(tp, PR_MillisecondsToInterval(500), - print_stats, sp, PR_FALSE); + jobp = PR_QueueJob_Timer(tp, PR_MillisecondsToInterval(500), + print_stats, sp, PR_FALSE); - PR_ASSERT(NULL != jobp); + PR_ASSERT(NULL != jobp); } static int job_counter = 0; /* * TCP Server * Server binds an address to a socket, starts a client process and - * listens for incoming connections. + * listens for incoming connections. * Each client connects to the server and sends a chunk of data * Starts a Serve_Client job for each incoming connection, to read * the data from the client and send it back to the client, unmodified. * Each client checks that data received from server is same as the * data it sent to the server. - * Finally, the threadpool is shutdown + * Finally, the threadpool is shutdown */ static void PR_CALLBACK TCP_Server(void *arg) @@ -283,10 +283,10 @@ TCP_Server(void *arg) Server_Param *sp; PRFileDesc *sockfd; PRNetAddr netaddr; - PRMonitor *sc_mon; - PRJob *jobp; - int i; - PRStatus rval; + PRMonitor *sc_mon; + PRJob *jobp; + int i; + PRStatus rval; /* * Create a tcp socket @@ -295,7 +295,7 @@ TCP_Server(void *arg) fprintf(stderr,"%s: PR_NewTCPSocket failed\n", program_name); return; } - memset(&netaddr, 0 , sizeof(netaddr)); + memset(&netaddr, 0, sizeof(netaddr)); netaddr.inet.family = PR_AF_INET; netaddr.inet.port = PR_htons(TCP_SERVER_PORT); netaddr.inet.ip = PR_htonl(PR_INADDR_ANY); @@ -303,12 +303,13 @@ TCP_Server(void *arg) * try a few times to bind server's address, if addresses are in * use */ - i = 0; + i = 0; while (PR_Bind(sockfd, &netaddr) < 0) { if (PR_GetError() == PR_ADDRESS_IN_USE_ERROR) { netaddr.inet.port += 2; - if (i++ < SERVER_MAX_BIND_COUNT) + if (i++ < SERVER_MAX_BIND_COUNT) { continue; + } } fprintf(stderr,"%s: ERROR - PR_Bind failed\n", program_name); perror("PR_Bind"); @@ -329,39 +330,39 @@ TCP_Server(void *arg) } DPRINTF(( - "TCP_Server: PR_BIND netaddr.inet.ip = 0x%lx, netaddr.inet.port = %d\n", - netaddr.inet.ip, netaddr.inet.port)); - - sp = PR_NEW(Server_Param); - if (sp == NULL) { - fprintf(stderr,"%s: PR_NEW failed\n", program_name); - failed_already=1; - return; - } - sp->iod.socket = sockfd; - sp->iod.timeout = PR_SecondsToInterval(60); - sp->datalen = tcp_mesg_size; - sp->exit_mon = sc_mon; - sp->job_counterp = &job_counter; - sp->conn_counter = 0; - sp->tp = tp; - sp->netaddr = netaddr; - - /* create and cancel an io job */ - jobp = PR_QueueJob_Accept(tp, &sp->iod, TCP_Server_Accept, sp, - PR_FALSE); - PR_ASSERT(NULL != jobp); - rval = PR_CancelJob(jobp); - PR_ASSERT(PR_SUCCESS == rval); - - /* - * create the client process - */ - { + "TCP_Server: PR_BIND netaddr.inet.ip = 0x%lx, netaddr.inet.port = %d\n", + netaddr.inet.ip, netaddr.inet.port)); + + sp = PR_NEW(Server_Param); + if (sp == NULL) { + fprintf(stderr,"%s: PR_NEW failed\n", program_name); + failed_already=1; + return; + } + sp->iod.socket = sockfd; + sp->iod.timeout = PR_SecondsToInterval(60); + sp->datalen = tcp_mesg_size; + sp->exit_mon = sc_mon; + sp->job_counterp = &job_counter; + sp->conn_counter = 0; + sp->tp = tp; + sp->netaddr = netaddr; + + /* create and cancel an io job */ + jobp = PR_QueueJob_Accept(tp, &sp->iod, TCP_Server_Accept, sp, + PR_FALSE); + PR_ASSERT(NULL != jobp); + rval = PR_CancelJob(jobp); + PR_ASSERT(PR_SUCCESS == rval); + + /* + * create the client process + */ + { #define MAX_ARGS 4 - char *argv[MAX_ARGS + 1]; - int index = 0; - char port[32]; + char *argv[MAX_ARGS + 1]; + int index = 0; + char port[32]; char path[1024 + sizeof("/thrpool_client")]; getcwd(path, sizeof(path)); @@ -371,7 +372,7 @@ TCP_Server(void *arg) (void)strcat(path, ".exe"); #endif argv[index++] = path; - sprintf(port,"%d",PR_ntohs(netaddr.inet.port)); + sprintf(port,"%d",PR_ntohs(netaddr.inet.port)); if (_debug_on) { argv[index++] = "-d"; @@ -381,18 +382,18 @@ TCP_Server(void *arg) } else { argv[index++] = "-p"; argv[index++] = port; - argv[index++] = NULL; - } - PR_ASSERT(MAX_ARGS >= (index - 1)); - + argv[index++] = NULL; + } + PR_ASSERT(MAX_ARGS >= (index - 1)); + DPRINTF(("creating client process %s ...\n", path)); if (PR_FAILURE == PR_CreateProcessDetached(path, argv, NULL, NULL)) { - fprintf(stderr, - "thrpool_server: ERROR - PR_CreateProcessDetached failed\n"); - failed_already=1; - return; - } - } + fprintf(stderr, + "thrpool_server: ERROR - PR_CreateProcessDetached failed\n"); + failed_already=1; + return; + } + } sc_mon = PR_NewMonitor(); if (sc_mon == NULL) { @@ -401,28 +402,28 @@ TCP_Server(void *arg) return; } - sp->iod.socket = sockfd; - sp->iod.timeout = PR_SecondsToInterval(60); - sp->datalen = tcp_mesg_size; - sp->exit_mon = sc_mon; - sp->job_counterp = &job_counter; - sp->conn_counter = 0; - sp->tp = tp; - sp->netaddr = netaddr; - - /* create and cancel a timer job */ - jobp = PR_QueueJob_Timer(tp, PR_MillisecondsToInterval(5000), - print_stats, sp, PR_FALSE); - PR_ASSERT(NULL != jobp); - rval = PR_CancelJob(jobp); - PR_ASSERT(PR_SUCCESS == rval); + sp->iod.socket = sockfd; + sp->iod.timeout = PR_SecondsToInterval(60); + sp->datalen = tcp_mesg_size; + sp->exit_mon = sc_mon; + sp->job_counterp = &job_counter; + sp->conn_counter = 0; + sp->tp = tp; + sp->netaddr = netaddr; + + /* create and cancel a timer job */ + jobp = PR_QueueJob_Timer(tp, PR_MillisecondsToInterval(5000), + print_stats, sp, PR_FALSE); + PR_ASSERT(NULL != jobp); + rval = PR_CancelJob(jobp); + PR_ASSERT(PR_SUCCESS == rval); DPRINTF(("TCP_Server: Accepting connections \n")); - jobp = PR_QueueJob_Accept(tp, &sp->iod, TCP_Server_Accept, sp, - PR_FALSE); - PR_ASSERT(NULL != jobp); - return; + jobp = PR_QueueJob_Accept(tp, &sp->iod, TCP_Server_Accept, sp, + PR_FALSE); + PR_ASSERT(NULL != jobp); + return; } static void @@ -431,97 +432,97 @@ TCP_Server_Accept(void *arg) Server_Param *sp = (Server_Param *) arg; PRThreadPool *tp = sp->tp; Serve_Client_Param *scp; - PRFileDesc *newsockfd; - PRJob *jobp; - - if ((newsockfd = PR_Accept(sp->iod.socket, &sp->netaddr, - PR_INTERVAL_NO_TIMEOUT)) == NULL) { - fprintf(stderr,"%s: ERROR - PR_Accept failed\n", program_name); - failed_already=1; - goto exit; - } - scp = PR_NEW(Serve_Client_Param); - if (scp == NULL) { - fprintf(stderr,"%s: PR_NEW failed\n", program_name); - failed_already=1; - goto exit; - } - - /* - * Start a Serve_Client job for each incoming connection - */ - scp->iod.socket = newsockfd; - scp->iod.timeout = PR_SecondsToInterval(60); - scp->datalen = tcp_mesg_size; - scp->exit_mon = sp->exit_mon; - scp->job_counterp = sp->job_counterp; - scp->tp = sp->tp; - - PR_EnterMonitor(sp->exit_mon); - (*sp->job_counterp)++; - PR_ExitMonitor(sp->exit_mon); - jobp = PR_QueueJob(tp, Serve_Client, scp, - PR_FALSE); - - PR_ASSERT(NULL != jobp); - DPRINTF(("TCP_Server: Created Serve_Client = 0x%lx\n", jobp)); - - /* - * single-threaded update; no lock needed - */ + PRFileDesc *newsockfd; + PRJob *jobp; + + if ((newsockfd = PR_Accept(sp->iod.socket, &sp->netaddr, + PR_INTERVAL_NO_TIMEOUT)) == NULL) { + fprintf(stderr,"%s: ERROR - PR_Accept failed\n", program_name); + failed_already=1; + goto exit; + } + scp = PR_NEW(Serve_Client_Param); + if (scp == NULL) { + fprintf(stderr,"%s: PR_NEW failed\n", program_name); + failed_already=1; + goto exit; + } + + /* + * Start a Serve_Client job for each incoming connection + */ + scp->iod.socket = newsockfd; + scp->iod.timeout = PR_SecondsToInterval(60); + scp->datalen = tcp_mesg_size; + scp->exit_mon = sp->exit_mon; + scp->job_counterp = sp->job_counterp; + scp->tp = sp->tp; + + PR_EnterMonitor(sp->exit_mon); + (*sp->job_counterp)++; + PR_ExitMonitor(sp->exit_mon); + jobp = PR_QueueJob(tp, Serve_Client, scp, + PR_FALSE); + + PR_ASSERT(NULL != jobp); + DPRINTF(("TCP_Server: Created Serve_Client = 0x%lx\n", jobp)); + + /* + * single-threaded update; no lock needed + */ sp->conn_counter++; if (sp->conn_counter < - (num_tcp_clients * num_tcp_connections_per_client)) { - jobp = PR_QueueJob_Accept(tp, &sp->iod, TCP_Server_Accept, sp, - PR_FALSE); - PR_ASSERT(NULL != jobp); - return; - } - jobp = PR_QueueJob_Timer(tp, PR_MillisecondsToInterval(500), - print_stats, sp, PR_FALSE); - - PR_ASSERT(NULL != jobp); - DPRINTF(("TCP_Server: Created print_stats timer job = 0x%lx\n", jobp)); + (num_tcp_clients * num_tcp_connections_per_client)) { + jobp = PR_QueueJob_Accept(tp, &sp->iod, TCP_Server_Accept, sp, + PR_FALSE); + PR_ASSERT(NULL != jobp); + return; + } + jobp = PR_QueueJob_Timer(tp, PR_MillisecondsToInterval(500), + print_stats, sp, PR_FALSE); + + PR_ASSERT(NULL != jobp); + DPRINTF(("TCP_Server: Created print_stats timer job = 0x%lx\n", jobp)); exit: - PR_EnterMonitor(sp->exit_mon); + PR_EnterMonitor(sp->exit_mon); /* Wait for server jobs to finish */ while (0 != *sp->job_counterp) { PR_Wait(sp->exit_mon, PR_INTERVAL_NO_TIMEOUT); DPRINTF(("TCP_Server: conn_counter = %d\n", - *sp->job_counterp)); + *sp->job_counterp)); } PR_ExitMonitor(sp->exit_mon); if (sp->iod.socket) { PR_Close(sp->iod.socket); } - PR_DestroyMonitor(sp->exit_mon); + PR_DestroyMonitor(sp->exit_mon); printf("%30s","TCP_Socket_Client_Server_Test:"); printf("%2ld Server %2ld Clients %2ld connections_per_client\n",1l, - num_tcp_clients, num_tcp_connections_per_client); + num_tcp_clients, num_tcp_connections_per_client); printf("%30s %2ld messages_per_connection %4ld bytes_per_message\n",":", - num_tcp_mesgs_per_connection, tcp_mesg_size); + num_tcp_mesgs_per_connection, tcp_mesg_size); - DPRINTF(("%s: calling PR_ShutdownThreadPool\n", program_name)); - PR_ShutdownThreadPool(sp->tp); - PR_DELETE(sp); + DPRINTF(("%s: calling PR_ShutdownThreadPool\n", program_name)); + PR_ShutdownThreadPool(sp->tp); + PR_DELETE(sp); } /************************************************************************/ -#define DEFAULT_INITIAL_THREADS 4 -#define DEFAULT_MAX_THREADS 100 -#define DEFAULT_STACKSIZE (512 * 1024) +#define DEFAULT_INITIAL_THREADS 4 +#define DEFAULT_MAX_THREADS 100 +#define DEFAULT_STACKSIZE (512 * 1024) int main(int argc, char **argv) { - PRInt32 initial_threads = DEFAULT_INITIAL_THREADS; - PRInt32 max_threads = DEFAULT_MAX_THREADS; - PRInt32 stacksize = DEFAULT_STACKSIZE; - PRThreadPool *tp = NULL; - PRStatus rv; - PRJob *jobp; + PRInt32 initial_threads = DEFAULT_INITIAL_THREADS; + PRInt32 max_threads = DEFAULT_MAX_THREADS; + PRInt32 stacksize = DEFAULT_STACKSIZE; + PRThreadPool *tp = NULL; + PRStatus rv; + PRJob *jobp; /* * -d debug mode @@ -529,18 +530,20 @@ int main(int argc, char **argv) PLOptStatus os; PLOptState *opt; - program_name = argv[0]; + program_name = argv[0]; opt = PL_CreateOptState(argc, argv, "d"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - _debug_on = 1; - break; - default: - break; + case 'd': /* debug mode */ + _debug_on = 1; + break; + default: + break; } } PL_DestroyOptState(opt); @@ -550,23 +553,27 @@ int main(int argc, char **argv) PR_SetConcurrency(4); - tp = PR_CreateThreadPool(initial_threads, max_threads, stacksize); + tp = PR_CreateThreadPool(initial_threads, max_threads, stacksize); if (NULL == tp) { printf("PR_CreateThreadPool failed\n"); failed_already=1; goto done; - } - jobp = PR_QueueJob(tp, TCP_Server, tp, PR_TRUE); - rv = PR_JoinJob(jobp); - PR_ASSERT(PR_SUCCESS == rv); + } + jobp = PR_QueueJob(tp, TCP_Server, tp, PR_TRUE); + rv = PR_JoinJob(jobp); + PR_ASSERT(PR_SUCCESS == rv); - DPRINTF(("%s: calling PR_JoinThreadPool\n", program_name)); - rv = PR_JoinThreadPool(tp); - PR_ASSERT(PR_SUCCESS == rv); - DPRINTF(("%s: returning from PR_JoinThreadPool\n", program_name)); + DPRINTF(("%s: calling PR_JoinThreadPool\n", program_name)); + rv = PR_JoinThreadPool(tp); + PR_ASSERT(PR_SUCCESS == rv); + DPRINTF(("%s: returning from PR_JoinThreadPool\n", program_name)); done: PR_Cleanup(); - if (failed_already) return 1; - else return 0; + if (failed_already) { + return 1; + } + else { + return 0; + } } diff --git a/nsprpub/pr/tests/thruput.c b/nsprpub/pr/tests/thruput.c index fd7ecf2e2..a772deaab 100644 --- a/nsprpub/pr/tests/thruput.c +++ b/nsprpub/pr/tests/thruput.c @@ -55,9 +55,12 @@ static PRStatus PrintAddress(const PRNetAddr* address) { char buffer[ADDR_BUFFER]; PRStatus rv = PR_NetAddrToString(address, buffer, sizeof(buffer)); - if (PR_SUCCESS == rv) + if (PR_SUCCESS == rv) { PR_fprintf(err, "%s:%u\n", buffer, PR_ntohs(address->inet.port)); - else PL_FPrintError(err, "PR_NetAddrToString"); + } + else { + PL_FPrintError(err, "PR_NetAddrToString"); + } return rv; } /* PrintAddress */ @@ -93,21 +96,24 @@ static void PR_CALLBACK Clientel(void *arg) data.option = PR_SockOpt_RecvBufferSize; data.value.recv_buffer_size = (PRSize)xport_buffer; rv = PR_SetSocketOption(xport, &data); - if (PR_FAILURE == rv) + if (PR_FAILURE == rv) { PL_FPrintError(err, "PR_SetSocketOption - ignored"); + } data.option = PR_SockOpt_SendBufferSize; data.value.send_buffer_size = (PRSize)xport_buffer; rv = PR_SetSocketOption(xport, &data); - if (PR_FAILURE == rv) + if (PR_FAILURE == rv) { PL_FPrintError(err, "PR_SetSocketOption - ignored"); + } } rv = PR_Connect(xport, server_address, connect_timeout); if (PR_FAILURE == rv) { PL_FPrintError(err, "PR_Connect"); - if (PR_IO_TIMEOUT_ERROR != PR_GetError()) + if (PR_IO_TIMEOUT_ERROR != PR_GetError()) { PR_Sleep(connect_timeout); + } PR_Close(xport); /* delete it and start over */ } } while (PR_FAILURE == rv); @@ -115,7 +121,7 @@ static void PR_CALLBACK Clientel(void *arg) do { bytes = PR_Recv( - xport, buffer, buffer_size, 0, PR_INTERVAL_NO_TIMEOUT); + xport, buffer, buffer_size, 0, PR_INTERVAL_NO_TIMEOUT); PR_Lock(shared->ml); now = PR_IntervalNow(); shared->sampled += bytes; @@ -147,13 +153,15 @@ static void Client(const char *server_name) 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) + if (PR_FAILURE == rv) { PL_FPrintError(err, "PR_GetHostByName"); + } else { if (PR_EnumerateHostEnt( - 0, &host, PORT_NUMBER, &shared->server_address) < 0) + 0, &host, PORT_NUMBER, &shared->server_address) < 0) { PL_FPrintError(err, "PR_EnumerateHostEnt"); + } else { do @@ -189,19 +197,21 @@ static void PR_CALLBACK Servette(void *arg) data.option = PR_SockOpt_RecvBufferSize; data.value.recv_buffer_size = (PRSize)xport_buffer; rv = PR_SetSocketOption(client, &data); - if (PR_FAILURE == rv) + if (PR_FAILURE == rv) { PL_FPrintError(err, "PR_SetSocketOption - ignored"); + } data.option = PR_SockOpt_SendBufferSize; data.value.send_buffer_size = (PRSize)xport_buffer; rv = PR_SetSocketOption(client, &data); - if (PR_FAILURE == rv) + if (PR_FAILURE == rv) { PL_FPrintError(err, "PR_SetSocketOption - ignored"); + } } do { bytes = PR_Send( - client, buffer, buffer_size, 0, PR_INTERVAL_NO_TIMEOUT); + client, buffer, buffer_size, 0, PR_INTERVAL_NO_TIMEOUT); PR_Lock(shared->ml); now = PR_IntervalNow(); @@ -238,11 +248,15 @@ static void Server(void) } rv = PR_InitializeNetAddr(PR_IpAddrAny, PORT_NUMBER, &server_address); - if (PR_FAILURE == rv) PL_FPrintError(err, "PR_InitializeNetAddr"); + if (PR_FAILURE == rv) { + PL_FPrintError(err, "PR_InitializeNetAddr"); + } else { rv = PR_Bind(xport, &server_address); - if (PR_FAILURE == rv) PL_FPrintError(err, "PR_Bind"); + if (PR_FAILURE == rv) { + PL_FPrintError(err, "PR_Bind"); + } else { PRFileDesc *client; @@ -252,8 +266,10 @@ static void Server(void) do { client = PR_Accept( - xport, &client_address, PR_INTERVAL_NO_TIMEOUT); - if (NULL == client) PL_FPrintError(err, "PR_Accept"); + xport, &client_address, PR_INTERVAL_NO_TIMEOUT); + if (NULL == client) { + PL_FPrintError(err, "PR_Accept"); + } else { PR_fprintf(err, "Server accepting from "); @@ -296,37 +312,39 @@ int main(int argc, char **argv) while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 0: /* Name of server */ - server_name = opt->value; - break; - case 'G': /* Globular threads */ - thread_scope = PR_GLOBAL_THREAD; - break; - case 'X': /* Use XTP as the transport */ - protocol = 36; - break; - case '6': /* Use IPv6 */ - domain = PR_AF_INET6; - break; - case 's': /* initial_streams */ - initial_streams = atoi(opt->value); - break; - case 'C': /* concurrency */ - concurrency = atoi(opt->value); - break; - case 'b': /* buffer size */ - buffer_size = 1024 * atoi(opt->value); - break; - case 'B': /* buffer size */ - xport_buffer = 1024 * atoi(opt->value); - break; - case 'h': /* user wants some guidance */ - default: - Help(); /* so give him an earful */ - return 2; /* but not a lot else */ + case 0: /* Name of server */ + server_name = opt->value; + break; + case 'G': /* Globular threads */ + thread_scope = PR_GLOBAL_THREAD; + break; + case 'X': /* Use XTP as the transport */ + protocol = 36; + break; + case '6': /* Use IPv6 */ + domain = PR_AF_INET6; + break; + case 's': /* initial_streams */ + initial_streams = atoi(opt->value); + break; + case 'C': /* concurrency */ + concurrency = atoi(opt->value); + break; + case 'b': /* buffer size */ + buffer_size = 1024 * atoi(opt->value); + break; + case 'B': /* buffer size */ + xport_buffer = 1024 * atoi(opt->value); + break; + case 'h': /* user wants some guidance */ + default: + Help(); /* so give him an earful */ + return 2; /* but not a lot else */ } } PL_DestroyOptState(opt); @@ -335,12 +353,12 @@ int main(int argc, char **argv) shared->ml = PR_NewLock(); PR_fprintf(err, - "This machine is %s\n", - (NULL == server_name) ? "the SERVER" : "a CLIENT"); + "This machine is %s\n", + (NULL == server_name) ? "the SERVER" : "a CLIENT"); PR_fprintf(err, - "Transport being used is %s\n", - (6 == protocol) ? "TCP" : "XTP"); + "Transport being used is %s\n", + (6 == protocol) ? "TCP" : "XTP"); if (PR_GLOBAL_THREAD == thread_scope) { @@ -359,18 +377,22 @@ int main(int argc, char **argv) } PR_fprintf(err, - "All threads will be %s\n", - (PR_GLOBAL_THREAD == thread_scope) ? "GLOBAL" : "LOCAL"); + "All threads will be %s\n", + (PR_GLOBAL_THREAD == thread_scope) ? "GLOBAL" : "LOCAL"); PR_fprintf(err, "Client buffer size will be %u\n", buffer_size); - + if (-1 != xport_buffer) - PR_fprintf( - err, "Transport send & receive buffer size will be %u\n", xport_buffer); - + PR_fprintf( + err, "Transport send & receive buffer size will be %u\n", xport_buffer); + - if (NULL == server_name) Server(); - else Client(server_name); + if (NULL == server_name) { + Server(); + } + else { + Client(server_name); + } return 0; } /* main */ diff --git a/nsprpub/pr/tests/time.c b/nsprpub/pr/tests/time.c index ed0bff8e9..cdb3ef73a 100644 --- a/nsprpub/pr/tests/time.c +++ b/nsprpub/pr/tests/time.c @@ -37,34 +37,36 @@ hrtime_t ihrtime; void ftime_init() { - itime = time(NULL); - ihrtime = gethrtime(); + itime = time(NULL); + ihrtime = gethrtime(); } time_t ftime() { - hrtime_t now = gethrtime(); + hrtime_t now = gethrtime(); - return itime + ((now - ihrtime) / 1000000000ll); + return itime + ((now - ihrtime) / 1000000000ll); } static void timeTime(void) { PRInt32 index = count; time_t rv; - - for (;index--;) + + for (; index--;) { rv = time(NULL); + } } static void timeGethrtime(void) { PRInt32 index = count; time_t rv; - - for (;index--;) + + for (; index--;) { rv = ftime(); + } } static void timeGettimeofday(void) @@ -72,9 +74,10 @@ static void timeGettimeofday(void) PRInt32 index = count; time_t rv; struct timeval tp; - - for (;index--;) + + for (; index--;) { rv = gettimeofday(&tp, NULL); + } } static void timePRTime32(void) @@ -85,8 +88,8 @@ static void timePRTime32(void) PRTime rv; LL_I2L(q, 1000000); - - for (;index--;) { + + for (; index--;) { rv = PR_Now(); LL_DIV(rv, rv, q); LL_L2I(rv32, rv); @@ -97,9 +100,10 @@ static void timePRTime64(void) { PRInt32 index = count; PRTime rv; - - for (;index--;) + + for (; index--;) { rv = PR_Now(); + } } /************************************************************************/ @@ -117,40 +121,44 @@ static void Measure(void (*func)(void), const char *msg) d = (double)PR_IntervalToMicroseconds(stop - start); tot = PR_IntervalToMilliseconds(stop-start); - if (debug_mode) printf("%40s: %6.2f usec avg, %d msec total\n", msg, d / count, tot); + if (debug_mode) { + printf("%40s: %6.2f usec avg, %d msec total\n", msg, d / count, tot); + } } int main(int argc, char **argv) { - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "d:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); if (argc > 1) { - count = atoi(argv[1]); + count = atoi(argv[1]); } else { - count = DEFAULT_COUNT; + count = DEFAULT_COUNT; } ftime_init(); @@ -161,8 +169,8 @@ int main(int argc, char **argv) Measure(timePRTime32, "time to get time with PR_Time() (32bit)"); Measure(timePRTime64, "time to get time with PR_Time() (64bit)"); - PR_Cleanup(); - return 0; + PR_Cleanup(); + return 0; } diff --git a/nsprpub/pr/tests/timemac.c b/nsprpub/pr/tests/timemac.c index f714aeb4f..b0f8b17d8 100644 --- a/nsprpub/pr/tests/timemac.c +++ b/nsprpub/pr/tests/timemac.c @@ -13,10 +13,11 @@ static char *dayOfWeek[] = - { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "???" }; +{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "???" }; static char *month[] = - { "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "???" }; +{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "???" +}; static void printExplodedTime(const PRExplodedTime *et) { PRInt32 totalOffset; @@ -25,18 +26,18 @@ static void printExplodedTime(const PRExplodedTime *et) { /* Print day of the week, month, day, hour, minute, and second */ printf( "%s %s %ld %02ld:%02ld:%02ld ", - dayOfWeek[et->tm_wday], month[et->tm_month], et->tm_mday, - et->tm_hour, et->tm_min, et->tm_sec); + dayOfWeek[et->tm_wday], month[et->tm_month], et->tm_mday, + et->tm_hour, et->tm_min, et->tm_sec); /* Print time zone */ totalOffset = et->tm_params.tp_gmt_offset + et->tm_params.tp_dst_offset; if (totalOffset == 0) { - printf("UTC "); + printf("UTC "); } else { sign = ""; if (totalOffset < 0) { - totalOffset = -totalOffset; - sign = "-"; + totalOffset = -totalOffset; + sign = "-"; } hourOffset = totalOffset / 3600; minOffset = (totalOffset % 3600) / 60; @@ -52,58 +53,58 @@ int main(int argc, char** argv) PR_STDIO_INIT(); PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); - - /* - ************************************************************* - ** - ** Testing PR_Now(), PR_ExplodeTime, and PR_ImplodeTime - ** on the current time - ** - ************************************************************* - */ + + /* + ************************************************************* + ** + ** Testing PR_Now(), PR_ExplodeTime, and PR_ImplodeTime + ** on the current time + ** + ************************************************************* + */ { - PRTime t1, t2; - PRExplodedTime et; + PRTime t1, t2; + PRExplodedTime et; - printf("*********************************************\n"); - printf("** **\n"); + printf("*********************************************\n"); + printf("** **\n"); printf("** Testing PR_Now(), PR_ExplodeTime, and **\n"); - printf("** PR_ImplodeTime on the current time **\n"); - printf("** **\n"); - printf("*********************************************\n\n"); + printf("** PR_ImplodeTime on the current time **\n"); + printf("** **\n"); + printf("*********************************************\n\n"); t1 = PR_Now(); /* First try converting to UTC */ PR_ExplodeTime(t1, PR_GMTParameters, &et); if (et.tm_params.tp_gmt_offset || et.tm_params.tp_dst_offset) { - printf("ERROR: UTC has nonzero gmt or dst offset.\n"); - return 1; + printf("ERROR: UTC has nonzero gmt or dst offset.\n"); + return 1; } printf("Current UTC is "); - printExplodedTime(&et); - printf("\n"); + printExplodedTime(&et); + printf("\n"); t2 = PR_ImplodeTime(&et); if (LL_NE(t1, t2)) { - printf("ERROR: Explode and implode are NOT inverse.\n"); - return 1; + printf("ERROR: Explode and implode are NOT inverse.\n"); + return 1; } /* Next, try converting to local (US Pacific) time */ PR_ExplodeTime(t1, PR_LocalTimeParameters, &et); printf("Current local time is "); - printExplodedTime(&et); - printf("\n"); - printf("GMT offset is %ld, DST offset is %ld\n", - et.tm_params.tp_gmt_offset, et.tm_params.tp_dst_offset); + printExplodedTime(&et); + printf("\n"); + printf("GMT offset is %ld, DST offset is %ld\n", + et.tm_params.tp_gmt_offset, et.tm_params.tp_dst_offset); t2 = PR_ImplodeTime(&et); if (LL_NE(t1, t2)) { - printf("ERROR: Explode and implode are NOT inverse.\n"); - return 1; - } + printf("ERROR: Explode and implode are NOT inverse.\n"); + return 1; + } } printf("Please examine the results\n"); diff --git a/nsprpub/pr/tests/timetest.c b/nsprpub/pr/tests/timetest.c index c9bdf9c27..9f96025d2 100644 --- a/nsprpub/pr/tests/timetest.c +++ b/nsprpub/pr/tests/timetest.c @@ -25,10 +25,11 @@ int failed_already=0; PRBool debug_mode = PR_FALSE; static char *dayOfWeek[] = - { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "???" }; +{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "???" }; static char *month[] = - { "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "???" }; +{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "???" +}; static void PrintExplodedTime(const PRExplodedTime *et) { PRInt32 totalOffset; @@ -37,46 +38,51 @@ static void PrintExplodedTime(const PRExplodedTime *et) { /* Print day of the week, month, day, hour, minute, and second */ if (debug_mode) printf("%s %s %ld %02ld:%02ld:%02ld ", - dayOfWeek[et->tm_wday], month[et->tm_month], et->tm_mday, - et->tm_hour, et->tm_min, et->tm_sec); + dayOfWeek[et->tm_wday], month[et->tm_month], et->tm_mday, + et->tm_hour, et->tm_min, et->tm_sec); /* Print time zone */ totalOffset = et->tm_params.tp_gmt_offset + et->tm_params.tp_dst_offset; if (totalOffset == 0) { - if (debug_mode) printf("UTC "); + if (debug_mode) { + printf("UTC "); + } } else { sign = "+"; if (totalOffset < 0) { - totalOffset = -totalOffset; - sign = "-"; + totalOffset = -totalOffset; + sign = "-"; } hourOffset = totalOffset / 3600; minOffset = (totalOffset % 3600) / 60; - if (debug_mode) + if (debug_mode) { printf("%s%02ld%02ld ", sign, hourOffset, minOffset); + } } /* Print year */ - if (debug_mode) printf("%hd", et->tm_year); + if (debug_mode) { + printf("%hd", et->tm_year); + } } static int ExplodedTimeIsEqual(const PRExplodedTime *et1, - const PRExplodedTime *et2) + const PRExplodedTime *et2) { if (et1->tm_usec == et2->tm_usec && - et1->tm_sec == et2->tm_sec && - et1->tm_min == et2->tm_min && - et1->tm_hour == et2->tm_hour && - et1->tm_mday == et2->tm_mday && - et1->tm_month == et2->tm_month && - et1->tm_year == et2->tm_year && - et1->tm_wday == et2->tm_wday && - et1->tm_yday == et2->tm_yday && - et1->tm_params.tp_gmt_offset == et2->tm_params.tp_gmt_offset && - et1->tm_params.tp_dst_offset == et2->tm_params.tp_dst_offset) { + et1->tm_sec == et2->tm_sec && + et1->tm_min == et2->tm_min && + et1->tm_hour == et2->tm_hour && + et1->tm_mday == et2->tm_mday && + et1->tm_month == et2->tm_month && + et1->tm_year == et2->tm_year && + et1->tm_wday == et2->tm_wday && + et1->tm_yday == et2->tm_yday && + et1->tm_params.tp_gmt_offset == et2->tm_params.tp_gmt_offset && + et1->tm_params.tp_dst_offset == et2->tm_params.tp_dst_offset) { return 1; } else { - return 0; + return 0; } } @@ -101,87 +107,95 @@ testParseTimeString(PRTime t) /* Print day of the week, month, day, hour, minute, and second */ PR_snprintf(timeString, 128, "%s %s %ld %02ld:%02ld:%02ld ", - dayOfWeek[et.tm_wday], month[et.tm_month], et.tm_mday, - et.tm_hour, et.tm_min, et.tm_sec); + dayOfWeek[et.tm_wday], month[et.tm_month], et.tm_mday, + et.tm_hour, et.tm_min, et.tm_sec); /* Print time zone */ totalOffset = et.tm_params.tp_gmt_offset + et.tm_params.tp_dst_offset; if (totalOffset == 0) { - strcat(timeString, "GMT "); /* I wanted to use "UTC" here, but - * PR_ParseTimeString doesn't + strcat(timeString, "GMT "); /* I wanted to use "UTC" here, but + * PR_ParseTimeString doesn't * understand "UTC". */ } else { sign = "+"; if (totalOffset < 0) { - totalOffset = -totalOffset; - sign = "-"; + totalOffset = -totalOffset; + sign = "-"; } hourOffset = totalOffset / 3600; minOffset = (totalOffset % 3600) / 60; PR_snprintf(buf, 128, "%s%02ld%02ld ", sign, hourOffset, minOffset); - strcat(timeString, buf); + strcat(timeString, buf); } /* Print year */ PR_snprintf(buf, 128, "%hd", et.tm_year); strcat(timeString, buf); if (PR_ParseTimeString(timeString, PR_FALSE, &t2) == PR_FAILURE) { - fprintf(stderr, "PR_ParseTimeString() failed\n"); - exit(1); + fprintf(stderr, "PR_ParseTimeString() failed\n"); + exit(1); } if (LL_NE(t, t2)) { - fprintf(stderr, "PR_ParseTimeString() incorrect\n"); - PR_snprintf(buf, 128, "t is %lld, t2 is %lld, time string is %s\n", - t, t2, timeString); - fprintf(stderr, "%s\n", buf); - exit(1); + fprintf(stderr, "PR_ParseTimeString() incorrect\n"); + PR_snprintf(buf, 128, "t is %lld, t2 is %lld, time string is %s\n", + t, t2, timeString); + fprintf(stderr, "%s\n", buf); + exit(1); } } int main(int argc, char** argv) { - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt; - + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt; + PR_STDIO_INIT(); - opt = PL_CreateOptState(argc, argv, "d"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + opt = PL_CreateOptState(argc, argv, "d"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = PR_TRUE; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = PR_TRUE; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); /* Testing zero PRTime (the epoch) */ { - PRTime t; - PRExplodedTime et; + PRTime t; + PRExplodedTime et; - LL_I2L(t, 0); - if (debug_mode) printf("The NSPR epoch is:\n"); + LL_I2L(t, 0); + if (debug_mode) { + printf("The NSPR epoch is:\n"); + } PR_ExplodeTime(t, PR_LocalTimeParameters, &et); - PrintExplodedTime(&et); - if (debug_mode) printf("\n"); - PR_ExplodeTime(t, PR_GMTParameters, &et); - PrintExplodedTime(&et); - if (debug_mode) printf("\n\n"); - testParseTimeString(t); + PrintExplodedTime(&et); + if (debug_mode) { + printf("\n"); + } + PR_ExplodeTime(t, PR_GMTParameters, &et); + PrintExplodedTime(&et); + if (debug_mode) { + printf("\n\n"); + } + testParseTimeString(t); } /* @@ -194,54 +208,74 @@ int main(int argc, char** argv) */ { - PRTime t1, t2; - PRExplodedTime et; - - if (debug_mode) { - printf("*********************************************\n"); - printf("** **\n"); - printf("** Testing PR_Now(), PR_ExplodeTime, and **\n"); - printf("** PR_ImplodeTime on the current time **\n"); - printf("** **\n"); - printf("*********************************************\n\n"); - } - t1 = PR_Now(); + PRTime t1, t2; + PRExplodedTime et; + + if (debug_mode) { + printf("*********************************************\n"); + printf("** **\n"); + printf("** Testing PR_Now(), PR_ExplodeTime, and **\n"); + printf("** PR_ImplodeTime on the current time **\n"); + printf("** **\n"); + printf("*********************************************\n\n"); + } + t1 = PR_Now(); /* First try converting to UTC */ PR_ExplodeTime(t1, PR_GMTParameters, &et); if (et.tm_params.tp_gmt_offset || et.tm_params.tp_dst_offset) { - if (debug_mode) printf("ERROR: UTC has nonzero gmt or dst offset.\n"); - else failed_already=1; - return 1; + if (debug_mode) { + printf("ERROR: UTC has nonzero gmt or dst offset.\n"); + } + else { + failed_already=1; + } + return 1; + } + if (debug_mode) { + printf("Current UTC is "); + } + PrintExplodedTime(&et); + if (debug_mode) { + printf("\n"); } - if (debug_mode) printf("Current UTC is "); - PrintExplodedTime(&et); - if (debug_mode) printf("\n"); t2 = PR_ImplodeTime(&et); if (LL_NE(t1, t2)) { - if (debug_mode) printf("ERROR: Explode and implode are NOT inverse.\n"); - else printf("FAIL\n"); - return 1; + if (debug_mode) { + printf("ERROR: Explode and implode are NOT inverse.\n"); + } + else { + printf("FAIL\n"); + } + return 1; } /* Next, try converting to local (US Pacific) time */ PR_ExplodeTime(t1, PR_LocalTimeParameters, &et); - if (debug_mode) printf("Current local time is "); - PrintExplodedTime(&et); - if (debug_mode) printf("\n"); - if (debug_mode) printf("GMT offset is %ld, DST offset is %ld\n", - et.tm_params.tp_gmt_offset, et.tm_params.tp_dst_offset); + if (debug_mode) { + printf("Current local time is "); + } + PrintExplodedTime(&et); + if (debug_mode) { + printf("\n"); + } + if (debug_mode) printf("GMT offset is %ld, DST offset is %ld\n", + et.tm_params.tp_gmt_offset, et.tm_params.tp_dst_offset); t2 = PR_ImplodeTime(&et); if (LL_NE(t1, t2)) { - if (debug_mode) printf("ERROR: Explode and implode are NOT inverse.\n"); - return 1; - } + if (debug_mode) { + printf("ERROR: Explode and implode are NOT inverse.\n"); + } + return 1; + } - if (debug_mode) printf("Please examine the results\n"); - testParseTimeString(t1); + if (debug_mode) { + printf("Please examine the results\n"); + } + testParseTimeString(t1); } @@ -255,36 +289,44 @@ int main(int argc, char** argv) /* July 4, 2001 is Wednesday */ { - PRExplodedTime et; - - if (debug_mode) { - printf("\n"); - printf("**********************************\n"); - printf("** **\n"); - printf("** Testing PR_NormalizeTime() **\n"); - printf("** **\n"); - printf("**********************************\n\n"); - } + PRExplodedTime et; + + if (debug_mode) { + printf("\n"); + printf("**********************************\n"); + printf("** **\n"); + printf("** Testing PR_NormalizeTime() **\n"); + printf("** **\n"); + printf("**********************************\n\n"); + } et.tm_year = 2001; et.tm_month = 7 - 1; et.tm_mday = 4; et.tm_hour = 0; et.tm_min = 0; et.tm_sec = 0; - et.tm_usec = 0; + et.tm_usec = 0; et.tm_params = PR_GMTParameters(&et); - PR_NormalizeTime(&et, PR_GMTParameters); + PR_NormalizeTime(&et, PR_GMTParameters); - if (debug_mode) printf("July 4, 2001 is %s.\n", dayOfWeek[et.tm_wday]); - if (et.tm_wday == 3) { - if (debug_mode) printf("PASS\n"); + if (debug_mode) { + printf("July 4, 2001 is %s.\n", dayOfWeek[et.tm_wday]); + } + if (et.tm_wday == 3) { + if (debug_mode) { + printf("PASS\n"); + } } else { - if (debug_mode) printf("ERROR: It should be Wednesday\n"); - else failed_already=1; - return 1; - } - testParseTimeString(PR_ImplodeTime(&et)); + if (debug_mode) { + printf("ERROR: It should be Wednesday\n"); + } + else { + failed_already=1; + } + return 1; + } + testParseTimeString(PR_ImplodeTime(&et)); /* June 12, 1997 23:00 PST == June 13, 1997 00:00 PDT */ et.tm_year = 1997; @@ -293,25 +335,33 @@ int main(int argc, char** argv) et.tm_hour = 23; et.tm_min = 0; et.tm_sec = 0; - et.tm_usec = 0; + et.tm_usec = 0; et.tm_params.tp_gmt_offset = -8 * 3600; - et.tm_params.tp_dst_offset = 0; + et.tm_params.tp_dst_offset = 0; - PR_NormalizeTime(&et, PR_USPacificTimeParameters); + PR_NormalizeTime(&et, PR_USPacificTimeParameters); - if (debug_mode) { - printf("Thu Jun 12, 1997 23:00:00 PST is "); - } - PrintExplodedTime(&et); - if (debug_mode) printf(".\n"); - if (et.tm_wday == 5) { - if (debug_mode) printf("PASS\n"); + if (debug_mode) { + printf("Thu Jun 12, 1997 23:00:00 PST is "); + } + PrintExplodedTime(&et); + if (debug_mode) { + printf(".\n"); + } + if (et.tm_wday == 5) { + if (debug_mode) { + printf("PASS\n"); + } } else { - if (debug_mode) printf("ERROR: It should be Friday\n"); - else failed_already=1; - return 1; - } - testParseTimeString(PR_ImplodeTime(&et)); + if (debug_mode) { + printf("ERROR: It should be Friday\n"); + } + else { + failed_already=1; + } + return 1; + } + testParseTimeString(PR_ImplodeTime(&et)); /* Feb 14, 1997 00:00:00 PDT == Feb 13, 1997 23:00:00 PST */ et.tm_year = 1997; @@ -320,25 +370,33 @@ int main(int argc, char** argv) et.tm_hour = 0; et.tm_min = 0; et.tm_sec = 0; - et.tm_usec = 0; + et.tm_usec = 0; et.tm_params.tp_gmt_offset = -8 * 3600; - et.tm_params.tp_dst_offset = 3600; + et.tm_params.tp_dst_offset = 3600; - PR_NormalizeTime(&et, PR_USPacificTimeParameters); + PR_NormalizeTime(&et, PR_USPacificTimeParameters); - if (debug_mode) { - printf("Fri Feb 14, 1997 00:00:00 PDT is "); - } - PrintExplodedTime(&et); - if (debug_mode) printf(".\n"); - if (et.tm_wday == 4) { - if (debug_mode) printf("PASS\n"); + if (debug_mode) { + printf("Fri Feb 14, 1997 00:00:00 PDT is "); + } + PrintExplodedTime(&et); + if (debug_mode) { + printf(".\n"); + } + if (et.tm_wday == 4) { + if (debug_mode) { + printf("PASS\n"); + } } else { - if (debug_mode) printf("ERROR: It should be Thursday\n"); - else failed_already=1; - return 1; - } - testParseTimeString(PR_ImplodeTime(&et)); + if (debug_mode) { + printf("ERROR: It should be Thursday\n"); + } + else { + failed_already=1; + } + return 1; + } + testParseTimeString(PR_ImplodeTime(&et)); /* What time is Nov. 7, 1996, 18:29:23 PDT? */ et.tm_year = 1996; @@ -347,15 +405,19 @@ int main(int argc, char** argv) et.tm_hour = 18; et.tm_min = 29; et.tm_sec = 23; - et.tm_usec = 0; + et.tm_usec = 0; et.tm_params.tp_gmt_offset = -8 * 3600; /* PDT */ - et.tm_params.tp_dst_offset = 3600; + et.tm_params.tp_dst_offset = 3600; - PR_NormalizeTime(&et, PR_LocalTimeParameters); - if (debug_mode) printf("Nov 7 18:29:23 PDT 1996 is "); - PrintExplodedTime(&et); - if (debug_mode) printf(".\n"); - testParseTimeString(PR_ImplodeTime(&et)); + PR_NormalizeTime(&et, PR_LocalTimeParameters); + if (debug_mode) { + printf("Nov 7 18:29:23 PDT 1996 is "); + } + PrintExplodedTime(&et); + if (debug_mode) { + printf(".\n"); + } + testParseTimeString(PR_ImplodeTime(&et)); /* What time is Oct. 7, 1995, 18:29:23 PST? */ et.tm_year = 1995; @@ -365,15 +427,21 @@ int main(int argc, char** argv) et.tm_min = 29; et.tm_sec = 23; et.tm_params.tp_gmt_offset = -8 * 3600; /* PST */ - et.tm_params.tp_dst_offset = 0; + et.tm_params.tp_dst_offset = 0; - PR_NormalizeTime(&et, PR_LocalTimeParameters); - if (debug_mode) printf("Oct 7 18:29:23 PST 1995 is "); - PrintExplodedTime(&et); - if (debug_mode) printf(".\n"); - testParseTimeString(PR_ImplodeTime(&et)); + PR_NormalizeTime(&et, PR_LocalTimeParameters); + if (debug_mode) { + printf("Oct 7 18:29:23 PST 1995 is "); + } + PrintExplodedTime(&et); + if (debug_mode) { + printf(".\n"); + } + testParseTimeString(PR_ImplodeTime(&et)); - if (debug_mode) printf("Please examine the results\n"); + if (debug_mode) { + printf("Please examine the results\n"); + } } /* @@ -385,74 +453,82 @@ int main(int argc, char** argv) */ { - PRExplodedTime et1, et2; - PRTime ttt; - PRTime secs; - - if (debug_mode) { - printf("\n"); - printf("***************************************\n"); - printf("** **\n"); - printf("** Testing range of years **\n"); - printf("** **\n"); - printf("***************************************\n\n"); - } - /* April 4, 1917 GMT */ - et1.tm_usec = 0; - et1.tm_sec = 0; - et1.tm_min = 0; - et1.tm_hour = 0; - et1.tm_mday = 4; - et1.tm_month = 4 - 1; - et1.tm_year = 1917; - et1.tm_params = PR_GMTParameters(&et1); - PR_NormalizeTime(&et1, PR_LocalTimeParameters); - secs = PR_ImplodeTime(&et1); - if (LL_GE_ZERO(secs)) { - if (debug_mode) - printf("ERROR: April 4, 1917 GMT returns a nonnegative second count\n"); - failed_already = 1; - return 1; - } - PR_ExplodeTime(secs, PR_LocalTimeParameters, &et2); - if (!ExplodedTimeIsEqual(&et1, &et2)) { - if (debug_mode) - printf("ERROR: PR_ImplodeTime and PR_ExplodeTime are not inverse for April 4, 1917 GMT\n"); - failed_already=1; - return 1; - } - ttt = PR_ImplodeTime(&et1); - testParseTimeString( ttt ); - - if (debug_mode) printf("Test passed for April 4, 1917\n"); - - /* July 4, 2050 */ - et1.tm_usec = 0; - et1.tm_sec = 0; - et1.tm_min = 0; - et1.tm_hour = 0; - et1.tm_mday = 4; - et1.tm_month = 7 - 1; - et1.tm_year = 2050; - et1.tm_params = PR_GMTParameters(&et1); - PR_NormalizeTime(&et1, PR_LocalTimeParameters); - secs = PR_ImplodeTime(&et1); - if (!LL_GE_ZERO(secs)) { - if (debug_mode) - printf("ERROR: July 4, 2050 GMT returns a negative second count\n"); - failed_already = 1; - return 1; - } - PR_ExplodeTime(secs, PR_LocalTimeParameters, &et2); - if (!ExplodedTimeIsEqual(&et1, &et2)) { - if (debug_mode) - printf("ERROR: PR_ImplodeTime and PR_ExplodeTime are not inverse for July 4, 2050 GMT\n"); - failed_already=1; - return 1; - } - testParseTimeString(PR_ImplodeTime(&et1)); - - if (debug_mode) printf("Test passed for July 4, 2050\n"); + PRExplodedTime et1, et2; + PRTime ttt; + PRTime secs; + + if (debug_mode) { + printf("\n"); + printf("***************************************\n"); + printf("** **\n"); + printf("** Testing range of years **\n"); + printf("** **\n"); + printf("***************************************\n\n"); + } + /* April 4, 1917 GMT */ + et1.tm_usec = 0; + et1.tm_sec = 0; + et1.tm_min = 0; + et1.tm_hour = 0; + et1.tm_mday = 4; + et1.tm_month = 4 - 1; + et1.tm_year = 1917; + et1.tm_params = PR_GMTParameters(&et1); + PR_NormalizeTime(&et1, PR_LocalTimeParameters); + secs = PR_ImplodeTime(&et1); + if (LL_GE_ZERO(secs)) { + if (debug_mode) { + printf("ERROR: April 4, 1917 GMT returns a nonnegative second count\n"); + } + failed_already = 1; + return 1; + } + PR_ExplodeTime(secs, PR_LocalTimeParameters, &et2); + if (!ExplodedTimeIsEqual(&et1, &et2)) { + if (debug_mode) { + printf("ERROR: PR_ImplodeTime and PR_ExplodeTime are not inverse for April 4, 1917 GMT\n"); + } + failed_already=1; + return 1; + } + ttt = PR_ImplodeTime(&et1); + testParseTimeString( ttt ); + + if (debug_mode) { + printf("Test passed for April 4, 1917\n"); + } + + /* July 4, 2050 */ + et1.tm_usec = 0; + et1.tm_sec = 0; + et1.tm_min = 0; + et1.tm_hour = 0; + et1.tm_mday = 4; + et1.tm_month = 7 - 1; + et1.tm_year = 2050; + et1.tm_params = PR_GMTParameters(&et1); + PR_NormalizeTime(&et1, PR_LocalTimeParameters); + secs = PR_ImplodeTime(&et1); + if (!LL_GE_ZERO(secs)) { + if (debug_mode) { + printf("ERROR: July 4, 2050 GMT returns a negative second count\n"); + } + failed_already = 1; + return 1; + } + PR_ExplodeTime(secs, PR_LocalTimeParameters, &et2); + if (!ExplodedTimeIsEqual(&et1, &et2)) { + if (debug_mode) { + printf("ERROR: PR_ImplodeTime and PR_ExplodeTime are not inverse for July 4, 2050 GMT\n"); + } + failed_already=1; + return 1; + } + testParseTimeString(PR_ImplodeTime(&et1)); + + if (debug_mode) { + printf("Test passed for July 4, 2050\n"); + } } @@ -469,271 +545,279 @@ int main(int argc, char** argv) */ { - PRExplodedTime et, et1, et2; - PRInt64 usecPer10Min; - int day, hour, min; - PRTime usecs; - int dstInEffect = 0; - - if (debug_mode) { - printf("\n"); - printf("*******************************************************\n"); - printf("** **\n"); - printf("** Stress test Pacific Time **\n"); - printf("** Starting from midnight Jan. 1, 2005 PST, **\n"); - printf("** going through four years in 10-minute increment **\n"); - printf("** **\n"); - printf("*******************************************************\n\n"); - } - LL_I2L(usecPer10Min, 600000000L); - - /* 00:00:00 PST Jan. 1, 2005 */ - et.tm_usec = 0; - et.tm_sec = 0; - et.tm_min = 0; - et.tm_hour = 0; - et.tm_mday = 1; - et.tm_month = 0; - et.tm_year = 2005; - et.tm_params.tp_gmt_offset = -8 * 3600; - et.tm_params.tp_dst_offset = 0; - usecs = PR_ImplodeTime(&et); + PRExplodedTime et, et1, et2; + PRInt64 usecPer10Min; + int day, hour, min; + PRTime usecs; + int dstInEffect = 0; + + if (debug_mode) { + printf("\n"); + printf("*******************************************************\n"); + printf("** **\n"); + printf("** Stress test Pacific Time **\n"); + printf("** Starting from midnight Jan. 1, 2005 PST, **\n"); + printf("** going through four years in 10-minute increment **\n"); + printf("** **\n"); + printf("*******************************************************\n\n"); + } + LL_I2L(usecPer10Min, 600000000L); + + /* 00:00:00 PST Jan. 1, 2005 */ + et.tm_usec = 0; + et.tm_sec = 0; + et.tm_min = 0; + et.tm_hour = 0; + et.tm_mday = 1; + et.tm_month = 0; + et.tm_year = 2005; + et.tm_params.tp_gmt_offset = -8 * 3600; + et.tm_params.tp_dst_offset = 0; + usecs = PR_ImplodeTime(&et); for (day = 0; day < 4 * 365 + 1; day++) { - for (hour = 0; hour < 24; hour++) { - for (min = 0; min < 60; min += 10) { - LL_ADD(usecs, usecs, usecPer10Min); - PR_ExplodeTime(usecs, PR_USPacificTimeParameters, &et1); - - et2 = et; - et2.tm_usec += 600000000L; - PR_NormalizeTime(&et2, PR_USPacificTimeParameters); - - if (!ExplodedTimeIsEqual(&et1, &et2)) { - printf("ERROR: componentwise comparison failed\n"); - PrintExplodedTime(&et1); - printf("\n"); - PrintExplodedTime(&et2); - printf("\n"); - failed_already=1; - return 1; - } - - if (LL_NE(usecs, PR_ImplodeTime(&et1))) { - printf("ERROR: PR_ExplodeTime and PR_ImplodeTime are not inverse\n"); - PrintExplodedTime(&et1); - printf("\n"); - failed_already=1; - return 1; - } - testParseTimeString(usecs); - - if (!dstInEffect && et1.tm_params.tp_dst_offset) { - dstInEffect = 1; - if (debug_mode) { - printf("DST changeover from "); - PrintExplodedTime(&et); - printf(" to "); - PrintExplodedTime(&et1); - printf(".\n"); - } + for (hour = 0; hour < 24; hour++) { + for (min = 0; min < 60; min += 10) { + LL_ADD(usecs, usecs, usecPer10Min); + PR_ExplodeTime(usecs, PR_USPacificTimeParameters, &et1); + + et2 = et; + et2.tm_usec += 600000000L; + PR_NormalizeTime(&et2, PR_USPacificTimeParameters); + + if (!ExplodedTimeIsEqual(&et1, &et2)) { + printf("ERROR: componentwise comparison failed\n"); + PrintExplodedTime(&et1); + printf("\n"); + PrintExplodedTime(&et2); + printf("\n"); + failed_already=1; + return 1; + } + + if (LL_NE(usecs, PR_ImplodeTime(&et1))) { + printf("ERROR: PR_ExplodeTime and PR_ImplodeTime are not inverse\n"); + PrintExplodedTime(&et1); + printf("\n"); + failed_already=1; + return 1; + } + testParseTimeString(usecs); + + if (!dstInEffect && et1.tm_params.tp_dst_offset) { + dstInEffect = 1; + if (debug_mode) { + printf("DST changeover from "); + PrintExplodedTime(&et); + printf(" to "); + PrintExplodedTime(&et1); + printf(".\n"); + } } else if (dstInEffect && !et1.tm_params.tp_dst_offset) { - dstInEffect = 0; - if (debug_mode) { - printf("DST changeover from "); - PrintExplodedTime(&et); - printf(" to "); - PrintExplodedTime(&et1); - printf(".\n"); - } + dstInEffect = 0; + if (debug_mode) { + printf("DST changeover from "); + PrintExplodedTime(&et); + printf(" to "); + PrintExplodedTime(&et1); + printf(".\n"); + } } - et = et1; - } - } + et = et1; + } + } + } + if (debug_mode) { + printf("Test passed\n"); } - if (debug_mode) printf("Test passed\n"); } /* Same stress test, but with PR_LocalTimeParameters */ { - PRExplodedTime et, et1, et2; - PRInt64 usecPer10Min; - int day, hour, min; - PRTime usecs; - int dstInEffect = 0; - - if (debug_mode) { - printf("\n"); - printf("*******************************************************\n"); - printf("** **\n"); - printf("** Stress test Local Time **\n"); - printf("** Starting from midnight Jan. 1, 2005 PST, **\n"); - printf("** going through four years in 10-minute increment **\n"); - printf("** **\n"); - printf("*******************************************************\n\n"); - } - - LL_I2L(usecPer10Min, 600000000L); - - /* 00:00:00 PST Jan. 1, 2005 */ - et.tm_usec = 0; - et.tm_sec = 0; - et.tm_min = 0; - et.tm_hour = 0; - et.tm_mday = 1; - et.tm_month = 0; - et.tm_year = 2005; - et.tm_params.tp_gmt_offset = -8 * 3600; - et.tm_params.tp_dst_offset = 0; - usecs = PR_ImplodeTime(&et); + PRExplodedTime et, et1, et2; + PRInt64 usecPer10Min; + int day, hour, min; + PRTime usecs; + int dstInEffect = 0; + + if (debug_mode) { + printf("\n"); + printf("*******************************************************\n"); + printf("** **\n"); + printf("** Stress test Local Time **\n"); + printf("** Starting from midnight Jan. 1, 2005 PST, **\n"); + printf("** going through four years in 10-minute increment **\n"); + printf("** **\n"); + printf("*******************************************************\n\n"); + } + + LL_I2L(usecPer10Min, 600000000L); + + /* 00:00:00 PST Jan. 1, 2005 */ + et.tm_usec = 0; + et.tm_sec = 0; + et.tm_min = 0; + et.tm_hour = 0; + et.tm_mday = 1; + et.tm_month = 0; + et.tm_year = 2005; + et.tm_params.tp_gmt_offset = -8 * 3600; + et.tm_params.tp_dst_offset = 0; + usecs = PR_ImplodeTime(&et); for (day = 0; day < 4 * 365 + 1; day++) { - for (hour = 0; hour < 24; hour++) { - for (min = 0; min < 60; min += 10) { - LL_ADD(usecs, usecs, usecPer10Min); - PR_ExplodeTime(usecs, PR_LocalTimeParameters, &et1); - - et2 = et; - et2.tm_usec += 600000000L; - PR_NormalizeTime(&et2, PR_LocalTimeParameters); - - if (!ExplodedTimeIsEqual(&et1, &et2)) { - printf("ERROR: componentwise comparison failed\n"); - PrintExplodedTime(&et1); - printf("\n"); - PrintExplodedTime(&et2); - printf("\n"); - return 1; - } - - if (LL_NE(usecs, PR_ImplodeTime(&et1))) { + for (hour = 0; hour < 24; hour++) { + for (min = 0; min < 60; min += 10) { + LL_ADD(usecs, usecs, usecPer10Min); + PR_ExplodeTime(usecs, PR_LocalTimeParameters, &et1); + + et2 = et; + et2.tm_usec += 600000000L; + PR_NormalizeTime(&et2, PR_LocalTimeParameters); + + if (!ExplodedTimeIsEqual(&et1, &et2)) { + printf("ERROR: componentwise comparison failed\n"); + PrintExplodedTime(&et1); + printf("\n"); + PrintExplodedTime(&et2); + printf("\n"); + return 1; + } + + if (LL_NE(usecs, PR_ImplodeTime(&et1))) { printf("ERROR: PR_ExplodeTime and PR_ImplodeTime are not inverse\n"); - PrintExplodedTime(&et1); - printf("\n"); - failed_already=1; - return 1; - } - testParseTimeString(usecs); - - if (!dstInEffect && et1.tm_params.tp_dst_offset) { - dstInEffect = 1; - if (debug_mode) { - printf("DST changeover from "); - PrintExplodedTime(&et); - printf(" to "); - PrintExplodedTime(&et1); - printf(".\n"); - } + PrintExplodedTime(&et1); + printf("\n"); + failed_already=1; + return 1; + } + testParseTimeString(usecs); + + if (!dstInEffect && et1.tm_params.tp_dst_offset) { + dstInEffect = 1; + if (debug_mode) { + printf("DST changeover from "); + PrintExplodedTime(&et); + printf(" to "); + PrintExplodedTime(&et1); + printf(".\n"); + } } else if (dstInEffect && !et1.tm_params.tp_dst_offset) { - dstInEffect = 0; - if (debug_mode) { - printf("DST changeover from "); - PrintExplodedTime(&et); - printf(" to "); - PrintExplodedTime(&et1); - printf(".\n"); - } + dstInEffect = 0; + if (debug_mode) { + printf("DST changeover from "); + PrintExplodedTime(&et); + printf(" to "); + PrintExplodedTime(&et1); + printf(".\n"); + } } - et = et1; - } - } + et = et1; + } + } + } + if (debug_mode) { + printf("Test passed\n"); } - if (debug_mode) printf("Test passed\n"); } /* Same stress test, but with PR_LocalTimeParameters and going backward */ { - PRExplodedTime et, et1, et2; - PRInt64 usecPer10Min; - int day, hour, min; - PRTime usecs; - int dstInEffect = 0; - - if (debug_mode) { - printf("\n"); - printf("*******************************************************\n"); - printf("** **\n"); - printf("** Stress test Local Time **\n"); - printf("** Starting from midnight Jan. 1, 2009 PST, **\n"); - printf("** going back four years in 10-minute increment **\n"); - printf("** **\n"); - printf("*******************************************************\n\n"); - } - - LL_I2L(usecPer10Min, 600000000L); - - /* 00:00:00 PST Jan. 1, 2009 */ - et.tm_usec = 0; - et.tm_sec = 0; - et.tm_min = 0; - et.tm_hour = 0; - et.tm_mday = 1; - et.tm_month = 0; - et.tm_year = 2009; - et.tm_params.tp_gmt_offset = -8 * 3600; - et.tm_params.tp_dst_offset = 0; - usecs = PR_ImplodeTime(&et); + PRExplodedTime et, et1, et2; + PRInt64 usecPer10Min; + int day, hour, min; + PRTime usecs; + int dstInEffect = 0; + + if (debug_mode) { + printf("\n"); + printf("*******************************************************\n"); + printf("** **\n"); + printf("** Stress test Local Time **\n"); + printf("** Starting from midnight Jan. 1, 2009 PST, **\n"); + printf("** going back four years in 10-minute increment **\n"); + printf("** **\n"); + printf("*******************************************************\n\n"); + } + + LL_I2L(usecPer10Min, 600000000L); + + /* 00:00:00 PST Jan. 1, 2009 */ + et.tm_usec = 0; + et.tm_sec = 0; + et.tm_min = 0; + et.tm_hour = 0; + et.tm_mday = 1; + et.tm_month = 0; + et.tm_year = 2009; + et.tm_params.tp_gmt_offset = -8 * 3600; + et.tm_params.tp_dst_offset = 0; + usecs = PR_ImplodeTime(&et); for (day = 0; day < 4 * 365 + 1; day++) { - for (hour = 0; hour < 24; hour++) { - for (min = 0; min < 60; min += 10) { - LL_SUB(usecs, usecs, usecPer10Min); - PR_ExplodeTime(usecs, PR_LocalTimeParameters, &et1); - - et2 = et; - et2.tm_usec -= 600000000L; - PR_NormalizeTime(&et2, PR_LocalTimeParameters); - - if (!ExplodedTimeIsEqual(&et1, &et2)) { - printf("ERROR: componentwise comparison failed\n"); - PrintExplodedTime(&et1); - printf("\n"); - PrintExplodedTime(&et2); - printf("\n"); - return 1; - } - - if (LL_NE(usecs, PR_ImplodeTime(&et1))) { - printf("ERROR: PR_ExplodeTime and PR_ImplodeTime are not inverse\n"); - PrintExplodedTime(&et1); - printf("\n"); - failed_already=1; - return 1; - } - testParseTimeString(usecs); - - if (!dstInEffect && et1.tm_params.tp_dst_offset) { - dstInEffect = 1; - if (debug_mode) { - printf("DST changeover from "); - PrintExplodedTime(&et); - printf(" to "); - PrintExplodedTime(&et1); - printf(".\n"); - } + for (hour = 0; hour < 24; hour++) { + for (min = 0; min < 60; min += 10) { + LL_SUB(usecs, usecs, usecPer10Min); + PR_ExplodeTime(usecs, PR_LocalTimeParameters, &et1); + + et2 = et; + et2.tm_usec -= 600000000L; + PR_NormalizeTime(&et2, PR_LocalTimeParameters); + + if (!ExplodedTimeIsEqual(&et1, &et2)) { + printf("ERROR: componentwise comparison failed\n"); + PrintExplodedTime(&et1); + printf("\n"); + PrintExplodedTime(&et2); + printf("\n"); + return 1; + } + + if (LL_NE(usecs, PR_ImplodeTime(&et1))) { + printf("ERROR: PR_ExplodeTime and PR_ImplodeTime are not inverse\n"); + PrintExplodedTime(&et1); + printf("\n"); + failed_already=1; + return 1; + } + testParseTimeString(usecs); + + if (!dstInEffect && et1.tm_params.tp_dst_offset) { + dstInEffect = 1; + if (debug_mode) { + printf("DST changeover from "); + PrintExplodedTime(&et); + printf(" to "); + PrintExplodedTime(&et1); + printf(".\n"); + } } else if (dstInEffect && !et1.tm_params.tp_dst_offset) { - dstInEffect = 0; - if (debug_mode) { - printf("DST changeover from "); - PrintExplodedTime(&et); - printf(" to "); - PrintExplodedTime(&et1); - printf(".\n"); - } + dstInEffect = 0; + if (debug_mode) { + printf("DST changeover from "); + PrintExplodedTime(&et); + printf(" to "); + PrintExplodedTime(&et1); + printf(".\n"); + } } - et = et1; - } - } + et = et1; + } + } } } - if (failed_already) return 1; - else return 0; + if (failed_already) { + return 1; + } + else { + return 0; + } } diff --git a/nsprpub/pr/tests/tmoacc.c b/nsprpub/pr/tests/tmoacc.c index 12c39c912..a4d14daaa 100644 --- a/nsprpub/pr/tests/tmoacc.c +++ b/nsprpub/pr/tests/tmoacc.c @@ -54,45 +54,54 @@ static void Accept(void *arg) PRInt32 recv_length = 0, flags = 0; PRFileDesc *clientSock; PRIntn toread, byte, bytes, loop = 0; - struct Descriptor { PRInt32 length; PRUint32 checksum; } descriptor; + struct Descriptor { + PRInt32 length; + PRUint32 checksum; + } descriptor; do { PRUint32 checksum = 0; - if (NULL != shared->debug) + if (NULL != shared->debug) { PR_fprintf(shared->debug, "[%d]accepting ... ", loop++); + } clientSock = PR_Accept( - shared->listenSock, &clientAddr, Timeout(shared)); + shared->listenSock, &clientAddr, Timeout(shared)); if (clientSock != NULL) { - if (NULL != shared->debug) + if (NULL != shared->debug) { PR_fprintf(shared->debug, "reading length ... "); + } bytes = PR_Recv( - clientSock, &descriptor, sizeof(descriptor), - flags, Timeout(shared)); + clientSock, &descriptor, sizeof(descriptor), + flags, Timeout(shared)); if (sizeof(descriptor) == bytes) { /* and, before doing something stupid ... */ descriptor.length = PR_ntohl(descriptor.length); descriptor.checksum = PR_ntohl(descriptor.checksum); - if (NULL != shared->debug) + if (NULL != shared->debug) { PR_fprintf(shared->debug, "%d bytes ... ", descriptor.length); + } toread = descriptor.length; if (recv_length < descriptor.length) { - if (NULL != buffer) PR_DELETE(buffer); + if (NULL != buffer) { + PR_DELETE(buffer); + } buffer = (char*)PR_MALLOC(descriptor.length); recv_length = descriptor.length; } for (toread = descriptor.length; toread > 0; toread -= bytes) { bytes = PR_Recv( - clientSock, &buffer[descriptor.length - toread], - toread, flags, Timeout(shared)); + clientSock, &buffer[descriptor.length - toread], + toread, flags, Timeout(shared)); if (-1 == bytes) { - if (NULL != shared->debug) + if (NULL != shared->debug) { PR_fprintf(shared->debug, "read data failed..."); + } bytes = 0; } } @@ -102,8 +111,9 @@ static void Accept(void *arg) PR_fprintf(shared->debug, "read desciptor failed..."); descriptor.length = -1; } - if (NULL != shared->debug) + if (NULL != shared->debug) { PR_fprintf(shared->debug, "closing"); + } rv = PR_Shutdown(clientSock, PR_SHUTDOWN_BOTH); if ((PR_FAILURE == rv) && (NULL != shared->debug)) { @@ -112,17 +122,19 @@ static void Accept(void *arg) } rv = PR_Close(clientSock); if (PR_FAILURE == rv) if (NULL != shared->debug) - { - PR_fprintf(shared->debug, " failed"); - shared->passed = PR_FALSE; - } + { + PR_fprintf(shared->debug, " failed"); + shared->passed = PR_FALSE; + } if (descriptor.length > 0) { for (byte = 0; byte < descriptor.length; ++byte) { PRUint32 overflow = checksum & 0x80000000; checksum = (checksum << 1); - if (0x00000000 != overflow) checksum += 1; + if (0x00000000 != overflow) { + checksum += 1; + } checksum += buffer[byte]; } if ((descriptor.checksum != checksum) && (NULL != shared->debug)) @@ -138,19 +150,24 @@ static void Accept(void *arg) PR_NotifyCondVar(shared->cv); PR_Unlock(shared->ml); } - if (NULL != shared->debug) + if (NULL != shared->debug) { PR_fprintf(shared->debug, "\n"); + } } else { if (PR_PENDING_INTERRUPT_ERROR != PR_GetError()) { - if (NULL != shared->debug) PL_PrintError("Accept"); + if (NULL != shared->debug) { + PL_PrintError("Accept"); + } shared->passed = PR_FALSE; } - } + } } while (running == shared->status); - if (NULL != buffer) PR_DELETE(buffer); + if (NULL != buffer) { + PR_DELETE(buffer); + } } /* Accept */ PRIntn Tmoacc(PRIntn argc, char **argv) @@ -158,9 +175,9 @@ PRIntn Tmoacc(PRIntn argc, char **argv) PRStatus rv; PRIntn exitStatus; PRIntn index; - Shared *shared; - PLOptStatus os; - PRThread **thread; + Shared *shared; + PLOptStatus os; + PRThread **thread; PRNetAddr listenAddr; PRSocketOptionData sockOpt; PRIntn timeout = DEFAULT_TIMEOUT; @@ -168,7 +185,7 @@ PRIntn Tmoacc(PRIntn argc, char **argv) PRIntn backlog = DEFAULT_BACKLOG; PRThreadScope thread_scope = PR_LOCAL_THREAD; - PLOptState *opt = PL_CreateOptState(argc, argv, "dGb:t:T:R"); + PLOptState *opt = PL_CreateOptState(argc, argv, "dGb:t:T:R"); shared = PR_NEWZAP(Shared); @@ -179,38 +196,46 @@ PRIntn Tmoacc(PRIntn argc, char **argv) shared->ml = PR_NewLock(); shared->cv = PR_NewCondVar(shared->ml); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - shared->debug = PR_GetSpecialFD(PR_StandardError); - break; - case 'G': /* use global threads */ - thread_scope = PR_GLOBAL_THREAD; - break; - case 'b': /* size of listen backlog */ - backlog = atoi(opt->value); - break; - case 't': /* number of threads doing accept */ - threads = atoi(opt->value); - break; - case 'T': /* timeout used for network operations */ - timeout = atoi(opt->value); - break; - case 'R': /* randomize the timeout values */ - shared->random = PR_TRUE; - break; - default: - break; + case 'd': /* debug mode */ + shared->debug = PR_GetSpecialFD(PR_StandardError); + break; + case 'G': /* use global threads */ + thread_scope = PR_GLOBAL_THREAD; + break; + case 'b': /* size of listen backlog */ + backlog = atoi(opt->value); + break; + case 't': /* number of threads doing accept */ + threads = atoi(opt->value); + break; + case 'T': /* timeout used for network operations */ + timeout = atoi(opt->value); + break; + case 'R': /* randomize the timeout values */ + shared->random = PR_TRUE; + break; + default: + break; } } - PL_DestroyOptState(opt); - if (0 == threads) threads = DEFAULT_THREADS; - if (0 == backlog) backlog = DEFAULT_BACKLOG; - if (0 == timeout) timeout = DEFAULT_TIMEOUT; - + PL_DestroyOptState(opt); + if (0 == threads) { + threads = DEFAULT_THREADS; + } + if (0 == backlog) { + backlog = DEFAULT_BACKLOG; + } + if (0 == timeout) { + timeout = DEFAULT_TIMEOUT; + } + PR_STDIO_INIT(); memset(&listenAddr, 0, sizeof(listenAddr)); rv = PR_InitializeNetAddr(PR_IpAddrAny, BASE_PORT, &listenAddr); @@ -236,15 +261,16 @@ PRIntn Tmoacc(PRIntn argc, char **argv) for (index = 0; index < threads; ++index) { thread[index] = PR_CreateThread( - PR_USER_THREAD, Accept, shared, - PR_PRIORITY_NORMAL, thread_scope, - PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, Accept, shared, + PR_PRIORITY_NORMAL, thread_scope, + PR_JOINABLE_THREAD, 0); PR_ASSERT(NULL != thread[index]); } PR_Lock(shared->ml); - while (shared->status == running) + while (shared->status == running) { PR_WaitCondVar(shared->cv, PR_INTERVAL_NO_TIMEOUT); + } PR_Unlock(shared->ml); for (index = 0; index < threads; ++index) { @@ -257,13 +283,17 @@ PRIntn Tmoacc(PRIntn argc, char **argv) } else { - if (shared->debug) PL_PrintError("Listen"); + if (shared->debug) { + PL_PrintError("Listen"); + } shared->passed = PR_FALSE; } } else { - if (shared->debug) PL_PrintError("Bind"); + if (shared->debug) { + PL_PrintError("Bind"); + } shared->passed = PR_FALSE; } @@ -271,7 +301,9 @@ PRIntn Tmoacc(PRIntn argc, char **argv) } else { - if (shared->debug) PL_PrintError("Create"); + if (shared->debug) { + PL_PrintError("Create"); + } shared->passed = PR_FALSE; } @@ -290,7 +322,7 @@ PRIntn Tmoacc(PRIntn argc, char **argv) int main(int argc, char **argv) { return (PR_VersionCheck(PR_VERSION)) ? - PR_Initialize(Tmoacc, argc, argv, 4) : -1; + PR_Initialize(Tmoacc, argc, argv, 4) : -1; } /* main */ /* tmoacc */ diff --git a/nsprpub/pr/tests/tmocon.c b/nsprpub/pr/tests/tmocon.c index 48a72f673..9d214bc5d 100644 --- a/nsprpub/pr/tests/tmocon.c +++ b/nsprpub/pr/tests/tmocon.c @@ -11,10 +11,10 @@ ** ** Modification History: ** 19-May-97 AGarcia- Converted the test to accomodate the debug_mode flag. -** The debug mode will print all of the printfs associated with this test. -** The regress mode will be the default mode. Since the regress tool limits +** The debug mode will print all of the printfs associated with this test. +** The regress mode will be the default mode. Since the regress tool limits ** the output to a one line status:PASS or FAIL,all of the printf statements -** have been handled with an if (debug_mode) statement. +** have been handled with an if (debug_mode) statement. ***********************************************************************/ /*********************************************************************** @@ -34,7 +34,7 @@ #include <string.h> /* for getcwd */ -#if defined(XP_UNIX) || defined (XP_OS2) || defined(XP_BEOS) +#if defined(XP_UNIX) || defined (XP_OS2) #include <unistd.h> #elif defined(XP_PC) #include <direct.h> @@ -87,7 +87,9 @@ static PRIntervalTime Timeout(const Shared *shared) static void CauseTimeout(const Shared *shared) { - if (shared->intermittant) PR_Sleep(Timeout(shared)); + if (shared->intermittant) { + PR_Sleep(Timeout(shared)); + } } /* CauseTimeout */ static PRStatus MakeReceiver(Shared *shared) @@ -110,24 +112,30 @@ static PRStatus MakeReceiver(Shared *shared) argv[1] = "-d"; argv[2] = NULL; } - else argv[1] = NULL; - if (shared->debug > 1) + else { + argv[1] = NULL; + } + if (shared->debug > 1) { PR_fprintf(debug_out, " creating accept process %s ...", path); + } fflush(stdout); rv = PR_CreateProcessDetached(path, argv, NULL, NULL); if (PR_SUCCESS == rv) { - if (shared->debug > 1) + if (shared->debug > 1) { PR_fprintf(debug_out, " wait 5 seconds"); - if (shared->debug > 1) + } + if (shared->debug > 1) { PR_fprintf(debug_out, " before connecting to accept process ..."); + } fflush(stdout); PR_Sleep(PR_SecondsToInterval(5)); return rv; } shared->failed = PR_TRUE; - if (shared->debug > 0) + if (shared->debug > 0) { PL_FPrintError(debug_out, "PR_CreateProcessDetached failed"); + } } return rv; } /* MakeReceiver */ @@ -139,28 +147,35 @@ static void Connect(void *arg) PRFileDesc *clientSock; Shared *shared = (Shared*)arg; PRInt32 loop, bytes, flags = 0; - struct Descriptor { PRInt32 length; PRUint32 checksum; } descriptor; + struct Descriptor { + PRInt32 length; + PRUint32 checksum; + } descriptor; debug_out = (0 == shared->debug) ? NULL : PR_GetSpecialFD(PR_StandardError); buffer = (char*)PR_MALLOC(shared->message_length); - for (bytes = 0; bytes < shared->message_length; ++bytes) + for (bytes = 0; bytes < shared->message_length; ++bytes) { buffer[bytes] = (char)bytes; + } descriptor.checksum = 0; for (bytes = 0; bytes < shared->message_length; ++bytes) { PRUint32 overflow = descriptor.checksum & 0x80000000; descriptor.checksum = (descriptor.checksum << 1); - if (0x00000000 != overflow) descriptor.checksum += 1; + if (0x00000000 != overflow) { + descriptor.checksum += 1; + } descriptor.checksum += buffer[bytes]; } descriptor.checksum = PR_htonl(descriptor.checksum); for (loop = 0; loop < shared->messages; ++loop) { - if (shared->debug > 1) + if (shared->debug > 1) { PR_fprintf(debug_out, "[%d]socket ... ", loop); + } clientSock = PR_NewTCPSocket(); if (clientSock) { @@ -179,58 +194,72 @@ static void Connect(void *arg) PR_fprintf(debug_out, "connecting to %s ... ", buf); } rv = PR_Connect( - clientSock, &shared->serverAddress, Timeout(shared)); + clientSock, &shared->serverAddress, Timeout(shared)); if (PR_SUCCESS == rv) { PRInt32 descriptor_length = (loop < (shared->messages - 1)) ? - shared->message_length : 0; + shared->message_length : 0; descriptor.length = PR_htonl(descriptor_length); if (shared->debug > 1) PR_fprintf( debug_out, "sending %d bytes ... ", descriptor_length); CauseTimeout(shared); /* might cause server to timeout */ bytes = PR_Send( - clientSock, &descriptor, sizeof(descriptor), - flags, Timeout(shared)); + clientSock, &descriptor, sizeof(descriptor), + flags, Timeout(shared)); if (bytes != sizeof(descriptor)) { shared->failed = PR_TRUE; - if (shared->debug > 0) + if (shared->debug > 0) { PL_FPrintError(debug_out, "PR_Send failed"); + } } if (0 != descriptor_length) { CauseTimeout(shared); bytes = PR_Send( - clientSock, buffer, descriptor_length, - flags, Timeout(shared)); + clientSock, buffer, descriptor_length, + flags, Timeout(shared)); if (bytes != descriptor_length) { shared->failed = PR_TRUE; - if (shared->debug > 0) + if (shared->debug > 0) { PL_FPrintError(debug_out, "PR_Send failed"); + } } } - if (shared->debug > 1) PR_fprintf(debug_out, "closing ... "); + if (shared->debug > 1) { + PR_fprintf(debug_out, "closing ... "); + } rv = PR_Shutdown(clientSock, PR_SHUTDOWN_BOTH); rv = PR_Close(clientSock); if (shared->debug > 1) { - if (PR_SUCCESS == rv) PR_fprintf(debug_out, "\n"); - else PL_FPrintError(debug_out, "shutdown failed"); + if (PR_SUCCESS == rv) { + PR_fprintf(debug_out, "\n"); + } + else { + PL_FPrintError(debug_out, "shutdown failed"); + } } } else { - if (shared->debug > 1) PL_FPrintError(debug_out, "connect failed"); + if (shared->debug > 1) { + PL_FPrintError(debug_out, "connect failed"); + } PR_Close(clientSock); if ((loop == 0) && (PR_GetError() == PR_CONNECT_REFUSED_ERROR)) { - if (MakeReceiver(shared) == PR_FAILURE) break; + if (MakeReceiver(shared) == PR_FAILURE) { + break; + } } else { - if (shared->debug > 1) PR_fprintf(debug_out, " exiting\n"); + if (shared->debug > 1) { + PR_fprintf(debug_out, " exiting\n"); + } break; } } @@ -238,7 +267,9 @@ static void Connect(void *arg) else { shared->failed = PR_TRUE; - if (shared->debug > 0) PL_FPrintError(debug_out, "create socket"); + if (shared->debug > 0) { + PL_FPrintError(debug_out, "create socket"); + } break; } } @@ -285,28 +316,34 @@ int Tmocon(int argc, char **argv) memset(&shared->serverAddress, 0, sizeof(shared->serverAddress)); rv = PR_InitializeNetAddr(PR_IpAddrLoopback, BASE_PORT, &shared->serverAddress); PR_ASSERT(PR_SUCCESS == rv); - + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': - if (0 == shared->debug) shared->debug = 1; - break; - case 'v': - if (0 == shared->debug) shared->debug = 2; - break; - case 'i': - shared->intermittant = PR_TRUE; - break; - case 'R': - shared->random = PR_TRUE; - break; - case 'G': - thread_scope = PR_GLOBAL_THREAD; - break; - case 'h': /* the value for backlock */ + case 'd': + if (0 == shared->debug) { + shared->debug = 1; + } + break; + case 'v': + if (0 == shared->debug) { + shared->debug = 2; + } + break; + case 'i': + shared->intermittant = PR_TRUE; + break; + case 'R': + shared->random = PR_TRUE; + break; + case 'G': + thread_scope = PR_GLOBAL_THREAD; + break; + case 'h': /* the value for backlock */ { PRIntn es = 0; PRHostEnt host; @@ -314,35 +351,43 @@ int Tmocon(int argc, char **argv) (void)PR_GetHostByName( opt->value, buffer, sizeof(buffer), &host); es = PR_EnumerateHostEnt( - es, &host, BASE_PORT, &shared->serverAddress); + es, &host, BASE_PORT, &shared->serverAddress); PR_ASSERT(es > 0); } break; - case 'm': /* number of messages to send */ - shared->messages = atoi(opt->value); - break; - case 't': /* number of threads sending */ - threads = atoi(opt->value); - break; - case 'D': /* dally time between transmissions */ - dally = atoi(opt->value); - break; - case 'T': /* timeout on I/O operations */ - timeout = atoi(opt->value); - break; - case 's': /* total size of each message */ - shared->message_length = atoi(opt->value); - break; - default: - break; + case 'm': /* number of messages to send */ + shared->messages = atoi(opt->value); + break; + case 't': /* number of threads sending */ + threads = atoi(opt->value); + break; + case 'D': /* dally time between transmissions */ + dally = atoi(opt->value); + break; + case 'T': /* timeout on I/O operations */ + timeout = atoi(opt->value); + break; + case 's': /* total size of each message */ + shared->message_length = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); - if (0 == timeout) timeout = DEFAULT_TIMEOUT; - if (0 == threads) threads = DEFAULT_THREADS; - if (0 == shared->messages) shared->messages = DEFAULT_MESSAGES; - if (0 == shared->message_length) shared->message_length = DEFAULT_MESSAGESIZE; + if (0 == timeout) { + timeout = DEFAULT_TIMEOUT; + } + if (0 == threads) { + threads = DEFAULT_THREADS; + } + if (0 == shared->messages) { + shared->messages = DEFAULT_MESSAGES; + } + if (0 == shared->message_length) { + shared->message_length = DEFAULT_MESSAGESIZE; + } shared->dally = PR_SecondsToInterval(dally); shared->timeout = PR_SecondsToInterval(timeout); @@ -351,11 +396,12 @@ int Tmocon(int argc, char **argv) for (index = 0; index < threads; ++index) thread[index] = PR_CreateThread( - PR_USER_THREAD, Connect, shared, - PR_PRIORITY_NORMAL, thread_scope, - PR_JOINABLE_THREAD, 0); - for (index = 0; index < threads; ++index) + PR_USER_THREAD, Connect, shared, + PR_PRIORITY_NORMAL, thread_scope, + PR_JOINABLE_THREAD, 0); + for (index = 0; index < threads; ++index) { rv = PR_JoinThread(thread[index]); + } PR_DELETE(thread); @@ -370,7 +416,7 @@ int Tmocon(int argc, char **argv) int main(int argc, char **argv) { return (PR_VersionCheck(PR_VERSION)) ? - PR_Initialize(Tmocon, argc, argv, 4) : -1; + PR_Initialize(Tmocon, argc, argv, 4) : -1; } /* main */ /* tmocon.c */ diff --git a/nsprpub/pr/tests/tpd.c b/nsprpub/pr/tests/tpd.c index eef1a1d80..cac8c59aa 100644 --- a/nsprpub/pr/tests/tpd.c +++ b/nsprpub/pr/tests/tpd.c @@ -36,7 +36,7 @@ static void PrintProgress(PRIntn line) printf( "@ line %d destructor should%s have been called and was%s\n", line, ((should) ? "" : " NOT"), ((did) ? "" : " NOT")); -#else +#else PR_fprintf( fout, "@ line %d destructor should%s have been called and was%s\n", line, ((should) ? "" : " NOT"), ((did) ? "" : " NOT")); @@ -46,8 +46,9 @@ static void PrintProgress(PRIntn line) static void MyAssert(const char *expr, const char *file, PRIntn line) { - if (debug > 0) + if (debug > 0) { (void)PR_fprintf(fout, "'%s' in file: %s: %d\n", expr, file, line); + } } /* MyAssert */ #define MY_ASSERT(_expr) \ @@ -57,8 +58,12 @@ static void MyAssert(const char *expr, const char *file, PRIntn line) static void PR_CALLBACK Destructor(void *data) { MY_ASSERT(NULL != data); - if (should) did = PR_TRUE; - else failed = PR_TRUE; + if (should) { + did = PR_TRUE; + } + else { + failed = PR_TRUE; + } /* * We don't actually free the storage since it's actually allocated * on the stack. Normally, this would not be the case and this is @@ -74,8 +79,9 @@ static void PR_CALLBACK Thread(void *null) PRUintn keys; char *key_string[] = { "Key #0", "Key #1", "Key #2", "Key #3", - "Bogus #5", "Bogus #6", "Bogus #7", "Bogus #8"}; - + "Bogus #5", "Bogus #6", "Bogus #7", "Bogus #8" + }; + did = should = PR_FALSE; for (keys = 0; keys < 8; ++keys) { @@ -99,7 +105,7 @@ static void PR_CALLBACK Thread(void *null) MY_ASSERT(PR_FAILURE == rv); } PrintProgress(__LINE__); - + did = PR_FALSE; should = PR_TRUE; for (keys = 0; keys < 4; ++keys) { @@ -167,8 +173,9 @@ static PRIntn PR_CALLBACK Tpd(PRIntn argc, char **argv) PRThread *thread; char *key_string[] = { "Key #0", "Key #1", "Key #2", "Key #3", - "Bogus #5", "Bogus #6", "Bogus #7", "Bogus #8"}; - + "Bogus #5", "Bogus #6", "Bogus #7", "Bogus #8" + }; + fout = PR_STDOUT; did = should = PR_FALSE; @@ -195,8 +202,9 @@ static PRIntn PR_CALLBACK Tpd(PRIntn argc, char **argv) } PrintProgress(__LINE__); - for (keys = 4; keys < 8; ++keys) - key[keys] = 4096; /* set to invalid value */ + for (keys = 4; keys < 8; ++keys) { + key[keys] = 4096; /* set to invalid value */ + } did = should = PR_FALSE; for (keys = 4; keys < 8; ++keys) { @@ -204,7 +212,7 @@ static PRIntn PR_CALLBACK Tpd(PRIntn argc, char **argv) MY_ASSERT(PR_FAILURE == rv); } PrintProgress(__LINE__); - + did = PR_FALSE; should = PR_TRUE; for (keys = 0; keys < 4; ++keys) { @@ -255,8 +263,8 @@ static PRIntn PR_CALLBACK Tpd(PRIntn argc, char **argv) } thread = PR_CreateThread( - PR_USER_THREAD, Thread, NULL, PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, Thread, NULL, PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); (void)PR_JoinThread(thread); @@ -268,7 +276,7 @@ static PRIntn PR_CALLBACK Tpd(PRIntn argc, char **argv) #else (void)PR_fprintf( fout, "%s\n",((PR_TRUE == failed) ? "FAILED" : "PASSED")); -#endif +#endif return 0; @@ -276,21 +284,23 @@ static PRIntn PR_CALLBACK Tpd(PRIntn argc, char **argv) int main(int argc, char **argv) { - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "dl:r:"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "dl:r:"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug = PR_TRUE; - break; - default: - break; + case 'd': /* debug mode */ + debug = PR_TRUE; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); PR_STDIO_INIT(); return PR_Initialize(Tpd, argc, argv, 0); } /* main */ diff --git a/nsprpub/pr/tests/udpsrv.c b/nsprpub/pr/tests/udpsrv.c index 805bccbbb..39a919c60 100644 --- a/nsprpub/pr/tests/udpsrv.c +++ b/nsprpub/pr/tests/udpsrv.c @@ -22,21 +22,21 @@ ** He detects an EOF condition set by UDP_Client(). For each ** packet received by UDP_Server(), he checks its content for ** expected content, then sends the packet back to UDP_Client(). -** +** ** UDP_Client() sends packets to UDP_Server() using sendto() ** he recieves packets back from the server via recvfrom(). ** After he sends enough packets containing UDP_AMOUNT_TO_WRITE ** bytes of data, he sends an EOF message. -** +** ** The test issues a pass/fail message at end. -** +** ** Notes: ** The variable "_debug_on" can be set to 1 to cause diagnostic ** messages related to client/server synchronization. Useful when ** the test hangs. -** +** ** Error messages are written to stdout. -** +** ******************************************************************** */ /* --- include files --- */ @@ -96,11 +96,11 @@ static PRFileDesc *output = NULL; void ListNetAddr( char *msg, PRNetAddr *na ) { char mbuf[256]; - + sprintf( mbuf, "ListNetAddr: %s family: %d, port: %d, ip: %8.8X\n", - msg, na->inet.family, PR_ntohs( na->inet.port), PR_ntohl(na->inet.ip) ); -#if 0 - DPRINTF( mbuf ); + msg, na->inet.family, PR_ntohs( na->inet.port), PR_ntohl(na->inet.ip) ); +#if 0 + DPRINTF( mbuf ); #endif } /* --- end ListNetAddr() --- */ @@ -127,7 +127,7 @@ static void PR_CALLBACK UDP_Server( void *arg ) PRBool bound = PR_FALSE; PRBool endOfInput = PR_FALSE; PRInt32 numBytes = UDP_DGRAM_SIZE; - + DPRINTF("udpsrv: UDP_Server(): starting\n" ); /* --- Create the socket --- */ @@ -138,16 +138,16 @@ static void PR_CALLBACK UDP_Server( void *arg ) passed = PR_FALSE; if (debug_mode) PR_fprintf(output, - "udpsrv: UDP_Server(): PR_NewUDPSocket() returned NULL\n" ); + "udpsrv: UDP_Server(): PR_NewUDPSocket() returned NULL\n" ); return; } - + /* --- Initialize the sockaddr_in structure --- */ - memset( &netaddr, 0, sizeof( netaddr )); + memset( &netaddr, 0, sizeof( netaddr )); netaddr.inet.family = PR_AF_INET; netaddr.inet.port = PR_htons( UDP_SERVER_PORT ); netaddr.inet.ip = PR_htonl( MY_INADDR ); - + /* --- Bind the socket --- */ while ( !bound ) { @@ -167,16 +167,17 @@ static void PR_CALLBACK UDP_Server( void *arg ) passed = PR_FALSE; if (debug_mode) PR_fprintf(output, "udpsrv: UDP_Server(): \ PR_Bind(): failed: %ld with error: %ld\n", - rv, PR_GetError() ); + rv, PR_GetError() ); PR_Close( svrSock ); return; } } - else + else { bound = PR_TRUE; + } } ListNetAddr( "UDP_Server: after bind", &netaddr ); - + /* --- Recv the socket --- */ while( !endOfInput ) { @@ -187,21 +188,21 @@ static void PR_CALLBACK UDP_Server( void *arg ) passed = PR_FALSE; if (debug_mode) PR_fprintf(output, - "udpsrv: UDP_Server(): PR_RecvFrom(): failed with error: %ld\n", - PR_GetError() ); + "udpsrv: UDP_Server(): PR_RecvFrom(): failed with error: %ld\n", + PR_GetError() ); PR_Close( svrSock ); return; } ListNetAddr( "UDP_Server after RecvFrom", &netaddr ); - + srvBytesRead += rv; - + if ( svrBuf[0] == 'E' ) { DPRINTF("udpsrv: UDP_Server(): EOF on input detected\n" ); endOfInput = PR_TRUE; } - + /* --- Send the socket --- */ DPRINTF("udpsrv: UDP_Server(): SendTo(): socket\n" ); rv = PR_SendTo( svrSock, svrBuf, rv, 0, &netaddr, PR_INTERVAL_NO_TIMEOUT ); @@ -210,14 +211,14 @@ static void PR_CALLBACK UDP_Server( void *arg ) passed = PR_FALSE; if (debug_mode) PR_fprintf(output, - "udpsrv: UDP_Server(): PR_SendTo(): failed with error: %ld\n", - PR_GetError() ); + "udpsrv: UDP_Server(): PR_SendTo(): failed with error: %ld\n", + PR_GetError() ); PR_Close( svrSock ); return; } ListNetAddr( "UDP_Server after SendTo", &netaddr ); } - + /* --- Close the socket --- */ DPRINTF("udpsrv: UDP_Server(): Closing socket\n" ); rv = PR_Close( svrSock ); @@ -226,10 +227,10 @@ static void PR_CALLBACK UDP_Server( void *arg ) passed = PR_FALSE; if (debug_mode) PR_fprintf(output, - "udpsrv: UDP_Server(): PR_Close(): failed to close socket\n" ); + "udpsrv: UDP_Server(): PR_Close(): failed to close socket\n" ); return; } - + DPRINTF("udpsrv: UDP_Server(): Normal end\n" ); } /* --- end UDP_Server() --- */ @@ -264,10 +265,10 @@ static void PR_CALLBACK UDP_Client( void *arg ) PRInt32 numBytes = UDP_DGRAM_SIZE; PRInt32 writeThisMany = UDP_AMOUNT_TO_WRITE; int i; - - + + DPRINTF("udpsrv: UDP_Client(): starting\n" ); - + /* --- Create the socket --- */ cltSock = PR_NewUDPSocket(); if ( cltSock == NULL ) @@ -275,20 +276,21 @@ static void PR_CALLBACK UDP_Client( void *arg ) passed = PR_FALSE; if (debug_mode) PR_fprintf(output, - "udpsrv: UDP_Client(): PR_NewUDPSocket() returned NULL\n" ); + "udpsrv: UDP_Client(): PR_NewUDPSocket() returned NULL\n" ); return; } - + /* --- Initialize the sockaddr_in structure --- */ - memset( &netaddr, 0, sizeof( netaddr )); + memset( &netaddr, 0, sizeof( netaddr )); netaddr.inet.family = PR_AF_INET; netaddr.inet.ip = PR_htonl( MY_INADDR ); netaddr.inet.port = PR_htons( UDP_CLIENT_PORT ); - - /* --- Initialize the write buffer --- */ - for ( i = 0; i < UDP_BUF_SIZE ; i++ ) + + /* --- Initialize the write buffer --- */ + for ( i = 0; i < UDP_BUF_SIZE ; i++ ) { cltBuf[i] = i; - + } + /* --- Bind the socket --- */ while ( !bound ) { @@ -300,7 +302,7 @@ static void PR_CALLBACK UDP_Client( void *arg ) { if (debug_mode) PR_fprintf(output, - "udpsrv: UDP_Client(): PR_Bind(): reports: PR_ADDRESS_IN_USE_ERROR\n"); + "udpsrv: UDP_Client(): PR_Bind(): reports: PR_ADDRESS_IN_USE_ERROR\n"); PR_Sleep( PR_MillisecondsToInterval( 2000 )); continue; } @@ -309,49 +311,52 @@ static void PR_CALLBACK UDP_Client( void *arg ) passed = PR_FALSE; if (debug_mode) PR_fprintf(output, - "udpsrv: UDP_Client(): PR_Bind(): failed: %ld with error: %ld\n", - rv, PR_GetError() ); + "udpsrv: UDP_Client(): PR_Bind(): failed: %ld with error: %ld\n", + rv, PR_GetError() ); PR_Close( cltSock ); return; } } - else + else { bound = PR_TRUE; + } } ListNetAddr( "UDP_Client after Bind", &netaddr ); - + /* --- Initialize the sockaddr_in structure --- */ - memset( &netaddr, 0, sizeof( netaddr )); + memset( &netaddr, 0, sizeof( netaddr )); netaddr.inet.family = PR_AF_INET; netaddr.inet.ip = PR_htonl( PEER_INADDR ); netaddr.inet.port = PR_htons( UDP_SERVER_PORT ); - - /* --- send and receive packets until no more data left */ + + /* --- send and receive packets until no more data left */ while( !endOfInput ) { /* ** Signal EOF in the data stream on the last packet - */ + */ if ( writeThisMany <= UDP_DGRAM_SIZE ) { DPRINTF("udpsrv: UDP_Client(): Send EOF packet\n" ); cltBuf[0] = 'E'; endOfInput = PR_TRUE; } - + /* --- SendTo the socket --- */ - if ( writeThisMany > UDP_DGRAM_SIZE ) + if ( writeThisMany > UDP_DGRAM_SIZE ) { numBytes = UDP_DGRAM_SIZE; - else + } + else { numBytes = writeThisMany; + } writeThisMany -= numBytes; { char mbuf[256]; - sprintf( mbuf, "udpsrv: UDP_Client(): write_this_many: %d, numbytes: %d\n", - writeThisMany, numBytes ); + sprintf( mbuf, "udpsrv: UDP_Client(): write_this_many: %d, numbytes: %d\n", + writeThisMany, numBytes ); DPRINTF( mbuf ); } - + DPRINTF("udpsrv: UDP_Client(): SendTo(): socket\n" ); rv = PR_SendTo( cltSock, cltBuf, numBytes, 0, &netaddr, UDP_TIMEOUT ); if ( rv == -1 ) @@ -359,8 +364,8 @@ static void PR_CALLBACK UDP_Client( void *arg ) passed = PR_FALSE; if (debug_mode) PR_fprintf(output, - "udpsrv: UDP_Client(): PR_SendTo(): failed with error: %ld\n", - PR_GetError() ); + "udpsrv: UDP_Client(): PR_SendTo(): failed with error: %ld\n", + PR_GetError() ); PR_Close( cltSock ); return; } @@ -374,32 +379,35 @@ static void PR_CALLBACK UDP_Client( void *arg ) { passed = PR_FALSE; if (debug_mode) PR_fprintf(output, - "udpsrv: UDP_Client(): PR_RecvFrom(): failed with error: %ld\n", - PR_GetError() ); + "udpsrv: UDP_Client(): PR_RecvFrom(): failed with error: %ld\n", + PR_GetError() ); PR_Close( cltSock ); return; } ListNetAddr( "UDP_Client after RecvFrom()", &netaddr ); cltBytesRead += rv; - + /* --- verify buffer --- */ for ( i = 0; i < rv ; i++ ) { if ( cltBufin[i] != i ) { /* --- special case, end of input --- */ - if ( endOfInput && i == 0 && cltBufin[0] == 'E' ) + if ( endOfInput && i == 0 && cltBufin[0] == 'E' ) { continue; + } passed = PR_FALSE; if (debug_mode) PR_fprintf(output, - "udpsrv: UDP_Client(): return data mismatch\n" ); + "udpsrv: UDP_Client(): return data mismatch\n" ); PR_Close( cltSock ); return; } } - if (debug_mode) PR_fprintf(output, "."); + if (debug_mode) { + PR_fprintf(output, "."); + } } - + /* --- Close the socket --- */ DPRINTF("udpsrv: UDP_Server(): Closing socket\n" ); rv = PR_Close( cltSock ); @@ -407,7 +415,7 @@ static void PR_CALLBACK UDP_Client( void *arg ) { passed = PR_FALSE; if (debug_mode) PR_fprintf(output, - "udpsrv: UDP_Client(): PR_Close(): failed to close socket\n" ); + "udpsrv: UDP_Client(): PR_Close(): failed to close socket\n" ); return; } DPRINTF("udpsrv: UDP_Client(): ending\n" ); @@ -434,97 +442,105 @@ static void PR_CALLBACK UDP_Client( void *arg ) int main(int argc, char **argv) { PRThread *srv, *clt; -/* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d -v - */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "dv"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d -v + */ + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "dv"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = 1; - break; - case 'v': /* verbose mode */ - _debug_on = 1; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = 1; + break; + case 'v': /* verbose mode */ + _debug_on = 1; + break; + default: + break; } } - PL_DestroyOptState(opt); - + PL_DestroyOptState(opt); + PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); PR_STDIO_INIT(); output = PR_STDERR; PR_SetConcurrency(4); - + /* ** Create the Server thread - */ + */ DPRINTF( "udpsrv: Creating Server Thread\n" ); srv = PR_CreateThread( PR_USER_THREAD, - UDP_Server, - (void *) 0, - PR_PRIORITY_LOW, - PR_LOCAL_THREAD, - PR_JOINABLE_THREAD, - 0 ); + UDP_Server, + (void *) 0, + PR_PRIORITY_LOW, + PR_LOCAL_THREAD, + PR_JOINABLE_THREAD, + 0 ); if ( srv == NULL ) { - if (debug_mode) PR_fprintf(output, "udpsrv: Cannot create server thread\n" ); + if (debug_mode) { + PR_fprintf(output, "udpsrv: Cannot create server thread\n" ); + } passed = PR_FALSE; } - + /* ** Give the Server time to Start - */ + */ DPRINTF( "udpsrv: Pausing to allow Server to start\n" ); PR_Sleep( PR_MillisecondsToInterval(200) ); - + /* ** Create the Client thread - */ + */ DPRINTF( "udpsrv: Creating Client Thread\n" ); clt = PR_CreateThread( PR_USER_THREAD, - UDP_Client, - (void *) 0, - PR_PRIORITY_LOW, - PR_LOCAL_THREAD, - PR_JOINABLE_THREAD, - 0 ); + UDP_Client, + (void *) 0, + PR_PRIORITY_LOW, + PR_LOCAL_THREAD, + PR_JOINABLE_THREAD, + 0 ); if ( clt == NULL ) { - if (debug_mode) PR_fprintf(output, "udpsrv: Cannot create server thread\n" ); + if (debug_mode) { + PR_fprintf(output, "udpsrv: Cannot create server thread\n" ); + } passed = PR_FALSE; } - + /* ** */ DPRINTF("udpsrv: Waiting to join Server & Client Threads\n" ); PR_JoinThread( srv ); - PR_JoinThread( clt ); - + PR_JoinThread( clt ); + /* ** Evaluate test results */ if (debug_mode) PR_fprintf(output, "\n\nudpsrv: main(): cltBytesRead(%ld), \ srvBytesRead(%ld), expected(%ld)\n", - cltBytesRead, srvBytesRead, UDP_AMOUNT_TO_WRITE ); + cltBytesRead, srvBytesRead, UDP_AMOUNT_TO_WRITE ); if ( cltBytesRead != srvBytesRead || cltBytesRead != UDP_AMOUNT_TO_WRITE ) { passed = PR_FALSE; } PR_Cleanup(); - if ( passed ) + if ( passed ) { return 0; - else - return 1; + } + else { + return 1; + } } /* --- end main() --- */ diff --git a/nsprpub/pr/tests/vercheck.c b/nsprpub/pr/tests/vercheck.c index 5e6588f9d..6217e97d2 100644 --- a/nsprpub/pr/tests/vercheck.c +++ b/nsprpub/pr/tests/vercheck.c @@ -40,7 +40,8 @@ static char *compatible_version[] = { "4.10", "4.10.1", "4.10.2", "4.10.3", "4.10.4", "4.10.5", "4.10.6", "4.10.7", "4.10.8", "4.10.9", "4.10.10", "4.11", "4.12", "4.13", "4.14", "4.15", - "4.16", "4.17", "4.18", "4.19", + "4.16", "4.17", "4.18", "4.19", "4.20", "4.21", "4.22", + "4.23", PR_VERSION }; @@ -56,8 +57,8 @@ static char *incompatible_version[] = { "3.0", "3.0.1", "3.1", "3.1.1", "3.1.2", "3.1.3", "3.5", "3.5.1", - "4.20.1", - "4.21", "4.21.1", + "4.24.1", + "4.25", "4.25.1", "10.0", "11.1", "12.14.20" }; diff --git a/nsprpub/pr/tests/version.c b/nsprpub/pr/tests/version.c index a026de94c..49e8a05d7 100644 --- a/nsprpub/pr/tests/version.c +++ b/nsprpub/pr/tests/version.c @@ -21,26 +21,28 @@ int main(int argc, char **argv) PRLibrary *runtime = NULL; const char *library_name = NULL; const PRVersionDescription *version_info; - char buffer[100]; - PRExplodedTime exploded; + char buffer[100]; + PRExplodedTime exploded; PLOptState *opt = PL_CreateOptState(argc, argv, "d"); PRFileDesc *err = PR_GetSpecialFD(PR_StandardError); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 0: /* fully qualified library name */ - library_name = opt->value; - break; - case 'd': /* verbodity */ - verbosity += 1; - break; - default: - PR_fprintf(err, "Usage: version [-d] {fully qualified library name}\n"); - return 2; /* but not a lot else */ + case 0: /* fully qualified library name */ + library_name = opt->value; + break; + case 'd': /* verbodity */ + verbosity += 1; + break; + default: + PR_fprintf(err, "Usage: version [-d] {fully qualified library name}\n"); + return 2; /* but not a lot else */ } } PL_DestroyOptState(opt); @@ -49,42 +51,43 @@ int main(int argc, char **argv) { runtime = PR_LoadLibrary(library_name); if (NULL == runtime) { - PL_FPrintError(err, "PR_LoadLibrary"); - return 3; - } else { + PL_FPrintError(err, "PR_LoadLibrary"); + return 3; + } else { versionEntryPointType versionPoint = (versionEntryPointType) - PR_FindSymbol(runtime, "libVersionPoint"); + PR_FindSymbol(runtime, "libVersionPoint"); if (NULL == versionPoint) { - PL_FPrintError(err, "PR_FindSymbol"); - return 4; - } - version_info = versionPoint(); - } - } else - version_info = libVersionPoint(); /* NSPR's version info */ + PL_FPrintError(err, "PR_FindSymbol"); + return 4; + } + version_info = versionPoint(); + } + } else { + version_info = libVersionPoint(); /* NSPR's version info */ + } - (void)PR_fprintf(err, "Runtime library version information\n"); - PR_ExplodeTime( - version_info->buildTime, PR_GMTParameters, &exploded); - (void)PR_FormatTime( - buffer, sizeof(buffer), "%d %b %Y %H:%M:%S", &exploded); - (void)PR_fprintf(err, " Build time: %s GMT\n", buffer); - (void)PR_fprintf( - err, " Build time: %s\n", version_info->buildTimeString); - (void)PR_fprintf( - err, " %s V%u.%u.%u (%s%s%s)\n", - version_info->description, - version_info->vMajor, - version_info->vMinor, - version_info->vPatch, - (version_info->beta ? " beta " : ""), - (version_info->debug ? " debug " : ""), - (version_info->special ? " special" : "")); - (void)PR_fprintf(err, " filename: %s\n", version_info->filename); - (void)PR_fprintf(err, " security: %s\n", version_info->security); - (void)PR_fprintf(err, " copyright: %s\n", version_info->copyright); - (void)PR_fprintf(err, " comment: %s\n", version_info->comment); - rv = 0; + (void)PR_fprintf(err, "Runtime library version information\n"); + PR_ExplodeTime( + version_info->buildTime, PR_GMTParameters, &exploded); + (void)PR_FormatTime( + buffer, sizeof(buffer), "%d %b %Y %H:%M:%S", &exploded); + (void)PR_fprintf(err, " Build time: %s GMT\n", buffer); + (void)PR_fprintf( + err, " Build time: %s\n", version_info->buildTimeString); + (void)PR_fprintf( + err, " %s V%u.%u.%u (%s%s%s)\n", + version_info->description, + version_info->vMajor, + version_info->vMinor, + version_info->vPatch, + (version_info->beta ? " beta " : ""), + (version_info->debug ? " debug " : ""), + (version_info->special ? " special" : "")); + (void)PR_fprintf(err, " filename: %s\n", version_info->filename); + (void)PR_fprintf(err, " security: %s\n", version_info->security); + (void)PR_fprintf(err, " copyright: %s\n", version_info->copyright); + (void)PR_fprintf(err, " comment: %s\n", version_info->comment); + rv = 0; return rv; } diff --git a/nsprpub/pr/tests/writev.c b/nsprpub/pr/tests/writev.c index 24544a46e..7b761648f 100644 --- a/nsprpub/pr/tests/writev.c +++ b/nsprpub/pr/tests/writev.c @@ -31,7 +31,10 @@ int PR_CALLBACK Writev(int argc, char **argv) PRIntervalTime tmo_min = 0x7fffffff, tmo_max = 0, tmo_elapsed = 0; PRInt32 tmo_counted = 0, iov_index, loop, bytes, number_fragments; PRInt32 message_length = 100, fragment_length = 100, messages = 100; - struct Descriptor { PRInt32 length; PRUint32 checksum; } descriptor; + struct Descriptor { + PRInt32 length; + PRUint32 checksum; + } descriptor; /* * USAGE @@ -41,19 +44,21 @@ int PR_CALLBACK Writev(int argc, char **argv) * -f size of each message fragment (default = 100) */ - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "dh:m:s:f:"); + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "dh:m:s:f:"); PR_STDIO_INIT(); rv = PR_InitializeNetAddr(PR_IpAddrLoopback, BASE_PORT, &serverAddr); PR_ASSERT(PR_SUCCESS == rv); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'h': /* the remote host */ + case 'h': /* the remote host */ { PRIntn es = 0; PRHostEnt host; @@ -63,23 +68,23 @@ int PR_CALLBACK Writev(int argc, char **argv) PR_ASSERT(es > 0); } break; - case 'd': /* debug mode */ - debug = PR_GetSpecialFD(PR_StandardError); - break; - case 'm': /* number of messages to send */ - messages = atoi(opt->value); - break; - case 's': /* total size of each message */ - message_length = atoi(opt->value); - break; - case 'f': /* size of each message fragment */ - fragment_length = atoi(opt->value); - break; - default: - break; + case 'd': /* debug mode */ + debug = PR_GetSpecialFD(PR_StandardError); + break; + case 'm': /* number of messages to send */ + messages = atoi(opt->value); + break; + case 's': /* total size of each message */ + message_length = atoi(opt->value); + break; + case 'f': /* size of each message fragment */ + fragment_length = atoi(opt->value); + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); buffer = (char*)malloc(message_length); @@ -88,9 +93,9 @@ int PR_CALLBACK Writev(int argc, char **argv) { fragment_length = message_length / (IOV_MAX - 2); number_fragments = (message_length + fragment_length - 1) / - fragment_length + 1; - if (NULL != debug) PR_fprintf(debug, - "Too many fragments - reset fragment length to %ld\n", fragment_length); + fragment_length + 1; + if (NULL != debug) PR_fprintf(debug, + "Too many fragments - reset fragment length to %ld\n", fragment_length); } iov = (PRIOVec*)malloc(number_fragments * sizeof(PRIOVec)); @@ -102,60 +107,72 @@ int PR_CALLBACK Writev(int argc, char **argv) iov[iov_index].iov_len = fragment_length; } - for (bytes = 0; bytes < message_length; ++bytes) + for (bytes = 0; bytes < message_length; ++bytes) { buffer[bytes] = (char)bytes; + } timeout = PR_SecondsToInterval(1); for (loop = 0; loop < messages; ++loop) { - if (NULL != debug) + if (NULL != debug) { PR_fprintf(debug, "[%d]socket ... ", loop); + } clientSock = PR_NewTCPSocket(); if (clientSock) { timein = PR_IntervalNow(); - if (NULL != debug) + if (NULL != debug) { PR_fprintf(debug, "connecting ... "); + } rv = PR_Connect(clientSock, &serverAddr, timeout); if (PR_SUCCESS == rv) { descriptor.checksum = 0; descriptor.length = (loop < (messages - 1)) ? message_length : 0; - if (0 == descriptor.length) number_fragments = 1; + if (0 == descriptor.length) { + number_fragments = 1; + } else for (iov_index = 0; iov_index < descriptor.length; ++iov_index) { PRUint32 overflow = descriptor.checksum & 0x80000000; descriptor.checksum = (descriptor.checksum << 1); - if (0x00000000 != overflow) descriptor.checksum += 1; + if (0x00000000 != overflow) { + descriptor.checksum += 1; + } descriptor.checksum += buffer[iov_index]; } if (NULL != debug) PR_fprintf( - debug, "sending %d bytes ... ", descriptor.length); + debug, "sending %d bytes ... ", descriptor.length); /* then, at the last moment ... */ descriptor.length = PR_ntohl(descriptor.length); descriptor.checksum = PR_ntohl(descriptor.checksum); bytes = PR_Writev(clientSock, iov, number_fragments, timeout); - if (NULL != debug) + if (NULL != debug) { PR_fprintf(debug, "closing ... "); + } rv = PR_Shutdown(clientSock, PR_SHUTDOWN_BOTH); rv = PR_Close(clientSock); if (NULL != debug) PR_fprintf( - debug, "%s\n", ((PR_SUCCESS == rv) ? "good" : "bad")); + debug, "%s\n", ((PR_SUCCESS == rv) ? "good" : "bad")); elapsed = PR_IntervalNow() - timein; - if (elapsed < tmo_min) tmo_min = elapsed; - else if (elapsed > tmo_max) tmo_max = elapsed; + if (elapsed < tmo_min) { + tmo_min = elapsed; + } + else if (elapsed > tmo_max) { + tmo_max = elapsed; + } tmo_elapsed += elapsed; tmo_counted += 1; } else { if (NULL != debug) PR_fprintf( - debug, "failed - retrying (%d, %d)\n", - PR_GetError(), PR_GetOSError()); + debug, "failed - retrying (%d, %d)\n", + PR_GetError(), PR_GetOSError()); PR_Close(clientSock); } } @@ -169,12 +186,12 @@ int PR_CALLBACK Writev(int argc, char **argv) if (0 == tmo_counted) { PR_fprintf(debug, "No connection made\n"); } else { - PR_fprintf( - debug, "\nTimings: %d [%d] %d (microseconds)\n", - PR_IntervalToMicroseconds(tmo_min), - PR_IntervalToMicroseconds(tmo_elapsed / tmo_counted), - PR_IntervalToMicroseconds(tmo_max)); - } + PR_fprintf( + debug, "\nTimings: %d [%d] %d (microseconds)\n", + PR_IntervalToMicroseconds(tmo_min), + PR_IntervalToMicroseconds(tmo_elapsed / tmo_counted), + PR_IntervalToMicroseconds(tmo_max)); + } } PR_DELETE(buffer); @@ -189,7 +206,7 @@ int PR_CALLBACK Writev(int argc, char **argv) int main(int argc, char **argv) { return (PR_VersionCheck(PR_VERSION)) ? - PR_Initialize(Writev, argc, argv, 4) : -1; + PR_Initialize(Writev, argc, argv, 4) : -1; } /* main */ /* writev.c */ diff --git a/nsprpub/pr/tests/xnotify.c b/nsprpub/pr/tests/xnotify.c index 97096cc68..7e6f0e293 100644 --- a/nsprpub/pr/tests/xnotify.c +++ b/nsprpub/pr/tests/xnotify.c @@ -43,8 +43,12 @@ static void LogNow(const char *msg, PRStatus rv) PRIntervalTime now = PR_IntervalNow(); PR_Lock(ml); PR_fprintf(err, "%6ld: %s", (now - base), msg); - if (PR_FAILURE == rv) PL_FPrintError(err, " "); - else PR_fprintf(err, "\n"); + if (PR_FAILURE == rv) { + PL_FPrintError(err, " "); + } + else { + PR_fprintf(err, "\n"); + } PR_Unlock(ml); } /* LogNow */ @@ -66,12 +70,20 @@ static void PR_CALLBACK T2CMon(void *arg) PR_CEnterMonitor(&shared->o1); LogNow("T2 waiting 5 seconds on o1", PR_SUCCESS); rv = PR_CWait(&shared->o1, PR_SecondsToInterval(5)); - if (PR_SUCCESS == rv) LogNow("T2 resuming on o1", rv); - else LogNow("T2 wait failed on o1", rv); + if (PR_SUCCESS == rv) { + LogNow("T2 resuming on o1", rv); + } + else { + LogNow("T2 wait failed on o1", rv); + } rv = PR_CNotify(&shared->o1); - if (PR_SUCCESS == rv) LogNow("T2 notified o1", rv); - else LogNow("T2 notify on o1 failed", rv); + if (PR_SUCCESS == rv) { + LogNow("T2 notified o1", rv); + } + else { + LogNow("T2 notify on o1 failed", rv); + } PR_CExitMonitor(&shared->o1); } /* T2CMon */ @@ -84,8 +96,12 @@ static void PR_CALLBACK T3CMon(void *arg) PR_CEnterMonitor(&shared->o2); LogNow("T3 waiting 5 seconds on o2", PR_SUCCESS); rv = PR_CWait(&shared->o2, PR_SecondsToInterval(5)); - if (PR_SUCCESS == rv) LogNow("T3 resuming on o2", rv); - else LogNow("T3 wait failed on o2", rv); + if (PR_SUCCESS == rv) { + LogNow("T3 resuming on o2", rv); + } + else { + LogNow("T3 wait failed on o2", rv); + } rv = PR_CNotify(&shared->o2); LogNow("T3 notify on o2", rv); PR_CExitMonitor(&shared->o2); @@ -108,25 +124,33 @@ static void T1CMon(void) PR_CEnterMonitor(&sharedCM.o1); LogNow("T1 waiting 3 seconds on o1", PR_SUCCESS); rv = PR_CWait(&sharedCM.o1, PR_SecondsToInterval(3)); - if (PR_SUCCESS == rv) LogNow("T1 resuming on o1", rv); - else LogNow("T1 wait on o1 failed", rv); + if (PR_SUCCESS == rv) { + LogNow("T1 resuming on o1", rv); + } + else { + LogNow("T1 wait on o1 failed", rv); + } PR_CExitMonitor(&sharedCM.o1); LogNow("T1 creating T2", PR_SUCCESS); t2 = PR_CreateThread( - PR_USER_THREAD, T2CMon, &sharedCM, PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, T2CMon, &sharedCM, PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); LogNow("T1 creating T3", PR_SUCCESS); t3 = PR_CreateThread( - PR_USER_THREAD, T3CMon, &sharedCM, PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, T3CMon, &sharedCM, PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); PR_CEnterMonitor(&sharedCM.o2); LogNow("T1 waiting forever on o2", PR_SUCCESS); rv = PR_CWait(&sharedCM.o2, PR_INTERVAL_NO_TIMEOUT); - if (PR_SUCCESS == rv) LogNow("T1 resuming on o2", rv); - else LogNow("T1 wait on o2 failed", rv); + if (PR_SUCCESS == rv) { + LogNow("T1 resuming on o2", rv); + } + else { + LogNow("T1 wait on o2 failed", rv); + } PR_CExitMonitor(&sharedCM.o2); (void)PR_JoinThread(t2); @@ -142,12 +166,20 @@ static void PR_CALLBACK T2Mon(void *arg) PR_EnterMonitor(shared->o1); LogNow("T2 waiting 5 seconds on o1", PR_SUCCESS); rv = PR_Wait(shared->o1, PR_SecondsToInterval(5)); - if (PR_SUCCESS == rv) LogNow("T2 resuming on o1", rv); - else LogNow("T2 wait failed on o1", rv); + if (PR_SUCCESS == rv) { + LogNow("T2 resuming on o1", rv); + } + else { + LogNow("T2 wait failed on o1", rv); + } rv = PR_Notify(shared->o1); - if (PR_SUCCESS == rv) LogNow("T2 notified o1", rv); - else LogNow("T2 notify on o1 failed", rv); + if (PR_SUCCESS == rv) { + LogNow("T2 notified o1", rv); + } + else { + LogNow("T2 notify on o1 failed", rv); + } PR_ExitMonitor(shared->o1); } /* T2Mon */ @@ -160,8 +192,12 @@ static void PR_CALLBACK T3Mon(void *arg) PR_EnterMonitor(shared->o2); LogNow("T3 waiting 5 seconds on o2", PR_SUCCESS); rv = PR_Wait(shared->o2, PR_SecondsToInterval(5)); - if (PR_SUCCESS == rv) LogNow("T3 resuming on o2", rv); - else LogNow("T3 wait failed on o2", rv); + if (PR_SUCCESS == rv) { + LogNow("T3 resuming on o2", rv); + } + else { + LogNow("T3 wait failed on o2", rv); + } rv = PR_Notify(shared->o2); LogNow("T3 notify on o2", rv); PR_ExitMonitor(shared->o2); @@ -186,25 +222,33 @@ static void T1Mon(void) PR_EnterMonitor(sharedM.o1); LogNow("T1 waiting 3 seconds on o1", PR_SUCCESS); rv = PR_Wait(sharedM.o1, PR_SecondsToInterval(3)); - if (PR_SUCCESS == rv) LogNow("T1 resuming on o1", rv); - else LogNow("T1 wait on o1 failed", rv); + if (PR_SUCCESS == rv) { + LogNow("T1 resuming on o1", rv); + } + else { + LogNow("T1 wait on o1 failed", rv); + } PR_ExitMonitor(sharedM.o1); LogNow("T1 creating T2", PR_SUCCESS); t2 = PR_CreateThread( - PR_USER_THREAD, T2Mon, &sharedM, PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, T2Mon, &sharedM, PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); LogNow("T1 creating T3", PR_SUCCESS); t3 = PR_CreateThread( - PR_USER_THREAD, T3Mon, &sharedM, PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, T3Mon, &sharedM, PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); PR_EnterMonitor(sharedM.o2); LogNow("T1 waiting forever on o2", PR_SUCCESS); rv = PR_Wait(sharedM.o2, PR_INTERVAL_NO_TIMEOUT); - if (PR_SUCCESS == rv) LogNow("T1 resuming on o2", rv); - else LogNow("T1 wait on o2 failed", rv); + if (PR_SUCCESS == rv) { + LogNow("T1 resuming on o2", rv); + } + else { + LogNow("T1 wait on o2 failed", rv); + } PR_ExitMonitor(sharedM.o2); (void)PR_JoinThread(t2); @@ -223,12 +267,20 @@ static void PR_CALLBACK T2Lock(void *arg) PR_Lock(shared->o1); LogNow("T2 waiting 5 seconds on o1", PR_SUCCESS); rv = PR_WaitCondVar(shared->cv1, PR_SecondsToInterval(5)); - if (PR_SUCCESS == rv) LogNow("T2 resuming on o1", rv); - else LogNow("T2 wait failed on o1", rv); + if (PR_SUCCESS == rv) { + LogNow("T2 resuming on o1", rv); + } + else { + LogNow("T2 wait failed on o1", rv); + } rv = PR_NotifyCondVar(shared->cv1); - if (PR_SUCCESS == rv) LogNow("T2 notified o1", rv); - else LogNow("T2 notify on o1 failed", rv); + if (PR_SUCCESS == rv) { + LogNow("T2 notified o1", rv); + } + else { + LogNow("T2 notify on o1 failed", rv); + } PR_Unlock(shared->o1); } /* T2Lock */ @@ -241,8 +293,12 @@ static void PR_CALLBACK T3Lock(void *arg) PR_Lock(shared->o2); LogNow("T3 waiting 5 seconds on o2", PR_SUCCESS); rv = PR_WaitCondVar(shared->cv2, PR_SecondsToInterval(5)); - if (PR_SUCCESS == rv) LogNow("T3 resuming on o2", rv); - else LogNow("T3 wait failed on o2", rv); + if (PR_SUCCESS == rv) { + LogNow("T3 resuming on o2", rv); + } + else { + LogNow("T3 wait failed on o2", rv); + } rv = PR_NotifyCondVar(shared->cv2); LogNow("T3 notify on o2", rv); PR_Unlock(shared->o2); @@ -272,25 +328,33 @@ static void T1Lock(void) PR_Lock(sharedL.o1); LogNow("T1 waiting 3 seconds on o1", PR_SUCCESS); rv = PR_WaitCondVar(sharedL.cv1, PR_SecondsToInterval(3)); - if (PR_SUCCESS == rv) LogNow("T1 resuming on o1", rv); - else LogNow("T1 wait on o1 failed", rv); + if (PR_SUCCESS == rv) { + LogNow("T1 resuming on o1", rv); + } + else { + LogNow("T1 wait on o1 failed", rv); + } PR_Unlock(sharedL.o1); LogNow("T1 creating T2", PR_SUCCESS); t2 = PR_CreateThread( - PR_USER_THREAD, T2Lock, &sharedL, PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, T2Lock, &sharedL, PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); LogNow("T1 creating T3", PR_SUCCESS); t3 = PR_CreateThread( - PR_USER_THREAD, T3Lock, &sharedL, PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + PR_USER_THREAD, T3Lock, &sharedL, PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); PR_Lock(sharedL.o2); LogNow("T1 waiting forever on o2", PR_SUCCESS); rv = PR_WaitCondVar(sharedL.cv2, PR_INTERVAL_NO_TIMEOUT); - if (PR_SUCCESS == rv) LogNow("T1 resuming on o2", rv); - else LogNow("T1 wait on o2 failed", rv); + if (PR_SUCCESS == rv) { + LogNow("T1 resuming on o2", rv); + } + else { + LogNow("T1 wait on o2 failed", rv); + } PR_Unlock(sharedL.o2); (void)PR_JoinThread(t2); @@ -304,44 +368,52 @@ static void T1Lock(void) static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) { - PLOptStatus os; - PLOptState *opt = PL_CreateOptState(argc, argv, "dhlmc"); - PRBool locks = PR_FALSE, monitors = PR_FALSE, cmonitors = PR_FALSE; + PLOptStatus os; + PLOptState *opt = PL_CreateOptState(argc, argv, "dhlmc"); + PRBool locks = PR_FALSE, monitors = PR_FALSE, cmonitors = PR_FALSE; err = PR_GetSpecialFD(PR_StandardError); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode (noop) */ - break; - case 'l': /* locks */ - locks = PR_TRUE; - break; - case 'm': /* monitors */ - monitors = PR_TRUE; - break; - case 'c': /* cached monitors */ - cmonitors = PR_TRUE; - break; - case 'h': /* needs guidance */ - default: - Help(); - return 2; + case 'd': /* debug mode (noop) */ + break; + case 'l': /* locks */ + locks = PR_TRUE; + break; + case 'm': /* monitors */ + monitors = PR_TRUE; + break; + case 'c': /* cached monitors */ + cmonitors = PR_TRUE; + break; + case 'h': /* needs guidance */ + default: + Help(); + return 2; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); ml = PR_NewLock(); - if (locks) T1Lock(); - if (monitors) T1Mon(); - if (cmonitors) T1CMon(); + if (locks) { + T1Lock(); + } + if (monitors) { + T1Mon(); + } + if (cmonitors) { + T1CMon(); + } PR_DestroyLock(ml); - PR_fprintf(err, "Done!\n"); + PR_fprintf(err, "Done!\n"); return 0; } /* main */ @@ -349,7 +421,7 @@ static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv ) int main(int argc, char **argv) { PRIntn rv; - + PR_STDIO_INIT(); rv = PR_Initialize(RealMain, argc, argv, 0); return rv; diff --git a/nsprpub/pr/tests/y2k.c b/nsprpub/pr/tests/y2k.c index 12cc16f40..31b35e7e8 100644 --- a/nsprpub/pr/tests/y2k.c +++ b/nsprpub/pr/tests/y2k.c @@ -30,10 +30,11 @@ int failed_already=0; PRBool debug_mode = PR_FALSE; static char *dayOfWeek[] = - { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "???" }; +{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "???" }; static char *month[] = - { "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "???" }; +{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "???" +}; PRLogModuleInfo *lm; @@ -44,8 +45,8 @@ static void PrintExplodedTime(const PRExplodedTime *et) { /* Print day of the week, month, day, hour, minute, and second */ printf("%s %s %2ld %02ld:%02ld:%02ld ", - dayOfWeek[et->tm_wday], month[et->tm_month], et->tm_mday, - et->tm_hour, et->tm_min, et->tm_sec); + dayOfWeek[et->tm_wday], month[et->tm_month], et->tm_mday, + et->tm_hour, et->tm_min, et->tm_sec); /* Print year */ printf("%hd ", et->tm_year); @@ -53,49 +54,49 @@ static void PrintExplodedTime(const PRExplodedTime *et) { /* Print time zone */ totalOffset = et->tm_params.tp_gmt_offset + et->tm_params.tp_dst_offset; if (totalOffset == 0) { - printf("UTC "); + printf("UTC "); } else { sign = "+"; if (totalOffset < 0) { - totalOffset = -totalOffset; - sign = "-"; + totalOffset = -totalOffset; + sign = "-"; } hourOffset = totalOffset / 3600; minOffset = (totalOffset % 3600) / 60; printf("%s%02ld%02ld ", sign, hourOffset, minOffset); } #ifdef PRINT_DETAILS - printf("{%d, %d, %d, %d, %d, %d, %d, %d, %d, { %d, %d}}\n",et->tm_usec, - et->tm_sec, - et->tm_min, - et->tm_hour, - et->tm_mday, - et->tm_month, - et->tm_year, - et->tm_wday, - et->tm_yday, - et->tm_params.tp_gmt_offset, - et->tm_params.tp_dst_offset); + printf("{%d, %d, %d, %d, %d, %d, %d, %d, %d, { %d, %d}}\n",et->tm_usec, + et->tm_sec, + et->tm_min, + et->tm_hour, + et->tm_mday, + et->tm_month, + et->tm_year, + et->tm_wday, + et->tm_yday, + et->tm_params.tp_gmt_offset, + et->tm_params.tp_dst_offset); #endif } static int ExplodedTimeIsEqual(const PRExplodedTime *et1, - const PRExplodedTime *et2) + const PRExplodedTime *et2) { if (et1->tm_usec == et2->tm_usec && - et1->tm_sec == et2->tm_sec && - et1->tm_min == et2->tm_min && - et1->tm_hour == et2->tm_hour && - et1->tm_mday == et2->tm_mday && - et1->tm_month == et2->tm_month && - et1->tm_year == et2->tm_year && - et1->tm_wday == et2->tm_wday && - et1->tm_yday == et2->tm_yday && - et1->tm_params.tp_gmt_offset == et2->tm_params.tp_gmt_offset && - et1->tm_params.tp_dst_offset == et2->tm_params.tp_dst_offset) { + et1->tm_sec == et2->tm_sec && + et1->tm_min == et2->tm_min && + et1->tm_hour == et2->tm_hour && + et1->tm_mday == et2->tm_mday && + et1->tm_month == et2->tm_month && + et1->tm_year == et2->tm_year && + et1->tm_wday == et2->tm_wday && + et1->tm_yday == et2->tm_yday && + et1->tm_params.tp_gmt_offset == et2->tm_params.tp_gmt_offset && + et1->tm_params.tp_dst_offset == et2->tm_params.tp_dst_offset) { return 1; } else { - return 0; + return 0; } } @@ -115,14 +116,14 @@ static int ExplodedTimeIsEqual(const PRExplodedTime *et1, * * Call PR_ImplodeTime for each of the exploded values and compare * the resulting PRTime values with the original input. - * + * * This test is run for the values of time T corresponding to the * following dates: - * - 12/31/99 - before 2000 - * - 01/01/00 - after 2000 - * - Leap year - Feb 29, 2000 - * - March 1st, 2001 (after 1 year) - * - March 1st, 2005 (after second leap year) + * - 12/31/99 - before 2000 + * - 01/01/00 - after 2000 + * - Leap year - Feb 29, 2000 + * - March 1st, 2001 (after 1 year) + * - March 1st, 2005 (after second leap year) * - 09/09/99 (used by some programs as an end of file marker) * * Call PR_Now, convert to calendar time using PR_ExplodeTime and @@ -130,7 +131,7 @@ static int ExplodedTimeIsEqual(const PRExplodedTime *et1, * the system clock. * * Tested functions: PR_Now, PR_ExplodeTime, PR_ImplodeTime, - * PR_LocalTimeParameters, PR_GMTParameters. + * PR_LocalTimeParameters, PR_GMTParameters. */ static PRTime prt[] = { @@ -164,12 +165,12 @@ static PRExplodedTime gmt[] = { }; static PRExplodedTime uspt[] = { -{ 0, 0, 0, 2, 31, 11, 1999, 5, 364, {-28800, 0}}, /* 1999/12/31 2:00:00 PST */ -{ 0, 0, 0, 2, 1, 0, 2000, 6, 0, {-28800, 0}}, /* 2000/01/01 2:00:00 PST */ -{ 0, 0, 0, 2, 29, 1, 2000, 2, 59, {-28800, 0}}, /* 2000/02/29 2:00:00 PST */ -{ 0, 0, 0, 2, 1, 2, 2001, 4, 59, {-28800, 0}}, /* 2001/3/1 2:00:00 PST */ -{ 0, 0, 0, 2, 1, 2, 2005, 2, 59, {-28800, 0}}, /* 2005/3/1 2:00:00 PST */ -{ 0, 0, 0, 3, 9, 8, 1999, 4, 251, {-28800, 3600}}, /* 1999/9/9 3:00:00 PDT */ + { 0, 0, 0, 2, 31, 11, 1999, 5, 364, {-28800, 0}}, /* 1999/12/31 2:00:00 PST */ + { 0, 0, 0, 2, 1, 0, 2000, 6, 0, {-28800, 0}}, /* 2000/01/01 2:00:00 PST */ + { 0, 0, 0, 2, 29, 1, 2000, 2, 59, {-28800, 0}}, /* 2000/02/29 2:00:00 PST */ + { 0, 0, 0, 2, 1, 2, 2001, 4, 59, {-28800, 0}}, /* 2001/3/1 2:00:00 PST */ + { 0, 0, 0, 2, 1, 2, 2005, 2, 59, {-28800, 0}}, /* 2005/3/1 2:00:00 PST */ + { 0, 0, 0, 3, 9, 8, 1999, 4, 251, {-28800, 3600}}, /* 1999/9/9 3:00:00 PDT */ /* Sun's dates follow */ { 0, 0, 0, 2, 31, 11, 1998, 4, 364, {-28800, 0}}, /* 12/31/1998 00:00:00 GMT */ { 0, 0, 0, 3, 10, 8, 1999, 5, 252, {-28800, 3600}}, /* 9/10/1999 00:00:00 GMT */ @@ -186,12 +187,12 @@ static PRExplodedTime uspt[] = { * Zone is provided as an example. */ static PRExplodedTime localt[] = { -{ 0, 0, 0, 2, 31, 11, 1999, 5, 364, {-28800, 0}}, /* 1999/12/31 2:00:00 PST */ -{ 0, 0, 0, 2, 1, 0, 2000, 6, 0, {-28800, 0}}, /* 2000/01/01 2:00:00 PST */ -{ 0, 0, 0, 2, 29, 1, 2000, 2, 59, {-28800, 0}}, /* 2000/02/29 2:00:00 PST */ -{ 0, 0, 0, 2, 1, 2, 2001, 4, 59, {-28800, 0}}, /* 2001/3/1 2:00:00 PST */ -{ 0, 0, 0, 2, 1, 2, 2005, 2, 59, {-28800, 0}}, /* 2005/3/1 2:00:00 PST */ -{ 0, 0, 0, 3, 9, 8, 1999, 4, 251, {-28800, 3600}}, /* 1999/9/9 3:00:00 PDT */ + { 0, 0, 0, 2, 31, 11, 1999, 5, 364, {-28800, 0}}, /* 1999/12/31 2:00:00 PST */ + { 0, 0, 0, 2, 1, 0, 2000, 6, 0, {-28800, 0}}, /* 2000/01/01 2:00:00 PST */ + { 0, 0, 0, 2, 29, 1, 2000, 2, 59, {-28800, 0}}, /* 2000/02/29 2:00:00 PST */ + { 0, 0, 0, 2, 1, 2, 2001, 4, 59, {-28800, 0}}, /* 2001/3/1 2:00:00 PST */ + { 0, 0, 0, 2, 1, 2, 2005, 2, 59, {-28800, 0}}, /* 2005/3/1 2:00:00 PST */ + { 0, 0, 0, 3, 9, 8, 1999, 4, 251, {-28800, 3600}}, /* 1999/9/9 3:00:00 PDT */ /* Sun's dates follow */ { 0, 0, 0, 2, 31, 11, 1998, 4, 364, {-28800, 0}}, /* 12/31/1998 00:00:00 GMT */ { 0, 0, 0, 3, 10, 8, 1999, 5, 252, {-28800, 3600}}, /* 9/10/1999 00:00:00 GMT */ @@ -202,12 +203,12 @@ static PRExplodedTime localt[] = { #ifdef US_EASTERN_TIME static PRExplodedTime localt[] = { -{ 0, 0, 0, 5, 31, 11, 1999, 5, 364, {-18000, 0}}, /* 1999/12/31 2:00:00 EST */ -{ 0, 0, 0, 5, 1, 0, 2000, 6, 0, {-18000, 0}}, /* 2000/01/01 2:00:00 EST */ -{ 0, 0, 0, 5, 29, 1, 2000, 2, 59, {-18000, 0}}, /* 2000/02/29 2:00:00 EST */ -{ 0, 0, 0, 5, 1, 2, 2001, 4, 59, {-18000, 0}}, /* 2001/3/1 2:00:00 EST */ -{ 0, 0, 0, 5, 1, 2, 2005, 2, 59, {-18000, 0}}, /* 2005/3/1 2:00:00 EST */ -{ 0, 0, 0, 6, 9, 8, 1999, 4, 251, {-18000, 3600}}, /* 1999/9/9 3:00:00 EDT */ + { 0, 0, 0, 5, 31, 11, 1999, 5, 364, {-18000, 0}}, /* 1999/12/31 2:00:00 EST */ + { 0, 0, 0, 5, 1, 0, 2000, 6, 0, {-18000, 0}}, /* 2000/01/01 2:00:00 EST */ + { 0, 0, 0, 5, 29, 1, 2000, 2, 59, {-18000, 0}}, /* 2000/02/29 2:00:00 EST */ + { 0, 0, 0, 5, 1, 2, 2001, 4, 59, {-18000, 0}}, /* 2001/3/1 2:00:00 EST */ + { 0, 0, 0, 5, 1, 2, 2005, 2, 59, {-18000, 0}}, /* 2005/3/1 2:00:00 EST */ + { 0, 0, 0, 6, 9, 8, 1999, 4, 251, {-18000, 3600}}, /* 1999/9/9 3:00:00 EDT */ /* Sun's dates follow */ { 0, 0, 0, 5, 31, 11, 1998, 4, 364, {-18000 0}}, /* 12/31/1998 00:00:00 GMT */ { 0, 0, 0, 6, 10, 8, 1999, 5, 252, {-18000 3600}}, /* 9/10/1999 00:00:00 GMT */ @@ -228,7 +229,9 @@ static PRStatus TestExplodeImplodeTime(void) for (idx = 0; idx < array_size; idx++) { PR_snprintf(buf, sizeof(buf), "%lld", prt[idx]); - if (debug_mode) printf("Time stamp %s\n", buf); + if (debug_mode) { + printf("Time stamp %s\n", buf); + } PR_ExplodeTime(prt[idx], PR_GMTParameters, &et_tmp); if (!ExplodedTimeIsEqual(&et_tmp, &gmt[idx])) { fprintf(stderr, "GMT not equal\n"); @@ -314,7 +317,9 @@ static PRStatus TestExplodeImplodeTime(void) } printf("Please verify the results\n\n"); - if (debug_mode) printf("Test 1 passed\n"); + if (debug_mode) { + printf("Test 1 passed\n"); + } return PR_SUCCESS; } /* End of Test 1: TestExplodeImplodeTime */ @@ -327,165 +332,166 @@ static PRStatus TestExplodeImplodeTime(void) * time increment for addition to PRExplodeTime */ typedef struct time_increment { - PRInt32 ti_usec; - PRInt32 ti_sec; - PRInt32 ti_min; - PRInt32 ti_hour; + PRInt32 ti_usec; + PRInt32 ti_sec; + PRInt32 ti_min; + PRInt32 ti_hour; } time_increment_t; /* * Data for testing PR_Normalize - * Add the increment to base_time, normalize it to GMT and US Pacific - * Time zone. + * Add the increment to base_time, normalize it to GMT and US Pacific + * Time zone. */ typedef struct normalize_test_data { - PRExplodedTime base_time; - time_increment_t increment; - PRExplodedTime expected_gmt_time; - PRExplodedTime expected_uspt_time; + PRExplodedTime base_time; + time_increment_t increment; + PRExplodedTime expected_gmt_time; + PRExplodedTime expected_uspt_time; } normalize_test_data_t; /* - * Test data - the base time values cover dates of interest including y2k - 1, - * y2k + 1, y2k leap year, y2k leap date + 1year, - * y2k leap date + 4 years + * Test data - the base time values cover dates of interest including y2k - 1, + * y2k + 1, y2k leap year, y2k leap date + 1year, + * y2k leap date + 4 years */ normalize_test_data_t normalize_test_array[] = { - /*usec sec min hour mday mo year wday yday {gmtoff, dstoff }*/ - - /* Fri 12/31/1999 19:32:48 PST */ - {{0, 48, 32, 19, 31, 11, 1999, 5, 364, { -28800, 0}}, - {0, 0, 30, 20}, - {0, 48, 2, 0, 2, 0, 2000, 0, 1, { 0, 0}}, /*Sun Jan 2 00:02:48 UTC 2000*/ - {0, 48, 2, 16, 1, 0, 2000, 6, 0, { -28800, 0}},/* Sat Jan 1 16:02:48 - PST 2000*/ - }, - /* Fri 99-12-31 23:59:02 GMT */ - {{0, 2, 59, 23, 31, 11, 1999, 5, 364, { 0, 0}}, - {0, 0, 45, 0}, - {0, 2, 44, 0, 1, 0, 2000, 6, 0, { 0, 0}},/* Sat Jan 1 00:44:02 UTC 2000*/ - {0, 2, 44, 16, 31, 11, 1999, 5, 364, { -28800, 0}}/*Fri Dec 31 16:44:02 - PST 1999*/ - }, - /* 99-12-25 12:00:00 GMT */ - {{0, 0, 0, 12, 25, 11, 1999, 6, 358, { 0, 0}}, - {0, 0, 0, 364 * 24}, - {0, 0, 0, 12, 23, 11, 2000, 6, 357, { 0, 0}},/*Sat Dec 23 12:00:00 - 2000 UTC*/ - {0, 0, 0, 4, 23, 11, 2000, 6, 357, { -28800, 0}}/*Sat Dec 23 04:00:00 - 2000 -0800*/ - }, - /* 00-01-1 00:00:00 PST */ - {{0, 0, 0, 0, 1, 0, 2000, 6, 0, { -28800, 0}}, - {0, 0, 0, 48}, - {0, 0, 0, 8, 3, 0, 2000, 1, 2, { 0, 0}},/*Mon Jan 3 08:00:00 2000 UTC*/ - {0, 0, 0, 0, 3, 0, 2000, 1, 2, { -28800, 0}}/*Mon Jan 3 00:00:00 2000 - -0800*/ - }, - /* 00-01-10 12:00:00 PST */ - {{0, 0, 0, 12, 10, 0, 2000, 1, 9, { -28800, 0}}, - {0, 0, 0, 364 * 5 * 24}, - {0, 0, 0, 20, 3, 0, 2005, 1, 2, { 0, 0}},/*Mon Jan 3 20:00:00 2005 UTC */ - {0, 0, 0, 12, 3, 0, 2005, 1, 2, { -28800, 0}}/*Mon Jan 3 12:00:00 - 2005 -0800*/ - }, - /* 00-02-28 15:39 GMT */ - {{0, 0, 39, 15, 28, 1, 2000, 1, 58, { 0, 0}}, - {0, 0, 0, 24}, - {0, 0, 39, 15, 29, 1, 2000, 2, 59, { 0, 0}}, /*Tue Feb 29 15:39:00 2000 - UTC*/ - {0, 0, 39, 7, 29, 1, 2000, 2, 59, { -28800, 0}}/*Tue Feb 29 07:39:00 - 2000 -0800*/ - }, - /* 01-03-01 12:00 PST */ - {{0, 0, 0, 12, 3, 0, 2001, 3, 2, { -28800, 0}},/*Wed Jan 3 12:00:00 - -0800 2001*/ - {0, 30, 30,45}, - {0, 30, 30, 17, 5, 0, 2001, 5, 4, { 0, 0}}, /*Fri Jan 5 17:30:30 2001 - UTC*/ - {0, 30, 30, 9, 5, 0, 2001, 5, 4, { -28800, 0}} /*Fri Jan 5 09:30:30 - 2001 -0800*/ - }, - /* 2004-04-26 12:00 GMT */ - {{0, 0, 0, 20, 3, 0, 2001, 3, 2, { 0, 0}}, - {0, 0, 30,0}, - {0, 0, 30, 20, 3, 0, 2001, 3, 2, { 0, 0}},/*Wed Jan 3 20:30:00 2001 UTC*/ - {0, 0, 30, 12, 3, 0, 2001, 3, 2, { -28800, 0}}/*Wed Jan 3 12:30:00 - 2001 -0800*/ - }, - /* 99-09-09 00:00 GMT */ - {{0, 0, 0, 0, 9, 8, 1999, 4, 251, { 0, 0}}, - {0, 0, 0, 12}, - {0, 0, 0, 12, 9, 8, 1999, 4, 251, { 0, 0}},/*Thu Sep 9 12:00:00 1999 UTC*/ - {0, 0, 0, 5, 9, 8, 1999, 4, 251, { -28800, 3600}}/*Thu Sep 9 05:00:00 - 1999 -0700*/ - } + /*usec sec min hour mday mo year wday yday {gmtoff, dstoff }*/ + + /* Fri 12/31/1999 19:32:48 PST */ + { {0, 48, 32, 19, 31, 11, 1999, 5, 364, { -28800, 0}}, + {0, 0, 30, 20}, + {0, 48, 2, 0, 2, 0, 2000, 0, 1, { 0, 0}}, /*Sun Jan 2 00:02:48 UTC 2000*/ + {0, 48, 2, 16, 1, 0, 2000, 6, 0, { -28800, 0}},/* Sat Jan 1 16:02:48 + PST 2000*/ + }, + /* Fri 99-12-31 23:59:02 GMT */ + { {0, 2, 59, 23, 31, 11, 1999, 5, 364, { 0, 0}}, + {0, 0, 45, 0}, + {0, 2, 44, 0, 1, 0, 2000, 6, 0, { 0, 0}},/* Sat Jan 1 00:44:02 UTC 2000*/ + {0, 2, 44, 16, 31, 11, 1999, 5, 364, { -28800, 0}}/*Fri Dec 31 16:44:02 + PST 1999*/ + }, + /* 99-12-25 12:00:00 GMT */ + { {0, 0, 0, 12, 25, 11, 1999, 6, 358, { 0, 0}}, + {0, 0, 0, 364 * 24}, + {0, 0, 0, 12, 23, 11, 2000, 6, 357, { 0, 0}},/*Sat Dec 23 12:00:00 + 2000 UTC*/ + {0, 0, 0, 4, 23, 11, 2000, 6, 357, { -28800, 0}}/*Sat Dec 23 04:00:00 + 2000 -0800*/ + }, + /* 00-01-1 00:00:00 PST */ + { {0, 0, 0, 0, 1, 0, 2000, 6, 0, { -28800, 0}}, + {0, 0, 0, 48}, + {0, 0, 0, 8, 3, 0, 2000, 1, 2, { 0, 0}},/*Mon Jan 3 08:00:00 2000 UTC*/ + {0, 0, 0, 0, 3, 0, 2000, 1, 2, { -28800, 0}}/*Mon Jan 3 00:00:00 2000 + -0800*/ + }, + /* 00-01-10 12:00:00 PST */ + { {0, 0, 0, 12, 10, 0, 2000, 1, 9, { -28800, 0}}, + {0, 0, 0, 364 * 5 * 24}, + {0, 0, 0, 20, 3, 0, 2005, 1, 2, { 0, 0}},/*Mon Jan 3 20:00:00 2005 UTC */ + {0, 0, 0, 12, 3, 0, 2005, 1, 2, { -28800, 0}}/*Mon Jan 3 12:00:00 + 2005 -0800*/ + }, + /* 00-02-28 15:39 GMT */ + { {0, 0, 39, 15, 28, 1, 2000, 1, 58, { 0, 0}}, + {0, 0, 0, 24}, + {0, 0, 39, 15, 29, 1, 2000, 2, 59, { 0, 0}}, /*Tue Feb 29 15:39:00 2000 + UTC*/ + {0, 0, 39, 7, 29, 1, 2000, 2, 59, { -28800, 0}}/*Tue Feb 29 07:39:00 + 2000 -0800*/ + }, + /* 01-03-01 12:00 PST */ + { {0, 0, 0, 12, 3, 0, 2001, 3, 2, { -28800, 0}},/*Wed Jan 3 12:00:00 + -0800 2001*/ + {0, 30, 30,45}, + {0, 30, 30, 17, 5, 0, 2001, 5, 4, { 0, 0}}, /*Fri Jan 5 17:30:30 2001 + UTC*/ + {0, 30, 30, 9, 5, 0, 2001, 5, 4, { -28800, 0}} /*Fri Jan 5 09:30:30 + 2001 -0800*/ + }, + /* 2004-04-26 12:00 GMT */ + { {0, 0, 0, 20, 3, 0, 2001, 3, 2, { 0, 0}}, + {0, 0, 30,0}, + {0, 0, 30, 20, 3, 0, 2001, 3, 2, { 0, 0}},/*Wed Jan 3 20:30:00 2001 UTC*/ + {0, 0, 30, 12, 3, 0, 2001, 3, 2, { -28800, 0}}/*Wed Jan 3 12:30:00 + 2001 -0800*/ + }, + /* 99-09-09 00:00 GMT */ + { {0, 0, 0, 0, 9, 8, 1999, 4, 251, { 0, 0}}, + {0, 0, 0, 12}, + {0, 0, 0, 12, 9, 8, 1999, 4, 251, { 0, 0}},/*Thu Sep 9 12:00:00 1999 UTC*/ + {0, 0, 0, 5, 9, 8, 1999, 4, 251, { -28800, 3600}}/*Thu Sep 9 05:00:00 + 1999 -0700*/ + } }; void add_time_increment(PRExplodedTime *et1, time_increment_t *it) { - et1->tm_usec += it->ti_usec; - et1->tm_sec += it->ti_sec; - et1->tm_min += it->ti_min; - et1->tm_hour += it->ti_hour; + et1->tm_usec += it->ti_usec; + et1->tm_sec += it->ti_sec; + et1->tm_min += it->ti_min; + et1->tm_hour += it->ti_hour; } /* ** TestNormalizeTime() -- Test PR_NormalizeTime() -** For each data item, add the time increment to the base_time and then -** normalize it for GMT and local time zones. This test assumes that -** the local time zone is the Pacific Time Zone. The normalized values -** should match the expected values in the data item. +** For each data item, add the time increment to the base_time and then +** normalize it for GMT and local time zones. This test assumes that +** the local time zone is the Pacific Time Zone. The normalized values +** should match the expected values in the data item. ** */ PRStatus TestNormalizeTime(void) { -int idx, count; -normalize_test_data_t *itemp; -time_increment_t *itp; - - count = sizeof(normalize_test_array)/sizeof(normalize_test_array[0]); - for (idx = 0; idx < count; idx++) { - itemp = &normalize_test_array[idx]; - if (debug_mode) { - printf("%2d. %15s",idx +1,"Base time: "); - PrintExplodedTime(&itemp->base_time); - printf("\n"); - } - itp = &itemp->increment; - if (debug_mode) { - printf("%20s %2d hrs %2d min %3d sec\n","Add",itp->ti_hour, - itp->ti_min, itp->ti_sec); - } - add_time_increment(&itemp->base_time, &itemp->increment); - PR_NormalizeTime(&itemp->base_time, PR_LocalTimeParameters); - if (debug_mode) { - printf("%19s","PST time: "); - PrintExplodedTime(&itemp->base_time); - printf("\n"); - } - if (!ExplodedTimeIsEqual(&itemp->base_time, - &itemp->expected_uspt_time)) { - printf("PR_NormalizeTime failed\n"); - if (debug_mode) - PrintExplodedTime(&itemp->expected_uspt_time); - return PR_FAILURE; - } - PR_NormalizeTime(&itemp->base_time, PR_GMTParameters); - if (debug_mode) { - printf("%19s","GMT time: "); - PrintExplodedTime(&itemp->base_time); - printf("\n"); - } - - if (!ExplodedTimeIsEqual(&itemp->base_time, - &itemp->expected_gmt_time)) { - printf("PR_NormalizeTime failed\n"); - return PR_FAILURE; - } - } - return PR_SUCCESS; + int idx, count; + normalize_test_data_t *itemp; + time_increment_t *itp; + + count = sizeof(normalize_test_array)/sizeof(normalize_test_array[0]); + for (idx = 0; idx < count; idx++) { + itemp = &normalize_test_array[idx]; + if (debug_mode) { + printf("%2d. %15s",idx +1,"Base time: "); + PrintExplodedTime(&itemp->base_time); + printf("\n"); + } + itp = &itemp->increment; + if (debug_mode) { + printf("%20s %2d hrs %2d min %3d sec\n","Add",itp->ti_hour, + itp->ti_min, itp->ti_sec); + } + add_time_increment(&itemp->base_time, &itemp->increment); + PR_NormalizeTime(&itemp->base_time, PR_LocalTimeParameters); + if (debug_mode) { + printf("%19s","PST time: "); + PrintExplodedTime(&itemp->base_time); + printf("\n"); + } + if (!ExplodedTimeIsEqual(&itemp->base_time, + &itemp->expected_uspt_time)) { + printf("PR_NormalizeTime failed\n"); + if (debug_mode) { + PrintExplodedTime(&itemp->expected_uspt_time); + } + return PR_FAILURE; + } + PR_NormalizeTime(&itemp->base_time, PR_GMTParameters); + if (debug_mode) { + printf("%19s","GMT time: "); + PrintExplodedTime(&itemp->base_time); + printf("\n"); + } + + if (!ExplodedTimeIsEqual(&itemp->base_time, + &itemp->expected_gmt_time)) { + printf("PR_NormalizeTime failed\n"); + return PR_FAILURE; + } + } + return PR_SUCCESS; } @@ -499,7 +505,7 @@ typedef struct ParseTest PRExplodedTime et; /* expected result of the conversion */ } ParseTest; -static ParseTest parseArray[] = +static ParseTest parseArray[] = { /* |<----- expected result ------------------------------------------->| */ /* "string to test" usec sec min hour day mo year wday julian {gmtoff, dstoff }*/ @@ -533,7 +539,7 @@ static ParseTest parseArray[] = { "69-12-31 00:00:00", { 000000, 00, 00, 00, 31, 11, 2069, 2, 364, {-28800, 0 }}}, { "69/12/31 00:00:00", { 000000, 00, 00, 00, 31, 11, 2069, 2, 364, {-28800, 0 }}}, - /* "Sun". 31-Dec-1998 (?) */ + /* "Sun". 31-Dec-1998 (?) */ { "Thu 31 Dec 1998 00:00:00", { 00000, 00, 00, 00, 31, 11, 1998, 4, 364, {-28800, 0 }}}, { "12/31/98 00:00:00", { 00000, 00, 00, 00, 31, 11, 1998, 4, 364, {-28800, 0 }}}, { "12/31/1998 00:00:00", { 00000, 00, 00, 00, 31, 11, 1998, 4, 364, {-28800, 0 }}}, @@ -551,7 +557,7 @@ static ParseTest parseArray[] = { "09-09-99 00:00:00", { 000000, 00, 00, 00, 9, 8, 1999, 4, 251, {-28800, 3600 }}}, { "09-09-1999 00:00:00", { 000000, 00, 00, 00, 9, 8, 1999, 4, 251, {-28800, 3600 }}}, { "99-09-09 00:00:00", { 000000, 00, 00, 00, 9, 8, 1999, 4, 251, {-28800, 3600 }}}, - + /* "Sun". 10-Sep-1999. Because Sun said so. */ { "10 Sep 1999 00:00:00", { 000000, 00, 00, 00, 10, 8, 1999, 5, 252, {-28800, 3600 }}}, { "9/10/99 00:00:00", { 000000, 00, 00, 00, 10, 8, 1999, 5, 252, {-28800, 3600 }}}, @@ -659,7 +665,7 @@ static ParseTest parseArray[] = { "03-01-2005 00:00:00", { 000000, 00, 00, 00, 1, 2, 2005, 2, 59, {-28800, 0 }}}, /* last element. string must be null */ - { NULL } + { NULL } }; /* end array of ParseTest */ /* @@ -696,7 +702,7 @@ static PRStatus TestParseTime( void ) } else { - PR_ExplodeTime( ct, PR_LocalTimeParameters , &cet ); + PR_ExplodeTime( ct, PR_LocalTimeParameters, &cet ); if ( !ExplodedTimeIsEqual( &cet, &ptp->et )) { @@ -708,12 +714,12 @@ static PRStatus TestParseTime( void ) PrintExplodedTime( &ptp->et ); printf("\n"); } - + rv = PR_FAILURE; failed_already = 1; } } - + /* point to next element in array, keep going */ ptp++; sp = ptp->sDate; @@ -724,63 +730,70 @@ static PRStatus TestParseTime( void ) int main(int argc, char** argv) { - /* The command line argument: -d is used to determine if the test is being run - in debug mode. The regress tool requires only one line output:PASS or FAIL. - All of the printfs associated with this test has been handled with a if (debug_mode) - test. - Usage: test_name -d - */ - PLOptStatus os; - PLOptState *opt; - + /* The command line argument: -d is used to determine if the test is being run + in debug mode. The regress tool requires only one line output:PASS or FAIL. + All of the printfs associated with this test has been handled with a if (debug_mode) + test. + Usage: test_name -d + */ + PLOptStatus os; + PLOptState *opt; + PR_STDIO_INIT(); - opt = PL_CreateOptState(argc, argv, "d"); - while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + opt = PL_CreateOptState(argc, argv, "d"); + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { - case 'd': /* debug mode */ - debug_mode = PR_TRUE; - break; - default: - break; + case 'd': /* debug mode */ + debug_mode = PR_TRUE; + break; + default: + break; } } - PL_DestroyOptState(opt); + PL_DestroyOptState(opt); + + /* main test */ - /* main test */ - PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); lm = PR_NewLogModule("test"); if ( PR_FAILURE == TestExplodeImplodeTime()) { PR_LOG( lm, PR_LOG_ERROR, - ("TestExplodeImplodeTime() failed")); + ("TestExplodeImplodeTime() failed")); + } + else { + printf("Test 1: Calendar Time Test passed\n"); } - else - printf("Test 1: Calendar Time Test passed\n"); if ( PR_FAILURE == TestNormalizeTime()) { PR_LOG( lm, PR_LOG_ERROR, - ("TestNormalizeTime() failed")); + ("TestNormalizeTime() failed")); + } + else { + printf("Test 2: Normalize Time Test passed\n"); } - else - printf("Test 2: Normalize Time Test passed\n"); if ( PR_FAILURE == TestParseTime()) { PR_LOG( lm, PR_LOG_ERROR, - ("TestParseTime() failed")); + ("TestParseTime() failed")); + } + else { + printf("Test 3: Parse Time Test passed\n"); } - else - printf("Test 3: Parse Time Test passed\n"); - if (failed_already) - return 1; - else - return 0; + if (failed_already) { + return 1; + } + else { + return 0; + } } /* end main() y2k.c */ diff --git a/nsprpub/pr/tests/y2ktmo.c b/nsprpub/pr/tests/y2ktmo.c index e55cf9977..b28467e4d 100644 --- a/nsprpub/pr/tests/y2ktmo.c +++ b/nsprpub/pr/tests/y2ktmo.c @@ -28,7 +28,7 @@ * time again, to rule out the possibility that PR_IntervalNow() * is broken. We allow the actual elapsed time to deviate from * the specified timeout by a certain tolerance (in milliseconds). - */ + */ #include "nspr.h" #include "plgetopt.h" @@ -95,7 +95,7 @@ static void SleepThread(void *arg) #if defined(XP_UNIX) gettimeofday(&end_time_tv, NULL); elapsed_msecs = 1000*(end_time_tv.tv_sec - start_time_tv.tv_sec) - + (end_time_tv.tv_usec - start_time_tv.tv_usec)/1000; + + (end_time_tv.tv_usec - start_time_tv.tv_usec)/1000; #endif #if defined(WIN32) #if defined(WINCE) @@ -103,12 +103,12 @@ static void SleepThread(void *arg) #else _ftime(&end_time_tb); elapsed_msecs = 1000*(end_time_tb.time - start_time_tb.time) - + (end_time_tb.millitm - start_time_tb.millitm); + + (end_time_tb.millitm - start_time_tb.millitm); #endif #endif #if defined(XP_UNIX) || defined(WIN32) if (elapsed_msecs + tolerance_msecs < timeout_msecs - || elapsed_msecs > timeout_msecs + tolerance_msecs) { + || elapsed_msecs > timeout_msecs + tolerance_msecs) { fprintf(stderr, "timeout wrong\n"); exit(1); } @@ -167,7 +167,7 @@ static void AcceptThread(void *arg) #if defined(XP_UNIX) gettimeofday(&end_time_tv, NULL); elapsed_msecs = 1000*(end_time_tv.tv_sec - start_time_tv.tv_sec) - + (end_time_tv.tv_usec - start_time_tv.tv_usec)/1000; + + (end_time_tv.tv_usec - start_time_tv.tv_usec)/1000; #endif #if defined(WIN32) #if defined(WINCE) @@ -175,12 +175,12 @@ static void AcceptThread(void *arg) #else _ftime(&end_time_tb); elapsed_msecs = 1000*(end_time_tb.time - start_time_tb.time) - + (end_time_tb.millitm - start_time_tb.millitm); + + (end_time_tb.millitm - start_time_tb.millitm); #endif #endif #if defined(XP_UNIX) || defined(WIN32) if (elapsed_msecs + tolerance_msecs < timeout_msecs - || elapsed_msecs > timeout_msecs + tolerance_msecs) { + || elapsed_msecs > timeout_msecs + tolerance_msecs) { fprintf(stderr, "timeout wrong\n"); exit(1); } @@ -246,7 +246,7 @@ static void PollThread(void *arg) #if defined(XP_UNIX) gettimeofday(&end_time_tv, NULL); elapsed_msecs = 1000*(end_time_tv.tv_sec - start_time_tv.tv_sec) - + (end_time_tv.tv_usec - start_time_tv.tv_usec)/1000; + + (end_time_tv.tv_usec - start_time_tv.tv_usec)/1000; #endif #if defined(WIN32) #if defined(WINCE) @@ -254,12 +254,12 @@ static void PollThread(void *arg) #else _ftime(&end_time_tb); elapsed_msecs = 1000*(end_time_tb.time - start_time_tb.time) - + (end_time_tb.millitm - start_time_tb.millitm); + + (end_time_tb.millitm - start_time_tb.millitm); #endif #endif #if defined(XP_UNIX) || defined(WIN32) if (elapsed_msecs + tolerance_msecs < timeout_msecs - || elapsed_msecs > timeout_msecs + tolerance_msecs) { + || elapsed_msecs > timeout_msecs + tolerance_msecs) { fprintf(stderr, "timeout wrong\n"); exit(1); } @@ -312,7 +312,7 @@ static void WaitCondVarThread(void *arg) #if defined(XP_UNIX) gettimeofday(&end_time_tv, NULL); elapsed_msecs = 1000*(end_time_tv.tv_sec - start_time_tv.tv_sec) - + (end_time_tv.tv_usec - start_time_tv.tv_usec)/1000; + + (end_time_tv.tv_usec - start_time_tv.tv_usec)/1000; #endif #if defined(WIN32) #if defined(WINCE) @@ -320,12 +320,12 @@ static void WaitCondVarThread(void *arg) #else _ftime(&end_time_tb); elapsed_msecs = 1000*(end_time_tb.time - start_time_tb.time) - + (end_time_tb.millitm - start_time_tb.millitm); + + (end_time_tb.millitm - start_time_tb.millitm); #endif #endif #if defined(XP_UNIX) || defined(WIN32) if (elapsed_msecs + tolerance_msecs < timeout_msecs - || elapsed_msecs > timeout_msecs + tolerance_msecs) { + || elapsed_msecs > timeout_msecs + tolerance_msecs) { fprintf(stderr, "timeout wrong\n"); exit(1); } @@ -370,7 +370,7 @@ static void WaitMonitorThread(void *arg) #if defined(XP_UNIX) gettimeofday(&end_time_tv, NULL); elapsed_msecs = 1000*(end_time_tv.tv_sec - start_time_tv.tv_sec) - + (end_time_tv.tv_usec - start_time_tv.tv_usec)/1000; + + (end_time_tv.tv_usec - start_time_tv.tv_usec)/1000; #endif #if defined(WIN32) #if defined(WINCE) @@ -378,12 +378,12 @@ static void WaitMonitorThread(void *arg) #else _ftime(&end_time_tb); elapsed_msecs = 1000*(end_time_tb.time - start_time_tb.time) - + (end_time_tb.millitm - start_time_tb.millitm); + + (end_time_tb.millitm - start_time_tb.millitm); #endif #endif #if defined(XP_UNIX) || defined(WIN32) if (elapsed_msecs + tolerance_msecs < timeout_msecs - || elapsed_msecs > timeout_msecs + tolerance_msecs) { + || elapsed_msecs > timeout_msecs + tolerance_msecs) { fprintf(stderr, "timeout wrong\n"); exit(1); } @@ -422,7 +422,7 @@ static void WaitCMonitorThread(void *arg) #if defined(XP_UNIX) gettimeofday(&end_time_tv, NULL); elapsed_msecs = 1000*(end_time_tv.tv_sec - start_time_tv.tv_sec) - + (end_time_tv.tv_usec - start_time_tv.tv_usec)/1000; + + (end_time_tv.tv_usec - start_time_tv.tv_usec)/1000; #endif #if defined(WIN32) #if defined(WINCE) @@ -430,12 +430,12 @@ static void WaitCMonitorThread(void *arg) #else _ftime(&end_time_tb); elapsed_msecs = 1000*(end_time_tb.time - start_time_tb.time) - + (end_time_tb.millitm - start_time_tb.millitm); + + (end_time_tb.millitm - start_time_tb.millitm); #endif #endif #if defined(XP_UNIX) || defined(WIN32) if (elapsed_msecs + tolerance_msecs < timeout_msecs - || elapsed_msecs > timeout_msecs + tolerance_msecs) { + || elapsed_msecs > timeout_msecs + tolerance_msecs) { fprintf(stderr, "timeout wrong\n"); exit(1); } @@ -450,10 +450,12 @@ typedef void (*NSPRThreadFunc)(void*); static NSPRThreadFunc threadFuncs[] = { SleepThread, AcceptThread, PollThread, - WaitCondVarThread, WaitMonitorThread, WaitCMonitorThread}; + WaitCondVarThread, WaitMonitorThread, WaitCMonitorThread +}; static PRThreadScope threadScopes[] = { - PR_LOCAL_THREAD, PR_GLOBAL_THREAD, PR_GLOBAL_BOUND_THREAD}; + PR_LOCAL_THREAD, PR_GLOBAL_THREAD, PR_GLOBAL_BOUND_THREAD +}; static void Help(void) { @@ -478,7 +480,9 @@ int main(int argc, char **argv) PLOptState *opt = PL_CreateOptState(argc, argv, "dl:t:h"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { - if (PL_OPT_BAD == os) continue; + if (PL_OPT_BAD == os) { + continue; + } switch (opt->option) { case 'd': /* debug mode */ debug_mode = PR_TRUE; @@ -516,7 +520,7 @@ int main(int argc, char **argv) tolerance = PR_MillisecondsToInterval(tolerance_msecs); threads = PR_Malloc( - num_thread_scopes * num_thread_funcs * sizeof(PRThread*)); + num_thread_scopes * num_thread_funcs * sizeof(PRThread*)); if (threads == NULL) { fprintf(stderr, "PR_Malloc failed\n"); exit(1); @@ -525,11 +529,11 @@ int main(int argc, char **argv) /* start to time out 5 seconds after a rollover date */ secs = lead_time_secs + 5; idx = 0; - for (i = 0; i < num_thread_scopes; i++) { + for (i = 0; i < num_thread_scopes; i++) { for (j = 0; j < num_thread_funcs; j++) { threads[idx] = PR_CreateThread(PR_USER_THREAD, threadFuncs[j], - (void*)PR_SecondsToInterval(secs), PR_PRIORITY_NORMAL, - threadScopes[i], PR_JOINABLE_THREAD, 0); + (void*)PR_SecondsToInterval(secs), PR_PRIORITY_NORMAL, + threadScopes[i], PR_JOINABLE_THREAD, 0); if (threads[idx] == NULL) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); diff --git a/nsprpub/pr/tests/yield.c b/nsprpub/pr/tests/yield.c index c68166e17..eb55926b5 100644 --- a/nsprpub/pr/tests/yield.c +++ b/nsprpub/pr/tests/yield.c @@ -17,7 +17,7 @@ #define THREADS 10 -void +void threadmain(void *_id) { int id = (int)_id; @@ -43,14 +43,15 @@ int main(int argc, char **argv) for (index=0; index<THREADS; index++) { a[index] = PR_CreateThread(PR_USER_THREAD, - threadmain, - (void *)index, - PR_PRIORITY_NORMAL, - index%2?PR_LOCAL_THREAD:PR_GLOBAL_THREAD, - PR_JOINABLE_THREAD, - 0); + threadmain, + (void *)index, + PR_PRIORITY_NORMAL, + index%2?PR_LOCAL_THREAD:PR_GLOBAL_THREAD, + PR_JOINABLE_THREAD, + 0); } - for(index=0; index<THREADS; index++) + for(index=0; index<THREADS; index++) { PR_JoinThread(a[index]); + } printf("main dying\n"); } diff --git a/nsprpub/pr/tests/zerolen.c b/nsprpub/pr/tests/zerolen.c index a31d419e5..a84bd4322 100644 --- a/nsprpub/pr/tests/zerolen.c +++ b/nsprpub/pr/tests/zerolen.c @@ -4,7 +4,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* - * Test: zerolen.c + * Test: zerolen.c * * Description: a test for Bugzilla bug #17699. We perform * the same test for PR_Writev, PR_Write, and PR_Send. In @@ -72,7 +72,7 @@ static void ClientThread(void *arg) /* * Then start reading. */ - while ((nbytes = PR_Read(sock, buf, sizeof(buf))) > 0) { + while (nbytes = PR_Read(sock, buf, sizeof(buf)) > 0) { /* empty loop body */ } if (-1 == nbytes) { @@ -95,9 +95,6 @@ int main() char buf[1024]; PRInt32 nbytes; PRIOVec iov; -#ifdef SYMBIAN - int loopcount=0; -#endif memset(buf, 0, sizeof(buf)); /* Initialize the buffer. */ listenSock = PR_NewTCPSocket(); @@ -127,8 +124,8 @@ int main() * First test PR_Writev. */ clientThread = PR_CreateThread(PR_USER_THREAD, - ClientThread, (void *) PR_ntohs(PR_NetAddrInetPort(&addr)), - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); + ClientThread, (void *) PR_ntohs(PR_NetAddrInetPort(&addr)), + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); if (NULL == clientThread) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); @@ -139,11 +136,8 @@ int main() exit(1); } osfd = PR_FileDesc2NativeHandle(acceptSock); - while ((nbytes = write(osfd, buf, sizeof(buf))) != -1) { + while (write(osfd, buf, sizeof(buf)) != -1) { /* empty loop body */ -#ifdef SYMBIAN - if (loopcount++>64) break; -#endif } if ((errno != EAGAIN) && (errno != EWOULDBLOCK)) { fprintf(stderr, "write failed\n"); @@ -171,26 +165,20 @@ int main() * Then test PR_Write. */ clientThread = PR_CreateThread(PR_USER_THREAD, - ClientThread, (void *) PR_ntohs(PR_NetAddrInetPort(&addr)), - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); + ClientThread, (void *) PR_ntohs(PR_NetAddrInetPort(&addr)), + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); if (NULL == clientThread) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); } -#ifdef SYMBIAN - loopcount = 0; -#endif acceptSock = PR_Accept(listenSock, NULL, PR_INTERVAL_NO_TIMEOUT); if (NULL == acceptSock) { fprintf(stderr, "PR_Accept failed\n"); exit(1); } osfd = PR_FileDesc2NativeHandle(acceptSock); - while ((nbytes = write(osfd, buf, sizeof(buf))) != -1) { + while (write(osfd, buf, sizeof(buf)) != -1) { /* empty loop body */ -#ifdef SYMBIAN - if (loopcount++>64) break; -#endif } if ((errno != EAGAIN) && (errno != EWOULDBLOCK)) { fprintf(stderr, "write failed\n"); @@ -216,26 +204,20 @@ int main() * Finally test PR_Send. */ clientThread = PR_CreateThread(PR_USER_THREAD, - ClientThread, (void *) PR_ntohs(PR_NetAddrInetPort(&addr)), - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); + ClientThread, (void *) PR_ntohs(PR_NetAddrInetPort(&addr)), + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); if (NULL == clientThread) { fprintf(stderr, "PR_CreateThread failed\n"); exit(1); } -#ifdef SYMBIAN - loopcount = 0; -#endif acceptSock = PR_Accept(listenSock, NULL, PR_INTERVAL_NO_TIMEOUT); if (NULL == acceptSock) { fprintf(stderr, "PR_Accept failed\n"); exit(1); } osfd = PR_FileDesc2NativeHandle(acceptSock); - while ((nbytes = write(osfd, buf, sizeof(buf))) != -1) { + while (write(osfd, buf, sizeof(buf)) != -1) { /* empty loop body */ -#ifdef SYMBIAN - if (loopcount++>64) break; -#endif } if ((errno != EAGAIN) && (errno != EWOULDBLOCK)) { fprintf(stderr, "write failed\n"); |