Delete bundled copy of NSS and replace with README.
We are no longer maintaining this repository and keeping it up-to-date for
security fixes. It must not be used.
BUG=none
[email protected]
Review URL: https://codereview.chromium.org/2078763002 .
diff --git a/README.chromium b/README.chromium
deleted file mode 100644
index 8115aca..0000000
--- a/README.chromium
+++ /dev/null
@@ -1,70 +0,0 @@
-Name: Network Security Services (NSS)
-Short Name: nss
-URL: http://www.mozilla.org/projects/security/pki/nss/
-Version: 3.21
-License: MPL 2
-License File: nss/COPYING
-Security Critical: yes
-
-Description:
-NSS 3.21 with NSPR 4.11
-
-This copy of NSS has been customized for Chromium. NSPR is also put here
-rather than in a separate directory to emphasize the fact that Chromium is
-using NSPR strictly as an NSS dependency.
-
-We took a subset of NSS, omitting the SSL and SMIME libraries.
-This NSS subset satisfies the dependencies of the NSS SSL library in
-src/net/third_party/nss. Do NOT use this copy of NSS on platforms that
-have NSS as system libraries, such as Linux.
-
-The source code was checked out from the mozilla.org CVS or hg repository using
-the nspr-checkout.sh and nss-checkout.sh scripts in the scripts directory.
-The current source code was checked out with the hg tag NSS_3_21_RTM
-and the hg tag NSPR_4_11_RTM.
-
-Local Modifications:
-
-We made the following local changes to NSPR.
-- patches/nspr-static.patch: to build NSPR as static libraries. See NSPR
- bug 533014 (https://bugzilla.mozilla.org/show_bug.cgi?id=533014).
-- patches/prcpucfg.h: added to the nspr/pr/include directory.
-- patches/nspr-attach-as-system-thread.patch: attach a "foreign" thread
- (a thread not created by NSPR) to NSPR as a "system" thread rather than
- a "user" thread, which needs to terminate before PR_Cleanup can return.
- (The "system" vs. "user" thread distinction comes from Java, and
- ultimately from Solaris threads.) This is a workaround for
- http://crbug.com/40663.
-- patches/nspr-remove-io.patch: Remove IO operations in NSPR to allow NSS
- to work in the sandbox. Do not initialize IO when initializing NSPR.
- Windows version of NSPR also tried to use getaddrinfo to resolve hostname
- in a SSL connection. By removing _PR_HAVE_GETADDRINFO this will force it
- to use PR_GetHostByName. Removing _PR_INET6_PROBE will prevent it from
- creating an IPv6 socket to probe if IPv6 is there.
- DO NOT upstream this patch.
-
-We made the following local changes to NSS.
-
-Files Added:
-- nss/lib/ckfw/builtins/certdata.c: a generated file. Do an upstream NSS
- build and copy the generated certdata.c.
-- nss/lib/freebl/nss_build_config_mac.h: a header that defines the target
- arch specific configuration macros for lib/freebl on iOS and Mac OS X.
- This works around the lack of support for the xcode_settings
- GCC_PREPROCESSOR_DEFINITIONS[arch=foo] by the ninja GYP generator
- (http://crbug.com/122592).
-- nss/lib/freebl/mpi/mpi_arm_mac.c: a wrapper file for mpi_arm.c for iOS
- and Mac OS X. This works around the inability to specify target arch
- specific source files in Xcode.
-
-Patches Applied:
-- patches/nss-remove-fortezza.patch: remove Fortezza certificate support
- from PK11_ImportPublicKey. See NSS bug 668397
- (https://bugzilla.mozilla.org/show_bug.cgi?id=668397).
-- patches/nss-urandom-abort.patch: call abort() if NSS cannot read from
- /dev/urandom. See Chromium issue 244661 (http://crbug.com/244661).
-- patches/nss-static.patch: to build NSS as static libraries and omit
- libpkix (the new certification path validation library) and
- softoken/legacydb (support for the old Berkeley DB databases). See NSS
- bug 534471 (https://bugzilla.mozilla.org/show_bug.cgi?id=534471).
-
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..dc49e05
--- /dev/null
+++ b/README.md
@@ -0,0 +1,10 @@
+This NSS repository is unmaintained
+===================================
+
+Chromium no longer bundles NSS and has instead moved to
+[BoringSSL](https://boringssl.googlesource.com/boringssl/). As a result, this
+repository is unmaintained. It should not be used.
+
+Note: Although, as of writing, the Linux and Chromium OS ports of Chromium do
+use a system copy NSS for certificate verification, that has never used this
+repository.
diff --git a/nspr/LICENSE b/nspr/LICENSE
deleted file mode 100644
index 14e2f77..0000000
--- a/nspr/LICENSE
+++ /dev/null
@@ -1,373 +0,0 @@
-Mozilla Public License Version 2.0
-==================================
-
-1. Definitions
---------------
-
-1.1. "Contributor"
- means each individual or legal entity that creates, contributes to
- the creation of, or owns Covered Software.
-
-1.2. "Contributor Version"
- means the combination of the Contributions of others (if any) used
- by a Contributor and that particular Contributor's Contribution.
-
-1.3. "Contribution"
- means Covered Software of a particular Contributor.
-
-1.4. "Covered Software"
- means Source Code Form to which the initial Contributor has attached
- the notice in Exhibit A, the Executable Form of such Source Code
- Form, and Modifications of such Source Code Form, in each case
- including portions thereof.
-
-1.5. "Incompatible With Secondary Licenses"
- means
-
- (a) that the initial Contributor has attached the notice described
- in Exhibit B to the Covered Software; or
-
- (b) that the Covered Software was made available under the terms of
- version 1.1 or earlier of the License, but not also under the
- terms of a Secondary License.
-
-1.6. "Executable Form"
- means any form of the work other than Source Code Form.
-
-1.7. "Larger Work"
- means a work that combines Covered Software with other material, in
- a separate file or files, that is not Covered Software.
-
-1.8. "License"
- means this document.
-
-1.9. "Licensable"
- means having the right to grant, to the maximum extent possible,
- whether at the time of the initial grant or subsequently, any and
- all of the rights conveyed by this License.
-
-1.10. "Modifications"
- means any of the following:
-
- (a) any file in Source Code Form that results from an addition to,
- deletion from, or modification of the contents of Covered
- Software; or
-
- (b) any new file in Source Code Form that contains any Covered
- Software.
-
-1.11. "Patent Claims" of a Contributor
- means any patent claim(s), including without limitation, method,
- process, and apparatus claims, in any patent Licensable by such
- Contributor that would be infringed, but for the grant of the
- License, by the making, using, selling, offering for sale, having
- made, import, or transfer of either its Contributions or its
- Contributor Version.
-
-1.12. "Secondary License"
- means either the GNU General Public License, Version 2.0, the GNU
- Lesser General Public License, Version 2.1, the GNU Affero General
- Public License, Version 3.0, or any later versions of those
- licenses.
-
-1.13. "Source Code Form"
- means the form of the work preferred for making modifications.
-
-1.14. "You" (or "Your")
- means an individual or a legal entity exercising rights under this
- License. For legal entities, "You" includes any entity that
- controls, is controlled by, or is under common control with You. For
- purposes of this definition, "control" means (a) the power, direct
- or indirect, to cause the direction or management of such entity,
- whether by contract or otherwise, or (b) ownership of more than
- fifty percent (50%) of the outstanding shares or beneficial
- ownership of such entity.
-
-2. License Grants and Conditions
---------------------------------
-
-2.1. Grants
-
-Each Contributor hereby grants You a world-wide, royalty-free,
-non-exclusive license:
-
-(a) under intellectual property rights (other than patent or trademark)
- Licensable by such Contributor to use, reproduce, make available,
- modify, display, perform, distribute, and otherwise exploit its
- Contributions, either on an unmodified basis, with Modifications, or
- as part of a Larger Work; and
-
-(b) under Patent Claims of such Contributor to make, use, sell, offer
- for sale, have made, import, and otherwise transfer either its
- Contributions or its Contributor Version.
-
-2.2. Effective Date
-
-The licenses granted in Section 2.1 with respect to any Contribution
-become effective for each Contribution on the date the Contributor first
-distributes such Contribution.
-
-2.3. Limitations on Grant Scope
-
-The licenses granted in this Section 2 are the only rights granted under
-this License. No additional rights or licenses will be implied from the
-distribution or licensing of Covered Software under this License.
-Notwithstanding Section 2.1(b) above, no patent license is granted by a
-Contributor:
-
-(a) for any code that a Contributor has removed from Covered Software;
- or
-
-(b) for infringements caused by: (i) Your and any other third party's
- modifications of Covered Software, or (ii) the combination of its
- Contributions with other software (except as part of its Contributor
- Version); or
-
-(c) under Patent Claims infringed by Covered Software in the absence of
- its Contributions.
-
-This License does not grant any rights in the trademarks, service marks,
-or logos of any Contributor (except as may be necessary to comply with
-the notice requirements in Section 3.4).
-
-2.4. Subsequent Licenses
-
-No Contributor makes additional grants as a result of Your choice to
-distribute the Covered Software under a subsequent version of this
-License (see Section 10.2) or under the terms of a Secondary License (if
-permitted under the terms of Section 3.3).
-
-2.5. Representation
-
-Each Contributor represents that the Contributor believes its
-Contributions are its original creation(s) or it has sufficient rights
-to grant the rights to its Contributions conveyed by this License.
-
-2.6. Fair Use
-
-This License is not intended to limit any rights You have under
-applicable copyright doctrines of fair use, fair dealing, or other
-equivalents.
-
-2.7. Conditions
-
-Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
-in Section 2.1.
-
-3. Responsibilities
--------------------
-
-3.1. Distribution of Source Form
-
-All distribution of Covered Software in Source Code Form, including any
-Modifications that You create or to which You contribute, must be under
-the terms of this License. You must inform recipients that the Source
-Code Form of the Covered Software is governed by the terms of this
-License, and how they can obtain a copy of this License. You may not
-attempt to alter or restrict the recipients' rights in the Source Code
-Form.
-
-3.2. Distribution of Executable Form
-
-If You distribute Covered Software in Executable Form then:
-
-(a) such Covered Software must also be made available in Source Code
- Form, as described in Section 3.1, and You must inform recipients of
- the Executable Form how they can obtain a copy of such Source Code
- Form by reasonable means in a timely manner, at a charge no more
- than the cost of distribution to the recipient; and
-
-(b) You may distribute such Executable Form under the terms of this
- License, or sublicense it under different terms, provided that the
- license for the Executable Form does not attempt to limit or alter
- the recipients' rights in the Source Code Form under this License.
-
-3.3. Distribution of a Larger Work
-
-You may create and distribute a Larger Work under terms of Your choice,
-provided that You also comply with the requirements of this License for
-the Covered Software. If the Larger Work is a combination of Covered
-Software with a work governed by one or more Secondary Licenses, and the
-Covered Software is not Incompatible With Secondary Licenses, this
-License permits You to additionally distribute such Covered Software
-under the terms of such Secondary License(s), so that the recipient of
-the Larger Work may, at their option, further distribute the Covered
-Software under the terms of either this License or such Secondary
-License(s).
-
-3.4. Notices
-
-You may not remove or alter the substance of any license notices
-(including copyright notices, patent notices, disclaimers of warranty,
-or limitations of liability) contained within the Source Code Form of
-the Covered Software, except that You may alter any license notices to
-the extent required to remedy known factual inaccuracies.
-
-3.5. Application of Additional Terms
-
-You may choose to offer, and to charge a fee for, warranty, support,
-indemnity or liability obligations to one or more recipients of Covered
-Software. However, You may do so only on Your own behalf, and not on
-behalf of any Contributor. You must make it absolutely clear that any
-such warranty, support, indemnity, or liability obligation is offered by
-You alone, and You hereby agree to indemnify every Contributor for any
-liability incurred by such Contributor as a result of warranty, support,
-indemnity or liability terms You offer. You may include additional
-disclaimers of warranty and limitations of liability specific to any
-jurisdiction.
-
-4. Inability to Comply Due to Statute or Regulation
----------------------------------------------------
-
-If it is impossible for You to comply with any of the terms of this
-License with respect to some or all of the Covered Software due to
-statute, judicial order, or regulation then You must: (a) comply with
-the terms of this License to the maximum extent possible; and (b)
-describe the limitations and the code they affect. Such description must
-be placed in a text file included with all distributions of the Covered
-Software under this License. Except to the extent prohibited by statute
-or regulation, such description must be sufficiently detailed for a
-recipient of ordinary skill to be able to understand it.
-
-5. Termination
---------------
-
-5.1. The rights granted under this License will terminate automatically
-if You fail to comply with any of its terms. However, if You become
-compliant, then the rights granted under this License from a particular
-Contributor are reinstated (a) provisionally, unless and until such
-Contributor explicitly and finally terminates Your grants, and (b) on an
-ongoing basis, if such Contributor fails to notify You of the
-non-compliance by some reasonable means prior to 60 days after You have
-come back into compliance. Moreover, Your grants from a particular
-Contributor are reinstated on an ongoing basis if such Contributor
-notifies You of the non-compliance by some reasonable means, this is the
-first time You have received notice of non-compliance with this License
-from such Contributor, and You become compliant prior to 30 days after
-Your receipt of the notice.
-
-5.2. If You initiate litigation against any entity by asserting a patent
-infringement claim (excluding declaratory judgment actions,
-counter-claims, and cross-claims) alleging that a Contributor Version
-directly or indirectly infringes any patent, then the rights granted to
-You by any and all Contributors for the Covered Software under Section
-2.1 of this License shall terminate.
-
-5.3. In the event of termination under Sections 5.1 or 5.2 above, all
-end user license agreements (excluding distributors and resellers) which
-have been validly granted by You or Your distributors under this License
-prior to termination shall survive termination.
-
-************************************************************************
-* *
-* 6. Disclaimer of Warranty *
-* ------------------------- *
-* *
-* Covered Software is provided under this License on an "as is" *
-* basis, without warranty of any kind, either expressed, implied, or *
-* statutory, including, without limitation, warranties that the *
-* Covered Software is free of defects, merchantable, fit for a *
-* particular purpose or non-infringing. The entire risk as to the *
-* quality and performance of the Covered Software is with You. *
-* Should any Covered Software prove defective in any respect, You *
-* (not any Contributor) assume the cost of any necessary servicing, *
-* repair, or correction. This disclaimer of warranty constitutes an *
-* essential part of this License. No use of any Covered Software is *
-* authorized under this License except under this disclaimer. *
-* *
-************************************************************************
-
-************************************************************************
-* *
-* 7. Limitation of Liability *
-* -------------------------- *
-* *
-* Under no circumstances and under no legal theory, whether tort *
-* (including negligence), contract, or otherwise, shall any *
-* Contributor, or anyone who distributes Covered Software as *
-* permitted above, be liable to You for any direct, indirect, *
-* special, incidental, or consequential damages of any character *
-* including, without limitation, damages for lost profits, loss of *
-* goodwill, work stoppage, computer failure or malfunction, or any *
-* and all other commercial damages or losses, even if such party *
-* shall have been informed of the possibility of such damages. This *
-* limitation of liability shall not apply to liability for death or *
-* personal injury resulting from such party's negligence to the *
-* extent applicable law prohibits such limitation. Some *
-* jurisdictions do not allow the exclusion or limitation of *
-* incidental or consequential damages, so this exclusion and *
-* limitation may not apply to You. *
-* *
-************************************************************************
-
-8. Litigation
--------------
-
-Any litigation relating to this License may be brought only in the
-courts of a jurisdiction where the defendant maintains its principal
-place of business and such litigation shall be governed by laws of that
-jurisdiction, without reference to its conflict-of-law provisions.
-Nothing in this Section shall prevent a party's ability to bring
-cross-claims or counter-claims.
-
-9. Miscellaneous
-----------------
-
-This License represents the complete agreement concerning the subject
-matter hereof. If any provision of this License is held to be
-unenforceable, such provision shall be reformed only to the extent
-necessary to make it enforceable. Any law or regulation which provides
-that the language of a contract shall be construed against the drafter
-shall not be used to construe this License against a Contributor.
-
-10. Versions of the License
----------------------------
-
-10.1. New Versions
-
-Mozilla Foundation is the license steward. Except as provided in Section
-10.3, no one other than the license steward has the right to modify or
-publish new versions of this License. Each version will be given a
-distinguishing version number.
-
-10.2. Effect of New Versions
-
-You may distribute the Covered Software under the terms of the version
-of the License under which You originally received the Covered Software,
-or under the terms of any subsequent version published by the license
-steward.
-
-10.3. Modified Versions
-
-If you create software not governed by this License, and you want to
-create a new license for such software, you may create and use a
-modified version of this License if you rename the license and remove
-any references to the name of the license steward (except to note that
-such modified license differs from this License).
-
-10.4. Distributing Source Code Form that is Incompatible With Secondary
-Licenses
-
-If You choose to distribute Source Code Form that is Incompatible With
-Secondary Licenses under the terms of this version of the License, the
-notice described in Exhibit B of this License must be attached.
-
-Exhibit A - Source Code Form License Notice
--------------------------------------------
-
- 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/.
-
-If it is not possible or desirable to put the notice in a particular
-file, then You may include the notice in a location (such as a LICENSE
-file in a relevant directory) where a recipient would be likely to look
-for such a notice.
-
-You may add additional accurate notices of copyright ownership.
-
-Exhibit B - "Incompatible With Secondary Licenses" Notice
----------------------------------------------------------
-
- This Source Code Form is "Incompatible With Secondary Licenses", as
- defined by the Mozilla Public License, v. 2.0.
diff --git a/nspr/lib/ds/plarena.c b/nspr/lib/ds/plarena.c
deleted file mode 100644
index 689496d..0000000
--- a/nspr/lib/ds/plarena.c
+++ /dev/null
@@ -1,452 +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/. */
-
-/*
- * Lifetime-based fast allocation, inspired by much prior art, including
- * "Fast Allocation and Deallocation of Memory Based on Object Lifetimes"
- * David R. Hanson, Software -- Practice and Experience, Vol. 20(1).
- */
-#include <stdlib.h>
-#include <string.h>
-#include "plarena.h"
-#include "prmem.h"
-#include "prbit.h"
-#include "prlog.h"
-#include "prlock.h"
-#include "prinit.h"
-
-static PLArena *arena_freelist;
-
-#ifdef PL_ARENAMETER
-static PLArenaStats *arena_stats_list;
-
-#define COUNT(pool,what) (pool)->stats.what++
-#else
-#define COUNT(pool,what) /* nothing */
-#endif
-
-#define PL_ARENA_DEFAULT_ALIGN sizeof(double)
-
-static PRLock *arenaLock;
-static PRCallOnceType once;
-static const PRCallOnceType pristineCallOnce;
-
-/*
-** InitializeArenas() -- Initialize arena operations.
-**
-** InitializeArenas() is called exactly once and only once from
-** LockArena(). This function creates the arena protection
-** lock: arenaLock.
-**
-** Note: If the arenaLock cannot be created, InitializeArenas()
-** fails quietly, returning only PR_FAILURE. This percolates up
-** to the application using the Arena API. He gets no arena
-** from PL_ArenaAllocate(). It's up to him to fail gracefully
-** or recover.
-**
-*/
-static PRStatus InitializeArenas( void )
-{
- PR_ASSERT( arenaLock == NULL );
- arenaLock = PR_NewLock();
- if ( arenaLock == NULL )
- return PR_FAILURE;
- else
- return PR_SUCCESS;
-} /* end ArenaInitialize() */
-
-static PRStatus LockArena( void )
-{
- PRStatus rc = PR_CallOnce( &once, InitializeArenas );
-
- if ( PR_FAILURE != rc )
- PR_Lock( arenaLock );
- return(rc);
-} /* end LockArena() */
-
-static void UnlockArena( void )
-{
- PR_Unlock( arenaLock );
- return;
-} /* end UnlockArena() */
-
-PR_IMPLEMENT(void) PL_InitArenaPool(
- PLArenaPool *pool, const char *name, PRUint32 size, PRUint32 align)
-{
- /*
- * Look-up table of PR_BITMASK(PR_CeilingLog2(align)) values for
- * align = 1 to 32.
- */
- static const PRUint8 pmasks[33] = {
- 0, /* not used */
- 0, 1, 3, 3, 7, 7, 7, 7,15,15,15,15,15,15,15,15, /* 1 ... 16 */
- 31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31}; /* 17 ... 32 */
-
- if (align == 0)
- align = PL_ARENA_DEFAULT_ALIGN;
-
- if (align < sizeof(pmasks)/sizeof(pmasks[0]))
- pool->mask = pmasks[align];
- else
- pool->mask = PR_BITMASK(PR_CeilingLog2(align));
-
- pool->first.next = NULL;
- /* Set all three addresses in pool->first to the same dummy value.
- * These addresses are only compared with each other, but never
- * dereferenced. */
- pool->first.base = pool->first.avail = pool->first.limit =
- (PRUword)PL_ARENA_ALIGN(pool, &pool->first + 1);
- pool->current = &pool->first;
- /*
- * Compute the net size so that each arena's gross size is |size|.
- * sizeof(PLArena) + pool->mask is the header and alignment slop
- * that PL_ArenaAllocate adds to the net size.
- */
- if (size > sizeof(PLArena) + pool->mask)
- pool->arenasize = size - (sizeof(PLArena) + pool->mask);
- else
- pool->arenasize = size;
-#ifdef PL_ARENAMETER
- memset(&pool->stats, 0, sizeof pool->stats);
- pool->stats.name = strdup(name);
- pool->stats.next = arena_stats_list;
- arena_stats_list = &pool->stats;
-#endif
-}
-
-
-/*
-** PL_ArenaAllocate() -- allocate space from an arena pool
-**
-** Description: PL_ArenaAllocate() allocates space from an arena
-** pool.
-**
-** First, try to satisfy the request from arenas starting at
-** pool->current.
-**
-** If there is not enough space in the arena pool->current, try
-** to claim an arena, on a first fit basis, from the global
-** freelist (arena_freelist).
-**
-** If no arena in arena_freelist is suitable, then try to
-** allocate a new arena from the heap.
-**
-** Returns: pointer to allocated space or NULL
-**
-** Notes: The original implementation had some difficult to
-** solve bugs; the code was difficult to read. Sometimes it's
-** just easier to rewrite it. I did that. larryh.
-**
-** See also: bugzilla: 45343.
-**
-*/
-
-PR_IMPLEMENT(void *) PL_ArenaAllocate(PLArenaPool *pool, PRUint32 nb)
-{
- PLArena *a;
- char *rp; /* returned pointer */
- PRUint32 nbOld;
-
- PR_ASSERT((nb & pool->mask) == 0);
-
- nbOld = nb;
- nb = (PRUword)PL_ARENA_ALIGN(pool, nb); /* force alignment */
- if (nb < nbOld)
- return NULL;
-
- /* attempt to allocate from arenas at pool->current */
- {
- a = pool->current;
- do {
- if ( nb <= a->limit - a->avail ) {
- pool->current = a;
- rp = (char *)a->avail;
- a->avail += nb;
- return rp;
- }
- } while( NULL != (a = a->next) );
- }
-
- /* attempt to allocate from arena_freelist */
- {
- PLArena *p; /* previous pointer, for unlinking from freelist */
-
- /* lock the arena_freelist. Make access to the freelist MT-Safe */
- if ( PR_FAILURE == LockArena())
- return(0);
-
- for ( a = arena_freelist, p = NULL; a != NULL ; p = a, a = a->next ) {
- if ( nb <= a->limit - a->base ) {
- if ( p == NULL )
- arena_freelist = a->next;
- else
- p->next = a->next;
- UnlockArena();
- a->avail = a->base;
- rp = (char *)a->avail;
- a->avail += nb;
- /* the newly allocated arena is linked after pool->current
- * and becomes pool->current */
- a->next = pool->current->next;
- pool->current->next = a;
- pool->current = a;
- if ( NULL == pool->first.next )
- pool->first.next = a;
- return(rp);
- }
- }
- UnlockArena();
- }
-
- /* attempt to allocate from the heap */
- {
- PRUint32 sz = PR_MAX(pool->arenasize, nb);
- if (PR_UINT32_MAX - sz < sizeof *a + pool->mask) {
- a = NULL;
- } else {
- sz += sizeof *a + pool->mask; /* header and alignment slop */
- a = (PLArena*)PR_MALLOC(sz);
- }
- if ( NULL != a ) {
- a->limit = (PRUword)a + sz;
- a->base = a->avail = (PRUword)PL_ARENA_ALIGN(pool, a + 1);
- PL_MAKE_MEM_NOACCESS((void*)a->avail, a->limit - a->avail);
- rp = (char *)a->avail;
- a->avail += nb;
- PR_ASSERT(a->avail <= a->limit);
- /* the newly allocated arena is linked after pool->current
- * and becomes pool->current */
- a->next = pool->current->next;
- pool->current->next = a;
- pool->current = a;
- if ( NULL == pool->first.next )
- pool->first.next = a;
- PL_COUNT_ARENA(pool,++);
- COUNT(pool, nmallocs);
- return(rp);
- }
- }
-
- /* we got to here, and there's no memory to allocate */
- return(NULL);
-} /* --- end PL_ArenaAllocate() --- */
-
-PR_IMPLEMENT(void *) PL_ArenaGrow(
- PLArenaPool *pool, void *p, PRUint32 size, PRUint32 incr)
-{
- void *newp;
-
- if (PR_UINT32_MAX - size < incr)
- return NULL;
- PL_ARENA_ALLOCATE(newp, pool, size + incr);
- if (newp)
- memcpy(newp, p, size);
- return newp;
-}
-
-static void ClearArenaList(PLArena *a, PRInt32 pattern)
-{
-
- for (; a; a = a->next) {
- PR_ASSERT(a->base <= a->avail && a->avail <= a->limit);
- a->avail = a->base;
- PL_CLEAR_UNUSED_PATTERN(a, pattern);
- PL_MAKE_MEM_NOACCESS((void*)a->avail, a->limit - a->avail);
- }
-}
-
-PR_IMPLEMENT(void) PL_ClearArenaPool(PLArenaPool *pool, PRInt32 pattern)
-{
- ClearArenaList(pool->first.next, pattern);
-}
-
-/*
- * Free tail arenas linked after head, which may not be the true list head.
- * Reset pool->current to point to head in case it pointed at a tail arena.
- */
-static void FreeArenaList(PLArenaPool *pool, PLArena *head, PRBool reallyFree)
-{
- PLArena **ap, *a;
-
- ap = &head->next;
- a = *ap;
- if (!a)
- return;
-
-#ifdef DEBUG
- ClearArenaList(a, PL_FREE_PATTERN);
-#endif
-
- if (reallyFree) {
- do {
- *ap = a->next;
- PL_CLEAR_ARENA(a);
- PL_COUNT_ARENA(pool,--);
- PR_DELETE(a);
- } while ((a = *ap) != 0);
- } else {
- /* Insert the whole arena chain at the front of the freelist. */
- do {
- PL_MAKE_MEM_NOACCESS((void*)(*ap)->base,
- (*ap)->limit - (*ap)->base);
- ap = &(*ap)->next;
- } while (*ap);
- LockArena();
- *ap = arena_freelist;
- arena_freelist = a;
- head->next = 0;
- UnlockArena();
- }
-
- pool->current = head;
-}
-
-PR_IMPLEMENT(void) PL_ArenaRelease(PLArenaPool *pool, char *mark)
-{
- PLArena *a;
-
- for (a = &pool->first; a; a = a->next) {
- if (PR_UPTRDIFF(mark, a->base) <= PR_UPTRDIFF(a->avail, a->base)) {
- a->avail = (PRUword)PL_ARENA_ALIGN(pool, mark);
- FreeArenaList(pool, a, PR_FALSE);
- return;
- }
- }
-}
-
-PR_IMPLEMENT(void) PL_FreeArenaPool(PLArenaPool *pool)
-{
- FreeArenaList(pool, &pool->first, PR_FALSE);
- COUNT(pool, ndeallocs);
-}
-
-PR_IMPLEMENT(void) PL_FinishArenaPool(PLArenaPool *pool)
-{
- FreeArenaList(pool, &pool->first, PR_TRUE);
-#ifdef PL_ARENAMETER
- {
- PLArenaStats *stats, **statsp;
-
- if (pool->stats.name)
- PR_DELETE(pool->stats.name);
- for (statsp = &arena_stats_list; (stats = *statsp) != 0;
- statsp = &stats->next) {
- if (stats == &pool->stats) {
- *statsp = stats->next;
- return;
- }
- }
- }
-#endif
-}
-
-PR_IMPLEMENT(void) PL_CompactArenaPool(PLArenaPool *ap)
-{
-}
-
-PR_IMPLEMENT(void) PL_ArenaFinish(void)
-{
- PLArena *a, *next;
-
- for (a = arena_freelist; a; a = next) {
- next = a->next;
- PR_DELETE(a);
- }
- arena_freelist = NULL;
-
- if (arenaLock) {
- PR_DestroyLock(arenaLock);
- arenaLock = NULL;
- }
- once = pristineCallOnce;
-}
-
-PR_IMPLEMENT(size_t) PL_SizeOfArenaPoolExcludingPool(
- const PLArenaPool *pool, PLMallocSizeFn mallocSizeOf)
-{
- /*
- * The first PLArena is within |pool|, so don't measure it. Subsequent
- * PLArenas are separate and must be measured.
- */
- size_t size = 0;
- const PLArena *arena = pool->first.next;
- while (arena) {
- size += mallocSizeOf(arena);
- arena = arena->next;
- }
- return size;
-}
-
-#ifdef PL_ARENAMETER
-PR_IMPLEMENT(void) PL_ArenaCountAllocation(PLArenaPool *pool, PRUint32 nb)
-{
- pool->stats.nallocs++;
- pool->stats.nbytes += nb;
- if (nb > pool->stats.maxalloc)
- pool->stats.maxalloc = nb;
- pool->stats.variance += nb * nb;
-}
-
-PR_IMPLEMENT(void) PL_ArenaCountInplaceGrowth(
- PLArenaPool *pool, PRUint32 size, PRUint32 incr)
-{
- pool->stats.ninplace++;
-}
-
-PR_IMPLEMENT(void) PL_ArenaCountGrowth(
- PLArenaPool *pool, PRUint32 size, PRUint32 incr)
-{
- pool->stats.ngrows++;
- pool->stats.nbytes += incr;
- pool->stats.variance -= size * size;
- size += incr;
- if (size > pool->stats.maxalloc)
- pool->stats.maxalloc = size;
- pool->stats.variance += size * size;
-}
-
-PR_IMPLEMENT(void) PL_ArenaCountRelease(PLArenaPool *pool, char *mark)
-{
- pool->stats.nreleases++;
-}
-
-PR_IMPLEMENT(void) PL_ArenaCountRetract(PLArenaPool *pool, char *mark)
-{
- pool->stats.nfastrels++;
-}
-
-#include <math.h>
-#include <stdio.h>
-
-PR_IMPLEMENT(void) PL_DumpArenaStats(FILE *fp)
-{
- PLArenaStats *stats;
- double mean, variance;
-
- for (stats = arena_stats_list; stats; stats = stats->next) {
- if (stats->nallocs != 0) {
- mean = (double)stats->nbytes / stats->nallocs;
- variance = fabs(stats->variance / stats->nallocs - mean * mean);
- } else {
- mean = variance = 0;
- }
-
- fprintf(fp, "\n%s allocation statistics:\n", stats->name);
- fprintf(fp, " number of arenas: %u\n", stats->narenas);
- fprintf(fp, " number of allocations: %u\n", stats->nallocs);
- fprintf(fp, " number of free arena reclaims: %u\n", stats->nreclaims);
- fprintf(fp, " number of malloc calls: %u\n", stats->nmallocs);
- fprintf(fp, " number of deallocations: %u\n", stats->ndeallocs);
- fprintf(fp, " number of allocation growths: %u\n", stats->ngrows);
- fprintf(fp, " number of in-place growths: %u\n", stats->ninplace);
- fprintf(fp, "number of released allocations: %u\n", stats->nreleases);
- fprintf(fp, " number of fast releases: %u\n", stats->nfastrels);
- fprintf(fp, " total bytes allocated: %u\n", stats->nbytes);
- fprintf(fp, " mean allocation size: %g\n", mean);
- fprintf(fp, " standard deviation: %g\n", sqrt(variance));
- fprintf(fp, " maximum allocation size: %u\n", stats->maxalloc);
- }
-}
-#endif /* PL_ARENAMETER */
diff --git a/nspr/lib/ds/plarena.h b/nspr/lib/ds/plarena.h
deleted file mode 100644
index 2673a2a..0000000
--- a/nspr/lib/ds/plarena.h
+++ /dev/null
@@ -1,258 +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/. */
-
-#ifndef plarena_h___
-#define plarena_h___
-/*
- * Lifetime-based fast allocation, inspired by much prior art, including
- * "Fast Allocation and Deallocation of Memory Based on Object Lifetimes"
- * David R. Hanson, Software -- Practice and Experience, Vol. 20(1).
- *
- * Also supports LIFO allocation (PL_ARENA_MARK/PL_ARENA_RELEASE).
- */
-#include "prtypes.h"
-#include "plarenas.h"
-
-PR_BEGIN_EXTERN_C
-
-typedef struct PLArena PLArena;
-
-struct PLArena {
- PLArena *next; /* next arena for this lifetime */
- PRUword base; /* aligned base address, follows this header */
- PRUword limit; /* one beyond last byte in arena */
- PRUword avail; /* points to next available byte */
-};
-
-#ifdef PL_ARENAMETER
-typedef struct PLArenaStats PLArenaStats;
-
-struct PLArenaStats {
- PLArenaStats *next; /* next in arenaStats list */
- char *name; /* name for debugging */
- PRUint32 narenas; /* number of arenas in pool */
- PRUint32 nallocs; /* number of PL_ARENA_ALLOCATE() calls */
- PRUint32 nreclaims; /* number of reclaims from freeArenas */
- PRUint32 nmallocs; /* number of malloc() calls */
- PRUint32 ndeallocs; /* number of lifetime deallocations */
- PRUint32 ngrows; /* number of PL_ARENA_GROW() calls */
- PRUint32 ninplace; /* number of in-place growths */
- PRUint32 nreleases; /* number of PL_ARENA_RELEASE() calls */
- PRUint32 nfastrels; /* number of "fast path" releases */
- PRUint32 nbytes; /* total bytes allocated */
- PRUint32 maxalloc; /* maximum allocation size in bytes */
- PRFloat64 variance; /* size variance accumulator */
-};
-#endif
-
-struct PLArenaPool {
- PLArena first; /* first arena in pool list */
- PLArena *current; /* arena from which to allocate space */
- PRUint32 arenasize; /* net exact size of a new arena */
- PRUword mask; /* alignment mask (power-of-2 - 1) */
-#ifdef PL_ARENAMETER
- PLArenaStats stats;
-#endif
-};
-
-/*
- * WARNING: The PL_MAKE_MEM_ macros are for internal use by NSPR. Do NOT use
- * them in your code.
- *
- * NOTE: Valgrind support to be added.
- *
- * The PL_MAKE_MEM_ macros are modeled after the MOZ_MAKE_MEM_ macros in
- * Mozilla's mfbt/MemoryChecking.h. Only AddressSanitizer is supported now.
- *
- * Provides a common interface to the ASan (AddressSanitizer) and Valgrind
- * functions used to mark memory in certain ways. In detail, the following
- * three macros are provided:
- *
- * PL_MAKE_MEM_NOACCESS - Mark memory as unsafe to access (e.g. freed)
- * PL_MAKE_MEM_UNDEFINED - Mark memory as accessible, with content undefined
- * PL_MAKE_MEM_DEFINED - Mark memory as accessible, with content defined
- *
- * With Valgrind in use, these directly map to the three respective Valgrind
- * macros. With ASan in use, the NOACCESS macro maps to poisoning the memory,
- * while the UNDEFINED/DEFINED macros unpoison memory.
- *
- * With no memory checker available, all macros expand to the empty statement.
- */
-
-/* WARNING: PL_SANITIZE_ADDRESS is for internal use by this header. Do NOT
- * define or test this macro in your code.
- */
-#if defined(__has_feature)
-#if __has_feature(address_sanitizer)
-#define PL_SANITIZE_ADDRESS 1
-#endif
-#elif defined(__SANITIZE_ADDRESS__)
-#define PL_SANITIZE_ADDRESS 1
-#endif
-
-#if defined(PL_SANITIZE_ADDRESS)
-
-/* These definitions are usually provided through the
- * sanitizer/asan_interface.h header installed by ASan.
- * See https://github.com/google/sanitizers/wiki/AddressSanitizerManualPoisoning
- */
-
-PR_IMPORT(void) __asan_poison_memory_region(void const volatile *addr, size_t size);
-PR_IMPORT(void) __asan_unpoison_memory_region(void const volatile *addr, size_t size);
-
-#define PL_MAKE_MEM_NOACCESS(addr, size) \
- __asan_poison_memory_region((addr), (size))
-
-#define PL_MAKE_MEM_UNDEFINED(addr, size) \
- __asan_unpoison_memory_region((addr), (size))
-
-#define PL_MAKE_MEM_DEFINED(addr, size) \
- __asan_unpoison_memory_region((addr), (size))
-
-#else
-
-#define PL_MAKE_MEM_NOACCESS(addr, size)
-#define PL_MAKE_MEM_UNDEFINED(addr, size)
-#define PL_MAKE_MEM_DEFINED(addr, size)
-
-#endif
-
-/*
- * If the including .c file uses only one power-of-2 alignment, it may define
- * PL_ARENA_CONST_ALIGN_MASK to the alignment mask and save a few instructions
- * per ALLOCATE and GROW.
- */
-#ifdef PL_ARENA_CONST_ALIGN_MASK
-#define PL_ARENA_ALIGN(pool, n) (((PRUword)(n) + PL_ARENA_CONST_ALIGN_MASK) \
- & ~PL_ARENA_CONST_ALIGN_MASK)
-
-#define PL_INIT_ARENA_POOL(pool, name, size) \
- PL_InitArenaPool(pool, name, size, PL_ARENA_CONST_ALIGN_MASK + 1)
-#else
-#define PL_ARENA_ALIGN(pool, n) (((PRUword)(n) + (pool)->mask) & ~(pool)->mask)
-#endif
-
-#define PL_ARENA_ALLOCATE(p, pool, nb) \
- PR_BEGIN_MACRO \
- PLArena *_a = (pool)->current; \
- PRUint32 _nb = PL_ARENA_ALIGN(pool, (PRUint32)nb); \
- PRUword _p = _a->avail; \
- if (_nb < (PRUint32)nb) { \
- _p = 0; \
- } else if (_nb > (_a->limit - _a->avail)) { \
- _p = (PRUword)PL_ArenaAllocate(pool, _nb); \
- } else { \
- _a->avail += _nb; \
- } \
- p = (void *)_p; \
- if (p) { \
- PL_MAKE_MEM_UNDEFINED(p, (PRUint32)nb); \
- PL_ArenaCountAllocation(pool, (PRUint32)nb); \
- } \
- PR_END_MACRO
-
-#define PL_ARENA_GROW(p, pool, size, incr) \
- PR_BEGIN_MACRO \
- PLArena *_a = (pool)->current; \
- PRUint32 _incr = PL_ARENA_ALIGN(pool, (PRUint32)incr); \
- if (_incr < (PRUint32)incr) { \
- p = NULL; \
- } else if (_a->avail == (PRUword)(p) + PL_ARENA_ALIGN(pool, size) && \
- _incr <= (_a->limit - _a->avail)) { \
- PL_MAKE_MEM_UNDEFINED((unsigned char *)(p) + size, (PRUint32)incr); \
- _a->avail += _incr; \
- PL_ArenaCountInplaceGrowth(pool, size, (PRUint32)incr); \
- } else { \
- p = PL_ArenaGrow(pool, p, size, (PRUint32)incr); \
- } \
- if (p) {\
- PL_ArenaCountGrowth(pool, size, (PRUint32)incr); \
- } \
- PR_END_MACRO
-
-#define PL_ARENA_MARK(pool) ((void *) (pool)->current->avail)
-#define PR_UPTRDIFF(p,q) ((PRUword)(p) - (PRUword)(q))
-
-#define PL_CLEAR_UNUSED_PATTERN(a, pattern) \
- PR_BEGIN_MACRO \
- PR_ASSERT((a)->avail <= (a)->limit); \
- PL_MAKE_MEM_UNDEFINED((void*)(a)->avail, (a)->limit - (a)->avail); \
- memset((void*)(a)->avail, (pattern), (a)->limit - (a)->avail); \
- PR_END_MACRO
-#ifdef DEBUG
-#define PL_FREE_PATTERN 0xDA
-#define PL_CLEAR_UNUSED(a) PL_CLEAR_UNUSED_PATTERN((a), PL_FREE_PATTERN)
-#define PL_CLEAR_ARENA(a) \
- PR_BEGIN_MACRO \
- PL_MAKE_MEM_UNDEFINED((void*)(a), (a)->limit - (PRUword)(a)); \
- memset((void*)(a), PL_FREE_PATTERN, (a)->limit - (PRUword)(a)); \
- PR_END_MACRO
-#else
-#define PL_CLEAR_UNUSED(a)
-#define PL_CLEAR_ARENA(a)
-#endif
-
-#define PL_ARENA_RELEASE(pool, mark) \
- PR_BEGIN_MACRO \
- char *_m = (char *)(mark); \
- PLArena *_a = (pool)->current; \
- if (PR_UPTRDIFF(_m, _a->base) <= PR_UPTRDIFF(_a->avail, _a->base)) { \
- _a->avail = (PRUword)PL_ARENA_ALIGN(pool, _m); \
- PL_CLEAR_UNUSED(_a); \
- PL_MAKE_MEM_NOACCESS((void*)_a->avail, _a->limit - _a->avail); \
- PL_ArenaCountRetract(pool, _m); \
- } else { \
- PL_ArenaRelease(pool, _m); \
- } \
- PL_ArenaCountRelease(pool, _m); \
- PR_END_MACRO
-
-#ifdef PL_ARENAMETER
-#define PL_COUNT_ARENA(pool,op) ((pool)->stats.narenas op)
-#else
-#define PL_COUNT_ARENA(pool,op)
-#endif
-
-#define PL_ARENA_DESTROY(pool, a, pnext) \
- PR_BEGIN_MACRO \
- PL_COUNT_ARENA(pool,--); \
- if ((pool)->current == (a)) (pool)->current = &(pool)->first; \
- *(pnext) = (a)->next; \
- PL_CLEAR_ARENA(a); \
- free(a); \
- (a) = 0; \
- PR_END_MACRO
-
-#ifdef PL_ARENAMETER
-
-#include <stdio.h>
-
-PR_EXTERN(void) PL_ArenaCountAllocation(PLArenaPool *pool, PRUint32 nb);
-
-PR_EXTERN(void) PL_ArenaCountInplaceGrowth(
- PLArenaPool *pool, PRUint32 size, PRUint32 incr);
-
-PR_EXTERN(void) PL_ArenaCountGrowth(
- PLArenaPool *pool, PRUint32 size, PRUint32 incr);
-
-PR_EXTERN(void) PL_ArenaCountRelease(PLArenaPool *pool, char *mark);
-
-PR_EXTERN(void) PL_ArenaCountRetract(PLArenaPool *pool, char *mark);
-
-PR_EXTERN(void) PL_DumpArenaStats(FILE *fp);
-
-#else /* !PL_ARENAMETER */
-
-#define PL_ArenaCountAllocation(ap, nb) /* nothing */
-#define PL_ArenaCountInplaceGrowth(ap, size, incr) /* nothing */
-#define PL_ArenaCountGrowth(ap, size, incr) /* nothing */
-#define PL_ArenaCountRelease(ap, mark) /* nothing */
-#define PL_ArenaCountRetract(ap, mark) /* nothing */
-
-#endif /* !PL_ARENAMETER */
-
-PR_END_EXTERN_C
-
-#endif /* plarena_h___ */
diff --git a/nspr/lib/ds/plarenas.h b/nspr/lib/ds/plarenas.h
deleted file mode 100644
index 98bd7f8..0000000
--- a/nspr/lib/ds/plarenas.h
+++ /dev/null
@@ -1,81 +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/. */
-
-#ifndef PLARENAS_H
-#define PLARENAS_H
-
-PR_BEGIN_EXTERN_C
-
-typedef struct PLArenaPool PLArenaPool;
-
-/*
-** Initialize an arena pool with the given name for debugging and metering,
-** with a minimum gross size per arena of size bytes. The net size per arena
-** is smaller than the gross size by a header of four pointers plus any
-** necessary padding for alignment.
-**
-** Note: choose a gross size that's a power of two to avoid the heap allocator
-** rounding the size up.
-**/
-PR_EXTERN(void) PL_InitArenaPool(
- PLArenaPool *pool, const char *name, PRUint32 size, PRUint32 align);
-
-/*
-** Finish using arenas, freeing all memory associated with them.
-**/
-PR_EXTERN(void) PL_ArenaFinish(void);
-
-/*
-** Free the arenas in pool. The user may continue to allocate from pool
-** after calling this function. There is no need to call PL_InitArenaPool()
-** again unless PL_FinishArenaPool(pool) has been called.
-**/
-PR_EXTERN(void) PL_FreeArenaPool(PLArenaPool *pool);
-
-/*
-** Free the arenas in pool and finish using it altogether.
-**/
-PR_EXTERN(void) PL_FinishArenaPool(PLArenaPool *pool);
-
-/*
-** Compact all of the arenas in a pool so that no space is wasted.
-** NOT IMPLEMENTED. Do not use.
-**/
-PR_EXTERN(void) PL_CompactArenaPool(PLArenaPool *pool);
-
-/*
-** Friend functions used by the PL_ARENA_*() macros.
-**
-** WARNING: do not call these functions directly. Always use the
-** PL_ARENA_*() macros.
-**/
-PR_EXTERN(void *) PL_ArenaAllocate(PLArenaPool *pool, PRUint32 nb);
-
-PR_EXTERN(void *) PL_ArenaGrow(
- PLArenaPool *pool, void *p, PRUint32 size, PRUint32 incr);
-
-PR_EXTERN(void) PL_ArenaRelease(PLArenaPool *pool, char *mark);
-
-/*
-** memset contents of all arenas in pool to pattern
-*/
-PR_EXTERN(void) PL_ClearArenaPool(PLArenaPool *pool, PRInt32 pattern);
-
-/*
-** A function like malloc_size() or malloc_usable_size() that measures the
-** size of a heap block.
-*/
-typedef size_t (*PLMallocSizeFn)(const void *ptr);
-
-/*
-** Measure all memory used by a PLArenaPool, excluding the PLArenaPool
-** structure.
-*/
-PR_EXTERN(size_t) PL_SizeOfArenaPoolExcludingPool(
- const PLArenaPool *pool, PLMallocSizeFn mallocSizeOf);
-
-PR_END_EXTERN_C
-
-#endif /* PLARENAS_H */
diff --git a/nspr/lib/ds/plhash.c b/nspr/lib/ds/plhash.c
deleted file mode 100644
index 0011df3..0000000
--- a/nspr/lib/ds/plhash.c
+++ /dev/null
@@ -1,483 +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/. */
-
-/*
- * PL hash table package.
- */
-#include "plhash.h"
-#include "prbit.h"
-#include "prlog.h"
-#include "prmem.h"
-#include "prtypes.h"
-#include <stdlib.h>
-#include <string.h>
-
-/* Compute the number of buckets in ht */
-#define NBUCKETS(ht) (1 << (PL_HASH_BITS - (ht)->shift))
-
-/* The smallest table has 16 buckets */
-#define MINBUCKETSLOG2 4
-#define MINBUCKETS (1 << MINBUCKETSLOG2)
-
-/* Compute the maximum entries given n buckets that we will tolerate, ~90% */
-#define OVERLOADED(n) ((n) - ((n) >> 3))
-
-/* Compute the number of entries below which we shrink the table by half */
-#define UNDERLOADED(n) (((n) > MINBUCKETS) ? ((n) >> 2) : 0)
-
-/*
-** Stubs for default hash allocator ops.
-*/
-static void * PR_CALLBACK
-DefaultAllocTable(void *pool, PRSize size)
-{
- return PR_MALLOC(size);
-}
-
-static void PR_CALLBACK
-DefaultFreeTable(void *pool, void *item)
-{
- PR_Free(item);
-}
-
-static PLHashEntry * PR_CALLBACK
-DefaultAllocEntry(void *pool, const void *key)
-{
- return PR_NEW(PLHashEntry);
-}
-
-static void PR_CALLBACK
-DefaultFreeEntry(void *pool, PLHashEntry *he, PRUintn flag)
-{
- if (flag == HT_FREE_ENTRY)
- PR_Free(he);
-}
-
-static PLHashAllocOps defaultHashAllocOps = {
- DefaultAllocTable, DefaultFreeTable,
- DefaultAllocEntry, DefaultFreeEntry
-};
-
-PR_IMPLEMENT(PLHashTable *)
-PL_NewHashTable(PRUint32 n, PLHashFunction keyHash,
- PLHashComparator keyCompare, PLHashComparator valueCompare,
- const PLHashAllocOps *allocOps, void *allocPriv)
-{
- PLHashTable *ht;
- PRSize nb;
-
- if (n <= MINBUCKETS) {
- n = MINBUCKETSLOG2;
- } else {
- n = PR_CeilingLog2(n);
- if ((PRInt32)n < 0)
- return 0;
- }
-
- if (!allocOps) allocOps = &defaultHashAllocOps;
-
- ht = (PLHashTable*)((*allocOps->allocTable)(allocPriv, sizeof *ht));
- if (!ht)
- return 0;
- memset(ht, 0, sizeof *ht);
- ht->shift = PL_HASH_BITS - n;
- n = 1 << n;
- nb = n * sizeof(PLHashEntry *);
- ht->buckets = (PLHashEntry**)((*allocOps->allocTable)(allocPriv, nb));
- if (!ht->buckets) {
- (*allocOps->freeTable)(allocPriv, ht);
- return 0;
- }
- memset(ht->buckets, 0, nb);
-
- ht->keyHash = keyHash;
- ht->keyCompare = keyCompare;
- ht->valueCompare = valueCompare;
- ht->allocOps = allocOps;
- ht->allocPriv = allocPriv;
- return ht;
-}
-
-PR_IMPLEMENT(void)
-PL_HashTableDestroy(PLHashTable *ht)
-{
- PRUint32 i, n;
- PLHashEntry *he, *next;
- const PLHashAllocOps *allocOps = ht->allocOps;
- void *allocPriv = ht->allocPriv;
-
- n = NBUCKETS(ht);
- for (i = 0; i < n; i++) {
- for (he = ht->buckets[i]; he; he = next) {
- next = he->next;
- (*allocOps->freeEntry)(allocPriv, he, HT_FREE_ENTRY);
- }
- }
-#ifdef DEBUG
- memset(ht->buckets, 0xDB, n * sizeof ht->buckets[0]);
-#endif
- (*allocOps->freeTable)(allocPriv, ht->buckets);
-#ifdef DEBUG
- memset(ht, 0xDB, sizeof *ht);
-#endif
- (*allocOps->freeTable)(allocPriv, ht);
-}
-
-/*
-** Multiplicative hash, from Knuth 6.4.
-*/
-#define GOLDEN_RATIO 0x9E3779B9U /* 2/(1+sqrt(5))*(2^32) */
-
-PR_IMPLEMENT(PLHashEntry **)
-PL_HashTableRawLookup(PLHashTable *ht, PLHashNumber keyHash, const void *key)
-{
- PLHashEntry *he, **hep, **hep0;
- PLHashNumber h;
-
-#ifdef HASHMETER
- ht->nlookups++;
-#endif
- h = keyHash * GOLDEN_RATIO;
- h >>= ht->shift;
- hep = hep0 = &ht->buckets[h];
- while ((he = *hep) != 0) {
- if (he->keyHash == keyHash && (*ht->keyCompare)(key, he->key)) {
- /* Move to front of chain if not already there */
- if (hep != hep0) {
- *hep = he->next;
- he->next = *hep0;
- *hep0 = he;
- }
- return hep0;
- }
- hep = &he->next;
-#ifdef HASHMETER
- ht->nsteps++;
-#endif
- }
- return hep;
-}
-
-/*
-** Same as PL_HashTableRawLookup but doesn't reorder the hash entries.
-*/
-PR_IMPLEMENT(PLHashEntry **)
-PL_HashTableRawLookupConst(PLHashTable *ht, PLHashNumber keyHash,
- const void *key)
-{
- PLHashEntry *he, **hep;
- PLHashNumber h;
-
-#ifdef HASHMETER
- ht->nlookups++;
-#endif
- h = keyHash * GOLDEN_RATIO;
- h >>= ht->shift;
- hep = &ht->buckets[h];
- while ((he = *hep) != 0) {
- if (he->keyHash == keyHash && (*ht->keyCompare)(key, he->key)) {
- break;
- }
- hep = &he->next;
-#ifdef HASHMETER
- ht->nsteps++;
-#endif
- }
- return hep;
-}
-
-PR_IMPLEMENT(PLHashEntry *)
-PL_HashTableRawAdd(PLHashTable *ht, PLHashEntry **hep,
- PLHashNumber keyHash, const void *key, void *value)
-{
- PRUint32 i, n;
- PLHashEntry *he, *next, **oldbuckets;
- PRSize nb;
-
- /* Grow the table if it is overloaded */
- n = NBUCKETS(ht);
- if (ht->nentries >= OVERLOADED(n)) {
- oldbuckets = ht->buckets;
- nb = 2 * n * sizeof(PLHashEntry *);
- ht->buckets = (PLHashEntry**)
- ((*ht->allocOps->allocTable)(ht->allocPriv, nb));
- if (!ht->buckets) {
- ht->buckets = oldbuckets;
- return 0;
- }
- memset(ht->buckets, 0, nb);
-#ifdef HASHMETER
- ht->ngrows++;
-#endif
- ht->shift--;
-
- for (i = 0; i < n; i++) {
- for (he = oldbuckets[i]; he; he = next) {
- next = he->next;
- hep = PL_HashTableRawLookup(ht, he->keyHash, he->key);
- PR_ASSERT(*hep == 0);
- he->next = 0;
- *hep = he;
- }
- }
-#ifdef DEBUG
- memset(oldbuckets, 0xDB, n * sizeof oldbuckets[0]);
-#endif
- (*ht->allocOps->freeTable)(ht->allocPriv, oldbuckets);
- hep = PL_HashTableRawLookup(ht, keyHash, key);
- }
-
- /* Make a new key value entry */
- he = (*ht->allocOps->allocEntry)(ht->allocPriv, key);
- if (!he)
- return 0;
- he->keyHash = keyHash;
- he->key = key;
- he->value = value;
- he->next = *hep;
- *hep = he;
- ht->nentries++;
- return he;
-}
-
-PR_IMPLEMENT(PLHashEntry *)
-PL_HashTableAdd(PLHashTable *ht, const void *key, void *value)
-{
- PLHashNumber keyHash;
- PLHashEntry *he, **hep;
-
- keyHash = (*ht->keyHash)(key);
- hep = PL_HashTableRawLookup(ht, keyHash, key);
- if ((he = *hep) != 0) {
- /* Hit; see if values match */
- if ((*ht->valueCompare)(he->value, value)) {
- /* key,value pair is already present in table */
- return he;
- }
- if (he->value)
- (*ht->allocOps->freeEntry)(ht->allocPriv, he, HT_FREE_VALUE);
- he->value = value;
- return he;
- }
- return PL_HashTableRawAdd(ht, hep, keyHash, key, value);
-}
-
-PR_IMPLEMENT(void)
-PL_HashTableRawRemove(PLHashTable *ht, PLHashEntry **hep, PLHashEntry *he)
-{
- PRUint32 i, n;
- PLHashEntry *next, **oldbuckets;
- PRSize nb;
-
- *hep = he->next;
- (*ht->allocOps->freeEntry)(ht->allocPriv, he, HT_FREE_ENTRY);
-
- /* Shrink table if it's underloaded */
- n = NBUCKETS(ht);
- if (--ht->nentries < UNDERLOADED(n)) {
- oldbuckets = ht->buckets;
- nb = n * sizeof(PLHashEntry*) / 2;
- ht->buckets = (PLHashEntry**)(
- (*ht->allocOps->allocTable)(ht->allocPriv, nb));
- if (!ht->buckets) {
- ht->buckets = oldbuckets;
- return;
- }
- memset(ht->buckets, 0, nb);
-#ifdef HASHMETER
- ht->nshrinks++;
-#endif
- ht->shift++;
-
- for (i = 0; i < n; i++) {
- for (he = oldbuckets[i]; he; he = next) {
- next = he->next;
- hep = PL_HashTableRawLookup(ht, he->keyHash, he->key);
- PR_ASSERT(*hep == 0);
- he->next = 0;
- *hep = he;
- }
- }
-#ifdef DEBUG
- memset(oldbuckets, 0xDB, n * sizeof oldbuckets[0]);
-#endif
- (*ht->allocOps->freeTable)(ht->allocPriv, oldbuckets);
- }
-}
-
-PR_IMPLEMENT(PRBool)
-PL_HashTableRemove(PLHashTable *ht, const void *key)
-{
- PLHashNumber keyHash;
- PLHashEntry *he, **hep;
-
- keyHash = (*ht->keyHash)(key);
- hep = PL_HashTableRawLookup(ht, keyHash, key);
- if ((he = *hep) == 0)
- return PR_FALSE;
-
- /* Hit; remove element */
- PL_HashTableRawRemove(ht, hep, he);
- return PR_TRUE;
-}
-
-PR_IMPLEMENT(void *)
-PL_HashTableLookup(PLHashTable *ht, const void *key)
-{
- PLHashNumber keyHash;
- PLHashEntry *he, **hep;
-
- keyHash = (*ht->keyHash)(key);
- hep = PL_HashTableRawLookup(ht, keyHash, key);
- if ((he = *hep) != 0) {
- return he->value;
- }
- return 0;
-}
-
-/*
-** Same as PL_HashTableLookup but doesn't reorder the hash entries.
-*/
-PR_IMPLEMENT(void *)
-PL_HashTableLookupConst(PLHashTable *ht, const void *key)
-{
- PLHashNumber keyHash;
- PLHashEntry *he, **hep;
-
- keyHash = (*ht->keyHash)(key);
- hep = PL_HashTableRawLookupConst(ht, keyHash, key);
- if ((he = *hep) != 0) {
- return he->value;
- }
- return 0;
-}
-
-/*
-** Iterate over the entries in the hash table calling func for each
-** entry found. Stop if "f" says to (return value & PR_ENUMERATE_STOP).
-** Return a count of the number of elements scanned.
-*/
-PR_IMPLEMENT(int)
-PL_HashTableEnumerateEntries(PLHashTable *ht, PLHashEnumerator f, void *arg)
-{
- PLHashEntry *he, **hep;
- PRUint32 i, nbuckets;
- int rv, n = 0;
- PLHashEntry *todo = 0;
-
- nbuckets = NBUCKETS(ht);
- for (i = 0; i < nbuckets; i++) {
- hep = &ht->buckets[i];
- while ((he = *hep) != 0) {
- rv = (*f)(he, n, arg);
- n++;
- if (rv & (HT_ENUMERATE_REMOVE | HT_ENUMERATE_UNHASH)) {
- *hep = he->next;
- if (rv & HT_ENUMERATE_REMOVE) {
- he->next = todo;
- todo = he;
- }
- } else {
- hep = &he->next;
- }
- if (rv & HT_ENUMERATE_STOP) {
- goto out;
- }
- }
- }
-
-out:
- hep = &todo;
- while ((he = *hep) != 0) {
- PL_HashTableRawRemove(ht, hep, he);
- }
- return n;
-}
-
-#ifdef HASHMETER
-#include <math.h>
-#include <stdio.h>
-
-PR_IMPLEMENT(void)
-PL_HashTableDumpMeter(PLHashTable *ht, PLHashEnumerator dump, FILE *fp)
-{
- double mean, variance;
- PRUint32 nchains, nbuckets;
- PRUint32 i, n, maxChain, maxChainLen;
- PLHashEntry *he;
-
- variance = 0;
- nchains = 0;
- maxChainLen = 0;
- nbuckets = NBUCKETS(ht);
- for (i = 0; i < nbuckets; i++) {
- he = ht->buckets[i];
- if (!he)
- continue;
- nchains++;
- for (n = 0; he; he = he->next)
- n++;
- variance += n * n;
- if (n > maxChainLen) {
- maxChainLen = n;
- maxChain = i;
- }
- }
- mean = (double)ht->nentries / nchains;
- variance = fabs(variance / nchains - mean * mean);
-
- fprintf(fp, "\nHash table statistics:\n");
- fprintf(fp, " number of lookups: %u\n", ht->nlookups);
- fprintf(fp, " number of entries: %u\n", ht->nentries);
- fprintf(fp, " number of grows: %u\n", ht->ngrows);
- fprintf(fp, " number of shrinks: %u\n", ht->nshrinks);
- fprintf(fp, " mean steps per hash: %g\n", (double)ht->nsteps
- / ht->nlookups);
- fprintf(fp, "mean hash chain length: %g\n", mean);
- fprintf(fp, " standard deviation: %g\n", sqrt(variance));
- fprintf(fp, " max hash chain length: %u\n", maxChainLen);
- fprintf(fp, " max hash chain: [%u]\n", maxChain);
-
- for (he = ht->buckets[maxChain], i = 0; he; he = he->next, i++)
- if ((*dump)(he, i, fp) != HT_ENUMERATE_NEXT)
- break;
-}
-#endif /* HASHMETER */
-
-PR_IMPLEMENT(int)
-PL_HashTableDump(PLHashTable *ht, PLHashEnumerator dump, FILE *fp)
-{
- int count;
-
- count = PL_HashTableEnumerateEntries(ht, dump, fp);
-#ifdef HASHMETER
- PL_HashTableDumpMeter(ht, dump, fp);
-#endif
- return count;
-}
-
-PR_IMPLEMENT(PLHashNumber)
-PL_HashString(const void *key)
-{
- PLHashNumber h;
- const PRUint8 *s;
-
- h = 0;
- for (s = (const PRUint8*)key; *s; s++)
- h = PR_ROTATE_LEFT32(h, 4) ^ *s;
- return h;
-}
-
-PR_IMPLEMENT(int)
-PL_CompareStrings(const void *v1, const void *v2)
-{
- return strcmp((const char*)v1, (const char*)v2) == 0;
-}
-
-PR_IMPLEMENT(int)
-PL_CompareValues(const void *v1, const void *v2)
-{
- return v1 == v2;
-}
diff --git a/nspr/lib/ds/plhash.h b/nspr/lib/ds/plhash.h
deleted file mode 100644
index 2c221ae..0000000
--- a/nspr/lib/ds/plhash.h
+++ /dev/null
@@ -1,126 +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/. */
-
-#ifndef plhash_h___
-#define plhash_h___
-/*
- * API to portable hash table code.
- */
-#include <stdio.h>
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-typedef struct PLHashEntry PLHashEntry;
-typedef struct PLHashTable PLHashTable;
-typedef PRUint32 PLHashNumber;
-#define PL_HASH_BITS 32 /* Number of bits in PLHashNumber */
-typedef PLHashNumber (PR_CALLBACK *PLHashFunction)(const void *key);
-typedef PRIntn (PR_CALLBACK *PLHashComparator)(const void *v1, const void *v2);
-
-typedef PRIntn (PR_CALLBACK *PLHashEnumerator)(PLHashEntry *he, PRIntn i, void *arg);
-
-/* Flag bits in PLHashEnumerator's return value */
-#define HT_ENUMERATE_NEXT 0 /* continue enumerating entries */
-#define HT_ENUMERATE_STOP 1 /* stop enumerating entries */
-#define HT_ENUMERATE_REMOVE 2 /* remove and free the current entry */
-#define HT_ENUMERATE_UNHASH 4 /* just unhash the current entry */
-
-typedef struct PLHashAllocOps {
- void * (PR_CALLBACK *allocTable)(void *pool, PRSize size);
- void (PR_CALLBACK *freeTable)(void *pool, void *item);
- PLHashEntry * (PR_CALLBACK *allocEntry)(void *pool, const void *key);
- void (PR_CALLBACK *freeEntry)(void *pool, PLHashEntry *he, PRUintn flag);
-} PLHashAllocOps;
-
-#define HT_FREE_VALUE 0 /* just free the entry's value */
-#define HT_FREE_ENTRY 1 /* free value and entire entry */
-
-struct PLHashEntry {
- PLHashEntry *next; /* hash chain linkage */
- PLHashNumber keyHash; /* key hash function result */
- const void *key; /* ptr to opaque key */
- void *value; /* ptr to opaque value */
-};
-
-struct PLHashTable {
- PLHashEntry **buckets; /* vector of hash buckets */
- PRUint32 nentries; /* number of entries in table */
- PRUint32 shift; /* multiplicative hash shift */
- PLHashFunction keyHash; /* key hash function */
- PLHashComparator keyCompare; /* key comparison function */
- PLHashComparator valueCompare; /* value comparison function */
- const PLHashAllocOps *allocOps; /* allocation operations */
- void *allocPriv; /* allocation private data */
-#ifdef HASHMETER
- PRUint32 nlookups; /* total number of lookups */
- PRUint32 nsteps; /* number of hash chains traversed */
- PRUint32 ngrows; /* number of table expansions */
- PRUint32 nshrinks; /* number of table contractions */
-#endif
-};
-
-/*
- * Create a new hash table.
- * If allocOps is null, use default allocator ops built on top of malloc().
- */
-PR_EXTERN(PLHashTable *)
-PL_NewHashTable(PRUint32 numBuckets, PLHashFunction keyHash,
- PLHashComparator keyCompare, PLHashComparator valueCompare,
- const PLHashAllocOps *allocOps, void *allocPriv);
-
-PR_EXTERN(void)
-PL_HashTableDestroy(PLHashTable *ht);
-
-/* Higher level access methods */
-PR_EXTERN(PLHashEntry *)
-PL_HashTableAdd(PLHashTable *ht, const void *key, void *value);
-
-PR_EXTERN(PRBool)
-PL_HashTableRemove(PLHashTable *ht, const void *key);
-
-PR_EXTERN(void *)
-PL_HashTableLookup(PLHashTable *ht, const void *key);
-
-PR_EXTERN(void *)
-PL_HashTableLookupConst(PLHashTable *ht, const void *key);
-
-PR_EXTERN(PRIntn)
-PL_HashTableEnumerateEntries(PLHashTable *ht, PLHashEnumerator f, void *arg);
-
-/* General-purpose C string hash function. */
-PR_EXTERN(PLHashNumber)
-PL_HashString(const void *key);
-
-/* Compare strings using strcmp(), return true if equal. */
-PR_EXTERN(PRIntn)
-PL_CompareStrings(const void *v1, const void *v2);
-
-/* Stub function just returns v1 == v2 */
-PR_EXTERN(PRIntn)
-PL_CompareValues(const void *v1, const void *v2);
-
-/* Low level access methods */
-PR_EXTERN(PLHashEntry **)
-PL_HashTableRawLookup(PLHashTable *ht, PLHashNumber keyHash, const void *key);
-
-PR_EXTERN(PLHashEntry **)
-PL_HashTableRawLookupConst(PLHashTable *ht, PLHashNumber keyHash,
- const void *key);
-
-PR_EXTERN(PLHashEntry *)
-PL_HashTableRawAdd(PLHashTable *ht, PLHashEntry **hep, PLHashNumber keyHash,
- const void *key, void *value);
-
-PR_EXTERN(void)
-PL_HashTableRawRemove(PLHashTable *ht, PLHashEntry **hep, PLHashEntry *he);
-
-/* This can be trivially implemented using PL_HashTableEnumerateEntries. */
-PR_EXTERN(PRIntn)
-PL_HashTableDump(PLHashTable *ht, PLHashEnumerator dump, FILE *fp);
-
-PR_END_EXTERN_C
-
-#endif /* plhash_h___ */
diff --git a/nspr/lib/libc/include/plbase64.h b/nspr/lib/libc/include/plbase64.h
deleted file mode 100644
index 7d17ea7..0000000
--- a/nspr/lib/libc/include/plbase64.h
+++ /dev/null
@@ -1,76 +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/. */
-
-#ifndef _plbase64_h
-#define _plbase64_h
-
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-/*
- * PL_Base64Encode
- *
- * This routine encodes the data pointed to by the "src" parameter using the
- * base64 algorithm, and returns a pointer to the result. If the "srclen"
- * parameter is not zero, it specifies the length of the source data. If it
- * is zero, the source data is assumed to be null-terminated, and PL_strlen
- * is used to determine the source length. If the "dest" parameter is not
- * null, it is assumed to point to a buffer of sufficient size (which may be
- * calculated: ((srclen + 2)/3)*4) into which the encoded data is placed
- * (without any termination). If the "dest" parameter is null, a buffer is
- * allocated from the heap to hold the encoded data, and the result *will*
- * be terminated with an extra null character. It is the caller's
- * responsibility to free the result when it is allocated. A null is returned
- * if the allocation fails.
- *
- * NOTE: when calculating ((srclen + 2)/3)*4), first ensure that
- * srclen <= (PR_UINT32_MAX/4) * 3
- * to avoid PRUint32 overflow.
- */
-
-PR_EXTERN(char *)
-PL_Base64Encode
-(
- const char *src,
- PRUint32 srclen,
- char *dest
-);
-
-/*
- * PL_Base64Decode
- *
- * This routine decodes the data pointed to by the "src" parameter using
- * the base64 algorithm, and returns a pointer to the result. The source
- * may either include or exclude any trailing '=' characters. If the
- * "srclen" parameter is not zero, it specifies the length of the source
- * data. If it is zero, PL_strlen will be used to determine the source
- * length. If the "dest" parameter is not null, it is assumed to point to
- * a buffer of sufficient size (which may be calculated: (srclen * 3)/4
- * when srclen includes the '=' characters) into which the decoded data
- * is placed (without any termination). If the "dest" parameter is null,
- * a buffer is allocated from the heap to hold the decoded data, and the
- * result *will* be terminated with an extra null character. It is the
- * caller's responsibility to free the result when it is allocated. A null
- * is retuned if the allocation fails, or if the source is not well-coded.
- *
- * NOTE: when calculating (srclen * 3)/4, first ensure that
- * srclen <= PR_UINT32_MAX/3
- * to avoid PRUint32 overflow. Alternatively, calculate
- * (srclen/4) * 3 + ((srclen%4) * 3)/4
- * which is equivalent but doesn't overflow for any value of srclen.
- */
-
-PR_EXTERN(char *)
-PL_Base64Decode
-(
- const char *src,
- PRUint32 srclen,
- char *dest
-);
-
-PR_END_EXTERN_C
-
-#endif /* _plbase64_h */
diff --git a/nspr/lib/libc/include/plerror.h b/nspr/lib/libc/include/plerror.h
deleted file mode 100644
index cd85dd3..0000000
--- a/nspr/lib/libc/include/plerror.h
+++ /dev/null
@@ -1,34 +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/. */
-
-/*
-** File: plerror.h
-** Description: Simple routine to print translate the calling thread's
-** error numbers and print them.
-*/
-
-#if defined(PLERROR_H)
-#else
-#define PLERROR_H
-
-#include "prio.h"
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-/*
-** Print the messages to "syserr" prepending 'msg' if not NULL.
-*/
-PR_EXTERN(void) PL_PrintError(const char *msg);
-
-/*
-** Print the messages to specified output file prepending 'msg' if not NULL.
-*/
-PR_EXTERN(void) PL_FPrintError(PRFileDesc *output, const char *msg);
-
-PR_END_EXTERN_C
-
-#endif /* defined(PLERROR_H) */
-
-/* plerror.h */
diff --git a/nspr/lib/libc/include/plgetopt.h b/nspr/lib/libc/include/plgetopt.h
deleted file mode 100644
index 19cafa6..0000000
--- a/nspr/lib/libc/include/plgetopt.h
+++ /dev/null
@@ -1,125 +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/. */
-
-/*
-** File: plgetopt.h
-** Description: utilities to parse argc/argv
-*/
-
-#if defined(PLGETOPT_H_)
-#else
-#define PLGETOPT_H_
-
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-typedef struct PLOptionInternal PLOptionInternal;
-
-typedef enum
-{
- PL_OPT_OK, /* all's well with the option */
- PL_OPT_EOL, /* end of options list */
- PL_OPT_BAD /* invalid option (and value) */
-} PLOptStatus;
-
-typedef struct PLLongOpt
-{
- const char * longOptName; /* long option name string */
- PRIntn longOption; /* value put in PLOptState for this option. */
- PRBool valueRequired; /* If option name not followed by '=', */
- /* value is the next argument from argv. */
-} PLLongOpt;
-
-typedef struct PLOptState
-{
- char option; /* the name of the option */
- const char *value; /* the value of that option | NULL */
-
- PLOptionInternal *internal; /* private processing state */
-
- PRIntn longOption; /* value from PLLongOpt put here */
- PRIntn longOptIndex; /* index into caller's array of PLLongOpts */
-} PLOptState;
-
-/*
- * PL_CreateOptState
- *
- * The argument "options" points to a string of single-character option
- * names. Option names that may have an option argument value must be
- * followed immediately by a ':' character.
- */
-PR_EXTERN(PLOptState*) PL_CreateOptState(
- PRIntn argc, char **argv, const char *options);
-
-/*
- * PL_CreateLongOptState
- *
- * Alternative to PL_CreateOptState.
- * Allows caller to specify BOTH a string of single-character option names,
- * AND an array of structures describing "long" (keyword) option names.
- * The array is terminated by a structure in which longOptName is NULL.
- * Long option values (arguments) may always be given as "--name=value".
- * If PLLongOpt.valueRequired is not PR_FALSE, and the option name was not
- * followed by '=' then the next argument from argv is taken as the value.
- */
-PR_EXTERN(PLOptState*) PL_CreateLongOptState(
- PRIntn argc, char **argv, const char *options,
- const PLLongOpt *longOpts);
-/*
- * PL_DestroyOptState
- *
- * Call this to destroy the PLOptState returned from PL_CreateOptState or
- * PL_CreateLongOptState.
- */
-PR_EXTERN(void) PL_DestroyOptState(PLOptState *opt);
-
-/*
- * PL_GetNextOpt
- *
- * When this function returns PL_OPT_OK,
- * - opt->option will hold the single-character option name that was parsed,
- * or zero.
- * When opt->option is zero, the token parsed was either a "long" (keyword)
- * option or a positional parameter.
- * For a positional parameter,
- * - opt->longOptIndex will contain -1, and
- * - opt->value will point to the positional parameter string.
- * For a long option name,
- * - opt->longOptIndex will contain the non-negative index of the
- * PLLongOpt structure in the caller's array of PLLongOpt structures
- * corresponding to the long option name, and
- * For a single-character or long option,
- * - opt->longOption will contain the value of the single-character option
- * name, or the value of the longOption from the PLLongOpt structure
- * for that long option. See notes below.
- * - opt->value will point to the argument option string, or will
- * be NULL if option does not require argument. If option requires
- * argument but it is not provided, PL_OPT_BAD is returned.
- * When opt->option is non-zero,
- * - opt->longOptIndex will be -1
- * When this function returns PL_OPT_EOL, or PL_OPT_BAD, the contents of
- * opt are undefined.
- *
- * Notes: It is possible to ignore opt->option, and always look at
- * opt->longOption instead. opt->longOption will contain the same value
- * as opt->option for single-character option names, and will contain the
- * value of longOption from the PLLongOpt structure for long option names.
- * This means that it is possible to equivalence long option names to
- * single character names by giving the longOption in the PLLongOpt struct
- * the same value as the single-character option name.
- * For long options that are NOT intended to be equivalent to any single-
- * character option, the longOption value should be chosen to not match
- * any possible single character name. It might be advisable to choose
- * longOption values greater than 0xff for such long options.
- */
-PR_EXTERN(PLOptStatus) PL_GetNextOpt(PLOptState *opt);
-
-PR_END_EXTERN_C
-
-#endif /* defined(PLGETOPT_H_) */
-
-/* plgetopt.h */
-
diff --git a/nspr/lib/libc/include/plstr.h b/nspr/lib/libc/include/plstr.h
deleted file mode 100644
index 57814c7..0000000
--- a/nspr/lib/libc/include/plstr.h
+++ /dev/null
@@ -1,437 +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/. */
-
-#ifndef _plstr_h
-#define _plstr_h
-
-/*
- * plstr.h
- *
- * This header file exports the API to the NSPR portable library or string-
- * handling functions.
- *
- * This API was not designed as an "optimal" or "ideal" string library; it
- * was based on the good ol' unix string.3 functions, and was written to
- *
- * 1) replace the libc functions, for cross-platform consistency,
- * 2) complete the API on platforms lacking common functions (e.g.,
- * strcase*), and
- * 3) to implement some obvious "closure" functions that I've seen
- * people hacking around in our code.
- *
- * Point number three largely means that most functions have an "strn"
- * limited-length version, and all comparison routines have a non-case-
- * sensitive version available.
- */
-
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-/*
- * PL_strlen
- *
- * Returns the length of the provided string, not including the trailing '\0'.
- */
-
-PR_EXTERN(PRUint32)
-PL_strlen(const char *str);
-
-/*
- * PL_strnlen
- *
- * Returns the length of the provided string, not including the trailing '\0',
- * up to the indicated maximum. The string will not be examined beyond the
- * maximum; if no terminating '\0' is found, the maximum will be returned.
- */
-
-PR_EXTERN(PRUint32)
-PL_strnlen(const char *str, PRUint32 max);
-
-/*
- * PL_strcpy
- *
- * Copies the source string, up to and including the trailing '\0', into the
- * destination buffer. It does not (can not) verify that the destination
- * buffer is large enough. It returns the "dest" argument.
- */
-
-PR_EXTERN(char *)
-PL_strcpy(char *dest, const char *src);
-
-/*
- * PL_strncpy
- *
- * Copies the source string into the destination buffer, up to and including
- * the trailing '\0' or up to and including the max'th character, whichever
- * comes first. It does not (can not) verify that the destination buffer is
- * large enough. If the source string is longer than the maximum length,
- * the result will *not* be null-terminated (JLRU).
- */
-
-PR_EXTERN(char *)
-PL_strncpy(char *dest, const char *src, PRUint32 max);
-
-/*
- * PL_strncpyz
- *
- * Copies the source string into the destination buffer, up to and including
- * the trailing '\0' or up but not including the max'th character, whichever
- * comes first. It does not (can not) verify that the destination buffer is
- * large enough. The destination string is always terminated with a '\0',
- * unlike the traditional libc implementation. It returns the "dest" argument.
- *
- * NOTE: If you call this with a source "abcdefg" and a max of 5, the
- * destination will end up with "abcd\0" (i.e., its strlen length will be 4)!
- *
- * This means you can do this:
- *
- * char buffer[ SOME_SIZE ];
- * PL_strncpyz(buffer, src, sizeof(buffer));
- *
- * and the result will be properly terminated.
- */
-
-PR_EXTERN(char *)
-PL_strncpyz(char *dest, const char *src, PRUint32 max);
-
-/*
- * PL_strdup
- *
- * Returns a pointer to a malloc'd extent of memory containing a duplicate
- * of the argument string. The size of the allocated extent is one greater
- * than the length of the argument string, because of the terminator. A
- * null argument, like a zero-length argument, will result in a pointer to
- * a one-byte extent containing the null value. This routine returns null
- * upon malloc failure.
- */
-
-PR_EXTERN(char *)
-PL_strdup(const char *s);
-
-/*
- * PL_strfree
- *
- * Free memory allocated by PL_strdup
- */
-
-PR_EXTERN(void)
-PL_strfree(char *s);
-
-/*
- * PL_strndup
- *
- * Returns a pointer to a malloc'd extent of memory containing a duplicate
- * of the argument string, up to the maximum specified. If the argument
- * string has a length greater than the value of the specified maximum, the
- * return value will be a pointer to an extent of memory of length one
- * greater than the maximum specified. A null string, a zero-length string,
- * or a zero maximum will all result in a pointer to a one-byte extent
- * containing the null value. This routine returns null upon malloc failure.
- */
-
-PR_EXTERN(char *)
-PL_strndup(const char *s, PRUint32 max);
-
-/*
- * PL_strcat
- *
- * Appends a copy of the string pointed to by the second argument to the
- * end of the string pointed to by the first. The destination buffer is
- * not (can not be) checked for sufficient size. A null destination
- * argument returns null; otherwise, the first argument is returned.
- */
-
-PR_EXTERN(char *)
-PL_strcat(char *dst, const char *src);
-
-/*
- * PL_strncat
- *
- * Appends a copy of the string pointed to by the second argument, up to
- * the maximum size specified, to the end of the string pointed to by the
- * first. The destination buffer is not (can not be) checked for sufficient
- * size. A null destination argument returns null; otherwise, the first
- * argument is returned. If the maximum size limits the copy, then the
- * result will *not* be null-terminated (JLRU). A null destination
- * returns null; otherwise, the destination argument is returned.
- */
-
-PR_EXTERN(char *)
-PL_strncat(char *dst, const char *src, PRUint32 max);
-
-/*
- * PL_strcatn
- *
- * Appends a copy of the string pointed to by the third argument, to the
- * end of the string pointed to by the first. The second argument specifies
- * the maximum size of the destination buffer, including the null termination.
- * If the existing string in dst is longer than the max, no action is taken.
- * The resulting string will be null-terminated. A null destination returns
- * null; otherwise, the destination argument is returned.
- */
-
-PR_EXTERN(char *)
-PL_strcatn(char *dst, PRUint32 max, const char *src);
-
-/*
- * PL_strcmp
- *
- * Returns an integer, the sign of which -- positive, zero, or negative --
- * reflects the lexical sorting order of the two strings indicated. The
- * result is positive if the first string comes after the second. The
- * NSPR implementation is not i18n.
- */
-
-PR_EXTERN(PRIntn)
-PL_strcmp(const char *a, const char *b);
-
-/*
- * PL_strncmp
- *
- * Returns an integer, the sign of which -- positive, zero, or negative --
- * reflects the lexical sorting order of the two strings indicated, up to
- * the maximum specified. The result is positive if the first string comes
- * after the second. The NSPR implementation is not i18n. If the maximum
- * is zero, only the existance or non-existance (pointer is null) of the
- * strings is compared.
- */
-
-PR_EXTERN(PRIntn)
-PL_strncmp(const char *a, const char *b, PRUint32 max);
-
-/*
- * PL_strcasecmp
- *
- * Returns an integer, the sign of which -- positive, zero or negative --
- * reflects the case-insensitive lexical sorting order of the two strings
- * indicated. The result is positive if the first string comes after the
- * second. The NSPR implementation is not i18n.
- */
-
-PR_EXTERN(PRIntn)
-PL_strcasecmp(const char *a, const char *b);
-
-/*
- * PL_strncasecmp
- *
- * Returns an integer, the sign of which -- positive, zero or negative --
- * reflects the case-insensitive lexical sorting order of the first n characters
- * of the two strings indicated. The result is positive if the first string comes
- * after the second. The NSPR implementation is not i18n.
- */
-
-PR_EXTERN(PRIntn)
-PL_strncasecmp(const char *a, const char *b, PRUint32 max);
-
-/*
- * PL_strchr
- *
- * Returns a pointer to the first instance of the specified character in the
- * provided string. It returns null if the character is not found, or if the
- * provided string is null. The character may be the null character.
- */
-
-PR_EXTERN(char *)
-PL_strchr(const char *s, char c);
-
-/*
- * PL_strrchr
- *
- * Returns a pointer to the last instance of the specified character in the
- * provided string. It returns null if the character is not found, or if the
- * provided string is null. The character may be the null character.
- */
-
-PR_EXTERN(char *)
-PL_strrchr(const char *s, char c);
-
-/*
- * PL_strnchr
- *
- * Returns a pointer to the first instance of the specified character within the
- * first n characters of the provided string. It returns null if the character
- * is not found, or if the provided string is null. The character may be the
- * null character.
- */
-
-PR_EXTERN(char *)
-PL_strnchr(const char *s, char c, PRUint32 n);
-
-/*
- * PL_strnrchr
- *
- * Returns a pointer to the last instance of the specified character within the
- * first n characters of the provided string. It returns null if the character is
- * not found, or if the provided string is null. The character may be the null
- * character.
- */
-
-PR_EXTERN(char *)
-PL_strnrchr(const char *s, char c, PRUint32 n);
-
-/*
- * NOTE: Looking for strcasechr, strcaserchr, strncasechr, or strncaserchr?
- * Use strpbrk, strprbrk, strnpbrk or strnprbrk.
- */
-
-/*
- * PL_strpbrk
- *
- * Returns a pointer to the first instance in the first string of any character
- * (not including the terminating null character) of the second string. It returns
- * null if either string is null.
- */
-
-PR_EXTERN(char *)
-PL_strpbrk(const char *s, const char *list);
-
-/*
- * PL_strprbrk
- *
- * Returns a pointer to the last instance in the first string of any character
- * (not including the terminating null character) of the second string. It returns
- * null if either string is null.
- */
-
-PR_EXTERN(char *)
-PL_strprbrk(const char *s, const char *list);
-
-/*
- * PL_strnpbrk
- *
- * Returns a pointer to the first instance (within the first n characters) of any
- * character (not including the terminating null character) of the second string.
- * It returns null if either string is null.
- */
-
-PR_EXTERN(char *)
-PL_strnpbrk(const char *s, const char *list, PRUint32 n);
-
-/*
- * PL_strnprbrk
- *
- * Returns a pointer to the last instance (within the first n characters) of any
- * character (not including the terminating null character) of the second string.
- * It returns null if either string is null.
- */
-
-PR_EXTERN(char *)
-PL_strnprbrk(const char *s, const char *list, PRUint32 n);
-
-/*
- * PL_strstr
- *
- * Returns a pointer to the first instance of the little string within the
- * big one. It returns null if either string is null.
- */
-
-PR_EXTERN(char *)
-PL_strstr(const char *big, const char *little);
-
-/*
- * PL_strrstr
- *
- * Returns a pointer to the last instance of the little string within the big one.
- * It returns null if either string is null.
- */
-
-PR_EXTERN(char *)
-PL_strrstr(const char *big, const char *little);
-
-/*
- * PL_strnstr
- *
- * Returns a pointer to the first instance of the little string within the first
- * n characters of the big one. It returns null if either string is null. It
- * returns null if the length of the little string is greater than n.
- */
-
-PR_EXTERN(char *)
-PL_strnstr(const char *big, const char *little, PRUint32 n);
-
-/*
- * PL_strnrstr
- *
- * Returns a pointer to the last instance of the little string within the first
- * n characters of the big one. It returns null if either string is null. It
- * returns null if the length of the little string is greater than n.
- */
-
-PR_EXTERN(char *)
-PL_strnrstr(const char *big, const char *little, PRUint32 max);
-
-/*
- * PL_strcasestr
- *
- * Returns a pointer to the first instance of the little string within the big one,
- * ignoring case. It returns null if either string is null.
- */
-
-PR_EXTERN(char *)
-PL_strcasestr(const char *big, const char *little);
-
-/*
- * PL_strcaserstr
- *
- * Returns a pointer to the last instance of the little string within the big one,
- * ignoring case. It returns null if either string is null.
- */
-
-PR_EXTERN(char *)
-PL_strcaserstr(const char *big, const char *little);
-
-/*
- * PL_strncasestr
- *
- * Returns a pointer to the first instance of the little string within the first
- * n characters of the big one, ignoring case. It returns null if either string is
- * null. It returns null if the length of the little string is greater than n.
- */
-
-PR_EXTERN(char *)
-PL_strncasestr(const char *big, const char *little, PRUint32 max);
-
-/*
- * PL_strncaserstr
- *
- * Returns a pointer to the last instance of the little string within the first
- * n characters of the big one, ignoring case. It returns null if either string is
- * null. It returns null if the length of the little string is greater than n.
- */
-
-PR_EXTERN(char *)
-PL_strncaserstr(const char *big, const char *little, PRUint32 max);
-
-/*
- * PL_strtok_r
- *
- * Splits the string s1 into tokens, separated by one or more characters
- * from the separator string s2. The argument lasts points to a
- * user-supplied char * pointer in which PL_strtok_r stores information
- * for it to continue scanning the same string.
- *
- * In the first call to PL_strtok_r, s1 points to a string and the value
- * of *lasts is ignored. PL_strtok_r returns a pointer to the first
- * token, writes '\0' into the character following the first token, and
- * updates *lasts.
- *
- * In subsequent calls, s1 is null and lasts must stay unchanged from the
- * previous call. The separator string s2 may be different from call to
- * call. PL_strtok_r returns a pointer to the next token in s1. When no
- * token remains in s1, PL_strtok_r returns null.
- */
-
-PR_EXTERN(char *)
-PL_strtok_r(char *s1, const char *s2, char **lasts);
-
-/*
- * Things not (yet?) included: strspn/strcspn, strsep.
- * memchr, memcmp, memcpy, memccpy, index, rindex, bcmp, bcopy, bzero.
- * Any and all i18n/l10n stuff.
- */
-
-PR_END_EXTERN_C
-
-#endif /* _plstr_h */
diff --git a/nspr/lib/libc/src/base64.c b/nspr/lib/libc/src/base64.c
deleted file mode 100644
index 07a4902..0000000
--- a/nspr/lib/libc/src/base64.c
+++ /dev/null
@@ -1,416 +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/. */
-
-#include "plbase64.h"
-#include "prlog.h" /* For PR_NOT_REACHED */
-#include "prmem.h" /* for malloc / PR_MALLOC */
-
-#include <string.h> /* for strlen */
-
-static unsigned char *base = (unsigned char *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-
-static void
-encode3to4
-(
- const unsigned char *src,
- unsigned char *dest
-)
-{
- PRUint32 b32 = (PRUint32)0;
- PRIntn i, j = 18;
-
- for( i = 0; i < 3; i++ )
- {
- b32 <<= 8;
- b32 |= (PRUint32)src[i];
- }
-
- for( i = 0; i < 4; i++ )
- {
- dest[i] = base[ (PRUint32)((b32>>j) & 0x3F) ];
- j -= 6;
- }
-
- return;
-}
-
-static void
-encode2to4
-(
- const unsigned char *src,
- unsigned char *dest
-)
-{
- dest[0] = base[ (PRUint32)((src[0]>>2) & 0x3F) ];
- dest[1] = base[ (PRUint32)(((src[0] & 0x03) << 4) | ((src[1] >> 4) & 0x0F)) ];
- dest[2] = base[ (PRUint32)((src[1] & 0x0F) << 2) ];
- dest[3] = (unsigned char)'=';
- return;
-}
-
-static void
-encode1to4
-(
- const unsigned char *src,
- unsigned char *dest
-)
-{
- dest[0] = base[ (PRUint32)((src[0]>>2) & 0x3F) ];
- dest[1] = base[ (PRUint32)((src[0] & 0x03) << 4) ];
- dest[2] = (unsigned char)'=';
- dest[3] = (unsigned char)'=';
- return;
-}
-
-static void
-encode
-(
- const unsigned char *src,
- PRUint32 srclen,
- unsigned char *dest
-)
-{
- while( srclen >= 3 )
- {
- encode3to4(src, dest);
- src += 3;
- dest += 4;
- srclen -= 3;
- }
-
- switch( srclen )
- {
- case 2:
- encode2to4(src, dest);
- break;
- case 1:
- encode1to4(src, dest);
- break;
- case 0:
- break;
- default:
- PR_NOT_REACHED("coding error");
- }
-
- return;
-}
-
-/*
- * PL_Base64Encode
- *
- * If the destination argument is NULL, a return buffer is
- * allocated, and the data therein will be null-terminated.
- * If the destination argument is not NULL, it is assumed to
- * be of sufficient size, and the contents will not be null-
- * terminated by this routine.
- *
- * Returns null if the allocation fails.
- */
-
-PR_IMPLEMENT(char *)
-PL_Base64Encode
-(
- const char *src,
- PRUint32 srclen,
- char *dest
-)
-{
- if( 0 == srclen )
- {
- size_t len = strlen(src);
- srclen = len;
- /* Detect truncation. */
- if( srclen != len )
- {
- return (char *)0;
- }
- }
-
- if( (char *)0 == dest )
- {
- PRUint32 destlen;
- /* Ensure all PRUint32 values stay within range. */
- if( srclen > (PR_UINT32_MAX/4) * 3 )
- {
- return (char *)0;
- }
- destlen = ((srclen + 2)/3) * 4;
- dest = (char *)PR_MALLOC(destlen + 1);
- if( (char *)0 == dest )
- {
- return (char *)0;
- }
- dest[ destlen ] = (char)0; /* null terminate */
- }
-
- encode((const unsigned char *)src, srclen, (unsigned char *)dest);
- return dest;
-}
-
-static PRInt32
-codetovalue
-(
- unsigned char c
-)
-{
- if( (c >= (unsigned char)'A') && (c <= (unsigned char)'Z') )
- {
- return (PRInt32)(c - (unsigned char)'A');
- }
- else if( (c >= (unsigned char)'a') && (c <= (unsigned char)'z') )
- {
- return ((PRInt32)(c - (unsigned char)'a') +26);
- }
- else if( (c >= (unsigned char)'0') && (c <= (unsigned char)'9') )
- {
- return ((PRInt32)(c - (unsigned char)'0') +52);
- }
- else if( (unsigned char)'+' == c )
- {
- return (PRInt32)62;
- }
- else if( (unsigned char)'/' == c )
- {
- return (PRInt32)63;
- }
- else
- {
- return -1;
- }
-}
-
-static PRStatus
-decode4to3
-(
- const unsigned char *src,
- unsigned char *dest
-)
-{
- PRUint32 b32 = (PRUint32)0;
- PRInt32 bits;
- PRIntn i;
-
- for( i = 0; i < 4; i++ )
- {
- bits = codetovalue(src[i]);
- if( bits < 0 )
- {
- return PR_FAILURE;
- }
-
- b32 <<= 6;
- b32 |= bits;
- }
-
- dest[0] = (unsigned char)((b32 >> 16) & 0xFF);
- dest[1] = (unsigned char)((b32 >> 8) & 0xFF);
- dest[2] = (unsigned char)((b32 ) & 0xFF);
-
- return PR_SUCCESS;
-}
-
-static PRStatus
-decode3to2
-(
- const unsigned char *src,
- unsigned char *dest
-)
-{
- PRUint32 b32 = (PRUint32)0;
- PRInt32 bits;
- PRUint32 ubits;
-
- bits = codetovalue(src[0]);
- if( bits < 0 )
- {
- return PR_FAILURE;
- }
-
- b32 = (PRUint32)bits;
- b32 <<= 6;
-
- bits = codetovalue(src[1]);
- if( bits < 0 )
- {
- return PR_FAILURE;
- }
-
- b32 |= (PRUint32)bits;
- b32 <<= 4;
-
- bits = codetovalue(src[2]);
- if( bits < 0 )
- {
- return PR_FAILURE;
- }
-
- ubits = (PRUint32)bits;
- b32 |= (ubits >> 2);
-
- dest[0] = (unsigned char)((b32 >> 8) & 0xFF);
- dest[1] = (unsigned char)((b32 ) & 0xFF);
-
- return PR_SUCCESS;
-}
-
-static PRStatus
-decode2to1
-(
- const unsigned char *src,
- unsigned char *dest
-)
-{
- PRUint32 b32;
- PRUint32 ubits;
- PRInt32 bits;
-
- bits = codetovalue(src[0]);
- if( bits < 0 )
- {
- return PR_FAILURE;
- }
-
- ubits = (PRUint32)bits;
- b32 = (ubits << 2);
-
- bits = codetovalue(src[1]);
- if( bits < 0 )
- {
- return PR_FAILURE;
- }
-
- ubits = (PRUint32)bits;
- b32 |= (ubits >> 4);
-
- dest[0] = (unsigned char)b32;
-
- return PR_SUCCESS;
-}
-
-static PRStatus
-decode
-(
- const unsigned char *src,
- PRUint32 srclen,
- unsigned char *dest
-)
-{
- PRStatus rv;
-
- while( srclen >= 4 )
- {
- rv = decode4to3(src, dest);
- if( PR_SUCCESS != rv )
- {
- return PR_FAILURE;
- }
-
- src += 4;
- dest += 3;
- srclen -= 4;
- }
-
- switch( srclen )
- {
- case 3:
- rv = decode3to2(src, dest);
- break;
- case 2:
- rv = decode2to1(src, dest);
- break;
- case 1:
- rv = PR_FAILURE;
- break;
- case 0:
- rv = PR_SUCCESS;
- break;
- default:
- PR_NOT_REACHED("coding error");
- }
-
- return rv;
-}
-
-/*
- * PL_Base64Decode
- *
- * If the destination argument is NULL, a return buffer is
- * allocated and the data therein will be null-terminated.
- * If the destination argument is not null, it is assumed
- * to be of sufficient size, and the data will not be null-
- * terminated by this routine.
- *
- * Returns null if the allocation fails, or if the source string is
- * not well-formed.
- */
-
-PR_IMPLEMENT(char *)
-PL_Base64Decode
-(
- const char *src,
- PRUint32 srclen,
- char *dest
-)
-{
- PRStatus status;
- PRBool allocated = PR_FALSE;
-
- if( (char *)0 == src )
- {
- return (char *)0;
- }
-
- if( 0 == srclen )
- {
- size_t len = strlen(src);
- srclen = len;
- /* Detect truncation. */
- if( srclen != len )
- {
- return (char *)0;
- }
- }
-
- if( srclen && (0 == (srclen & 3)) )
- {
- if( (char)'=' == src[ srclen-1 ] )
- {
- if( (char)'=' == src[ srclen-2 ] )
- {
- srclen -= 2;
- }
- else
- {
- srclen -= 1;
- }
- }
- }
-
- if( (char *)0 == dest )
- {
- /* The following computes ((srclen * 3) / 4) without overflow. */
- PRUint32 destlen = (srclen / 4) * 3 + ((srclen % 4) * 3) / 4;
- dest = (char *)PR_MALLOC(destlen + 1);
- if( (char *)0 == dest )
- {
- return (char *)0;
- }
- dest[ destlen ] = (char)0; /* null terminate */
- allocated = PR_TRUE;
- }
-
- status = decode((const unsigned char *)src, srclen, (unsigned char *)dest);
- if( PR_SUCCESS != status )
- {
- if( PR_TRUE == allocated )
- {
- PR_DELETE(dest);
- }
-
- return (char *)0;
- }
-
- return dest;
-}
diff --git a/nspr/lib/libc/src/plerror.c b/nspr/lib/libc/src/plerror.c
deleted file mode 100644
index bb8e08d..0000000
--- a/nspr/lib/libc/src/plerror.c
+++ /dev/null
@@ -1,40 +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/. */
-
-/*
-** File:plerror.c
-** Description: Simple routine to print translate the calling thread's
-** error numbers and print them to "syserr".
-*/
-
-#include "plerror.h"
-
-#include "prprf.h"
-#include "prerror.h"
-
-PR_IMPLEMENT(void) PL_FPrintError(PRFileDesc *fd, const char *msg)
-{
-PRErrorCode error = PR_GetError();
-PRInt32 oserror = PR_GetOSError();
-const char *name = PR_ErrorToName(error);
-
- if (NULL != msg) PR_fprintf(fd, "%s: ", msg);
- if (NULL == name)
- PR_fprintf(
- fd, " (%d)OUT OF RANGE, oserror = %d\n", error, oserror);
- else
- PR_fprintf(
- fd, "%s(%d), oserror = %d\n",
- name, error, oserror);
-} /* PL_FPrintError */
-
-PR_IMPLEMENT(void) PL_PrintError(const char *msg)
-{
- static PRFileDesc *fd = NULL;
- if (NULL == fd) fd = PR_GetSpecialFD(PR_StandardError);
- PL_FPrintError(fd, msg);
-} /* PL_PrintError */
-
-/* plerror.c */
diff --git a/nspr/lib/libc/src/plgetopt.c b/nspr/lib/libc/src/plgetopt.c
deleted file mode 100644
index 960decf..0000000
--- a/nspr/lib/libc/src/plgetopt.c
+++ /dev/null
@@ -1,248 +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/. */
-
-/*
-** File: plgetopt.c
-** Description: utilities to parse argc/argv
-*/
-
-#include "prmem.h"
-#include "prlog.h"
-#include "prerror.h"
-#include "plstr.h"
-#include "plgetopt.h"
-
-#include <string.h>
-
-static char static_Nul = 0;
-
-struct PLOptionInternal
-{
- const char *options; /* client options list specification */
- PRIntn argc; /* original number of arguments */
- char **argv; /* vector of pointers to arguments */
- PRIntn xargc; /* which one we're processing now */
- const char *xargv; /* where within *argv[xargc] */
- PRIntn minus; /* do we already have the '-'? */
- const PLLongOpt *longOpts; /* Caller's array */
- PRBool endOfOpts; /* have reached a "--" argument */
- PRIntn optionsLen; /* is strlen(options) */
-};
-
-/*
-** Create the state in which to parse the tokens.
-**
-** argc the sum of the number of options and their values
-** argv the options and their values
-** options vector of single character options w/ | w/o ':
-*/
-PR_IMPLEMENT(PLOptState*) PL_CreateOptState(
- PRIntn argc, char **argv, const char *options)
-{
- return PL_CreateLongOptState( argc, argv, options, NULL);
-} /* PL_CreateOptState */
-
-PR_IMPLEMENT(PLOptState*) PL_CreateLongOptState(
- PRIntn argc, char **argv, const char *options,
- const PLLongOpt *longOpts)
-{
- PLOptState *opt = NULL;
- PLOptionInternal *internal;
-
- if (NULL == options)
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return opt;
- }
-
- opt = PR_NEWZAP(PLOptState);
- if (NULL == opt)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return opt;
- }
-
- internal = PR_NEW(PLOptionInternal);
- if (NULL == internal)
- {
- PR_DELETE(opt);
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
-
- opt->option = 0;
- opt->value = NULL;
- opt->internal = internal;
- opt->longOption = 0;
- opt->longOptIndex = -1;
-
- internal->argc = argc;
- internal->argv = argv;
- internal->xargc = 0;
- internal->xargv = &static_Nul;
- internal->minus = 0;
- internal->options = options;
- internal->longOpts = longOpts;
- internal->endOfOpts = PR_FALSE;
- internal->optionsLen = PL_strlen(options);
-
- return opt;
-} /* PL_CreateLongOptState */
-
-/*
-** Destroy object created by CreateOptState()
-*/
-PR_IMPLEMENT(void) PL_DestroyOptState(PLOptState *opt)
-{
- PR_DELETE(opt->internal);
- PR_DELETE(opt);
-} /* PL_DestroyOptState */
-
-PR_IMPLEMENT(PLOptStatus) PL_GetNextOpt(PLOptState *opt)
-{
- PLOptionInternal *internal = opt->internal;
-
- opt->longOption = 0;
- opt->longOptIndex = -1;
- /*
- ** If the current xarg points to nul, advance to the next
- ** element of the argv vector. If the vector index is equal
- ** to argc, we're out of arguments, so return an EOL.
- ** Note whether the first character of the new argument is
- ** a '-' and skip by it if it is.
- */
- while (0 == *internal->xargv)
- {
- internal->xargc += 1;
- if (internal->xargc >= internal->argc)
- {
- opt->option = 0;
- opt->value = NULL;
- return PL_OPT_EOL;
- }
- internal->xargv = internal->argv[internal->xargc];
- internal->minus = 0;
- if (!internal->endOfOpts && ('-' == *internal->xargv))
- {
- internal->minus++;
- internal->xargv++; /* and consume */
- if ('-' == *internal->xargv && internal->longOpts)
- {
- internal->minus++;
- internal->xargv++;
- if (0 == *internal->xargv)
- {
- internal->endOfOpts = PR_TRUE;
- }
- }
- }
- }
-
- /*
- ** If we already have a '-' or '--' in hand, xargv points to the next
- ** option. See if we can find a match in the list of possible
- ** options supplied.
- */
- if (internal->minus == 2)
- {
- char * foundEqual = strchr(internal->xargv,'=');
- PRIntn optNameLen = foundEqual ? (foundEqual - internal->xargv) :
- strlen(internal->xargv);
- const PLLongOpt *longOpt = internal->longOpts;
- PLOptStatus result = PL_OPT_BAD;
-
- opt->option = 0;
- opt->value = NULL;
-
- for (; longOpt->longOptName; ++longOpt)
- {
- if (strncmp(longOpt->longOptName, internal->xargv, optNameLen))
- continue; /* not a possible match */
- if (strlen(longOpt->longOptName) != optNameLen)
- continue; /* not a match */
- /* option name match */
- opt->longOptIndex = longOpt - internal->longOpts;
- opt->longOption = longOpt->longOption;
- /* value is part of the current argv[] element if = was found */
- /* note: this sets value even for long options that do not
- * require option if specified as --long=value */
- if (foundEqual)
- {
- opt->value = foundEqual + 1;
- }
- else if (longOpt->valueRequired)
- {
- /* value is the next argv[] element, if any */
- if (internal->xargc + 1 < internal->argc)
- {
- opt->value = internal->argv[++(internal->xargc)];
- }
- /* missing value */
- else
- {
- break; /* return PL_OPT_BAD */
- }
- }
- result = PL_OPT_OK;
- break;
- }
- internal->xargv = &static_Nul; /* consume this */
- return result;
- }
- if (internal->minus)
- {
- PRIntn cop;
- PRIntn eoo = internal->optionsLen;
- for (cop = 0; cop < eoo; ++cop)
- {
- if (internal->options[cop] == *internal->xargv)
- {
- opt->option = *internal->xargv++;
- opt->longOption = opt->option & 0xff;
- /*
- ** if options indicates that there's an associated
- ** value, it must be provided, either as part of this
- ** argv[] element or as the next one
- */
- if (':' == internal->options[cop + 1])
- {
- /* value is part of the current argv[] element */
- if (0 != *internal->xargv)
- {
- opt->value = internal->xargv;
- }
- /* value is the next argv[] element, if any */
- else if (internal->xargc + 1 < internal->argc)
- {
- opt->value = internal->argv[++(internal->xargc)];
- }
- /* missing value */
- else
- {
- return PL_OPT_BAD;
- }
-
- internal->xargv = &static_Nul;
- internal->minus = 0;
- }
- else
- opt->value = NULL;
- return PL_OPT_OK;
- }
- }
- internal->xargv += 1; /* consume that option */
- return PL_OPT_BAD;
- }
-
- /*
- ** No '-', so it must be a standalone value. The option is nul.
- */
- opt->value = internal->argv[internal->xargc];
- internal->xargv = &static_Nul;
- opt->option = 0;
- return PL_OPT_OK;
-} /* PL_GetNextOpt */
-
-/* plgetopt.c */
diff --git a/nspr/lib/libc/src/strcase.c b/nspr/lib/libc/src/strcase.c
deleted file mode 100644
index b938ba4..0000000
--- a/nspr/lib/libc/src/strcase.c
+++ /dev/null
@@ -1,170 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* 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 "plstr.h"
-#include <string.h>
-
-static const unsigned char uc[] =
-{
- '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007',
- '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017',
- '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027',
- '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037',
- ' ', '!', '"', '#', '$', '%', '&', '\'',
- '(', ')', '*', '+', ',', '-', '.', '/',
- '0', '1', '2', '3', '4', '5', '6', '7',
- '8', '9', ':', ';', '<', '=', '>', '?',
- '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
- 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
- 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
- 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
- '`', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
- 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
- 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
- 'X', 'Y', 'Z', '{', '|', '}', '~', '\177',
- 0200, 0201, 0202, 0203, 0204, 0205, 0206, 0207,
- 0210, 0211, 0212, 0213, 0214, 0215, 0216, 0217,
- 0220, 0221, 0222, 0223, 0224, 0225, 0226, 0227,
- 0230, 0231, 0232, 0233, 0234, 0235, 0236, 0237,
- 0240, 0241, 0242, 0243, 0244, 0245, 0246, 0247,
- 0250, 0251, 0252, 0253, 0254, 0255, 0256, 0257,
- 0260, 0261, 0262, 0263, 0264, 0265, 0266, 0267,
- 0270, 0271, 0272, 0273, 0274, 0275, 0276, 0277,
- 0300, 0301, 0302, 0303, 0304, 0305, 0306, 0307,
- 0310, 0311, 0312, 0313, 0314, 0315, 0316, 0317,
- 0320, 0321, 0322, 0323, 0324, 0325, 0326, 0327,
- 0330, 0331, 0332, 0333, 0334, 0335, 0336, 0337,
- 0340, 0341, 0342, 0343, 0344, 0345, 0346, 0347,
- 0350, 0351, 0352, 0353, 0354, 0355, 0356, 0357,
- 0360, 0361, 0362, 0363, 0364, 0365, 0366, 0367,
- 0370, 0371, 0372, 0373, 0374, 0375, 0376, 0377
-};
-
-PR_IMPLEMENT(PRIntn)
-PL_strcasecmp(const char *a, const char *b)
-{
- const unsigned char *ua = (const unsigned char *)a;
- const unsigned char *ub = (const unsigned char *)b;
-
- if( ((const char *)0 == a) || (const char *)0 == b )
- return (PRIntn)(a-b);
-
- while( (uc[*ua] == uc[*ub]) && ('\0' != *a) )
- {
- a++;
- ua++;
- ub++;
- }
-
- return (PRIntn)(uc[*ua] - uc[*ub]);
-}
-
-PR_IMPLEMENT(PRIntn)
-PL_strncasecmp(const char *a, const char *b, PRUint32 max)
-{
- const unsigned char *ua = (const unsigned char *)a;
- const unsigned char *ub = (const unsigned char *)b;
-
- if( ((const char *)0 == a) || (const char *)0 == b )
- return (PRIntn)(a-b);
-
- while( max && (uc[*ua] == uc[*ub]) && ('\0' != *a) )
- {
- a++;
- ua++;
- ub++;
- max--;
- }
-
- if( 0 == max ) return (PRIntn)0;
-
- return (PRIntn)(uc[*ua] - uc[*ub]);
-}
-
-PR_IMPLEMENT(char *)
-PL_strcasestr(const char *big, const char *little)
-{
- PRUint32 ll;
-
- if( ((const char *)0 == big) || ((const char *)0 == little) ) return (char *)0;
- if( ((char)0 == *big) || ((char)0 == *little) ) return (char *)0;
-
- ll = strlen(little);
-
- for( ; *big; big++ )
- /* obvious improvement available here */
- if( 0 == PL_strncasecmp(big, little, ll) )
- return (char *)big;
-
- return (char *)0;
-}
-
-PR_IMPLEMENT(char *)
-PL_strcaserstr(const char *big, const char *little)
-{
- const char *p;
- PRUint32 bl, ll;
-
- if( ((const char *)0 == big) || ((const char *)0 == little) ) return (char *)0;
- if( ((char)0 == *big) || ((char)0 == *little) ) return (char *)0;
-
- bl = strlen(big);
- ll = strlen(little);
- if( bl < ll ) return (char *)0;
- p = &big[ bl - ll ];
-
- for( ; p >= big; p-- )
- /* obvious improvement available here */
- if( 0 == PL_strncasecmp(p, little, ll) )
- return (char *)p;
-
- return (char *)0;
-}
-
-PR_IMPLEMENT(char *)
-PL_strncasestr(const char *big, const char *little, PRUint32 max)
-{
- PRUint32 ll;
-
- if( ((const char *)0 == big) || ((const char *)0 == little) ) return (char *)0;
- if( ((char)0 == *big) || ((char)0 == *little) ) return (char *)0;
-
- ll = strlen(little);
- if( ll > max ) return (char *)0;
- max -= ll;
- max++;
-
- for( ; max && *big; big++, max-- )
- /* obvious improvement available here */
- if( 0 == PL_strncasecmp(big, little, ll) )
- return (char *)big;
-
- return (char *)0;
-}
-
-PR_IMPLEMENT(char *)
-PL_strncaserstr(const char *big, const char *little, PRUint32 max)
-{
- const char *p;
- PRUint32 ll;
-
- if( ((const char *)0 == big) || ((const char *)0 == little) ) return (char *)0;
- if( ((char)0 == *big) || ((char)0 == *little) ) return (char *)0;
-
- ll = strlen(little);
-
- for( p = big; max && *p; p++, max-- )
- ;
-
- p -= ll;
- if( p < big ) return (char *)0;
-
- for( ; p >= big; p-- )
- /* obvious improvement available here */
- if( 0 == PL_strncasecmp(p, little, ll) )
- return (char *)p;
-
- return (char *)0;
-}
diff --git a/nspr/lib/libc/src/strcat.c b/nspr/lib/libc/src/strcat.c
deleted file mode 100644
index 05b7b46..0000000
--- a/nspr/lib/libc/src/strcat.c
+++ /dev/null
@@ -1,49 +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/. */
-
-#include "plstr.h"
-#include <string.h>
-
-PR_IMPLEMENT(char *)
-PL_strcat(char *dest, const char *src)
-{
- if( ((char *)0 == dest) || ((const char *)0 == src) )
- return dest;
-
- return strcat(dest, src);
-}
-
-PR_IMPLEMENT(char *)
-PL_strncat(char *dest, const char *src, PRUint32 max)
-{
- char *rv;
-
- if( ((char *)0 == dest) || ((const char *)0 == src) || (0 == max) )
- return dest;
-
- for( rv = dest; *dest; dest++ )
- ;
-
- (void)PL_strncpy(dest, src, max);
- return rv;
-}
-
-PR_IMPLEMENT(char *)
-PL_strcatn(char *dest, PRUint32 max, const char *src)
-{
- char *rv;
- PRUint32 dl;
-
- if( ((char *)0 == dest) || ((const char *)0 == src) )
- return dest;
-
- for( rv = dest, dl = 0; *dest; dest++, dl++ )
- ;
-
- if( max <= dl ) return rv;
- (void)PL_strncpyz(dest, src, max-dl);
-
- return rv;
-}
diff --git a/nspr/lib/libc/src/strchr.c b/nspr/lib/libc/src/strchr.c
deleted file mode 100644
index 523378b..0000000
--- a/nspr/lib/libc/src/strchr.c
+++ /dev/null
@@ -1,56 +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/. */
-
-#include "plstr.h"
-#include <string.h>
-
-PR_IMPLEMENT(char *)
-PL_strchr(const char *s, char c)
-{
- if( (const char *)0 == s ) return (char *)0;
-
- return strchr(s, c);
-}
-
-PR_IMPLEMENT(char *)
-PL_strrchr(const char *s, char c)
-{
- if( (const char *)0 == s ) return (char *)0;
-
- return strrchr(s, c);
-}
-
-PR_IMPLEMENT(char *)
-PL_strnchr(const char *s, char c, PRUint32 n)
-{
- if( (const char *)0 == s ) return (char *)0;
-
- for( ; n && *s; s++, n-- )
- if( *s == c )
- return (char *)s;
-
- if( ((char)0 == c) && (n > 0) && ((char)0 == *s) ) return (char *)s;
-
- return (char *)0;
-}
-
-PR_IMPLEMENT(char *)
-PL_strnrchr(const char *s, char c, PRUint32 n)
-{
- const char *p;
-
- if( (const char *)0 == s ) return (char *)0;
-
- for( p = s; n && *p; p++, n-- )
- ;
-
- if( ((char)0 == c) && (n > 0) && ((char)0 == *p) ) return (char *)p;
-
- for( p--; p >= s; p-- )
- if( *p == c )
- return (char *)p;
-
- return (char *)0;
-}
diff --git a/nspr/lib/libc/src/strcmp.c b/nspr/lib/libc/src/strcmp.c
deleted file mode 100644
index 2d8fbcd..0000000
--- a/nspr/lib/libc/src/strcmp.c
+++ /dev/null
@@ -1,25 +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/. */
-
-#include "plstr.h"
-#include <string.h>
-
-PR_IMPLEMENT(PRIntn)
-PL_strcmp(const char *a, const char *b)
-{
- if( ((const char *)0 == a) || (const char *)0 == b )
- return (PRIntn)(a-b);
-
- return (PRIntn)strcmp(a, b);
-}
-
-PR_IMPLEMENT(PRIntn)
-PL_strncmp(const char *a, const char *b, PRUint32 max)
-{
- if( ((const char *)0 == a) || (const char *)0 == b )
- return (PRIntn)(a-b);
-
- return (PRIntn)strncmp(a, b, (size_t)max);
-}
diff --git a/nspr/lib/libc/src/strcpy.c b/nspr/lib/libc/src/strcpy.c
deleted file mode 100644
index 9d319aa..0000000
--- a/nspr/lib/libc/src/strcpy.c
+++ /dev/null
@@ -1,52 +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/. */
-
-#include "plstr.h"
-#include <string.h>
-
-PR_IMPLEMENT(char *)
-PL_strcpy(char *dest, const char *src)
-{
- if( ((char *)0 == dest) || ((const char *)0 == src) ) return (char *)0;
-
- return strcpy(dest, src);
-}
-
-PR_IMPLEMENT(char *)
-PL_strncpy(char *dest, const char *src, PRUint32 max)
-{
- char *rv;
-
- if( (char *)0 == dest ) return (char *)0;
- if( (const char *)0 == src ) return (char *)0;
-
- for( rv = dest; max && ((*dest = *src) != 0); dest++, src++, max-- )
- ;
-
-#ifdef JLRU
- /* XXX I (wtc) think the -- and ++ operators should be postfix. */
- while( --max )
- *++dest = '\0';
-#endif /* JLRU */
-
- return rv;
-}
-
-PR_IMPLEMENT(char *)
-PL_strncpyz(char *dest, const char *src, PRUint32 max)
-{
- char *rv;
-
- if( (char *)0 == dest ) return (char *)0;
- if( (const char *)0 == src ) return (char *)0;
- if( 0 == max ) return (char *)0;
-
- for( rv = dest, max--; max && ((*dest = *src) != 0); dest++, src++, max-- )
- ;
-
- *dest = '\0';
-
- return rv;
-}
diff --git a/nspr/lib/libc/src/strdup.c b/nspr/lib/libc/src/strdup.c
deleted file mode 100644
index c267147..0000000
--- a/nspr/lib/libc/src/strdup.c
+++ /dev/null
@@ -1,53 +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/. */
-
-#include "plstr.h"
-#include "prmem.h"
-#include <string.h>
-
-PR_IMPLEMENT(char *)
-PL_strdup(const char *s)
-{
- char *rv;
- size_t n;
-
- if( (const char *)0 == s )
- s = "";
-
- n = strlen(s) + 1;
-
- rv = (char *)malloc(n);
- if( (char *)0 == rv ) return rv;
-
- (void)memcpy(rv, s, n);
-
- return rv;
-}
-
-PR_IMPLEMENT(void)
-PL_strfree(char *s)
-{
- free(s);
-}
-
-PR_IMPLEMENT(char *)
-PL_strndup(const char *s, PRUint32 max)
-{
- char *rv;
- size_t l;
-
- if( (const char *)0 == s )
- s = "";
-
- l = PL_strnlen(s, max);
-
- rv = (char *)malloc(l+1);
- if( (char *)0 == rv ) return rv;
-
- (void)memcpy(rv, s, l);
- rv[l] = '\0';
-
- return rv;
-}
diff --git a/nspr/lib/libc/src/strlen.c b/nspr/lib/libc/src/strlen.c
deleted file mode 100644
index ba6c612..0000000
--- a/nspr/lib/libc/src/strlen.c
+++ /dev/null
@@ -1,42 +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/. */
-
-#include "plstr.h"
-#include "prtypes.h"
-#include "prlog.h"
-#include <string.h>
-
-PR_IMPLEMENT(PRUint32)
-PL_strlen(const char *str)
-{
- size_t l;
-
- if( (const char *)0 == str ) return 0;
-
- l = strlen(str);
-
- /* error checking in case we have a 64-bit platform -- make sure
- * we don't have ultra long strings that overflow an int32
- */
- if( sizeof(PRUint32) < sizeof(size_t) )
- {
- if( l > PR_INT32_MAX )
- PR_Assert("l <= PR_INT32_MAX", __FILE__, __LINE__);
- }
-
- return (PRUint32)l;
-}
-
-PR_IMPLEMENT(PRUint32)
-PL_strnlen(const char *str, PRUint32 max)
-{
- register const char *s;
-
- if( (const char *)0 == str ) return 0;
- for( s = str; max && *s; s++, max-- )
- ;
-
- return (PRUint32)(s - str);
-}
diff --git a/nspr/lib/libc/src/strpbrk.c b/nspr/lib/libc/src/strpbrk.c
deleted file mode 100644
index 0d2be98..0000000
--- a/nspr/lib/libc/src/strpbrk.c
+++ /dev/null
@@ -1,68 +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/. */
-
-#include "plstr.h"
-#include <string.h>
-
-PR_IMPLEMENT(char *)
-PL_strpbrk(const char *s, const char *list)
-{
- if( ((const char *)0 == s) || ((const char *)0 == list) ) return (char *)0;
-
- return strpbrk(s, list);
-}
-
-PR_IMPLEMENT(char *)
-PL_strprbrk(const char *s, const char *list)
-{
- const char *p;
- const char *r;
-
- if( ((const char *)0 == s) || ((const char *)0 == list) ) return (char *)0;
-
- for( r = s; *r; r++ )
- ;
-
- for( r--; r >= s; r-- )
- for( p = list; *p; p++ )
- if( *r == *p )
- return (char *)r;
-
- return (char *)0;
-}
-
-PR_IMPLEMENT(char *)
-PL_strnpbrk(const char *s, const char *list, PRUint32 max)
-{
- const char *p;
-
- if( ((const char *)0 == s) || ((const char *)0 == list) ) return (char *)0;
-
- for( ; max && *s; s++, max-- )
- for( p = list; *p; p++ )
- if( *s == *p )
- return (char *)s;
-
- return (char *)0;
-}
-
-PR_IMPLEMENT(char *)
-PL_strnprbrk(const char *s, const char *list, PRUint32 max)
-{
- const char *p;
- const char *r;
-
- if( ((const char *)0 == s) || ((const char *)0 == list) ) return (char *)0;
-
- for( r = s; max && *r; r++, max-- )
- ;
-
- for( r--; r >= s; r-- )
- for( p = list; *p; p++ )
- if( *r == *p )
- return (char *)r;
-
- return (char *)0;
-}
diff --git a/nspr/lib/libc/src/strstr.c b/nspr/lib/libc/src/strstr.c
deleted file mode 100644
index a90d822..0000000
--- a/nspr/lib/libc/src/strstr.c
+++ /dev/null
@@ -1,85 +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/. */
-
-#include "plstr.h"
-#include <string.h>
-
-PR_IMPLEMENT(char *)
-PL_strstr(const char *big, const char *little)
-{
- if( ((const char *)0 == big) || ((const char *)0 == little) ) return (char *)0;
- if( ((char)0 == *big) || ((char)0 == *little) ) return (char *)0;
-
- return strstr(big, little);
-}
-
-PR_IMPLEMENT(char *)
-PL_strrstr(const char *big, const char *little)
-{
- const char *p;
- size_t ll;
- size_t bl;
-
- if( ((const char *)0 == big) || ((const char *)0 == little) ) return (char *)0;
- if( ((char)0 == *big) || ((char)0 == *little) ) return (char *)0;
-
- ll = strlen(little);
- bl = strlen(big);
- if( bl < ll ) return (char *)0;
- p = &big[ bl - ll ];
-
- for( ; p >= big; p-- )
- if( *little == *p )
- if( 0 == strncmp(p, little, ll) )
- return (char *)p;
-
- return (char *)0;
-}
-
-PR_IMPLEMENT(char *)
-PL_strnstr(const char *big, const char *little, PRUint32 max)
-{
- size_t ll;
-
- if( ((const char *)0 == big) || ((const char *)0 == little) ) return (char *)0;
- if( ((char)0 == *big) || ((char)0 == *little) ) return (char *)0;
-
- ll = strlen(little);
- if( ll > (size_t)max ) return (char *)0;
- max -= (PRUint32)ll;
- max++;
-
- for( ; max && *big; big++, max-- )
- if( *little == *big )
- if( 0 == strncmp(big, little, ll) )
- return (char *)big;
-
- return (char *)0;
-}
-
-PR_IMPLEMENT(char *)
-PL_strnrstr(const char *big, const char *little, PRUint32 max)
-{
- const char *p;
- size_t ll;
-
- if( ((const char *)0 == big) || ((const char *)0 == little) ) return (char *)0;
- if( ((char)0 == *big) || ((char)0 == *little) ) return (char *)0;
-
- ll = strlen(little);
-
- for( p = big; max && *p; p++, max-- )
- ;
-
- p -= ll;
- if( p < big ) return (char *)0;
-
- for( ; p >= big; p-- )
- if( *little == *p )
- if( 0 == strncmp(p, little, ll) )
- return (char *)p;
-
- return (char *)0;
-}
diff --git a/nspr/lib/libc/src/strtok.c b/nspr/lib/libc/src/strtok.c
deleted file mode 100644
index 2daaea3..0000000
--- a/nspr/lib/libc/src/strtok.c
+++ /dev/null
@@ -1,56 +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/. */
-
-#include "plstr.h"
-
-PR_IMPLEMENT(char *)
-PL_strtok_r(char *s1, const char *s2, char **lasts)
-{
- const char *sepp;
- int c, sc;
- char *tok;
-
- if( s1 == NULL )
- {
- if( *lasts == NULL )
- return NULL;
-
- s1 = *lasts;
- }
-
- for( ; (c = *s1) != 0; s1++ )
- {
- for( sepp = s2 ; (sc = *sepp) != 0 ; sepp++ )
- {
- if( c == sc )
- break;
- }
- if( sc == 0 )
- break;
- }
-
- if( c == 0 )
- {
- *lasts = NULL;
- return NULL;
- }
-
- tok = s1++;
-
- for( ; (c = *s1) != 0; s1++ )
- {
- for( sepp = s2; (sc = *sepp) != 0; sepp++ )
- {
- if( c == sc )
- {
- *s1++ = '\0';
- *lasts = s1;
- return tok;
- }
- }
- }
- *lasts = NULL;
- return tok;
-}
diff --git a/nspr/pr/include/md/_darwin.cfg b/nspr/pr/include/md/_darwin.cfg
deleted file mode 100644
index 5e11893..0000000
--- a/nspr/pr/include/md/_darwin.cfg
+++ /dev/null
@@ -1,165 +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/. */
-
-#ifndef nspr_cpucfg___
-#define nspr_cpucfg___
-
-#ifndef XP_UNIX
-#define XP_UNIX
-#endif
-
-#define PR_AF_INET6 30 /* same as AF_INET6 */
-
-#ifdef __LITTLE_ENDIAN__
-#undef IS_BIG_ENDIAN
-#define IS_LITTLE_ENDIAN 1
-#else
-#undef IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN 1
-#endif
-
-#ifdef __LP64__
-#define IS_64
-#endif
-
-#ifndef HAVE_LONG_LONG
-#define HAVE_LONG_LONG
-#endif
-#undef HAVE_ALIGNED_DOUBLES
-#define HAVE_ALIGNED_LONGLONGS 1
-
-#ifdef IS_64
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 8
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 8
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 64
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 64
-#define PR_BITS_PER_DWORD 64
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 6
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 6
-#define PR_BITS_PER_DWORD_LOG2 6
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 8
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 8
-#define PR_ALIGN_OF_WORD 8
-#define PR_ALIGN_OF_DWORD 8
-
-#else /* IS_64 */
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 32
-#define PR_BITS_PER_DWORD 64
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 5
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 4
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 4
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD 4
-
-#endif /* IS_64 */
-
-#ifndef NO_NSPR_10_SUPPORT
-
-#define BYTES_PER_BYTE PR_BYTES_PER_BYTE
-#define BYTES_PER_SHORT PR_BYTES_PER_SHORT
-#define BYTES_PER_INT PR_BYTES_PER_INT
-#define BYTES_PER_INT64 PR_BYTES_PER_INT64
-#define BYTES_PER_LONG PR_BYTES_PER_LONG
-#define BYTES_PER_FLOAT PR_BYTES_PER_FLOAT
-#define BYTES_PER_DOUBLE PR_BYTES_PER_DOUBLE
-#define BYTES_PER_WORD PR_BYTES_PER_WORD
-#define BYTES_PER_DWORD PR_BYTES_PER_DWORD
-
-#define BITS_PER_BYTE PR_BITS_PER_BYTE
-#define BITS_PER_SHORT PR_BITS_PER_SHORT
-#define BITS_PER_INT PR_BITS_PER_INT
-#define BITS_PER_INT64 PR_BITS_PER_INT64
-#define BITS_PER_LONG PR_BITS_PER_LONG
-#define BITS_PER_FLOAT PR_BITS_PER_FLOAT
-#define BITS_PER_DOUBLE PR_BITS_PER_DOUBLE
-#define BITS_PER_WORD PR_BITS_PER_WORD
-
-#define BITS_PER_BYTE_LOG2 PR_BITS_PER_BYTE_LOG2
-#define BITS_PER_SHORT_LOG2 PR_BITS_PER_SHORT_LOG2
-#define BITS_PER_INT_LOG2 PR_BITS_PER_INT_LOG2
-#define BITS_PER_INT64_LOG2 PR_BITS_PER_INT64_LOG2
-#define BITS_PER_LONG_LOG2 PR_BITS_PER_LONG_LOG2
-#define BITS_PER_FLOAT_LOG2 PR_BITS_PER_FLOAT_LOG2
-#define BITS_PER_DOUBLE_LOG2 PR_BITS_PER_DOUBLE_LOG2
-#define BITS_PER_WORD_LOG2 PR_BITS_PER_WORD_LOG2
-
-#define ALIGN_OF_SHORT PR_ALIGN_OF_SHORT
-#define ALIGN_OF_INT PR_ALIGN_OF_INT
-#define ALIGN_OF_LONG PR_ALIGN_OF_LONG
-#define ALIGN_OF_INT64 PR_ALIGN_OF_INT64
-#define ALIGN_OF_FLOAT PR_ALIGN_OF_FLOAT
-#define ALIGN_OF_DOUBLE PR_ALIGN_OF_DOUBLE
-#define ALIGN_OF_POINTER PR_ALIGN_OF_POINTER
-#define ALIGN_OF_WORD PR_ALIGN_OF_WORD
-
-#define BYTES_PER_WORD_LOG2 PR_BYTES_PER_WORD_LOG2
-#define BYTES_PER_DWORD_LOG2 PR_BYTES_PER_DWORD_LOG2
-#define WORDS_PER_DWORD_LOG2 PR_WORDS_PER_DWORD_LOG2
-
-#endif /* NO_NSPR_10_SUPPORT */
-
-#endif /* nspr_cpucfg___ */
-
diff --git a/nspr/pr/include/md/_darwin.h b/nspr/pr/include/md/_darwin.h
deleted file mode 100644
index d321023..0000000
--- a/nspr/pr/include/md/_darwin.h
+++ /dev/null
@@ -1,303 +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/. */
-
-#ifndef nspr_darwin_defs_h___
-#define nspr_darwin_defs_h___
-
-#include "prthread.h"
-
-#include <libkern/OSAtomic.h>
-#include <sys/syscall.h>
-
-#ifdef __APPLE__
-#include <AvailabilityMacros.h>
-#include <TargetConditionals.h>
-#endif
-
-#define PR_LINKER_ARCH "darwin"
-#define _PR_SI_SYSNAME "DARWIN"
-#ifdef __i386__
-#define _PR_SI_ARCHITECTURE "x86"
-#elif defined(__x86_64__)
-#define _PR_SI_ARCHITECTURE "x86-64"
-#elif defined(__ppc__)
-#define _PR_SI_ARCHITECTURE "ppc"
-#elif defined(__arm__)
-#define _PR_SI_ARCHITECTURE "arm"
-#elif defined(__aarch64__)
-#define _PR_SI_ARCHITECTURE "aarch64"
-#else
-#error "Unknown CPU architecture"
-#endif
-#define PR_DLL_SUFFIX ".dylib"
-
-#define _PR_VMBASE 0x30000000
-#define _PR_STACK_VMBASE 0x50000000
-#define _MD_DEFAULT_STACK_SIZE 65536L
-#define _MD_MMAP_FLAGS MAP_PRIVATE
-
-#undef HAVE_STACK_GROWING_UP
-#define HAVE_DLL
-#if defined(__x86_64__) || TARGET_OS_IPHONE
-#define USE_DLFCN
-#else
-#define USE_MACH_DYLD
-#endif
-#define _PR_HAVE_SOCKADDR_LEN
-#define _PR_STAT_HAS_ST_ATIMESPEC
-#define _PR_HAVE_LARGE_OFF_T
-#define _PR_HAVE_SYSV_SEMAPHORES
-#define PR_HAVE_SYSV_NAMED_SHARED_MEMORY
-
-#define _PR_INET6
-/*
- * I'd prefer to use getipnodebyname and getipnodebyaddr but the
- * getipnodebyname(3) man page on Mac OS X 10.2 says they are not
- * thread-safe. AI_V4MAPPED|AI_ADDRCONFIG doesn't work either.
- */
-#define _PR_HAVE_GETHOSTBYNAME2
-#define _PR_HAVE_GETADDRINFO
-/*
- * On Mac OS X 10.2, gethostbyaddr fails with h_errno=NO_RECOVERY
- * if you pass an IPv4-mapped IPv6 address to it.
- */
-#define _PR_GHBA_DISALLOW_V4MAPPED
-#ifdef __APPLE__
-#if !defined(MAC_OS_X_VERSION_10_3) || \
- MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3
-/*
- * socket(AF_INET6) fails with EPROTONOSUPPORT on Mac OS X 10.1.
- * IPv6 under OS X 10.2 and below is not complete (see bug 222031).
- */
-#define _PR_INET6_PROBE
-#endif /* DT < 10.3 */
-#if defined(MAC_OS_X_VERSION_10_2) && \
- MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_2
-/* Mac OS X 10.2 has inet_ntop and inet_pton. */
-#define _PR_HAVE_INET_NTOP
-#endif /* DT >= 10.2 */
-#endif /* __APPLE__ */
-#define _PR_IPV6_V6ONLY_PROBE
-/* The IPV6_V6ONLY socket option is not defined on Mac OS X 10.1. */
-#ifndef IPV6_V6ONLY
-#define IPV6_V6ONLY 27
-#endif
-
-#ifdef __ppc__
-#define _PR_HAVE_ATOMIC_OPS
-#define _MD_INIT_ATOMIC()
-extern PRInt32 _PR_DarwinPPC_AtomicIncrement(PRInt32 *val);
-#define _MD_ATOMIC_INCREMENT(val) _PR_DarwinPPC_AtomicIncrement(val)
-extern PRInt32 _PR_DarwinPPC_AtomicDecrement(PRInt32 *val);
-#define _MD_ATOMIC_DECREMENT(val) _PR_DarwinPPC_AtomicDecrement(val)
-extern PRInt32 _PR_DarwinPPC_AtomicSet(PRInt32 *val, PRInt32 newval);
-#define _MD_ATOMIC_SET(val, newval) _PR_DarwinPPC_AtomicSet(val, newval)
-extern PRInt32 _PR_DarwinPPC_AtomicAdd(PRInt32 *ptr, PRInt32 val);
-#define _MD_ATOMIC_ADD(ptr, val) _PR_DarwinPPC_AtomicAdd(ptr, val)
-#endif /* __ppc__ */
-
-#ifdef __i386__
-#define _PR_HAVE_ATOMIC_OPS
-#define _MD_INIT_ATOMIC()
-extern PRInt32 _PR_Darwin_x86_AtomicIncrement(PRInt32 *val);
-#define _MD_ATOMIC_INCREMENT(val) _PR_Darwin_x86_AtomicIncrement(val)
-extern PRInt32 _PR_Darwin_x86_AtomicDecrement(PRInt32 *val);
-#define _MD_ATOMIC_DECREMENT(val) _PR_Darwin_x86_AtomicDecrement(val)
-extern PRInt32 _PR_Darwin_x86_AtomicSet(PRInt32 *val, PRInt32 newval);
-#define _MD_ATOMIC_SET(val, newval) _PR_Darwin_x86_AtomicSet(val, newval)
-extern PRInt32 _PR_Darwin_x86_AtomicAdd(PRInt32 *ptr, PRInt32 val);
-#define _MD_ATOMIC_ADD(ptr, val) _PR_Darwin_x86_AtomicAdd(ptr, val)
-#endif /* __i386__ */
-
-#ifdef __x86_64__
-#define _PR_HAVE_ATOMIC_OPS
-#define _MD_INIT_ATOMIC()
-extern PRInt32 _PR_Darwin_x86_64_AtomicIncrement(PRInt32 *val);
-#define _MD_ATOMIC_INCREMENT(val) _PR_Darwin_x86_64_AtomicIncrement(val)
-extern PRInt32 _PR_Darwin_x86_64_AtomicDecrement(PRInt32 *val);
-#define _MD_ATOMIC_DECREMENT(val) _PR_Darwin_x86_64_AtomicDecrement(val)
-extern PRInt32 _PR_Darwin_x86_64_AtomicSet(PRInt32 *val, PRInt32 newval);
-#define _MD_ATOMIC_SET(val, newval) _PR_Darwin_x86_64_AtomicSet(val, newval)
-extern PRInt32 _PR_Darwin_x86_64_AtomicAdd(PRInt32 *ptr, PRInt32 val);
-#define _MD_ATOMIC_ADD(ptr, val) _PR_Darwin_x86_64_AtomicAdd(ptr, val)
-#endif /* __x86_64__ */
-
-#if defined(__arm__) || defined(__aarch64__)
-#define _PR_HAVE_ATOMIC_OPS
-#define _MD_INIT_ATOMIC()
-#define _MD_ATOMIC_INCREMENT(val) OSAtomicIncrement32(val)
-#define _MD_ATOMIC_DECREMENT(val) OSAtomicDecrement32(val)
-static inline PRInt32 _MD_ATOMIC_SET(PRInt32 *val, PRInt32 newval)
-{
- PRInt32 oldval;
- do {
- oldval = *val;
- } while (!OSAtomicCompareAndSwap32(oldval, newval, val));
- return oldval;
-}
-#define _MD_ATOMIC_ADD(ptr, val) OSAtomicAdd32(val, ptr)
-#endif /* __arm__ || __aarch64__ */
-
-#define USE_SETJMP
-
-#if !defined(_PR_PTHREADS)
-
-#include <setjmp.h>
-
-#define PR_CONTEXT_TYPE jmp_buf
-
-#define CONTEXT(_th) ((_th)->md.context)
-#define _MD_GET_SP(_th) (((struct sigcontext *) (_th)->md.context)->sc_onstack)
-#define PR_NUM_GCREGS _JBLEN
-
-/*
-** Initialize a thread context to run "_main()" when started
-*/
-#define _MD_INIT_CONTEXT(_thread, _sp, _main, status) \
-{ \
- *status = PR_TRUE; \
- if (setjmp(CONTEXT(_thread))) { \
- _main(); \
- } \
- _MD_GET_SP(_thread) = (unsigned char*) ((_sp) - 64); \
-}
-
-#define _MD_SWITCH_CONTEXT(_thread) \
- if (!setjmp(CONTEXT(_thread))) { \
- (_thread)->md.errcode = errno; \
- _PR_Schedule(); \
- }
-
-/*
-** Restore a thread context, saved by _MD_SWITCH_CONTEXT
-*/
-#define _MD_RESTORE_CONTEXT(_thread) \
-{ \
- errno = (_thread)->md.errcode; \
- _MD_SET_CURRENT_THREAD(_thread); \
- longjmp(CONTEXT(_thread), 1); \
-}
-
-/* Machine-dependent (MD) data structures */
-
-struct _MDThread {
- PR_CONTEXT_TYPE context;
- int id;
- int errcode;
-};
-
-struct _MDThreadStack {
- PRInt8 notused;
-};
-
-struct _MDLock {
- PRInt8 notused;
-};
-
-struct _MDSemaphore {
- PRInt8 notused;
-};
-
-struct _MDCVar {
- PRInt8 notused;
-};
-
-struct _MDSegment {
- PRInt8 notused;
-};
-
-/*
- * md-specific cpu structure field
- */
-#define _PR_MD_MAX_OSFD FD_SETSIZE
-
-struct _MDCPU_Unix {
- PRCList ioQ;
- PRUint32 ioq_timeout;
- PRInt32 ioq_max_osfd;
- PRInt32 ioq_osfd_cnt;
-#ifndef _PR_USE_POLL
- fd_set fd_read_set, fd_write_set, fd_exception_set;
- PRInt16 fd_read_cnt[_PR_MD_MAX_OSFD],fd_write_cnt[_PR_MD_MAX_OSFD],
- fd_exception_cnt[_PR_MD_MAX_OSFD];
-#else
- struct pollfd *ioq_pollfds;
- int ioq_pollfds_size;
-#endif /* _PR_USE_POLL */
-};
-
-#define _PR_IOQ(_cpu) ((_cpu)->md.md_unix.ioQ)
-#define _PR_ADD_TO_IOQ(_pq, _cpu) PR_APPEND_LINK(&_pq.links, &_PR_IOQ(_cpu))
-#define _PR_FD_READ_SET(_cpu) ((_cpu)->md.md_unix.fd_read_set)
-#define _PR_FD_READ_CNT(_cpu) ((_cpu)->md.md_unix.fd_read_cnt)
-#define _PR_FD_WRITE_SET(_cpu) ((_cpu)->md.md_unix.fd_write_set)
-#define _PR_FD_WRITE_CNT(_cpu) ((_cpu)->md.md_unix.fd_write_cnt)
-#define _PR_FD_EXCEPTION_SET(_cpu) ((_cpu)->md.md_unix.fd_exception_set)
-#define _PR_FD_EXCEPTION_CNT(_cpu) ((_cpu)->md.md_unix.fd_exception_cnt)
-#define _PR_IOQ_TIMEOUT(_cpu) ((_cpu)->md.md_unix.ioq_timeout)
-#define _PR_IOQ_MAX_OSFD(_cpu) ((_cpu)->md.md_unix.ioq_max_osfd)
-#define _PR_IOQ_OSFD_CNT(_cpu) ((_cpu)->md.md_unix.ioq_osfd_cnt)
-#define _PR_IOQ_POLLFDS(_cpu) ((_cpu)->md.md_unix.ioq_pollfds)
-#define _PR_IOQ_POLLFDS_SIZE(_cpu) ((_cpu)->md.md_unix.ioq_pollfds_size)
-
-#define _PR_IOQ_MIN_POLLFDS_SIZE(_cpu) 32
-
-struct _MDCPU {
- struct _MDCPU_Unix md_unix;
-};
-
-#define _MD_INIT_LOCKS()
-#define _MD_NEW_LOCK(lock) PR_SUCCESS
-#define _MD_FREE_LOCK(lock)
-#define _MD_LOCK(lock)
-#define _MD_UNLOCK(lock)
-#define _MD_INIT_IO()
-#define _MD_IOQ_LOCK()
-#define _MD_IOQ_UNLOCK()
-
-extern PRStatus _MD_InitializeThread(PRThread *thread);
-
-#define _MD_INIT_RUNNING_CPU(cpu) _MD_unix_init_running_cpu(cpu)
-#define _MD_INIT_THREAD _MD_InitializeThread
-#define _MD_EXIT_THREAD(thread)
-#define _MD_SUSPEND_THREAD(thread) _MD_suspend_thread
-#define _MD_RESUME_THREAD(thread) _MD_resume_thread
-#define _MD_CLEAN_THREAD(_thread)
-
-extern PRStatus _MD_CREATE_THREAD(
- PRThread *thread,
- void (*start) (void *),
- PRThreadPriority priority,
- PRThreadScope scope,
- PRThreadState state,
- PRUint32 stackSize);
-extern void _MD_SET_PRIORITY(struct _MDThread *thread, PRUintn newPri);
-extern PRStatus _MD_WAIT(PRThread *, PRIntervalTime timeout);
-extern PRStatus _MD_WAKEUP_WAITER(PRThread *);
-extern void _MD_YIELD(void);
-
-#endif /* ! _PR_PTHREADS */
-
-#define _MD_EARLY_INIT _MD_EarlyInit
-#define _MD_FINAL_INIT _PR_UnixInit
-#define _MD_INTERVAL_INIT _PR_Mach_IntervalInit
-#define _MD_GET_INTERVAL _PR_Mach_GetInterval
-#define _MD_INTERVAL_PER_SEC _PR_Mach_TicksPerSecond
-
-extern void _MD_EarlyInit(void);
-extern void _PR_Mach_IntervalInit(void);
-extern PRIntervalTime _PR_Mach_GetInterval(void);
-extern PRIntervalTime _PR_Mach_TicksPerSecond(void);
-
-/*
- * We wrapped the select() call. _MD_SELECT refers to the built-in,
- * unwrapped version.
- */
-#define _MD_SELECT(nfds,r,w,e,tv) syscall(SYS_select,nfds,r,w,e,tv)
-
-/* For writev() */
-#include <sys/uio.h>
-
-#endif /* nspr_darwin_defs_h___ */
diff --git a/nspr/pr/include/md/_linux.cfg b/nspr/pr/include/md/_linux.cfg
deleted file mode 100644
index 8cbf0cb..0000000
--- a/nspr/pr/include/md/_linux.cfg
+++ /dev/null
@@ -1,1081 +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/. */
-
-/*
- * This file is used by not only Linux but also other glibc systems
- * such as GNU/Hurd and GNU/k*BSD.
- */
-
-#ifndef nspr_cpucfg___
-#define nspr_cpucfg___
-
-#ifndef XP_UNIX
-#define XP_UNIX
-#endif
-
-#if !defined(LINUX) && defined(__linux__)
-#define LINUX
-#endif
-
-#ifdef __FreeBSD_kernel__
-#define PR_AF_INET6 28 /* same as AF_INET6 */
-#elif defined(__GNU__)
-#define PR_AF_INET6 26 /* same as AF_INET6 */
-#else
-#define PR_AF_INET6 10 /* same as AF_INET6 */
-#endif
-
-#ifdef __powerpc64__
-
-#ifdef __LITTLE_ENDIAN__
-#define IS_LITTLE_ENDIAN 1
-#undef IS_BIG_ENDIAN
-#else
-#undef IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN 1
-#endif
-#define IS_64
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 8
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 8
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 64
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 64
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 6
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 6
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 8
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 8
-#define PR_ALIGN_OF_WORD 8
-
-#define PR_BYTES_PER_WORD_LOG2 3
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__powerpc__)
-
-#ifdef __LITTLE_ENDIAN__
-#define IS_LITTLE_ENDIAN 1
-#undef IS_BIG_ENDIAN
-#else
-#undef IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN 1
-#endif
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 32
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 5
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD 4
-
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__alpha)
-
-#define IS_LITTLE_ENDIAN 1
-#undef IS_BIG_ENDIAN
-#define IS_64
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 8
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 8
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 64
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 64
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 6
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 6
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 8
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 8
-#define PR_ALIGN_OF_WORD 8
-
-#define PR_BYTES_PER_WORD_LOG2 3
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__ia64__)
-
-#define IS_LITTLE_ENDIAN 1
-#undef IS_BIG_ENDIAN
-#define IS_64
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 8
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 8
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 64
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 64
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 6
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 6
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 8
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 8
-#define PR_ALIGN_OF_WORD 8
-
-#define PR_BYTES_PER_WORD_LOG2 3
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__x86_64__)
-
-#ifdef __ILP32__
-
-#define IS_LITTLE_ENDIAN 1
-#undef IS_BIG_ENDIAN
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 32
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 5
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD 4
-
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#else
-
-#define IS_LITTLE_ENDIAN 1
-#undef IS_BIG_ENDIAN
-#define IS_64
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 8
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 8
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 64
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 64
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 6
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 6
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 8
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 8
-#define PR_ALIGN_OF_WORD 8
-
-#define PR_BYTES_PER_WORD_LOG2 3
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#endif
-
-#elif defined(__mc68000__)
-
-#undef IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN 1
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 32
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 5
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 2
-#define PR_ALIGN_OF_LONG 2
-#define PR_ALIGN_OF_INT64 2
-#define PR_ALIGN_OF_FLOAT 2
-#define PR_ALIGN_OF_DOUBLE 2
-#define PR_ALIGN_OF_POINTER 2
-#define PR_ALIGN_OF_WORD 2
-
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__sparc__) && defined (__arch64__)
-
-#undef IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN 1
-#define IS_64
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 8
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 8
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 64
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 64
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 6
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 6
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_LONG 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 8
-#define PR_ALIGN_OF_WORD 8
-
-#define PR_BYTES_PER_WORD_LOG2 3
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__sparc__)
-
-#undef IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN 1
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 32
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 5
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD 4
-
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__i386__)
-
-#define IS_LITTLE_ENDIAN 1
-#undef IS_BIG_ENDIAN
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 32
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 5
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 4
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 4
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD 4
-
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__mips__)
-
-#ifdef __MIPSEB__
-#define IS_BIG_ENDIAN 1
-#undef IS_LITTLE_ENDIAN
-#elif defined(__MIPSEL__)
-#define IS_LITTLE_ENDIAN 1
-#undef IS_BIG_ENDIAN
-#else
-#error "Unknown MIPS endianness."
-#endif
-
-#if _MIPS_SIM == _ABI64
-
-#define IS_64
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 8
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 8
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 64
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 64
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 6
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 6
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 8
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 8
-#define PR_ALIGN_OF_WORD 8
-
-#define PR_BYTES_PER_WORD_LOG2 3
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#else /* _ABI64 */
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 32
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 5
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD 4
-
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#endif /* _ABI64 */
-
-#elif defined(__arm__)
-
-#ifdef __ARMEB__
-#undef IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN 1
-#elif defined(__ARMEL__)
-#define IS_LITTLE_ENDIAN 1
-#undef IS_BIG_ENDIAN
-#else
-#error "Unknown ARM endianness."
-#endif
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 32
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 5
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 4
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 4
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD 4
-
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__aarch64__)
-
-#ifdef __AARCH64EB__
-#undef IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN 1
-#elif defined(__AARCH64EL__)
-#define IS_LITTLE_ENDIAN 1
-#undef IS_BIG_ENDIAN
-#else
-#error "Unknown Aarch64 endianness."
-#endif
-#define IS_64
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 8
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 8
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 64
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 64
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 6
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 6
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 8
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 8
-#define PR_ALIGN_OF_WORD 8
-
-#define PR_BYTES_PER_WORD_LOG2 3
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__hppa__)
-
-#undef IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN 1
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 32
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 5
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD 4
-
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__s390x__)
-
-#define IS_BIG_ENDIAN 1
-#undef IS_LITTLE_ENDIAN
-#define IS_64
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 8
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 8
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 64
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 64
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 6
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 6
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 8
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 8
-#define PR_ALIGN_OF_WORD 8
-
-#define PR_BYTES_PER_WORD_LOG2 3
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__s390__)
-
-#define IS_BIG_ENDIAN 1
-#undef IS_LITTLE_ENDIAN
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 32
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 5
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 4
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 4
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD 4
-
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__sh__)
-
-#define IS_LITTLE_ENDIAN 1
-#undef IS_BIG_ENDIAN
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 32
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 5
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 4
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 4
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD 4
-
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__avr32__)
-
-#undef IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN 1
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 32
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 5
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 4
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 4
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD 4
-
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__m32r__)
-
-#undef IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN 1
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 32
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 5
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 4
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 4
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD 4
-
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__or1k__)
-
-#undef IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN 1
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_DOUBLE 64
-#define PR_BITS_PER_WORD 32
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2 5
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 4
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_DOUBLE 4
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD 4
-
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#else
-
-#error "Unknown CPU architecture"
-
-#endif
-
-#ifndef HAVE_LONG_LONG
-#define HAVE_LONG_LONG
-#endif
-#if PR_ALIGN_OF_DOUBLE == 8
-#define HAVE_ALIGNED_DOUBLES
-#endif
-#if PR_ALIGN_OF_INT64 == 8
-#define HAVE_ALIGNED_LONGLONGS
-#endif
-
-#ifndef NO_NSPR_10_SUPPORT
-
-#define BYTES_PER_BYTE PR_BYTES_PER_BYTE
-#define BYTES_PER_SHORT PR_BYTES_PER_SHORT
-#define BYTES_PER_INT PR_BYTES_PER_INT
-#define BYTES_PER_INT64 PR_BYTES_PER_INT64
-#define BYTES_PER_LONG PR_BYTES_PER_LONG
-#define BYTES_PER_FLOAT PR_BYTES_PER_FLOAT
-#define BYTES_PER_DOUBLE PR_BYTES_PER_DOUBLE
-#define BYTES_PER_WORD PR_BYTES_PER_WORD
-#define BYTES_PER_DWORD PR_BYTES_PER_DWORD
-
-#define BITS_PER_BYTE PR_BITS_PER_BYTE
-#define BITS_PER_SHORT PR_BITS_PER_SHORT
-#define BITS_PER_INT PR_BITS_PER_INT
-#define BITS_PER_INT64 PR_BITS_PER_INT64
-#define BITS_PER_LONG PR_BITS_PER_LONG
-#define BITS_PER_FLOAT PR_BITS_PER_FLOAT
-#define BITS_PER_DOUBLE PR_BITS_PER_DOUBLE
-#define BITS_PER_WORD PR_BITS_PER_WORD
-
-#define BITS_PER_BYTE_LOG2 PR_BITS_PER_BYTE_LOG2
-#define BITS_PER_SHORT_LOG2 PR_BITS_PER_SHORT_LOG2
-#define BITS_PER_INT_LOG2 PR_BITS_PER_INT_LOG2
-#define BITS_PER_INT64_LOG2 PR_BITS_PER_INT64_LOG2
-#define BITS_PER_LONG_LOG2 PR_BITS_PER_LONG_LOG2
-#define BITS_PER_FLOAT_LOG2 PR_BITS_PER_FLOAT_LOG2
-#define BITS_PER_DOUBLE_LOG2 PR_BITS_PER_DOUBLE_LOG2
-#define BITS_PER_WORD_LOG2 PR_BITS_PER_WORD_LOG2
-
-#define ALIGN_OF_SHORT PR_ALIGN_OF_SHORT
-#define ALIGN_OF_INT PR_ALIGN_OF_INT
-#define ALIGN_OF_LONG PR_ALIGN_OF_LONG
-#define ALIGN_OF_INT64 PR_ALIGN_OF_INT64
-#define ALIGN_OF_FLOAT PR_ALIGN_OF_FLOAT
-#define ALIGN_OF_DOUBLE PR_ALIGN_OF_DOUBLE
-#define ALIGN_OF_POINTER PR_ALIGN_OF_POINTER
-#define ALIGN_OF_WORD PR_ALIGN_OF_WORD
-
-#define BYTES_PER_WORD_LOG2 PR_BYTES_PER_WORD_LOG2
-#define BYTES_PER_DWORD_LOG2 PR_BYTES_PER_DWORD_LOG2
-#define WORDS_PER_DWORD_LOG2 PR_WORDS_PER_DWORD_LOG2
-
-#endif /* NO_NSPR_10_SUPPORT */
-
-#endif /* nspr_cpucfg___ */
diff --git a/nspr/pr/include/md/_linux.h b/nspr/pr/include/md/_linux.h
deleted file mode 100644
index b4b298b..0000000
--- a/nspr/pr/include/md/_linux.h
+++ /dev/null
@@ -1,694 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* 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/. */
-
-/*
- * This file is used by not only Linux but also other glibc systems
- * such as GNU/Hurd and GNU/k*BSD.
- */
-
-#ifndef nspr_linux_defs_h___
-#define nspr_linux_defs_h___
-
-#include "prthread.h"
-
-/*
- * Internal configuration macros
- */
-
-#define PR_LINKER_ARCH "linux"
-#define _PR_SI_SYSNAME "LINUX"
-#ifdef __powerpc64__
-#define _PR_SI_ARCHITECTURE "ppc64"
-#elif defined(__powerpc__)
-#define _PR_SI_ARCHITECTURE "ppc"
-#elif defined(__alpha)
-#define _PR_SI_ARCHITECTURE "alpha"
-#elif defined(__ia64__)
-#define _PR_SI_ARCHITECTURE "ia64"
-#elif defined(__x86_64__)
-#define _PR_SI_ARCHITECTURE "x86-64"
-#elif defined(__mc68000__)
-#define _PR_SI_ARCHITECTURE "m68k"
-#elif defined(__sparc__) && defined(__arch64__)
-#define _PR_SI_ARCHITECTURE "sparc64"
-#elif defined(__sparc__)
-#define _PR_SI_ARCHITECTURE "sparc"
-#elif defined(__i386__)
-#define _PR_SI_ARCHITECTURE "x86"
-#elif defined(__mips__)
-#define _PR_SI_ARCHITECTURE "mips"
-#elif defined(__arm__)
-#define _PR_SI_ARCHITECTURE "arm"
-#elif defined(__aarch64__)
-#define _PR_SI_ARCHITECTURE "aarch64"
-#elif defined(__hppa__)
-#define _PR_SI_ARCHITECTURE "hppa"
-#elif defined(__s390x__)
-#define _PR_SI_ARCHITECTURE "s390x"
-#elif defined(__s390__)
-#define _PR_SI_ARCHITECTURE "s390"
-#elif defined(__sh__)
-#define _PR_SI_ARCHITECTURE "sh"
-#elif defined(__avr32__)
-#define _PR_SI_ARCHITECTURE "avr32"
-#elif defined(__m32r__)
-#define _PR_SI_ARCHITECTURE "m32r"
-#elif defined(__or1k__)
-#define _PR_SI_ARCHITECTURE "or1k"
-#else
-#error "Unknown CPU architecture"
-#endif
-#define PR_DLL_SUFFIX ".so"
-
-#define _PR_VMBASE 0x30000000
-#define _PR_STACK_VMBASE 0x50000000
-#define _MD_DEFAULT_STACK_SIZE 65536L
-#define _MD_MMAP_FLAGS MAP_PRIVATE
-
-#if defined(__aarch64__) || defined(__mips__)
-#define _MD_MINIMUM_STACK_SIZE 0x20000
-#endif
-
-#undef HAVE_STACK_GROWING_UP
-
-/*
- * Elf linux supports dl* functions
- */
-#define HAVE_DLL
-#define USE_DLFCN
-#if defined(ANDROID)
-#define NO_DLOPEN_NULL
-#endif
-
-#if defined(__FreeBSD_kernel__) || defined(__GNU__)
-#define _PR_HAVE_SOCKADDR_LEN
-#endif
-
-#if defined(__i386__)
-#define _PR_HAVE_ATOMIC_OPS
-#define _MD_INIT_ATOMIC()
-extern PRInt32 _PR_x86_AtomicIncrement(PRInt32 *val);
-#define _MD_ATOMIC_INCREMENT _PR_x86_AtomicIncrement
-extern PRInt32 _PR_x86_AtomicDecrement(PRInt32 *val);
-#define _MD_ATOMIC_DECREMENT _PR_x86_AtomicDecrement
-extern PRInt32 _PR_x86_AtomicAdd(PRInt32 *ptr, PRInt32 val);
-#define _MD_ATOMIC_ADD _PR_x86_AtomicAdd
-extern PRInt32 _PR_x86_AtomicSet(PRInt32 *val, PRInt32 newval);
-#define _MD_ATOMIC_SET _PR_x86_AtomicSet
-#endif
-
-#if defined(__ia64__)
-#define _PR_HAVE_ATOMIC_OPS
-#define _MD_INIT_ATOMIC()
-extern PRInt32 _PR_ia64_AtomicIncrement(PRInt32 *val);
-#define _MD_ATOMIC_INCREMENT _PR_ia64_AtomicIncrement
-extern PRInt32 _PR_ia64_AtomicDecrement(PRInt32 *val);
-#define _MD_ATOMIC_DECREMENT _PR_ia64_AtomicDecrement
-extern PRInt32 _PR_ia64_AtomicAdd(PRInt32 *ptr, PRInt32 val);
-#define _MD_ATOMIC_ADD _PR_ia64_AtomicAdd
-extern PRInt32 _PR_ia64_AtomicSet(PRInt32 *val, PRInt32 newval);
-#define _MD_ATOMIC_SET _PR_ia64_AtomicSet
-#endif
-
-#if defined(__x86_64__)
-#define _PR_HAVE_ATOMIC_OPS
-#define _MD_INIT_ATOMIC()
-extern PRInt32 _PR_x86_64_AtomicIncrement(PRInt32 *val);
-#define _MD_ATOMIC_INCREMENT _PR_x86_64_AtomicIncrement
-extern PRInt32 _PR_x86_64_AtomicDecrement(PRInt32 *val);
-#define _MD_ATOMIC_DECREMENT _PR_x86_64_AtomicDecrement
-extern PRInt32 _PR_x86_64_AtomicAdd(PRInt32 *ptr, PRInt32 val);
-#define _MD_ATOMIC_ADD _PR_x86_64_AtomicAdd
-extern PRInt32 _PR_x86_64_AtomicSet(PRInt32 *val, PRInt32 newval);
-#define _MD_ATOMIC_SET _PR_x86_64_AtomicSet
-#endif
-
-#if defined(__or1k__)
-#if defined(__GNUC__)
-/* Use GCC built-in functions */
-#define _PR_HAVE_ATOMIC_OPS
-#define _MD_INIT_ATOMIC()
-#define _MD_ATOMIC_INCREMENT(ptr) __sync_add_and_fetch(ptr, 1)
-#define _MD_ATOMIC_DECREMENT(ptr) __sync_sub_and_fetch(ptr, 1)
-#define _MD_ATOMIC_ADD(ptr, i) __sync_add_and_fetch(ptr, i)
-#define _MD_ATOMIC_SET(ptr, nv) __sync_lock_test_and_set(ptr, nv)
-#endif
-#endif
-
-#if defined(__powerpc__) && !defined(__powerpc64__)
-#define _PR_HAVE_ATOMIC_OPS
-#define _MD_INIT_ATOMIC()
-extern PRInt32 _PR_ppc_AtomicIncrement(PRInt32 *val);
-#define _MD_ATOMIC_INCREMENT _PR_ppc_AtomicIncrement
-extern PRInt32 _PR_ppc_AtomicDecrement(PRInt32 *val);
-#define _MD_ATOMIC_DECREMENT _PR_ppc_AtomicDecrement
-extern PRInt32 _PR_ppc_AtomicAdd(PRInt32 *ptr, PRInt32 val);
-#define _MD_ATOMIC_ADD _PR_ppc_AtomicAdd
-extern PRInt32 _PR_ppc_AtomicSet(PRInt32 *val, PRInt32 newval);
-#define _MD_ATOMIC_SET _PR_ppc_AtomicSet
-#endif
-
-#if defined(__powerpc64__)
-#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)
-/* Use GCC built-in functions */
-#define _PR_HAVE_ATOMIC_OPS
-#define _MD_INIT_ATOMIC()
-#define _MD_ATOMIC_INCREMENT(ptr) __sync_add_and_fetch(ptr, 1)
-#define _MD_ATOMIC_DECREMENT(ptr) __sync_sub_and_fetch(ptr, 1)
-#define _MD_ATOMIC_ADD(ptr, i) __sync_add_and_fetch(ptr, i)
-#define _MD_ATOMIC_SET(ptr, nv) __sync_lock_test_and_set(ptr, nv)
-#endif
-#endif
-
-#if defined(__mips__) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)
-/* Use GCC built-in functions */
-#define _PR_HAVE_ATOMIC_OPS
-#define _MD_INIT_ATOMIC()
-#define _MD_ATOMIC_INCREMENT(ptr) __sync_add_and_fetch(ptr, 1)
-#define _MD_ATOMIC_DECREMENT(ptr) __sync_sub_and_fetch(ptr, 1)
-#define _MD_ATOMIC_ADD(ptr, i) __sync_add_and_fetch(ptr, i)
-#define _MD_ATOMIC_SET(ptr, nv) __sync_lock_test_and_set(ptr, nv)
-#endif
-
-#if defined(__alpha)
-#define _PR_HAVE_ATOMIC_OPS
-#define _MD_INIT_ATOMIC()
-#define _MD_ATOMIC_ADD(ptr, i) ({ \
- PRInt32 __atomic_tmp, __atomic_ret; \
- __asm__ __volatile__( \
- "1: ldl_l %[ret], %[val] \n" \
- " addl %[ret], %[inc], %[tmp] \n" \
- " addl %[ret], %[inc], %[ret] \n" \
- " stl_c %[tmp], %[val] \n" \
- " beq %[tmp], 2f \n" \
- ".subsection 2 \n" \
- "2: br 1b \n" \
- ".previous" \
- : [ret] "=&r" (__atomic_ret), \
- [tmp] "=&r" (__atomic_tmp), \
- [val] "=m" (*ptr) \
- : [inc] "Ir" (i), "m" (*ptr)); \
- __atomic_ret; \
-})
-#define _MD_ATOMIC_INCREMENT(ptr) _MD_ATOMIC_ADD(ptr, 1)
-#define _MD_ATOMIC_DECREMENT(ptr) ({ \
- PRInt32 __atomic_tmp, __atomic_ret; \
- __asm__ __volatile__( \
- "1: ldl_l %[ret], %[val] \n" \
- " subl %[ret], 1, %[tmp] \n" \
- " subl %[ret], 1, %[ret] \n" \
- " stl_c %[tmp], %[val] \n" \
- " beq %[tmp], 2f \n" \
- ".subsection 2 \n" \
- "2: br 1b \n" \
- ".previous" \
- : [ret] "=&r" (__atomic_ret), \
- [tmp] "=&r" (__atomic_tmp), \
- [val] "=m" (*ptr) \
- : "m" (*ptr)); \
- __atomic_ret; \
-})
-#define _MD_ATOMIC_SET(ptr, n) ({ \
- PRInt32 __atomic_tmp, __atomic_ret; \
- __asm__ __volatile__( \
- "1: ldl_l %[ret], %[val] \n" \
- " mov %[newval], %[tmp] \n" \
- " stl_c %[tmp], %[val] \n" \
- " beq %[tmp], 2f \n" \
- ".subsection 2 \n" \
- "2: br 1b \n" \
- ".previous" \
- : [ret] "=&r" (__atomic_ret), \
- [tmp] "=&r"(__atomic_tmp), \
- [val] "=m" (*ptr) \
- : [newval] "Ir" (n), "m" (*ptr)); \
- __atomic_ret; \
-})
-#endif
-
-#if defined(__arm__) || defined(__aarch64__)
-#if defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)
-/* Use GCC built-in functions */
-#define _PR_HAVE_ATOMIC_OPS
-#define _MD_INIT_ATOMIC()
-
-#define _MD_ATOMIC_INCREMENT(ptr) __sync_add_and_fetch(ptr, 1)
-#define _MD_ATOMIC_DECREMENT(ptr) __sync_sub_and_fetch(ptr, 1)
-#define _MD_ATOMIC_SET(ptr, nv) __sync_lock_test_and_set(ptr, nv)
-#define _MD_ATOMIC_ADD(ptr, i) __sync_add_and_fetch(ptr, i)
-
-#elif defined(_PR_ARM_KUSER)
-#define _PR_HAVE_ATOMIC_OPS
-#define _MD_INIT_ATOMIC()
-
-/*
- * The kernel provides this helper function at a fixed address with a fixed
- * ABI signature, directly callable from user space.
- *
- * Definition:
- * Atomically store newval in *ptr if *ptr is equal to oldval.
- * Return zero if *ptr was changed or non-zero if no exchange happened.
- */
-typedef int (__kernel_cmpxchg_t)(int oldval, int newval, volatile int *ptr);
-#define __kernel_cmpxchg (*(__kernel_cmpxchg_t *)0xffff0fc0)
-
-#define _MD_ATOMIC_INCREMENT(ptr) _MD_ATOMIC_ADD(ptr, 1)
-#define _MD_ATOMIC_DECREMENT(ptr) _MD_ATOMIC_ADD(ptr, -1)
-
-static inline PRInt32 _MD_ATOMIC_ADD(PRInt32 *ptr, PRInt32 n)
-{
- PRInt32 ov, nv;
- volatile PRInt32 *vp = ptr;
-
- do {
- ov = *vp;
- nv = ov + n;
- } while (__kernel_cmpxchg(ov, nv, vp));
-
- return nv;
-}
-
-static inline PRInt32 _MD_ATOMIC_SET(PRInt32 *ptr, PRInt32 nv)
-{
- PRInt32 ov;
- volatile PRInt32 *vp = ptr;
-
- do {
- ov = *vp;
- } while (__kernel_cmpxchg(ov, nv, vp));
-
- return ov;
-}
-#endif
-#endif /* __arm__ */
-
-#define USE_SETJMP
-#if (defined(__GLIBC__) && __GLIBC__ >= 2) || defined(ANDROID)
-#define _PR_POLL_AVAILABLE
-#endif
-#undef _PR_USE_POLL
-#define _PR_STAT_HAS_ONLY_ST_ATIME
-#if defined(__alpha) || defined(__ia64__)
-#define _PR_HAVE_LARGE_OFF_T
-#elif (__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1) \
- || defined(ANDROID)
-#define _PR_HAVE_OFF64_T
-#else
-#define _PR_NO_LARGE_FILES
-#endif
-#if (__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1) \
- || defined(ANDROID)
-#define _PR_INET6
-#define _PR_HAVE_INET_NTOP
-#define _PR_HAVE_GETHOSTBYNAME2
-#define _PR_HAVE_GETADDRINFO
-#define _PR_INET6_PROBE
-#endif
-#ifndef ANDROID
-#define _PR_HAVE_SYSV_SEMAPHORES
-#define PR_HAVE_SYSV_NAMED_SHARED_MEMORY
-#endif
-/* Android has gethostbyname_r but not gethostbyaddr_r or gethostbyname2_r. */
-#if (__GLIBC__ >= 2) && defined(_PR_PTHREADS)
-#define _PR_HAVE_GETHOST_R
-#define _PR_HAVE_GETHOST_R_INT
-#endif
-
-#ifdef _PR_PTHREADS
-
-extern void _MD_CleanupBeforeExit(void);
-#define _MD_CLEANUP_BEFORE_EXIT _MD_CleanupBeforeExit
-
-#else /* ! _PR_PTHREADS */
-
-#include <setjmp.h>
-
-#define PR_CONTEXT_TYPE sigjmp_buf
-
-#define CONTEXT(_th) ((_th)->md.context)
-
-#ifdef __powerpc__
-/*
- * PowerPC based MkLinux
- *
- * On the PowerPC, the new style jmp_buf isn't used until glibc
- * 2.1.
- */
-#if (__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1)
-#define _MD_GET_SP(_t) (_t)->md.context[0].__jmpbuf[JB_GPR1]
-#else
-#define _MD_GET_SP(_t) (_t)->md.context[0].__jmpbuf[0].__misc[0]
-#endif /* glibc 2.1 or later */
-#define _MD_SET_FP(_t, val)
-#define _MD_GET_SP_PTR(_t) &(_MD_GET_SP(_t))
-#define _MD_GET_FP_PTR(_t) ((void *) 0)
-/* aix = 64, macos = 70 */
-#define PR_NUM_GCREGS 64
-
-#elif defined(__alpha)
-/* Alpha based Linux */
-
-#if defined(__GLIBC__) && __GLIBC__ >= 2
-#define _MD_GET_SP(_t) (_t)->md.context[0].__jmpbuf[JB_SP]
-#define _MD_SET_FP(_t, val)
-#define _MD_GET_SP_PTR(_t) &(_MD_GET_SP(_t))
-#define _MD_GET_FP_PTR(_t) ((void *) 0)
-#define _MD_SP_TYPE long int
-#else
-#define _MD_GET_SP(_t) (_t)->md.context[0].__jmpbuf[0].__sp
-#define _MD_SET_FP(_t, val)
-#define _MD_GET_SP_PTR(_t) &(_MD_GET_SP(_t))
-#define _MD_GET_FP_PTR(_t) ((void *) 0)
-#define _MD_SP_TYPE __ptr_t
-#endif /* defined(__GLIBC__) && __GLIBC__ >= 2 */
-
-/* XXX not sure if this is correct, or maybe it should be 17? */
-#define PR_NUM_GCREGS 9
-
-#elif defined(__ia64__)
-
-#define _MD_GET_SP(_t) ((long *)((_t)->md.context[0].__jmpbuf)[0])
-#define _MD_SET_FP(_t, val)
-#define _MD_GET_SP_PTR(_t) &(_MD_GET_SP(_t))
-#define _MD_GET_FP_PTR(_t) ((void *) 0)
-#define _MD_SP_TYPE long int
-
-#define PR_NUM_GCREGS _JBLEN
-
-#elif defined(__mc68000__)
-/* m68k based Linux */
-
-/*
- * On the m68k, glibc still uses the old style sigjmp_buf, even
- * in glibc 2.0.7.
- */
-#if defined(__GLIBC__) && __GLIBC__ >= 2
-#define _MD_GET_SP(_t) (_t)->md.context[0].__jmpbuf[0].__sp
-#define _MD_SET_FP(_t, val)
-#define _MD_GET_SP_PTR(_t) &(_MD_GET_SP(_t))
-#define _MD_GET_FP_PTR(_t) ((void *) 0)
-#define _MD_SP_TYPE int
-#else
-#define _MD_GET_SP(_t) (_t)->md.context[0].__jmpbuf[0].__sp
-#define _MD_SET_FP(_t, val)
-#define _MD_GET_SP_PTR(_t) &(_MD_GET_SP(_t))
-#define _MD_GET_FP_PTR(_t) ((void *) 0)
-#define _MD_SP_TYPE __ptr_t
-#endif /* defined(__GLIBC__) && __GLIBC__ >= 2 */
-
-/* XXX not sure if this is correct, or maybe it should be 17? */
-#define PR_NUM_GCREGS 9
-
-#elif defined(__sparc__)
-/* Sparc */
-#if defined(__GLIBC__) && __GLIBC__ >= 2
-/*
- * You need glibc2-2.0.7-25 or later. The libraries that came with
- * Red Hat 5.1 are not new enough, but they are in 5.2.
- */
-#define _MD_GET_SP(_t) (_t)->md.context[0].__jmpbuf[JB_SP]
-#define _MD_SET_FP(_t, val) ((_t)->md.context[0].__jmpbuf[JB_FP] = val)
-#define _MD_GET_SP_PTR(_t) &(_MD_GET_SP(_t))
-#define _MD_GET_FP_PTR(_t) (&(_t)->md.context[0].__jmpbuf[JB_FP])
-#define _MD_SP_TYPE int
-#else
-#define _MD_GET_SP(_t) (_t)->md.context[0].__jmpbuf[0].__fp
-#define _MD_SET_FP(_t, val)
-#define _MD_GET_SP_PTR(_t) &(_MD_GET_SP(_t))
-#define _MD_GET_FP_PTR(_t) ((void *) 0)
-#define _MD_SP_TYPE __ptr_t
-#endif /* defined(__GLIBC__) && __GLIBC__ >= 2 */
-
-#elif defined(__i386__)
-/* Intel based Linux */
-#if defined(__GLIBC__) && __GLIBC__ >= 2
-#define _MD_GET_SP(_t) (_t)->md.context[0].__jmpbuf[JB_SP]
-#define _MD_SET_FP(_t, val) ((_t)->md.context[0].__jmpbuf[JB_BP] = val)
-#define _MD_GET_SP_PTR(_t) &(_MD_GET_SP(_t))
-#define _MD_GET_FP_PTR(_t) (&(_t)->md.context[0].__jmpbuf[JB_BP])
-#define _MD_SP_TYPE int
-#else
-#define _MD_GET_SP(_t) (_t)->md.context[0].__jmpbuf[0].__sp
-#define _MD_SET_FP(_t, val) ((_t)->md.context[0].__jmpbuf[0].__bp = val)
-#define _MD_GET_SP_PTR(_t) &(_MD_GET_SP(_t))
-#define _MD_GET_FP_PTR(_t) &((_t)->md.context[0].__jmpbuf[0].__bp)
-#define _MD_SP_TYPE __ptr_t
-#endif /* defined(__GLIBC__) && __GLIBC__ >= 2 */
-#define PR_NUM_GCREGS 6
-
-#elif defined(__mips__)
-/* Linux/MIPS */
-#if defined(__GLIBC__) && __GLIBC__ >= 2
-#define _MD_GET_SP(_t) (_t)->md.context[0].__jmpbuf[0].__sp
-#define _MD_SET_FP(_t, val) ((_t)->md.context[0].__jmpbuf[0].__fp = (val))
-#define _MD_GET_SP_PTR(_t) &(_MD_GET_SP(_t))
-#define _MD_GET_FP_PTR(_t) (&(_t)->md.context[0].__jmpbuf[0].__fp)
-#define _MD_SP_TYPE __ptr_t
-#else
-#error "Linux/MIPS pre-glibc2 not supported yet"
-#endif /* defined(__GLIBC__) && __GLIBC__ >= 2 */
-
-#elif defined(__arm__)
-/* ARM/Linux */
-#if defined(__GLIBC__) && __GLIBC__ >= 2
-#ifdef __ARM_EABI__
-/* EABI */
-#define _MD_GET_SP(_t) (_t)->md.context[0].__jmpbuf[8]
-#define _MD_SET_FP(_t, val) ((_t)->md.context[0].__jmpbuf[7] = (val))
-#define _MD_GET_SP_PTR(_t) &(_MD_GET_SP(_t))
-#define _MD_GET_FP_PTR(_t) (&(_t)->md.context[0].__jmpbuf[7])
-#define _MD_SP_TYPE __ptr_t
-#else /* __ARM_EABI__ */
-/* old ABI */
-#define _MD_GET_SP(_t) (_t)->md.context[0].__jmpbuf[20]
-#define _MD_SET_FP(_t, val) ((_t)->md.context[0].__jmpbuf[19] = (val))
-#define _MD_GET_SP_PTR(_t) &(_MD_GET_SP(_t))
-#define _MD_GET_FP_PTR(_t) (&(_t)->md.context[0].__jmpbuf[19])
-#define _MD_SP_TYPE __ptr_t
-#endif /* __ARM_EABI__ */
-#else
-#error "ARM/Linux pre-glibc2 not supported yet"
-#endif /* defined(__GLIBC__) && __GLIBC__ >= 2 */
-
-#elif defined(__sh__)
-/* SH/Linux */
-#if defined(__GLIBC__) && __GLIBC__ >= 2
-#define _MD_GET_SP(_t) (_t)->md.context[0].__jmpbuf[7]
-#define _MD_SET_FP(_t, val) ((_t)->md.context[0].__jmpbuf[6] = (val))
-#define _MD_GET_SP_PTR(_t) &(_MD_GET_SP(_t))
-#define _MD_GET_FP_PTR(_t) (&(_t)->md.context[0].__jmpbuf[6])
-#define _MD_SP_TYPE __ptr_t
-#else
-#error "SH/Linux pre-glibc2 not supported yet"
-#endif /* defined(__GLIBC__) && __GLIBC__ >= 2 */
-
-#elif defined(__m32r__)
-/* Linux/M32R */
-#if defined(__GLIBC__) && __GLIBC__ >= 2
-#define _MD_GET_SP(_t) (_t)->md.context[0].__jmpbuf[0].__regs[JB_SP]
-#define _MD_SET_FP(_t, val) ((_t)->md.context[0].__jmpbuf[0].__regs[JB_FP] = (val))
-#define _MD_GET_SP_PTR(_t) &(_MD_GET_SP(_t))
-#define _MD_GET_FP_PTR(_t) (&(_t)->md.context[0].__jmpbuf[0].__regs[JB_FP])
-#define _MD_SP_TYPE __ptr_t
-#else
-#error "Linux/M32R pre-glibc2 not supported yet"
-#endif /* defined(__GLIBC__) && __GLIBC__ >= 2 */
-
-#else
-
-#error "Unknown CPU architecture"
-
-#endif /*__powerpc__*/
-
-/*
-** Initialize a thread context to run "_main()" when started
-*/
-#ifdef __powerpc__
-
-#define _MD_INIT_CONTEXT(_thread, _sp, _main, status) \
-{ \
- *status = PR_TRUE; \
- if (sigsetjmp(CONTEXT(_thread), 1)) { \
- _main(); \
- } \
- _MD_GET_SP(_thread) = (unsigned char*) ((_sp) - 128); \
- _thread->md.sp = _MD_GET_SP_PTR(_thread); \
- _thread->md.fp = _MD_GET_FP_PTR(_thread); \
- _MD_SET_FP(_thread, 0); \
-}
-
-#elif defined(__mips__)
-
-#define _MD_INIT_CONTEXT(_thread, _sp, _main, status) \
-{ \
- *status = PR_TRUE; \
- (void) sigsetjmp(CONTEXT(_thread), 1); \
- _thread->md.context[0].__jmpbuf[0].__pc = (__ptr_t) _main; \
- _MD_GET_SP(_thread) = (_MD_SP_TYPE) ((_sp) - 64); \
- _thread->md.sp = _MD_GET_SP_PTR(_thread); \
- _thread->md.fp = _MD_GET_FP_PTR(_thread); \
- _MD_SET_FP(_thread, 0); \
-}
-
-#else
-
-#define _MD_INIT_CONTEXT(_thread, _sp, _main, status) \
-{ \
- *status = PR_TRUE; \
- if (sigsetjmp(CONTEXT(_thread), 1)) { \
- _main(); \
- } \
- _MD_GET_SP(_thread) = (_MD_SP_TYPE) ((_sp) - 64); \
- _thread->md.sp = _MD_GET_SP_PTR(_thread); \
- _thread->md.fp = _MD_GET_FP_PTR(_thread); \
- _MD_SET_FP(_thread, 0); \
-}
-
-#endif /*__powerpc__*/
-
-#define _MD_SWITCH_CONTEXT(_thread) \
- if (!sigsetjmp(CONTEXT(_thread), 1)) { \
- (_thread)->md.errcode = errno; \
- _PR_Schedule(); \
- }
-
-/*
-** Restore a thread context, saved by _MD_SWITCH_CONTEXT
-*/
-#define _MD_RESTORE_CONTEXT(_thread) \
-{ \
- errno = (_thread)->md.errcode; \
- _MD_SET_CURRENT_THREAD(_thread); \
- siglongjmp(CONTEXT(_thread), 1); \
-}
-
-/* Machine-dependent (MD) data structures */
-
-struct _MDThread {
- PR_CONTEXT_TYPE context;
- void *sp;
- void *fp;
- int id;
- int errcode;
-};
-
-struct _MDThreadStack {
- PRInt8 notused;
-};
-
-struct _MDLock {
- PRInt8 notused;
-};
-
-struct _MDSemaphore {
- PRInt8 notused;
-};
-
-struct _MDCVar {
- PRInt8 notused;
-};
-
-struct _MDSegment {
- PRInt8 notused;
-};
-
-/*
- * md-specific cpu structure field
- */
-#include <sys/time.h> /* for FD_SETSIZE */
-#define _PR_MD_MAX_OSFD FD_SETSIZE
-
-struct _MDCPU_Unix {
- PRCList ioQ;
- PRUint32 ioq_timeout;
- PRInt32 ioq_max_osfd;
- PRInt32 ioq_osfd_cnt;
-#ifndef _PR_USE_POLL
- fd_set fd_read_set, fd_write_set, fd_exception_set;
- PRInt16 fd_read_cnt[_PR_MD_MAX_OSFD],fd_write_cnt[_PR_MD_MAX_OSFD],
- fd_exception_cnt[_PR_MD_MAX_OSFD];
-#else
- struct pollfd *ioq_pollfds;
- int ioq_pollfds_size;
-#endif /* _PR_USE_POLL */
-};
-
-#define _PR_IOQ(_cpu) ((_cpu)->md.md_unix.ioQ)
-#define _PR_ADD_TO_IOQ(_pq, _cpu) PR_APPEND_LINK(&_pq.links, &_PR_IOQ(_cpu))
-#define _PR_FD_READ_SET(_cpu) ((_cpu)->md.md_unix.fd_read_set)
-#define _PR_FD_READ_CNT(_cpu) ((_cpu)->md.md_unix.fd_read_cnt)
-#define _PR_FD_WRITE_SET(_cpu) ((_cpu)->md.md_unix.fd_write_set)
-#define _PR_FD_WRITE_CNT(_cpu) ((_cpu)->md.md_unix.fd_write_cnt)
-#define _PR_FD_EXCEPTION_SET(_cpu) ((_cpu)->md.md_unix.fd_exception_set)
-#define _PR_FD_EXCEPTION_CNT(_cpu) ((_cpu)->md.md_unix.fd_exception_cnt)
-#define _PR_IOQ_TIMEOUT(_cpu) ((_cpu)->md.md_unix.ioq_timeout)
-#define _PR_IOQ_MAX_OSFD(_cpu) ((_cpu)->md.md_unix.ioq_max_osfd)
-#define _PR_IOQ_OSFD_CNT(_cpu) ((_cpu)->md.md_unix.ioq_osfd_cnt)
-#define _PR_IOQ_POLLFDS(_cpu) ((_cpu)->md.md_unix.ioq_pollfds)
-#define _PR_IOQ_POLLFDS_SIZE(_cpu) ((_cpu)->md.md_unix.ioq_pollfds_size)
-
-#define _PR_IOQ_MIN_POLLFDS_SIZE(_cpu) 32
-
-struct _MDCPU {
- struct _MDCPU_Unix md_unix;
-};
-
-#define _MD_INIT_LOCKS()
-#define _MD_NEW_LOCK(lock) PR_SUCCESS
-#define _MD_FREE_LOCK(lock)
-#define _MD_LOCK(lock)
-#define _MD_UNLOCK(lock)
-#define _MD_INIT_IO()
-#define _MD_IOQ_LOCK()
-#define _MD_IOQ_UNLOCK()
-
-extern PRStatus _MD_InitializeThread(PRThread *thread);
-
-#define _MD_INIT_RUNNING_CPU(cpu) _MD_unix_init_running_cpu(cpu)
-#define _MD_INIT_THREAD _MD_InitializeThread
-#define _MD_EXIT_THREAD(thread)
-#define _MD_SUSPEND_THREAD(thread) _MD_suspend_thread
-#define _MD_RESUME_THREAD(thread) _MD_resume_thread
-#define _MD_CLEAN_THREAD(_thread)
-
-extern PRStatus _MD_CREATE_THREAD(
- PRThread *thread,
- void (*start) (void *),
- PRThreadPriority priority,
- PRThreadScope scope,
- PRThreadState state,
- PRUint32 stackSize);
-extern void _MD_SET_PRIORITY(struct _MDThread *thread, PRUintn newPri);
-extern PRStatus _MD_WAIT(PRThread *, PRIntervalTime timeout);
-extern PRStatus _MD_WAKEUP_WAITER(PRThread *);
-extern void _MD_YIELD(void);
-
-#endif /* ! _PR_PTHREADS */
-
-extern void _MD_EarlyInit(void);
-
-#define _MD_EARLY_INIT _MD_EarlyInit
-#define _MD_FINAL_INIT _PR_UnixInit
-#define _PR_HAVE_CLOCK_MONOTONIC
-
-/*
- * We wrapped the select() call. _MD_SELECT refers to the built-in,
- * unwrapped version.
- */
-#define _MD_SELECT __select
-
-#ifdef _PR_POLL_AVAILABLE
-#include <sys/poll.h>
-extern int __syscall_poll(struct pollfd *ufds, unsigned long int nfds,
- int timeout);
-#define _MD_POLL __syscall_poll
-#endif
-
-/* For writev() */
-#include <sys/uio.h>
-
-extern void _MD_linux_map_sendfile_error(int err);
-
-#endif /* nspr_linux_defs_h___ */
diff --git a/nspr/pr/include/md/_pcos.h b/nspr/pr/include/md/_pcos.h
deleted file mode 100644
index 3b4f205..0000000
--- a/nspr/pr/include/md/_pcos.h
+++ /dev/null
@@ -1,51 +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/. */
-
-#ifndef prpcos_h___
-#define prpcos_h___
-
-#define PR_DLL_SUFFIX ".dll"
-
-#include <stdlib.h>
-
-#define DIRECTORY_SEPARATOR '\\'
-#define DIRECTORY_SEPARATOR_STR "\\"
-#define PATH_SEPARATOR ';'
-
-/*
-** Routines for processing command line arguments
-*/
-PR_BEGIN_EXTERN_C
-#ifndef XP_OS2
-extern char *optarg;
-extern int optind;
-extern int getopt(int argc, char **argv, char *spec);
-#endif
-PR_END_EXTERN_C
-
-
-/*
-** Definitions of directory structures amd functions
-** These definitions are from:
-** <dirent.h>
-*/
-#ifdef XP_OS2
-#include <sys/types.h>
-#endif
-#include <sys/stat.h>
-#include <io.h>
-#include <fcntl.h> /* O_BINARY */
-
-#ifdef OS2
-extern PRStatus _MD_OS2GetHostName(char *name, PRUint32 namelen);
-#define _MD_GETHOSTNAME _MD_OS2GetHostName
-#else
-extern PRStatus _MD_WindowsGetHostName(char *name, PRUint32 namelen);
-#define _MD_GETHOSTNAME _MD_WindowsGetHostName
-extern PRStatus _MD_WindowsGetSysInfo(PRSysInfo cmd, char *name, PRUint32 namelen);
-#define _MD_GETSYSINFO _MD_WindowsGetSysInfo
-#endif
-
-#endif /* prpcos_h___ */
diff --git a/nspr/pr/include/md/_pth.h b/nspr/pr/include/md/_pth.h
deleted file mode 100644
index eeeef04..0000000
--- a/nspr/pr/include/md/_pth.h
+++ /dev/null
@@ -1,270 +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/. */
-
-#ifndef nspr_pth_defs_h_
-#define nspr_pth_defs_h_
-
-/*
-** Appropriate definitions of entry points not used in a pthreads world
-*/
-#define _PR_MD_BLOCK_CLOCK_INTERRUPTS()
-#define _PR_MD_UNBLOCK_CLOCK_INTERRUPTS()
-#define _PR_MD_DISABLE_CLOCK_INTERRUPTS()
-#define _PR_MD_ENABLE_CLOCK_INTERRUPTS()
-
-/* In good standards fashion, the DCE threads (based on posix-4) are not
- * quite the same as newer posix implementations. These are mostly name
- * changes and small differences, so macros usually do the trick
- */
-#ifdef _PR_DCETHREADS
-#define _PT_PTHREAD_MUTEXATTR_INIT pthread_mutexattr_create
-#define _PT_PTHREAD_MUTEXATTR_DESTROY pthread_mutexattr_delete
-#define _PT_PTHREAD_MUTEX_INIT(m, a) pthread_mutex_init(&(m), a)
-#define _PT_PTHREAD_MUTEX_IS_LOCKED(m) (0 == pthread_mutex_trylock(&(m)))
-#define _PT_PTHREAD_CONDATTR_INIT pthread_condattr_create
-#define _PT_PTHREAD_COND_INIT(m, a) pthread_cond_init(&(m), a)
-#define _PT_PTHREAD_CONDATTR_DESTROY pthread_condattr_delete
-
-/* Notes about differences between DCE threads and pthreads 10:
- * 1. pthread_mutex_trylock returns 1 when it locks the mutex
- * 0 when it does not. The latest pthreads has a set of errno-like
- * return values.
- * 2. return values from pthread_cond_timedwait are different.
- *
- *
- *
- */
-#elif defined(BSDI)
-/*
- * Mutex and condition attributes are not supported. The attr
- * argument to pthread_mutex_init() and pthread_cond_init() must
- * be passed as NULL.
- *
- * The memset calls in _PT_PTHREAD_MUTEX_INIT and _PT_PTHREAD_COND_INIT
- * are to work around BSDI's using a single bit to indicate a mutex
- * or condition variable is initialized. This entire BSDI section
- * will go away when BSDI releases updated threads libraries for
- * BSD/OS 3.1 and 4.0.
- */
-#define _PT_PTHREAD_MUTEXATTR_INIT(x) 0
-#define _PT_PTHREAD_MUTEXATTR_DESTROY(x) /* */
-#define _PT_PTHREAD_MUTEX_INIT(m, a) (memset(&(m), 0, sizeof(m)), \
- pthread_mutex_init(&(m), NULL))
-#define _PT_PTHREAD_MUTEX_IS_LOCKED(m) (EBUSY == pthread_mutex_trylock(&(m)))
-#define _PT_PTHREAD_CONDATTR_INIT(x) 0
-#define _PT_PTHREAD_CONDATTR_DESTROY(x) /* */
-#define _PT_PTHREAD_COND_INIT(m, a) (memset(&(m), 0, sizeof(m)), \
- pthread_cond_init(&(m), NULL))
-#else
-#define _PT_PTHREAD_MUTEXATTR_INIT pthread_mutexattr_init
-#define _PT_PTHREAD_MUTEXATTR_DESTROY pthread_mutexattr_destroy
-#define _PT_PTHREAD_MUTEX_INIT(m, a) pthread_mutex_init(&(m), &(a))
-#if defined(FREEBSD)
-#define _PT_PTHREAD_MUTEX_IS_LOCKED(m) pt_pthread_mutex_is_locked(&(m))
-#else
-#define _PT_PTHREAD_MUTEX_IS_LOCKED(m) (EBUSY == pthread_mutex_trylock(&(m)))
-#endif
-#if defined(ANDROID)
-/* Conditional attribute init and destroy aren't implemented in bionic. */
-#define _PT_PTHREAD_CONDATTR_INIT(x) 0
-#define _PT_PTHREAD_CONDATTR_DESTROY(x) /* */
-#else
-#define _PT_PTHREAD_CONDATTR_INIT pthread_condattr_init
-#define _PT_PTHREAD_CONDATTR_DESTROY pthread_condattr_destroy
-#endif
-#define _PT_PTHREAD_COND_INIT(m, a) pthread_cond_init(&(m), &(a))
-#endif
-
-/* The pthreads standard does not specify an invalid value for the
- * pthread_t handle. (0 is usually an invalid pthread identifier
- * but there are exceptions, for example, DG/UX.) These macros
- * define a way to set the handle to or compare the handle with an
- * invalid identifier. These macros are not portable and may be
- * more of a problem as we adapt to more pthreads implementations.
- * They are only used in the PRMonitor functions. Do not use them
- * in new code.
- *
- * Unfortunately some of our clients depend on certain properties
- * of our PRMonitor implementation, preventing us from replacing
- * it by a portable implementation.
- * - High-performance servers like the fact that PR_EnterMonitor
- * only calls PR_Lock and PR_ExitMonitor only calls PR_Unlock.
- * (A portable implementation would use a PRLock and a PRCondVar
- * to implement the recursive lock in a monitor and call both
- * PR_Lock and PR_Unlock in PR_EnterMonitor and PR_ExitMonitor.)
- * Unfortunately this forces us to read the monitor owner field
- * without holding a lock.
- * - One way to make it safe to read the monitor owner field
- * without holding a lock is to make that field a PRThread*
- * (one should be able to read a pointer with a single machine
- * instruction). However, PR_GetCurrentThread calls calloc if
- * it is called by a thread that was not created by NSPR. The
- * malloc tracing tools in the Mozilla client use PRMonitor for
- * locking in their malloc, calloc, and free functions. If
- * PR_EnterMonitor calls any of these functions, infinite
- * recursion ensues.
- */
-#if defined(_PR_DCETHREADS)
-#define _PT_PTHREAD_INVALIDATE_THR_HANDLE(t) \
- memset(&(t), 0, sizeof(pthread_t))
-#define _PT_PTHREAD_THR_HANDLE_IS_INVALID(t) \
- (!memcmp(&(t), &pt_zero_tid, sizeof(pthread_t)))
-#define _PT_PTHREAD_COPY_THR_HANDLE(st, dt) (dt) = (st)
-#elif defined(IRIX) || defined(OSF1) || defined(AIX) || defined(SOLARIS) \
- || defined(LINUX) || defined(__GNU__) || defined(__GLIBC__) \
- || defined(HPUX) || defined(FREEBSD) \
- || defined(NETBSD) || defined(OPENBSD) || defined(BSDI) \
- || defined(NTO) || defined(DARWIN) \
- || defined(UNIXWARE) || defined(RISCOS) || defined(SYMBIAN)
-#define _PT_PTHREAD_INVALIDATE_THR_HANDLE(t) (t) = 0
-#define _PT_PTHREAD_THR_HANDLE_IS_INVALID(t) (t) == 0
-#define _PT_PTHREAD_COPY_THR_HANDLE(st, dt) (dt) = (st)
-#else
-#error "pthreads is not supported for this architecture"
-#endif
-
-#if defined(_PR_DCETHREADS)
-#define _PT_PTHREAD_ATTR_INIT pthread_attr_create
-#define _PT_PTHREAD_ATTR_DESTROY pthread_attr_delete
-#define _PT_PTHREAD_CREATE(t, a, f, r) pthread_create(t, a, f, r)
-#define _PT_PTHREAD_KEY_CREATE pthread_keycreate
-#define _PT_PTHREAD_ATTR_SETSCHEDPOLICY pthread_attr_setsched
-#define _PT_PTHREAD_ATTR_GETSTACKSIZE(a, s) \
- (*(s) = pthread_attr_getstacksize(*(a)), 0)
-#define _PT_PTHREAD_GETSPECIFIC(k, r) \
- pthread_getspecific((k), (pthread_addr_t *) &(r))
-#elif defined(_PR_PTHREADS)
-#define _PT_PTHREAD_ATTR_INIT pthread_attr_init
-#define _PT_PTHREAD_ATTR_DESTROY pthread_attr_destroy
-#define _PT_PTHREAD_CREATE(t, a, f, r) pthread_create(t, &a, f, r)
-#define _PT_PTHREAD_KEY_CREATE pthread_key_create
-#define _PT_PTHREAD_ATTR_SETSCHEDPOLICY pthread_attr_setschedpolicy
-#define _PT_PTHREAD_ATTR_GETSTACKSIZE(a, s) pthread_attr_getstacksize(a, s)
-#define _PT_PTHREAD_GETSPECIFIC(k, r) (r) = pthread_getspecific(k)
-#else
-#error "Cannot determine pthread strategy"
-#endif
-
-#if defined(_PR_DCETHREADS)
-#define _PT_PTHREAD_EXPLICIT_SCHED _PT_PTHREAD_DEFAULT_SCHED
-#endif
-
-/*
- * pthread_mutex_trylock returns different values in DCE threads and
- * pthreads.
- */
-#if defined(_PR_DCETHREADS)
-#define PT_TRYLOCK_SUCCESS 1
-#define PT_TRYLOCK_BUSY 0
-#else
-#define PT_TRYLOCK_SUCCESS 0
-#define PT_TRYLOCK_BUSY EBUSY
-#endif
-
-/*
- * These platforms don't have sigtimedwait()
- */
-#if (defined(AIX) && !defined(AIX4_3_PLUS)) \
- || defined(LINUX) || defined(__GNU__)|| defined(__GLIBC__) \
- || defined(FREEBSD) || defined(NETBSD) || defined(OPENBSD) \
- || defined(BSDI) || defined(UNIXWARE) \
- || defined(DARWIN) || defined(SYMBIAN)
-#define PT_NO_SIGTIMEDWAIT
-#endif
-
-#if defined(OSF1)
-#define PT_PRIO_MIN PRI_OTHER_MIN
-#define PT_PRIO_MAX PRI_OTHER_MAX
-#elif defined(IRIX)
-#include <sys/sched.h>
-#define PT_PRIO_MIN PX_PRIO_MIN
-#define PT_PRIO_MAX PX_PRIO_MAX
-#elif defined(AIX)
-#include <sys/priv.h>
-#include <sys/sched.h>
-#ifndef PTHREAD_CREATE_JOINABLE
-#define PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED
-#endif
-#define PT_PRIO_MIN DEFAULT_PRIO
-#define PT_PRIO_MAX DEFAULT_PRIO
-#elif defined(HPUX)
-
-#if defined(_PR_DCETHREADS)
-#define PT_PRIO_MIN PRI_OTHER_MIN
-#define PT_PRIO_MAX PRI_OTHER_MAX
-#else /* defined(_PR_DCETHREADS) */
-#include <sys/sched.h>
-#define PT_PRIO_MIN sched_get_priority_min(SCHED_OTHER)
-#define PT_PRIO_MAX sched_get_priority_max(SCHED_OTHER)
-#endif /* defined(_PR_DCETHREADS) */
-
-#elif defined(LINUX) || defined(__GNU__) || defined(__GLIBC__) \
- || defined(FREEBSD) || defined(SYMBIAN)
-#define PT_PRIO_MIN sched_get_priority_min(SCHED_OTHER)
-#define PT_PRIO_MAX sched_get_priority_max(SCHED_OTHER)
-#elif defined(NTO)
-/*
- * Neutrino has functions that return the priority range but
- * they return invalid numbers, so I just hard coded these here
- * for now. [email protected]
- */
-#define PT_PRIO_MIN 0
-#define PT_PRIO_MAX 30
-#elif defined(SOLARIS)
-/*
- * Solaris doesn't seem to have macros for the min/max priorities.
- * The range of 0-127 is mentioned in the pthread_setschedparam(3T)
- * man pages, and pthread_setschedparam indeed allows 0-127. However,
- * pthread_attr_setschedparam does not allow 0; it allows 1-127.
- */
-#define PT_PRIO_MIN 1
-#define PT_PRIO_MAX 127
-#elif defined(OPENBSD)
-#define PT_PRIO_MIN 0
-#define PT_PRIO_MAX 31
-#elif defined(NETBSD) \
- || defined(BSDI) || defined(DARWIN) || defined(UNIXWARE) \
- || defined(RISCOS) /* XXX */
-#define PT_PRIO_MIN 0
-#define PT_PRIO_MAX 126
-#else
-#error "pthreads is not supported for this architecture"
-#endif
-
-/*
- * The _PT_PTHREAD_YIELD function is called from a signal handler.
- * Needed for garbage collection -- Look at PR_Suspend/PR_Resume
- * implementation.
- */
-#if defined(_PR_DCETHREADS)
-#define _PT_PTHREAD_YIELD() pthread_yield()
-#elif defined(OSF1)
-/*
- * sched_yield can't be called from a signal handler. Must use
- * the _np version.
- */
-#define _PT_PTHREAD_YIELD() pthread_yield_np()
-#elif defined(AIX)
-extern int (*_PT_aix_yield_fcn)();
-#define _PT_PTHREAD_YIELD() (*_PT_aix_yield_fcn)()
-#elif defined(IRIX)
-#include <time.h>
-#define _PT_PTHREAD_YIELD() \
- PR_BEGIN_MACRO \
- struct timespec onemillisec = {0}; \
- onemillisec.tv_nsec = 1000000L; \
- nanosleep(&onemillisec,NULL); \
- PR_END_MACRO
-#elif defined(HPUX) || defined(SOLARIS) \
- || defined(LINUX) || defined(__GNU__) || defined(__GLIBC__) \
- || defined(FREEBSD) || defined(NETBSD) || defined(OPENBSD) \
- || defined(BSDI) || defined(NTO) || defined(DARWIN) \
- || defined(UNIXWARE) || defined(RISCOS) || defined(SYMBIAN)
-#define _PT_PTHREAD_YIELD() sched_yield()
-#else
-#error "Need to define _PT_PTHREAD_YIELD for this platform"
-#endif
-
-#endif /* nspr_pth_defs_h_ */
diff --git a/nspr/pr/include/md/_unix_errors.h b/nspr/pr/include/md/_unix_errors.h
deleted file mode 100644
index 96d72db..0000000
--- a/nspr/pr/include/md/_unix_errors.h
+++ /dev/null
@@ -1,139 +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/. */
-
-#ifndef prunixerrors_h___
-#define prunixerrors_h___
-
-#include <unistd.h>
-#include <stddef.h>
-
-PR_BEGIN_EXTERN_C
-
-extern void _MD_unix_map_default_error(int err);
-#define _PR_MD_MAP_DEFAULT_ERROR _MD_unix_map_default_error
-
-extern void _MD_unix_map_opendir_error(int err);
-#define _PR_MD_MAP_OPENDIR_ERROR _MD_unix_map_opendir_error
-
-extern void _MD_unix_map_closedir_error(int err);
-#define _PR_MD_MAP_CLOSEDIR_ERROR _MD_unix_map_closedir_error
-
-extern void _MD_unix_readdir_error(int err);
-#define _PR_MD_MAP_READDIR_ERROR _MD_unix_readdir_error
-
-extern void _MD_unix_map_unlink_error(int err);
-#define _PR_MD_MAP_UNLINK_ERROR _MD_unix_map_unlink_error
-
-extern void _MD_unix_map_stat_error(int err);
-#define _PR_MD_MAP_STAT_ERROR _MD_unix_map_stat_error
-
-extern void _MD_unix_map_fstat_error(int err);
-#define _PR_MD_MAP_FSTAT_ERROR _MD_unix_map_fstat_error
-
-extern void _MD_unix_map_rename_error(int err);
-#define _PR_MD_MAP_RENAME_ERROR _MD_unix_map_rename_error
-
-extern void _MD_unix_map_access_error(int err);
-#define _PR_MD_MAP_ACCESS_ERROR _MD_unix_map_access_error
-
-extern void _MD_unix_map_mkdir_error(int err);
-#define _PR_MD_MAP_MKDIR_ERROR _MD_unix_map_mkdir_error
-
-extern void _MD_unix_map_rmdir_error(int err);
-#define _PR_MD_MAP_RMDIR_ERROR _MD_unix_map_rmdir_error
-
-extern void _MD_unix_map_read_error(int err);
-#define _PR_MD_MAP_READ_ERROR _MD_unix_map_read_error
-
-extern void _MD_unix_map_write_error(int err);
-#define _PR_MD_MAP_WRITE_ERROR _MD_unix_map_write_error
-
-extern void _MD_unix_map_lseek_error(int err);
-#define _PR_MD_MAP_LSEEK_ERROR _MD_unix_map_lseek_error
-
-extern void _MD_unix_map_fsync_error(int err);
-#define _PR_MD_MAP_FSYNC_ERROR _MD_unix_map_fsync_error
-
-extern void _MD_unix_map_close_error(int err);
-#define _PR_MD_MAP_CLOSE_ERROR _MD_unix_map_close_error
-
-extern void _MD_unix_map_socket_error(int err);
-#define _PR_MD_MAP_SOCKET_ERROR _MD_unix_map_socket_error
-
-extern void _MD_unix_map_socketavailable_error(int err);
-#define _PR_MD_MAP_SOCKETAVAILABLE_ERROR _MD_unix_map_socketavailable_error
-
-extern void _MD_unix_map_recv_error(int err);
-#define _PR_MD_MAP_RECV_ERROR _MD_unix_map_recv_error
-
-extern void _MD_unix_map_recvfrom_error(int err);
-#define _PR_MD_MAP_RECVFROM_ERROR _MD_unix_map_recvfrom_error
-
-extern void _MD_unix_map_send_error(int err);
-#define _PR_MD_MAP_SEND_ERROR _MD_unix_map_send_error
-
-extern void _MD_unix_map_sendto_error(int err);
-#define _PR_MD_MAP_SENDTO_ERROR _MD_unix_map_sendto_error
-
-extern void _MD_unix_map_writev_error(int err);
-#define _PR_MD_MAP_WRITEV_ERROR _MD_unix_map_writev_error
-
-extern void _MD_unix_map_accept_error(int err);
-#define _PR_MD_MAP_ACCEPT_ERROR _MD_unix_map_accept_error
-
-extern void _MD_unix_map_connect_error(int err);
-#define _PR_MD_MAP_CONNECT_ERROR _MD_unix_map_connect_error
-
-extern void _MD_unix_map_bind_error(int err);
-#define _PR_MD_MAP_BIND_ERROR _MD_unix_map_bind_error
-
-extern void _MD_unix_map_listen_error(int err);
-#define _PR_MD_MAP_LISTEN_ERROR _MD_unix_map_listen_error
-
-extern void _MD_unix_map_shutdown_error(int err);
-#define _PR_MD_MAP_SHUTDOWN_ERROR _MD_unix_map_shutdown_error
-
-extern void _MD_unix_map_socketpair_error(int err);
-#define _PR_MD_MAP_SOCKETPAIR_ERROR _MD_unix_map_socketpair_error
-
-extern void _MD_unix_map_getsockname_error(int err);
-#define _PR_MD_MAP_GETSOCKNAME_ERROR _MD_unix_map_getsockname_error
-
-extern void _MD_unix_map_getpeername_error(int err);
-#define _PR_MD_MAP_GETPEERNAME_ERROR _MD_unix_map_getpeername_error
-
-extern void _MD_unix_map_getsockopt_error(int err);
-#define _PR_MD_MAP_GETSOCKOPT_ERROR _MD_unix_map_getsockopt_error
-
-extern void _MD_unix_map_setsockopt_error(int err);
-#define _PR_MD_MAP_SETSOCKOPT_ERROR _MD_unix_map_setsockopt_error
-
-extern void _MD_unix_map_open_error(int err);
-#define _PR_MD_MAP_OPEN_ERROR _MD_unix_map_open_error
-
-extern void _MD_unix_map_mmap_error(int err);
-#define _PR_MD_MAP_MMAP_ERROR _MD_unix_map_mmap_error
-
-extern void _MD_unix_map_gethostname_error(int err);
-#define _PR_MD_MAP_GETHOSTNAME_ERROR _MD_unix_map_gethostname_error
-
-extern void _MD_unix_map_select_error(int err);
-#define _PR_MD_MAP_SELECT_ERROR _MD_unix_map_select_error
-
-extern void _MD_unix_map_poll_error(int err);
-#define _PR_MD_MAP_POLL_ERROR _MD_unix_map_poll_error
-
-extern void _MD_unix_map_poll_revents_error(int err);
-#define _PR_MD_MAP_POLL_REVENTS_ERROR _MD_unix_map_poll_revents_error
-
-extern void _MD_unix_map_flock_error(int err);
-#define _PR_MD_MAP_FLOCK_ERROR _MD_unix_map_flock_error
-
-extern void _MD_unix_map_lockf_error(int err);
-#define _PR_MD_MAP_LOCKF_ERROR _MD_unix_map_lockf_error
-
-PR_END_EXTERN_C
-
-#endif /* prunixerrors_h___ */
diff --git a/nspr/pr/include/md/_unixos.h b/nspr/pr/include/md/_unixos.h
deleted file mode 100644
index ea46b3a..0000000
--- a/nspr/pr/include/md/_unixos.h
+++ /dev/null
@@ -1,624 +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/. */
-
-#ifndef prunixos_h___
-#define prunixos_h___
-
-/*
- * If FD_SETSIZE is not defined on the command line, set the default value
- * before include select.h
- */
-/*
- * Linux: FD_SETSIZE is defined in /usr/include/sys/select.h and should
- * not be redefined.
- */
-#if !defined(LINUX) && !defined(__GNU__) && !defined(__GLIBC__) \
- && !defined(DARWIN)
-#ifndef FD_SETSIZE
-#define FD_SETSIZE 4096
-#endif
-#endif
-
-#include <unistd.h>
-#include <stddef.h>
-#include <sys/stat.h>
-#include <dirent.h>
-#include <errno.h>
-
-#include "prio.h"
-#include "prmem.h"
-#include "prclist.h"
-
-/*
- * For select(), fd_set, and struct timeval.
- *
- * In The Single UNIX(R) Specification, Version 2,
- * the header file for select() is <sys/time.h>.
- * In Version 3, the header file for select() is
- * changed to <sys/select.h>.
- *
- * fd_set is defined in <sys/types.h>. Usually
- * <sys/time.h> includes <sys/types.h>, but on some
- * older systems <sys/time.h> does not include
- * <sys/types.h>, so we include it explicitly.
- */
-#include <sys/time.h>
-#include <sys/types.h>
-#if defined(AIX) || defined(SYMBIAN)
-#include <sys/select.h>
-#endif
-
-#ifndef SYMBIAN
-#define HAVE_NETINET_TCP_H
-#endif
-
-#define _PR_HAVE_O_APPEND
-
-#define PR_DIRECTORY_SEPARATOR '/'
-#define PR_DIRECTORY_SEPARATOR_STR "/"
-#define PR_PATH_SEPARATOR ':'
-#define PR_PATH_SEPARATOR_STR ":"
-typedef int (*FARPROC)();
-
-/*
- * intervals at which GLOBAL threads wakeup to check for pending interrupt
- */
-#define _PR_INTERRUPT_CHECK_INTERVAL_SECS 5
-extern PRIntervalTime intr_timeout_ticks;
-
-/*
- * The bit flags for the in_flags and out_flags fields
- * of _PR_UnixPollDesc
- */
-#ifdef _PR_USE_POLL
-#define _PR_UNIX_POLL_READ POLLIN
-#define _PR_UNIX_POLL_WRITE POLLOUT
-#define _PR_UNIX_POLL_EXCEPT POLLPRI
-#define _PR_UNIX_POLL_ERR POLLERR
-#define _PR_UNIX_POLL_NVAL POLLNVAL
-#define _PR_UNIX_POLL_HUP POLLHUP
-#else /* _PR_USE_POLL */
-#define _PR_UNIX_POLL_READ 0x1
-#define _PR_UNIX_POLL_WRITE 0x2
-#define _PR_UNIX_POLL_EXCEPT 0x4
-#define _PR_UNIX_POLL_ERR 0x8
-#define _PR_UNIX_POLL_NVAL 0x10
-#define _PR_UNIX_POLL_HUP 0x20
-#endif /* _PR_USE_POLL */
-
-typedef struct _PRUnixPollDesc {
- PRInt32 osfd;
- PRInt16 in_flags;
- PRInt16 out_flags;
-} _PRUnixPollDesc;
-
-typedef struct PRPollQueue {
- PRCList links; /* for linking PRPollQueue's together */
- _PRUnixPollDesc *pds; /* array of poll descriptors */
- PRUintn npds; /* length of the array */
- PRPackedBool on_ioq; /* is this on the async i/o work q? */
- PRIntervalTime timeout; /* timeout, in ticks */
- struct PRThread *thr;
-} PRPollQueue;
-
-#define _PR_POLLQUEUE_PTR(_qp) \
- ((PRPollQueue*) ((char*) (_qp) - offsetof(PRPollQueue,links)))
-
-
-extern PRInt32 _PR_WaitForMultipleFDs(
- _PRUnixPollDesc *unixpds,
- PRInt32 pdcnt,
- PRIntervalTime timeout);
-extern void _PR_Unblock_IO_Wait(struct PRThread *thr);
-
-#if defined(_PR_LOCAL_THREADS_ONLY) || defined(_PR_GLOBAL_THREADS_ONLY)
-#define _MD_CHECK_FOR_EXIT()
-#endif
-
-extern fd_set _pr_md_read_set, _pr_md_write_set, _pr_md_exception_set;
-extern PRInt16 _pr_md_read_cnt[], _pr_md_write_cnt[], _pr_md_exception_cnt[];
-extern PRInt32 _pr_md_ioq_max_osfd;
-extern PRUint32 _pr_md_ioq_timeout;
-
-struct _MDFileDesc {
- int osfd;
-#if defined(LINUX) && defined(_PR_PTHREADS)
- int tcp_nodelay; /* used by pt_LinuxSendFile */
-#endif
-};
-
-struct _MDDir {
- DIR *d;
-};
-
-struct _PRCPU;
-extern void _MD_unix_init_running_cpu(struct _PRCPU *cpu);
-
-/*
-** Make a redzone at both ends of the stack segment. Disallow access
-** to those pages of memory. It's ok if the mprotect call's don't
-** work - it just means that we don't really have a functional
-** redzone.
-*/
-#include <sys/mman.h>
-#ifndef PROT_NONE
-#define PROT_NONE 0x0
-#endif
-
-#if defined(DEBUG) && !defined(DARWIN)
-#if !defined(SOLARIS)
-#include <string.h> /* for memset() */
-#define _MD_INIT_STACK(ts,REDZONE) \
- PR_BEGIN_MACRO \
- (void) mprotect((void*)ts->seg->vaddr, REDZONE, PROT_NONE); \
- (void) mprotect((void*) ((char*)ts->seg->vaddr + REDZONE + ts->stackSize),\
- REDZONE, PROT_NONE); \
- /* \
- ** Fill stack memory with something that turns into an illegal \
- ** pointer value. This will sometimes find runtime references to \
- ** uninitialized pointers. We don't do this for solaris because we \
- ** can use purify instead. \
- */ \
- if (_pr_debugStacks) { \
- memset(ts->allocBase + REDZONE, 0xf7, ts->stackSize); \
- } \
- PR_END_MACRO
-#else /* !SOLARIS */
-#define _MD_INIT_STACK(ts,REDZONE) \
- PR_BEGIN_MACRO \
- (void) mprotect((void*)ts->seg->vaddr, REDZONE, PROT_NONE); \
- (void) mprotect((void*) ((char*)ts->seg->vaddr + REDZONE + ts->stackSize),\
- REDZONE, PROT_NONE); \
- PR_END_MACRO
-#endif /* !SOLARIS */
-
-/*
- * _MD_CLEAR_STACK
- * Allow access to the redzone pages; the access was turned off in
- * _MD_INIT_STACK.
- */
-#define _MD_CLEAR_STACK(ts) \
- PR_BEGIN_MACRO \
- (void) mprotect((void*)ts->seg->vaddr, REDZONE, PROT_READ|PROT_WRITE);\
- (void) mprotect((void*) ((char*)ts->seg->vaddr + REDZONE + ts->stackSize),\
- REDZONE, PROT_READ|PROT_WRITE); \
- PR_END_MACRO
-
-#else /* DEBUG */
-
-#define _MD_INIT_STACK(ts,REDZONE)
-#define _MD_CLEAR_STACK(ts)
-
-#endif /* DEBUG */
-
-#if !defined(SOLARIS)
-
-#define PR_SET_INTSOFF(newval)
-
-#endif
-
-/************************************************************************/
-
-extern void _PR_UnixInit(void);
-
-extern void _PR_UnixCleanup(void);
-#define _MD_EARLY_CLEANUP _PR_UnixCleanup
-
-/************************************************************************/
-
-struct _MDProcess {
- pid_t pid;
-};
-
-struct PRProcess;
-struct PRProcessAttr;
-
-/* Create a new process (fork() + exec()) */
-#define _MD_CREATE_PROCESS _MD_CreateUnixProcess
-extern struct PRProcess * _MD_CreateUnixProcess(
- const char *path,
- char *const *argv,
- char *const *envp,
- const struct PRProcessAttr *attr
-);
-
-#define _MD_DETACH_PROCESS _MD_DetachUnixProcess
-extern PRStatus _MD_DetachUnixProcess(struct PRProcess *process);
-
-/* Wait for a child process to terminate */
-#define _MD_WAIT_PROCESS _MD_WaitUnixProcess
-extern PRStatus _MD_WaitUnixProcess(struct PRProcess *process,
- PRInt32 *exitCode);
-
-#define _MD_KILL_PROCESS _MD_KillUnixProcess
-extern PRStatus _MD_KillUnixProcess(struct PRProcess *process);
-
-/************************************************************************/
-
-extern void _MD_EnableClockInterrupts(void);
-extern void _MD_DisableClockInterrupts(void);
-
-#define _MD_START_INTERRUPTS _MD_StartInterrupts
-#define _MD_STOP_INTERRUPTS _MD_StopInterrupts
-#define _MD_DISABLE_CLOCK_INTERRUPTS _MD_DisableClockInterrupts
-#define _MD_ENABLE_CLOCK_INTERRUPTS _MD_EnableClockInterrupts
-#define _MD_BLOCK_CLOCK_INTERRUPTS _MD_BlockClockInterrupts
-#define _MD_UNBLOCK_CLOCK_INTERRUPTS _MD_UnblockClockInterrupts
-
-/************************************************************************/
-
-extern void _MD_InitCPUS(void);
-#define _MD_INIT_CPUS _MD_InitCPUS
-
-extern void _MD_Wakeup_CPUs(void);
-#define _MD_WAKEUP_CPUS _MD_Wakeup_CPUs
-
-#define _MD_PAUSE_CPU _MD_PauseCPU
-
-#if defined(_PR_LOCAL_THREADS_ONLY) || defined(_PR_GLOBAL_THREADS_ONLY)
-#define _MD_CLEANUP_BEFORE_EXIT()
-#endif
-
-#ifndef IRIX
-#define _MD_EXIT(status) _exit(status)
-#endif
-
-/************************************************************************/
-
-#define _MD_GET_ENV getenv
-#define _MD_PUT_ENV putenv
-
-/************************************************************************/
-
-#define _MD_INIT_FILEDESC(fd)
-
-extern void _MD_MakeNonblock(PRFileDesc *fd);
-#define _MD_MAKE_NONBLOCK _MD_MakeNonblock
-
-/************************************************************************/
-
-#if !defined(_PR_PTHREADS)
-
-extern void _MD_InitSegs(void);
-extern PRStatus _MD_AllocSegment(PRSegment *seg, PRUint32 size,
- void *vaddr);
-extern void _MD_FreeSegment(PRSegment *seg);
-
-#define _MD_INIT_SEGS _MD_InitSegs
-#define _MD_ALLOC_SEGMENT _MD_AllocSegment
-#define _MD_FREE_SEGMENT _MD_FreeSegment
-
-#endif /* !defined(_PR_PTHREADS) */
-
-/************************************************************************/
-
-#ifdef _MD_INTERVAL_USE_GTOD
-extern PRIntervalTime _PR_UNIX_GetInterval(void);
-extern PRIntervalTime _PR_UNIX_TicksPerSecond(void);
-#define _MD_INTERVAL_INIT()
-#define _MD_GET_INTERVAL _PR_UNIX_GetInterval
-#define _MD_INTERVAL_PER_SEC _PR_UNIX_TicksPerSecond
-#endif
-
-#ifdef _PR_HAVE_CLOCK_MONOTONIC
-extern PRIntervalTime _PR_UNIX_GetInterval2(void);
-extern PRIntervalTime _PR_UNIX_TicksPerSecond2(void);
-#define _MD_INTERVAL_INIT()
-#define _MD_GET_INTERVAL _PR_UNIX_GetInterval2
-#define _MD_INTERVAL_PER_SEC _PR_UNIX_TicksPerSecond2
-#endif
-
-#define _MD_INTERVAL_PER_MILLISEC() (_PR_MD_INTERVAL_PER_SEC() / 1000)
-#define _MD_INTERVAL_PER_MICROSEC() (_PR_MD_INTERVAL_PER_SEC() / 1000000)
-
-/************************************************************************/
-
-#define _MD_ERRNO() (errno)
-#define _MD_GET_SOCKET_ERROR() (errno)
-
-/************************************************************************/
-
-extern PRInt32 _MD_AvailableSocket(PRInt32 osfd);
-
-extern void _MD_StartInterrupts(void);
-extern void _MD_StopInterrupts(void);
-extern void _MD_DisableClockInterrupts(void);
-extern void _MD_BlockClockInterrupts(void);
-extern void _MD_UnblockClockInterrupts(void);
-extern void _MD_PauseCPU(PRIntervalTime timeout);
-
-extern PRStatus _MD_open_dir(struct _MDDir *, const char *);
-extern PRInt32 _MD_close_dir(struct _MDDir *);
-extern char * _MD_read_dir(struct _MDDir *, PRIntn);
-extern PRInt32 _MD_open(const char *name, PRIntn osflags, PRIntn mode);
-extern PRInt32 _MD_delete(const char *name);
-extern PRInt32 _MD_getfileinfo(const char *fn, PRFileInfo *info);
-extern PRInt32 _MD_getfileinfo64(const char *fn, PRFileInfo64 *info);
-extern PRInt32 _MD_getopenfileinfo(const PRFileDesc *fd, PRFileInfo *info);
-extern PRInt32 _MD_getopenfileinfo64(const PRFileDesc *fd, PRFileInfo64 *info);
-extern PRInt32 _MD_rename(const char *from, const char *to);
-extern PRInt32 _MD_access(const char *name, PRAccessHow how);
-extern PRInt32 _MD_mkdir(const char *name, PRIntn mode);
-extern PRInt32 _MD_rmdir(const char *name);
-extern PRInt32 _MD_accept_read(PRInt32 sock, PRInt32 *newSock,
- PRNetAddr **raddr, void *buf, PRInt32 amount);
-extern PRInt32 _PR_UnixSendFile(PRFileDesc *sd, PRSendFileData *sfd,
- PRTransmitFileFlags flags, PRIntervalTime timeout);
-
-extern PRStatus _MD_LockFile(PRInt32 osfd);
-extern PRStatus _MD_TLockFile(PRInt32 osfd);
-extern PRStatus _MD_UnlockFile(PRInt32 osfd);
-
-#define _MD_OPEN_DIR(dir, name) _MD_open_dir(dir, name)
-#define _MD_CLOSE_DIR(dir) _MD_close_dir(dir)
-#define _MD_READ_DIR(dir, flags) _MD_read_dir(dir, flags)
-#define _MD_OPEN(name, osflags, mode) _MD_open(name, osflags, mode)
-#define _MD_OPEN_FILE(name, osflags, mode) _MD_open(name, osflags, mode)
-extern PRInt32 _MD_read(PRFileDesc *fd, void *buf, PRInt32 amount);
-#define _MD_READ(fd,buf,amount) _MD_read(fd,buf,amount)
-extern PRInt32 _MD_write(PRFileDesc *fd, const void *buf, PRInt32 amount);
-#define _MD_WRITE(fd,buf,amount) _MD_write(fd,buf,amount)
-#define _MD_DELETE(name) _MD_delete(name)
-#define _MD_GETFILEINFO(fn, info) _MD_getfileinfo(fn, info)
-#define _MD_GETFILEINFO64(fn, info) _MD_getfileinfo64(fn, info)
-#define _MD_GETOPENFILEINFO(fd, info) _MD_getopenfileinfo(fd, info)
-#define _MD_GETOPENFILEINFO64(fd, info) _MD_getopenfileinfo64(fd, info)
-#define _MD_RENAME(from, to) _MD_rename(from, to)
-#define _MD_ACCESS(name, how) _MD_access(name, how)
-#define _MD_MKDIR(name, mode) _MD_mkdir(name, mode)
-#define _MD_MAKE_DIR(name, mode) _MD_mkdir(name, mode)
-#define _MD_RMDIR(name) _MD_rmdir(name)
-#define _MD_ACCEPT_READ(sock, newSock, raddr, buf, amount) _MD_accept_read(sock, newSock, raddr, buf, amount)
-
-#define _MD_LOCKFILE _MD_LockFile
-#define _MD_TLOCKFILE _MD_TLockFile
-#define _MD_UNLOCKFILE _MD_UnlockFile
-
-
-extern PRInt32 _MD_socket(int af, int type, int flags);
-#define _MD_SOCKET _MD_socket
-extern PRInt32 _MD_connect(PRFileDesc *fd, const PRNetAddr *addr,
- PRUint32 addrlen, PRIntervalTime timeout);
-#define _MD_CONNECT _MD_connect
-extern PRInt32 _MD_accept(PRFileDesc *fd, PRNetAddr *addr, PRUint32 *addrlen,
- PRIntervalTime timeout);
-#define _MD_ACCEPT _MD_accept
-extern PRInt32 _MD_bind(PRFileDesc *fd, const PRNetAddr *addr, PRUint32 addrlen);
-#define _MD_BIND _MD_bind
-extern PRInt32 _MD_listen(PRFileDesc *fd, PRIntn backlog);
-#define _MD_LISTEN _MD_listen
-extern PRInt32 _MD_shutdown(PRFileDesc *fd, PRIntn how);
-#define _MD_SHUTDOWN _MD_shutdown
-
-extern PRInt32 _MD_recv(PRFileDesc *fd, void *buf, PRInt32 amount,
- PRIntn flags, PRIntervalTime timeout);
-#define _MD_RECV _MD_recv
-extern PRInt32 _MD_send(PRFileDesc *fd, const void *buf, PRInt32 amount,
- PRIntn flags, PRIntervalTime timeout);
-#define _MD_SEND _MD_send
-extern PRInt32 _MD_recvfrom(PRFileDesc *fd, void *buf, PRInt32 amount,
- PRIntn flags, PRNetAddr *addr, PRUint32 *addrlen,
- PRIntervalTime timeout);
-#define _MD_RECVFROM _MD_recvfrom
-extern PRInt32 _MD_sendto(PRFileDesc *fd, const void *buf, PRInt32 amount,
- PRIntn flags, const PRNetAddr *addr, PRUint32 addrlen,
- PRIntervalTime timeout);
-#define _MD_SENDTO _MD_sendto
-extern PRInt32 _MD_writev(PRFileDesc *fd, const struct PRIOVec *iov,
- PRInt32 iov_size, PRIntervalTime timeout);
-#define _MD_WRITEV _MD_writev
-
-extern PRInt32 _MD_socketavailable(PRFileDesc *fd);
-#define _MD_SOCKETAVAILABLE _MD_socketavailable
-extern PRInt64 _MD_socketavailable64(PRFileDesc *fd);
-#define _MD_SOCKETAVAILABLE64 _MD_socketavailable64
-
-#define _MD_PIPEAVAILABLE _MD_socketavailable
-
-extern PRInt32 _MD_pr_poll(PRPollDesc *pds, PRIntn npds,
- PRIntervalTime timeout);
-#define _MD_PR_POLL _MD_pr_poll
-
-extern PRInt32 _MD_close(PRInt32 osfd);
-#define _MD_CLOSE_FILE _MD_close
-extern PRInt32 _MD_lseek(PRFileDesc*, PRInt32, PRSeekWhence);
-#define _MD_LSEEK _MD_lseek
-extern PRInt64 _MD_lseek64(PRFileDesc*, PRInt64, PRSeekWhence);
-#define _MD_LSEEK64 _MD_lseek64
-extern PRInt32 _MD_fsync(PRFileDesc *fd);
-#define _MD_FSYNC _MD_fsync
-
-extern PRInt32 _MD_socketpair(int af, int type, int flags, PRInt32 *osfd);
-#define _MD_SOCKETPAIR _MD_socketpair
-
-#define _MD_CLOSE_SOCKET _MD_close
-
-#ifndef NO_NSPR_10_SUPPORT
-#define _MD_STAT stat
-#endif
-
-extern PRStatus _MD_getpeername(PRFileDesc *fd, PRNetAddr *addr,
- PRUint32 *addrlen);
-#define _MD_GETPEERNAME _MD_getpeername
-extern PRStatus _MD_getsockname(PRFileDesc *fd, PRNetAddr *addr,
- PRUint32 *addrlen);
-#define _MD_GETSOCKNAME _MD_getsockname
-
-extern PRStatus _MD_getsockopt(PRFileDesc *fd, PRInt32 level,
- PRInt32 optname, char* optval, PRInt32* optlen);
-#define _MD_GETSOCKOPT _MD_getsockopt
-extern PRStatus _MD_setsockopt(PRFileDesc *fd, PRInt32 level,
- PRInt32 optname, const char* optval, PRInt32 optlen);
-#define _MD_SETSOCKOPT _MD_setsockopt
-
-extern PRStatus _MD_set_fd_inheritable(PRFileDesc *fd, PRBool inheritable);
-#define _MD_SET_FD_INHERITABLE _MD_set_fd_inheritable
-
-extern void _MD_init_fd_inheritable(PRFileDesc *fd, PRBool imported);
-#define _MD_INIT_FD_INHERITABLE _MD_init_fd_inheritable
-
-extern void _MD_query_fd_inheritable(PRFileDesc *fd);
-#define _MD_QUERY_FD_INHERITABLE _MD_query_fd_inheritable
-
-extern PRStatus _MD_gethostname(char *name, PRUint32 namelen);
-#define _MD_GETHOSTNAME _MD_gethostname
-
-extern PRStatus _MD_getsysinfo(PRSysInfo cmd, char *name, PRUint32 namelen);
-#define _MD_GETSYSINFO _MD_getsysinfo
-
-extern int _MD_unix_get_nonblocking_connect_error(int osfd);
-
-/* Memory-mapped files */
-
-struct _MDFileMap {
- PRIntn prot;
- PRIntn flags;
- PRBool isAnonFM; /* when true, PR_CloseFileMap() must close the related fd */
-};
-
-extern PRStatus _MD_CreateFileMap(struct PRFileMap *fmap, PRInt64 size);
-#define _MD_CREATE_FILE_MAP _MD_CreateFileMap
-
-#define _MD_GET_MEM_MAP_ALIGNMENT() PR_GetPageSize()
-
-extern void * _MD_MemMap(struct PRFileMap *fmap, PRInt64 offset,
- PRUint32 len);
-#define _MD_MEM_MAP _MD_MemMap
-
-extern PRStatus _MD_MemUnmap(void *addr, PRUint32 size);
-#define _MD_MEM_UNMAP _MD_MemUnmap
-
-extern PRStatus _MD_CloseFileMap(struct PRFileMap *fmap);
-#define _MD_CLOSE_FILE_MAP _MD_CloseFileMap
-
-extern PRStatus _MD_SyncMemMap(
- PRFileDesc *fd,
- void *addr,
- PRUint32 len);
-#define _MD_SYNC_MEM_MAP _MD_SyncMemMap
-
-/*
- * The standard (XPG4) gettimeofday() (from BSD) takes two arguments.
- * On some SVR4 derivatives, gettimeofday() takes only one argument.
- * The GETTIMEOFDAY macro is intended to hide this difference.
- */
-#ifdef HAVE_SVID_GETTOD
-#define GETTIMEOFDAY(tp) gettimeofday(tp)
-#else
-#define GETTIMEOFDAY(tp) gettimeofday((tp), NULL)
-#endif
-
-#if defined(_PR_PTHREADS) && !defined(_PR_POLL_AVAILABLE)
-#define _PR_NEED_FAKE_POLL
-#endif
-
-#if defined(_PR_NEED_FAKE_POLL)
-
-/*
- * Some platforms don't have poll(), but our pthreads code calls poll().
- * As a temporary measure, I implemented a fake poll() using select().
- * Here are the struct and macro definitions copied from sys/poll.h
- * on Solaris 2.5.
- */
-
-struct pollfd {
- int fd;
- short events;
- short revents;
-};
-
-/* poll events */
-
-#define POLLIN 0x0001 /* fd is readable */
-#define POLLPRI 0x0002 /* high priority info at fd */
-#define POLLOUT 0x0004 /* fd is writeable (won't block) */
-#define POLLRDNORM 0x0040 /* normal data is readable */
-#define POLLWRNORM POLLOUT
-#define POLLRDBAND 0x0080 /* out-of-band data is readable */
-#define POLLWRBAND 0x0100 /* out-of-band data is writeable */
-
-#define POLLNORM POLLRDNORM
-
-#define POLLERR 0x0008 /* fd has error condition */
-#define POLLHUP 0x0010 /* fd has been hung up on */
-#define POLLNVAL 0x0020 /* invalid pollfd entry */
-
-extern int poll(struct pollfd *, unsigned long, int);
-
-#endif /* _PR_NEED_FAKE_POLL */
-
-/*
-** A vector of the UNIX I/O calls we use. These are here to smooth over
-** the rough edges needed for large files. All of NSPR's implmentaions
-** go through this vector using syntax of the form
-** result = _md_iovector.xxx64(args);
-*/
-
-#if defined(SOLARIS2_5)
-/*
-** Special case: Solaris 2.5.1
-** Solaris starts to have 64-bit file I/O in 2.6. We build on Solaris
-** 2.5.1 so that we can use the same binaries on both Solaris 2.5.1 and
-** 2.6. At run time, we detect whether 64-bit file I/O is available by
-** looking up the 64-bit file function symbols in libc. At build time,
-** we need to define the 64-bit file I/O datatypes that are compatible
-** with their definitions on Solaris 2.6.
-*/
-typedef PRInt64 off64_t;
-typedef PRUint64 ino64_t;
-typedef PRInt64 blkcnt64_t;
-struct stat64 {
- dev_t st_dev;
- long st_pad1[3];
- ino64_t st_ino;
- mode_t st_mode;
- nlink_t st_nlink;
- uid_t st_uid;
- gid_t st_gid;
- dev_t st_rdev;
- long t_pad2[2];
- off64_t st_size;
- timestruc_t st_atim;
- timestruc_t st_mtim;
- timestruc_t st_ctim;
- long st_blksize;
- blkcnt64_t st_blocks;
- char st_fstype[_ST_FSTYPSZ];
- long st_pad4[8];
-};
-typedef struct stat64 _MDStat64;
-typedef off64_t _MDOff64_t;
-
-#elif defined(_PR_HAVE_OFF64_T)
-typedef struct stat64 _MDStat64;
-typedef off64_t _MDOff64_t;
-#elif defined(_PR_HAVE_LARGE_OFF_T)
-typedef struct stat _MDStat64;
-typedef off_t _MDOff64_t;
-#elif defined(_PR_NO_LARGE_FILES)
-typedef struct stat _MDStat64;
-typedef PRInt64 _MDOff64_t;
-#else
-#error "I don't know yet"
-#endif
-
-typedef PRIntn (*_MD_Fstat64)(PRIntn osfd, _MDStat64 *buf);
-typedef PRIntn (*_MD_Open64)(const char *path, int oflag, ...);
-typedef PRIntn (*_MD_Stat64)(const char *path, _MDStat64 *buf);
-typedef _MDOff64_t (*_MD_Lseek64)(PRIntn osfd, _MDOff64_t, PRIntn whence);
-typedef void* (*_MD_Mmap64)(
- void *addr, PRSize len, PRIntn prot, PRIntn flags,
- PRIntn fildes, _MDOff64_t offset);
-struct _MD_IOVector
-{
- _MD_Open64 _open64;
- _MD_Mmap64 _mmap64;
- _MD_Stat64 _stat64;
- _MD_Fstat64 _fstat64;
- _MD_Lseek64 _lseek64;
-};
-extern struct _MD_IOVector _md_iovector;
-
-#endif /* prunixos_h___ */
diff --git a/nspr/pr/include/md/_win32_errors.h b/nspr/pr/include/md/_win32_errors.h
deleted file mode 100644
index 1c96237..0000000
--- a/nspr/pr/include/md/_win32_errors.h
+++ /dev/null
@@ -1,122 +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/. */
-
-#ifndef nspr_win32_errors_h___
-#define nspr_win32_errors_h___
-
-#include <windows.h>
-#include <winsock.h>
-#include <errno.h>
-
-
-extern void _MD_win32_map_default_error(PRInt32 err);
-#define _PR_MD_MAP_DEFAULT_ERROR _MD_win32_map_default_error
-
-extern void _MD_win32_map_opendir_error(PRInt32 err);
-#define _PR_MD_MAP_OPENDIR_ERROR _MD_win32_map_opendir_error
-
-extern void _MD_win32_map_closedir_error(PRInt32 err);
-#define _PR_MD_MAP_CLOSEDIR_ERROR _MD_win32_map_closedir_error
-
-extern void _MD_unix_readdir_error(PRInt32 err);
-#define _PR_MD_MAP_READDIR_ERROR _MD_unix_readdir_error
-
-extern void _MD_win32_map_delete_error(PRInt32 err);
-#define _PR_MD_MAP_DELETE_ERROR _MD_win32_map_delete_error
-
-extern void _MD_win32_map_stat_error(PRInt32 err);
-#define _PR_MD_MAP_STAT_ERROR _MD_win32_map_stat_error
-
-extern void _MD_win32_map_fstat_error(PRInt32 err);
-#define _PR_MD_MAP_FSTAT_ERROR _MD_win32_map_fstat_error
-
-extern void _MD_win32_map_rename_error(PRInt32 err);
-#define _PR_MD_MAP_RENAME_ERROR _MD_win32_map_rename_error
-
-extern void _MD_win32_map_access_error(PRInt32 err);
-#define _PR_MD_MAP_ACCESS_ERROR _MD_win32_map_access_error
-
-extern void _MD_win32_map_mkdir_error(PRInt32 err);
-#define _PR_MD_MAP_MKDIR_ERROR _MD_win32_map_mkdir_error
-
-extern void _MD_win32_map_rmdir_error(PRInt32 err);
-#define _PR_MD_MAP_RMDIR_ERROR _MD_win32_map_rmdir_error
-
-extern void _MD_win32_map_read_error(PRInt32 err);
-#define _PR_MD_MAP_READ_ERROR _MD_win32_map_read_error
-
-extern void _MD_win32_map_transmitfile_error(PRInt32 err);
-#define _PR_MD_MAP_TRANSMITFILE_ERROR _MD_win32_map_transmitfile_error
-
-extern void _MD_win32_map_write_error(PRInt32 err);
-#define _PR_MD_MAP_WRITE_ERROR _MD_win32_map_write_error
-
-extern void _MD_win32_map_lseek_error(PRInt32 err);
-#define _PR_MD_MAP_LSEEK_ERROR _MD_win32_map_lseek_error
-
-extern void _MD_win32_map_fsync_error(PRInt32 err);
-#define _PR_MD_MAP_FSYNC_ERROR _MD_win32_map_fsync_error
-
-extern void _MD_win32_map_close_error(PRInt32 err);
-#define _PR_MD_MAP_CLOSE_ERROR _MD_win32_map_close_error
-
-extern void _MD_win32_map_socket_error(PRInt32 err);
-#define _PR_MD_MAP_SOCKET_ERROR _MD_win32_map_socket_error
-
-extern void _MD_win32_map_recv_error(PRInt32 err);
-#define _PR_MD_MAP_RECV_ERROR _MD_win32_map_recv_error
-
-extern void _MD_win32_map_recvfrom_error(PRInt32 err);
-#define _PR_MD_MAP_RECVFROM_ERROR _MD_win32_map_recvfrom_error
-
-extern void _MD_win32_map_send_error(PRInt32 err);
-#define _PR_MD_MAP_SEND_ERROR _MD_win32_map_send_error
-
-extern void _MD_win32_map_sendto_error(PRInt32 err);
-#define _PR_MD_MAP_SENDTO_ERROR _MD_win32_map_sendto_error
-
-extern void _MD_win32_map_accept_error(PRInt32 err);
-#define _PR_MD_MAP_ACCEPT_ERROR _MD_win32_map_accept_error
-
-extern void _MD_win32_map_acceptex_error(PRInt32 err);
-#define _PR_MD_MAP_ACCEPTEX_ERROR _MD_win32_map_acceptex_error
-
-extern PRInt32 _MD_win32_map_connect_error(PRInt32 err);
-#define _PR_MD_MAP_CONNECT_ERROR _MD_win32_map_connect_error
-
-extern void _MD_win32_map_bind_error(PRInt32 err);
-#define _PR_MD_MAP_BIND_ERROR _MD_win32_map_bind_error
-
-extern void _MD_win32_map_listen_error(PRInt32 err);
-#define _PR_MD_MAP_LISTEN_ERROR _MD_win32_map_listen_error
-
-extern void _MD_win32_map_shutdown_error(PRInt32 err);
-#define _PR_MD_MAP_SHUTDOWN_ERROR _MD_win32_map_shutdown_error
-
-extern void _MD_win32_map_getsockname_error(PRInt32 err);
-#define _PR_MD_MAP_GETSOCKNAME_ERROR _MD_win32_map_getsockname_error
-
-extern void _MD_win32_map_getpeername_error(PRInt32 err);
-#define _PR_MD_MAP_GETPEERNAME_ERROR _MD_win32_map_getpeername_error
-
-extern void _MD_win32_map_getsockopt_error(PRInt32 err);
-#define _PR_MD_MAP_GETSOCKOPT_ERROR _MD_win32_map_getsockopt_error
-
-extern void _MD_win32_map_setsockopt_error(PRInt32 err);
-#define _PR_MD_MAP_SETSOCKOPT_ERROR _MD_win32_map_setsockopt_error
-
-extern void _MD_win32_map_open_error(PRInt32 err);
-#define _PR_MD_MAP_OPEN_ERROR _MD_win32_map_open_error
-
-extern void _MD_win32_map_gethostname_error(PRInt32 err);
-#define _PR_MD_MAP_GETHOSTNAME_ERROR _MD_win32_map_gethostname_error
-
-extern void _MD_win32_map_select_error(PRInt32 err);
-#define _PR_MD_MAP_SELECT_ERROR _MD_win32_map_select_error
-
-extern void _MD_win32_map_lockf_error(int err);
-#define _PR_MD_MAP_LOCKF_ERROR _MD_win32_map_lockf_error
-
-#endif /* nspr_win32_errors_h___ */
diff --git a/nspr/pr/include/md/_win95.cfg b/nspr/pr/include/md/_win95.cfg
deleted file mode 100644
index 1e693cc..0000000
--- a/nspr/pr/include/md/_win95.cfg
+++ /dev/null
@@ -1,272 +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/. */
-
-#ifndef nspr_cpucfg___
-#define nspr_cpucfg___
-
-#ifndef XP_PC
-#define XP_PC
-#endif
-
-#ifndef WIN32
-#define WIN32
-#endif
-
-#ifndef WIN95
-#define WIN95
-#endif
-
-#define PR_AF_INET6 23 /* same as AF_INET6 */
-
-#if defined(_M_IX86) || defined(_X86_)
-
-#define IS_LITTLE_ENDIAN 1
-#undef IS_BIG_ENDIAN
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-#define PR_BYTES_PER_DOUBLE 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_WORD 32
-#define PR_BITS_PER_DWORD 64
-#define PR_BITS_PER_DOUBLE 64
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_WORD_LOG2 5
-#define PR_BITS_PER_DWORD_LOG2 6
-#define PR_BITS_PER_DOUBLE_LOG2 6
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_WORD 4
-#define PR_ALIGN_OF_DWORD 8
-#define PR_ALIGN_OF_DOUBLE 4
-#define PR_ALIGN_OF_POINTER 4
-
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_)
-
-#define IS_LITTLE_ENDIAN 1
-#undef IS_BIG_ENDIAN
-#define IS_64
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_WORD 8
-#define PR_BYTES_PER_DWORD 8
-#define PR_BYTES_PER_DOUBLE 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_WORD 64
-#define PR_BITS_PER_DWORD 64
-#define PR_BITS_PER_DOUBLE 64
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_WORD_LOG2 6
-#define PR_BITS_PER_DWORD_LOG2 6
-#define PR_BITS_PER_DOUBLE_LOG2 6
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_WORD 8
-#define PR_ALIGN_OF_DWORD 8
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 8
-
-#define PR_BYTES_PER_WORD_LOG2 3
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(_M_IA64) || defined(_IA64_)
-
-#define IS_LITTLE_ENDIAN 1
-#undef IS_BIG_ENDIAN
-#define IS_64
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_WORD 8
-#define PR_BYTES_PER_DWORD 8
-#define PR_BYTES_PER_DOUBLE 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_WORD 64
-#define PR_BITS_PER_DWORD 64
-#define PR_BITS_PER_DOUBLE 64
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_WORD_LOG2 6
-#define PR_BITS_PER_DWORD_LOG2 6
-#define PR_BITS_PER_DOUBLE_LOG2 6
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_WORD 8
-#define PR_ALIGN_OF_DWORD 8
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 8
-
-#define PR_BYTES_PER_WORD_LOG2 3
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(_M_ARM) || defined(_ARM_)
-
-#define IS_LITTLE_ENDIAN 1
-#undef IS_BIG_ENDIAN
-
-#define PR_BYTES_PER_BYTE 1
-#define PR_BYTES_PER_SHORT 2
-#define PR_BYTES_PER_INT 4
-#define PR_BYTES_PER_INT64 8
-#define PR_BYTES_PER_LONG 4
-#define PR_BYTES_PER_FLOAT 4
-#define PR_BYTES_PER_WORD 4
-#define PR_BYTES_PER_DWORD 8
-#define PR_BYTES_PER_DOUBLE 8
-
-#define PR_BITS_PER_BYTE 8
-#define PR_BITS_PER_SHORT 16
-#define PR_BITS_PER_INT 32
-#define PR_BITS_PER_INT64 64
-#define PR_BITS_PER_LONG 32
-#define PR_BITS_PER_FLOAT 32
-#define PR_BITS_PER_WORD 32
-#define PR_BITS_PER_DWORD 64
-#define PR_BITS_PER_DOUBLE 64
-
-#define PR_BITS_PER_BYTE_LOG2 3
-#define PR_BITS_PER_SHORT_LOG2 4
-#define PR_BITS_PER_INT_LOG2 5
-#define PR_BITS_PER_INT64_LOG2 6
-#define PR_BITS_PER_LONG_LOG2 5
-#define PR_BITS_PER_FLOAT_LOG2 5
-#define PR_BITS_PER_WORD_LOG2 5
-#define PR_BITS_PER_DWORD_LOG2 6
-#define PR_BITS_PER_DOUBLE_LOG2 6
-
-#define PR_ALIGN_OF_SHORT 2
-#define PR_ALIGN_OF_INT 4
-#define PR_ALIGN_OF_LONG 4
-#define PR_ALIGN_OF_INT64 8
-#define PR_ALIGN_OF_FLOAT 4
-#define PR_ALIGN_OF_WORD 4
-#define PR_ALIGN_OF_DWORD 8
-#define PR_ALIGN_OF_DOUBLE 8
-#define PR_ALIGN_OF_POINTER 4
-
-#define PR_BYTES_PER_WORD_LOG2 2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#else /* defined(_M_IX86) || defined(_X86_) */
-
-#error unknown processor architecture
-
-#endif /* defined(_M_IX86) || defined(_X86_) */
-
-#ifndef HAVE_LONG_LONG
-#define HAVE_LONG_LONG
-#endif
-
-#ifndef NO_NSPR_10_SUPPORT
-
-#define BYTES_PER_BYTE PR_BYTES_PER_BYTE
-#define BYTES_PER_SHORT PR_BYTES_PER_SHORT
-#define BYTES_PER_INT PR_BYTES_PER_INT
-#define BYTES_PER_INT64 PR_BYTES_PER_INT64
-#define BYTES_PER_LONG PR_BYTES_PER_LONG
-#define BYTES_PER_FLOAT PR_BYTES_PER_FLOAT
-#define BYTES_PER_DOUBLE PR_BYTES_PER_DOUBLE
-#define BYTES_PER_WORD PR_BYTES_PER_WORD
-#define BYTES_PER_DWORD PR_BYTES_PER_DWORD
-
-#define BITS_PER_BYTE PR_BITS_PER_BYTE
-#define BITS_PER_SHORT PR_BITS_PER_SHORT
-#define BITS_PER_INT PR_BITS_PER_INT
-#define BITS_PER_INT64 PR_BITS_PER_INT64
-#define BITS_PER_LONG PR_BITS_PER_LONG
-#define BITS_PER_FLOAT PR_BITS_PER_FLOAT
-#define BITS_PER_DOUBLE PR_BITS_PER_DOUBLE
-#define BITS_PER_WORD PR_BITS_PER_WORD
-
-#define BITS_PER_BYTE_LOG2 PR_BITS_PER_BYTE_LOG2
-#define BITS_PER_SHORT_LOG2 PR_BITS_PER_SHORT_LOG2
-#define BITS_PER_INT_LOG2 PR_BITS_PER_INT_LOG2
-#define BITS_PER_INT64_LOG2 PR_BITS_PER_INT64_LOG2
-#define BITS_PER_LONG_LOG2 PR_BITS_PER_LONG_LOG2
-#define BITS_PER_FLOAT_LOG2 PR_BITS_PER_FLOAT_LOG2
-#define BITS_PER_DOUBLE_LOG2 PR_BITS_PER_DOUBLE_LOG2
-#define BITS_PER_WORD_LOG2 PR_BITS_PER_WORD_LOG2
-
-#define ALIGN_OF_SHORT PR_ALIGN_OF_SHORT
-#define ALIGN_OF_INT PR_ALIGN_OF_INT
-#define ALIGN_OF_LONG PR_ALIGN_OF_LONG
-#define ALIGN_OF_INT64 PR_ALIGN_OF_INT64
-#define ALIGN_OF_FLOAT PR_ALIGN_OF_FLOAT
-#define ALIGN_OF_DOUBLE PR_ALIGN_OF_DOUBLE
-#define ALIGN_OF_POINTER PR_ALIGN_OF_POINTER
-#define ALIGN_OF_WORD PR_ALIGN_OF_WORD
-
-#define BYTES_PER_WORD_LOG2 PR_BYTES_PER_WORD_LOG2
-#define BYTES_PER_DWORD_LOG2 PR_BYTES_PER_DWORD_LOG2
-#define WORDS_PER_DWORD_LOG2 PR_WORDS_PER_DWORD_LOG2
-
-#endif /* NO_NSPR_10_SUPPORT */
-
-#endif /* nspr_cpucfg___ */
diff --git a/nspr/pr/include/md/_win95.h b/nspr/pr/include/md/_win95.h
deleted file mode 100644
index 1da2b55..0000000
--- a/nspr/pr/include/md/_win95.h
+++ /dev/null
@@ -1,542 +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/. */
-
-#ifndef nspr_win95_defs_h___
-#define nspr_win95_defs_h___
-
-#include "prio.h"
-
-#include <windows.h>
-#include <winsock.h>
-#include <errno.h>
-
-/*
- * Internal configuration macros
- */
-
-#define PR_LINKER_ARCH "win32"
-#define _PR_SI_SYSNAME "WIN95"
-#if defined(_M_IX86) || defined(_X86_)
-#define _PR_SI_ARCHITECTURE "x86"
-#elif defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_)
-#define _PR_SI_ARCHITECTURE "x86-64"
-#elif defined(_M_IA64) || defined(_IA64_)
-#define _PR_SI_ARCHITECTURE "ia64"
-#elif defined(_M_ARM) || defined(_ARM_)
-#define _PR_SI_ARCHITECTURE "arm"
-#else
-#error unknown processor architecture
-#endif
-
-#define HAVE_DLL
-#undef HAVE_THREAD_AFFINITY
-#ifndef _PR_INET6
-#define AF_INET6 23
-/* newer ws2tcpip.h provides these */
-#ifndef AI_CANONNAME
-#define AI_CANONNAME 0x2
-#define AI_NUMERICHOST 0x4
-#define NI_NUMERICHOST 0x02
-struct addrinfo {
- int ai_flags;
- int ai_family;
- int ai_socktype;
- int ai_protocol;
- size_t ai_addrlen;
- char *ai_canonname;
- struct sockaddr *ai_addr;
- struct addrinfo *ai_next;
-};
-#endif
-#define _PR_HAVE_MD_SOCKADDR_IN6
-/* isomorphic to struct in6_addr on Windows */
-struct _md_in6_addr {
- union {
- PRUint8 _S6_u8[16];
- PRUint16 _S6_u16[8];
- } _S6_un;
-};
-/* isomorphic to struct sockaddr_in6 on Windows */
-struct _md_sockaddr_in6 {
- PRInt16 sin6_family;
- PRUint16 sin6_port;
- PRUint32 sin6_flowinfo;
- struct _md_in6_addr sin6_addr;
- PRUint32 sin6_scope_id;
-};
-#endif
-#define _PR_HAVE_THREADSAFE_GETHOST
-#define _PR_HAVE_ATOMIC_OPS
-#define PR_HAVE_WIN32_NAMED_SHARED_MEMORY
-
-/* --- Common User-Thread/Native-Thread Definitions --------------------- */
-
-/* --- Globals --- */
-extern struct PRLock *_pr_schedLock;
-
-/* --- Typedefs --- */
-typedef void (*FiberFunc)(void *);
-
-#define PR_NUM_GCREGS 8
-typedef PRInt32 PR_CONTEXT_TYPE[PR_NUM_GCREGS];
-#define GC_VMBASE 0x40000000
-#define GC_VMLIMIT 0x00FFFFFF
-
-#define _MD_MAGIC_THREAD 0x22222222
-#define _MD_MAGIC_THREADSTACK 0x33333333
-#define _MD_MAGIC_SEGMENT 0x44444444
-#define _MD_MAGIC_DIR 0x55555555
-#define _MD_MAGIC_CV 0x66666666
-
-struct _MDCPU {
- int unused;
-};
-
-struct _MDThread {
- HANDLE blocked_sema; /* Threads block on this when waiting
- * for IO or CondVar.
- */
- PRBool inCVWaitQueue; /* PR_TRUE if the thread is in the
- * wait queue of some cond var.
- * PR_FALSE otherwise. */
- HANDLE handle; /* Win32 thread handle */
- PRUint32 id;
- void *sp; /* only valid when suspended */
- PRUint32 magic; /* for debugging */
- PR_CONTEXT_TYPE gcContext; /* Thread context for GC */
- struct PRThread *prev, *next; /* used by the cvar wait queue to
- * chain the PRThread structures
- * together */
- void (*start)(void *); /* used by _PR_MD_CREATE_THREAD to
- * pass its 'start' argument to
- * pr_root. */
-};
-
-struct _MDThreadStack {
- PRUint32 magic; /* for debugging */
-};
-
-struct _MDSegment {
- PRUint32 magic; /* for debugging */
-};
-
-#undef PROFILE_LOCKS
-
-struct _MDDir {
- HANDLE d_hdl;
- WIN32_FIND_DATAA d_entry;
- PRBool firstEntry; /* Is this the entry returned
- * by FindFirstFile()? */
- PRUint32 magic; /* for debugging */
-};
-
-#ifdef MOZ_UNICODE
-struct _MDDirUTF16 {
- HANDLE d_hdl;
- WIN32_FIND_DATAW d_entry;
- PRBool firstEntry; /* Is this the entry returned
- * by FindFirstFileW()? */
- PRUint32 magic; /* for debugging */
-};
-#endif /* MOZ_UNICODE */
-
-struct _MDCVar {
- PRUint32 magic;
- struct PRThread *waitHead, *waitTail; /* the wait queue: a doubly-
- * linked list of threads
- * waiting on this condition
- * variable */
- PRIntn nwait; /* number of threads in the
- * wait queue */
-};
-
-#define _MD_CV_NOTIFIED_LENGTH 6
-typedef struct _MDNotified _MDNotified;
-struct _MDNotified {
- PRIntn length; /* # of used entries in this
- * structure */
- struct {
- struct _MDCVar *cv; /* the condition variable notified */
- PRIntn times; /* and the number of times notified */
- struct PRThread *notifyHead; /* list of threads to wake up */
- } cv[_MD_CV_NOTIFIED_LENGTH];
- _MDNotified *link; /* link to another of these, or NULL */
-};
-
-struct _MDLock {
- CRITICAL_SECTION mutex; /* this is recursive on NT */
-
- /*
- * When notifying cvars, there is no point in actually
- * waking up the threads waiting on the cvars until we've
- * released the lock. So, we temporarily record the cvars.
- * When doing an unlock, we'll then wake up the waiting threads.
- */
- struct _MDNotified notified; /* array of conditions notified */
-#ifdef PROFILE_LOCKS
- PRInt32 hitcount;
- PRInt32 misscount;
-#endif
-};
-
-struct _MDSemaphore {
- HANDLE sem;
-};
-
-struct _MDFileDesc {
- PROsfd osfd; /* The osfd can come from one of three spaces:
- * - For stdin, stdout, and stderr, we are using
- * the libc file handle (0, 1, 2), which is an int.
- * - For files and pipes, we are using Win32 HANDLE,
- * which is a void*.
- * - For sockets, we are using Winsock SOCKET, which
- * is a u_int.
- */
-};
-
-struct _MDProcess {
- HANDLE handle;
- DWORD id;
-};
-
-/* --- Misc stuff --- */
-#define _MD_GET_SP(thread) (thread)->md.gcContext[6]
-
-/* --- NT security stuff --- */
-
-extern void _PR_NT_InitSids(void);
-extern void _PR_NT_FreeSids(void);
-extern PRStatus _PR_NT_MakeSecurityDescriptorACL(
- PRIntn mode,
- DWORD accessTable[],
- PSECURITY_DESCRIPTOR *resultSD,
- PACL *resultACL
-);
-extern void _PR_NT_FreeSecurityDescriptorACL(
- PSECURITY_DESCRIPTOR pSD, PACL pACL);
-
-/* --- IO stuff --- */
-
-#define _MD_OPEN _PR_MD_OPEN
-#define _MD_OPEN_FILE _PR_MD_OPEN_FILE
-#define _MD_READ _PR_MD_READ
-#define _MD_WRITE _PR_MD_WRITE
-#define _MD_WRITEV _PR_MD_WRITEV
-#define _MD_LSEEK _PR_MD_LSEEK
-#define _MD_LSEEK64 _PR_MD_LSEEK64
-extern PRInt32 _MD_CloseFile(PROsfd osfd);
-#define _MD_CLOSE_FILE _MD_CloseFile
-#define _MD_GETFILEINFO _PR_MD_GETFILEINFO
-#define _MD_GETFILEINFO64 _PR_MD_GETFILEINFO64
-#define _MD_GETOPENFILEINFO _PR_MD_GETOPENFILEINFO
-#define _MD_GETOPENFILEINFO64 _PR_MD_GETOPENFILEINFO64
-#define _MD_STAT _PR_MD_STAT
-#define _MD_RENAME _PR_MD_RENAME
-#define _MD_ACCESS _PR_MD_ACCESS
-#define _MD_DELETE _PR_MD_DELETE
-#define _MD_MKDIR _PR_MD_MKDIR
-#define _MD_MAKE_DIR _PR_MD_MAKE_DIR
-#define _MD_RMDIR _PR_MD_RMDIR
-#define _MD_LOCKFILE _PR_MD_LOCKFILE
-#define _MD_TLOCKFILE _PR_MD_TLOCKFILE
-#define _MD_UNLOCKFILE _PR_MD_UNLOCKFILE
-
-/* --- UTF16 IO stuff --- */
-#ifdef MOZ_UNICODE
-#define _MD_OPEN_FILE_UTF16 _PR_MD_OPEN_FILE_UTF16
-#define _MD_OPEN_DIR_UTF16 _PR_MD_OPEN_DIR_UTF16
-#define _MD_READ_DIR_UTF16 _PR_MD_READ_DIR_UTF16
-#define _MD_CLOSE_DIR_UTF16 _PR_MD_CLOSE_DIR_UTF16
-#define _MD_GETFILEINFO64_UTF16 _PR_MD_GETFILEINFO64_UTF16
-#endif /* MOZ_UNICODE */
-
-/* --- Socket IO stuff --- */
-extern void _PR_MD_InitSockets(void);
-extern void _PR_MD_CleanupSockets(void);
-#define _MD_EACCES WSAEACCES
-#define _MD_EADDRINUSE WSAEADDRINUSE
-#define _MD_EADDRNOTAVAIL WSAEADDRNOTAVAIL
-#define _MD_EAFNOSUPPORT WSAEAFNOSUPPORT
-#define _MD_EAGAIN WSAEWOULDBLOCK
-#define _MD_EALREADY WSAEALREADY
-#define _MD_EBADF WSAEBADF
-#define _MD_ECONNREFUSED WSAECONNREFUSED
-#define _MD_ECONNRESET WSAECONNRESET
-#define _MD_EFAULT WSAEFAULT
-#define _MD_EINPROGRESS WSAEINPROGRESS
-#define _MD_EINTR WSAEINTR
-#define _MD_EINVAL EINVAL
-#define _MD_EISCONN WSAEISCONN
-#define _MD_ENETUNREACH WSAENETUNREACH
-#define _MD_ENOENT ENOENT
-#define _MD_ENOTCONN WSAENOTCONN
-#define _MD_ENOTSOCK WSAENOTSOCK
-#define _MD_EOPNOTSUPP WSAEOPNOTSUPP
-#define _MD_EWOULDBLOCK WSAEWOULDBLOCK
-#define _MD_GET_SOCKET_ERROR() WSAGetLastError()
-#define _MD_SET_SOCKET_ERROR(_err) WSASetLastError(_err)
-
-#define _MD_INIT_FILEDESC(fd)
-extern void _MD_MakeNonblock(PRFileDesc *f);
-#define _MD_MAKE_NONBLOCK _MD_MakeNonblock
-#define _MD_INIT_FD_INHERITABLE _PR_MD_INIT_FD_INHERITABLE
-#define _MD_QUERY_FD_INHERITABLE _PR_MD_QUERY_FD_INHERITABLE
-#define _MD_SHUTDOWN _PR_MD_SHUTDOWN
-#define _MD_LISTEN _PR_MD_LISTEN
-extern PRInt32 _MD_CloseSocket(PROsfd osfd);
-#define _MD_CLOSE_SOCKET _MD_CloseSocket
-#define _MD_SENDTO _PR_MD_SENDTO
-#define _MD_RECVFROM _PR_MD_RECVFROM
-#define _MD_SOCKETPAIR(s, type, proto, sv) -1
-#define _MD_GETSOCKNAME _PR_MD_GETSOCKNAME
-#define _MD_GETPEERNAME _PR_MD_GETPEERNAME
-#define _MD_GETSOCKOPT _PR_MD_GETSOCKOPT
-#define _MD_SETSOCKOPT _PR_MD_SETSOCKOPT
-#define _MD_SET_FD_INHERITABLE _PR_MD_SET_FD_INHERITABLE
-#define _MD_SELECT select
-#define _MD_FSYNC _PR_MD_FSYNC
-#define READ_FD 1
-#define WRITE_FD 2
-
-#define _MD_INIT_ATOMIC()
-#if defined(_M_IX86) || defined(_X86_)
-#define _MD_ATOMIC_INCREMENT _PR_MD_ATOMIC_INCREMENT
-#define _MD_ATOMIC_ADD _PR_MD_ATOMIC_ADD
-#define _MD_ATOMIC_DECREMENT _PR_MD_ATOMIC_DECREMENT
-#else /* non-x86 processors */
-#define _MD_ATOMIC_INCREMENT(x) InterlockedIncrement((PLONG)x)
-#define _MD_ATOMIC_ADD(ptr,val) (InterlockedExchangeAdd((PLONG)ptr, (LONG)val) + val)
-#define _MD_ATOMIC_DECREMENT(x) InterlockedDecrement((PLONG)x)
-#endif /* x86 */
-#define _MD_ATOMIC_SET(x,y) InterlockedExchange((PLONG)x, (LONG)y)
-
-#define _MD_INIT_IO _PR_MD_INIT_IO
-
-
-/* win95 doesn't have async IO */
-#define _MD_SOCKET _PR_MD_SOCKET
-extern PRInt32 _MD_SocketAvailable(PRFileDesc *fd);
-#define _MD_SOCKETAVAILABLE _MD_SocketAvailable
-#define _MD_PIPEAVAILABLE _PR_MD_PIPEAVAILABLE
-#define _MD_CONNECT _PR_MD_CONNECT
-extern PROsfd _MD_Accept(PRFileDesc *fd, PRNetAddr *raddr, PRUint32 *rlen,
- PRIntervalTime timeout);
-#define _MD_ACCEPT _MD_Accept
-#define _MD_BIND _PR_MD_BIND
-#define _MD_RECV _PR_MD_RECV
-#define _MD_SEND _PR_MD_SEND
-#define _MD_PR_POLL _PR_MD_PR_POLL
-
-/* --- Scheduler stuff --- */
-// #define _MD_PAUSE_CPU _PR_MD_PAUSE_CPU
-#define _MD_PAUSE_CPU
-
-/* --- DIR stuff --- */
-#define PR_DIRECTORY_SEPARATOR '\\'
-#define PR_DIRECTORY_SEPARATOR_STR "\\"
-#define PR_PATH_SEPARATOR ';'
-#define PR_PATH_SEPARATOR_STR ";"
-#define _MD_ERRNO() GetLastError()
-#define _MD_OPEN_DIR _PR_MD_OPEN_DIR
-#define _MD_CLOSE_DIR _PR_MD_CLOSE_DIR
-#define _MD_READ_DIR _PR_MD_READ_DIR
-
-/* --- Segment stuff --- */
-#define _MD_INIT_SEGS()
-#define _MD_ALLOC_SEGMENT(seg, size, vaddr) 0
-#define _MD_FREE_SEGMENT(seg)
-
-/* --- Environment Stuff --- */
-#define _MD_GET_ENV _PR_MD_GET_ENV
-#define _MD_PUT_ENV _PR_MD_PUT_ENV
-
-/* --- Threading Stuff --- */
-#define _MD_DEFAULT_STACK_SIZE 0
-#define _MD_INIT_THREAD _PR_MD_INIT_THREAD
-#define _MD_INIT_ATTACHED_THREAD _PR_MD_INIT_THREAD
-#define _MD_CREATE_THREAD _PR_MD_CREATE_THREAD
-#define _MD_YIELD _PR_MD_YIELD
-#define _MD_SET_PRIORITY _PR_MD_SET_PRIORITY
-#define _MD_SET_CURRENT_THREAD_NAME _PR_MD_SET_CURRENT_THREAD_NAME
-#define _MD_CLEAN_THREAD _PR_MD_CLEAN_THREAD
-#define _MD_SETTHREADAFFINITYMASK _PR_MD_SETTHREADAFFINITYMASK
-#define _MD_GETTHREADAFFINITYMASK _PR_MD_GETTHREADAFFINITYMASK
-#define _MD_EXIT_THREAD _PR_MD_EXIT_THREAD
-#define _MD_EXIT _PR_MD_EXIT
-#define _MD_SUSPEND_THREAD _PR_MD_SUSPEND_THREAD
-#define _MD_RESUME_THREAD _PR_MD_RESUME_THREAD
-#define _MD_SUSPEND_CPU _PR_MD_SUSPEND_CPU
-#define _MD_RESUME_CPU _PR_MD_RESUME_CPU
-#define _MD_BEGIN_SUSPEND_ALL()
-#define _MD_BEGIN_RESUME_ALL()
-#define _MD_END_SUSPEND_ALL()
-#define _MD_END_RESUME_ALL()
-
-/* --- Lock stuff --- */
-#define _PR_LOCK _MD_LOCK
-#define _PR_UNLOCK _MD_UNLOCK
-
-#define _MD_NEW_LOCK _PR_MD_NEW_LOCK
-#define _MD_FREE_LOCK(lock) DeleteCriticalSection(&((lock)->mutex))
-#define _MD_LOCK(lock) EnterCriticalSection(&((lock)->mutex))
-#define _MD_TEST_AND_LOCK(lock) (EnterCriticalSection(&((lock)->mutex)),0)
-#define _MD_UNLOCK _PR_MD_UNLOCK
-
-/* --- lock and cv waiting --- */
-#define _MD_WAIT _PR_MD_WAIT
-#define _MD_WAKEUP_WAITER _PR_MD_WAKEUP_WAITER
-
-/* --- CVar ------------------- */
-#define _MD_WAIT_CV _PR_MD_WAIT_CV
-#define _MD_NEW_CV _PR_MD_NEW_CV
-#define _MD_FREE_CV _PR_MD_FREE_CV
-#define _MD_NOTIFY_CV _PR_MD_NOTIFY_CV
-#define _MD_NOTIFYALL_CV _PR_MD_NOTIFYALL_CV
-
- /* XXXMB- the IOQ stuff is certainly not working correctly yet. */
-// extern struct _MDLock _pr_ioq_lock;
-#define _MD_IOQ_LOCK()
-#define _MD_IOQ_UNLOCK()
-
-
-/* --- Initialization stuff --- */
-#define _MD_START_INTERRUPTS()
-#define _MD_STOP_INTERRUPTS()
-#define _MD_DISABLE_CLOCK_INTERRUPTS()
-#define _MD_ENABLE_CLOCK_INTERRUPTS()
-#define _MD_BLOCK_CLOCK_INTERRUPTS()
-#define _MD_UNBLOCK_CLOCK_INTERRUPTS()
-#define _MD_EARLY_INIT _PR_MD_EARLY_INIT
-#define _MD_FINAL_INIT()
-#define _MD_EARLY_CLEANUP()
-#define _MD_INIT_CPUS()
-#define _MD_INIT_RUNNING_CPU(cpu)
-
-struct PRProcess;
-struct PRProcessAttr;
-
-#define _MD_CREATE_PROCESS _PR_CreateWindowsProcess
-extern struct PRProcess * _PR_CreateWindowsProcess(
- const char *path,
- char *const *argv,
- char *const *envp,
- const struct PRProcessAttr *attr
-);
-
-#define _MD_DETACH_PROCESS _PR_DetachWindowsProcess
-extern PRStatus _PR_DetachWindowsProcess(struct PRProcess *process);
-
-/* --- Wait for a child process to terminate --- */
-#define _MD_WAIT_PROCESS _PR_WaitWindowsProcess
-extern PRStatus _PR_WaitWindowsProcess(struct PRProcess *process,
- PRInt32 *exitCode);
-
-#define _MD_KILL_PROCESS _PR_KillWindowsProcess
-extern PRStatus _PR_KillWindowsProcess(struct PRProcess *process);
-
-#define _MD_CLEANUP_BEFORE_EXIT _PR_MD_CLEANUP_BEFORE_EXIT
-#define _MD_INIT_CONTEXT(_thread, _sp, _main, status) \
- PR_BEGIN_MACRO \
- *status = PR_TRUE; \
- PR_END_MACRO
-#define _MD_SWITCH_CONTEXT
-#define _MD_RESTORE_CONTEXT
-
-/* --- Intervals --- */
-#define _MD_INTERVAL_INIT _PR_MD_INTERVAL_INIT
-#define _MD_GET_INTERVAL _PR_MD_GET_INTERVAL
-#define _MD_INTERVAL_PER_SEC _PR_MD_INTERVAL_PER_SEC
-#define _MD_INTERVAL_PER_MILLISEC() (_PR_MD_INTERVAL_PER_SEC() / 1000)
-#define _MD_INTERVAL_PER_MICROSEC() (_PR_MD_INTERVAL_PER_SEC() / 1000000)
-
-/* --- Time --- */
-extern void _PR_FileTimeToPRTime(const FILETIME *filetime, PRTime *prtm);
-
-#ifdef WINCE
-extern void _MD_InitTime(void);
-extern void _MD_CleanupTime(void);
-#endif
-
-/* --- Native-Thread Specific Definitions ------------------------------- */
-
-extern struct PRThread * _MD_CURRENT_THREAD(void);
-
-#ifdef _PR_USE_STATIC_TLS
-extern __declspec(thread) struct PRThread *_pr_currentThread;
-#define _MD_GET_ATTACHED_THREAD() _pr_currentThread
-#define _MD_SET_CURRENT_THREAD(_thread) (_pr_currentThread = (_thread))
-
-extern __declspec(thread) struct PRThread *_pr_thread_last_run;
-#define _MD_LAST_THREAD() _pr_thread_last_run
-#define _MD_SET_LAST_THREAD(_thread) (_pr_thread_last_run = 0)
-
-extern __declspec(thread) struct _PRCPU *_pr_currentCPU;
-#define _MD_CURRENT_CPU() _pr_currentCPU
-#define _MD_SET_CURRENT_CPU(_cpu) (_pr_currentCPU = 0)
-#else /* _PR_USE_STATIC_TLS */
-extern DWORD _pr_currentThreadIndex;
-#define _MD_GET_ATTACHED_THREAD() ((PRThread *) TlsGetValue(_pr_currentThreadIndex))
-#define _MD_SET_CURRENT_THREAD(_thread) TlsSetValue(_pr_currentThreadIndex, (_thread))
-
-extern DWORD _pr_lastThreadIndex;
-#define _MD_LAST_THREAD() ((PRThread *) TlsGetValue(_pr_lastThreadIndex))
-#define _MD_SET_LAST_THREAD(_thread) TlsSetValue(_pr_lastThreadIndex, 0)
-
-extern DWORD _pr_currentCPUIndex;
-#define _MD_CURRENT_CPU() ((struct _PRCPU *) TlsGetValue(_pr_currentCPUIndex))
-#define _MD_SET_CURRENT_CPU(_cpu) TlsSetValue(_pr_currentCPUIndex, 0)
-#endif /* _PR_USE_STATIC_TLS */
-
-/* --- Scheduler stuff --- */
-#define LOCK_SCHEDULER() 0
-#define UNLOCK_SCHEDULER() 0
-#define _PR_LockSched() 0
-#define _PR_UnlockSched() 0
-
-/* --- Initialization stuff --- */
-#define _MD_INIT_LOCKS _PR_MD_INIT_LOCKS
-
-/* --- Stack stuff --- */
-#define _MD_INIT_STACK(stack, redzone)
-#define _MD_CLEAR_STACK(stack)
-
-/* --- Memory-mapped files stuff --- */
-
-struct _MDFileMap {
- HANDLE hFileMap;
- DWORD dwAccess;
-};
-
-extern PRStatus _MD_CreateFileMap(struct PRFileMap *fmap, PRInt64 size);
-#define _MD_CREATE_FILE_MAP _MD_CreateFileMap
-
-extern PRInt32 _MD_GetMemMapAlignment(void);
-#define _MD_GET_MEM_MAP_ALIGNMENT _MD_GetMemMapAlignment
-
-extern void * _MD_MemMap(struct PRFileMap *fmap, PRInt64 offset,
- PRUint32 len);
-#define _MD_MEM_MAP _MD_MemMap
-
-extern PRStatus _MD_MemUnmap(void *addr, PRUint32 size);
-#define _MD_MEM_UNMAP _MD_MemUnmap
-
-extern PRStatus _MD_CloseFileMap(struct PRFileMap *fmap);
-#define _MD_CLOSE_FILE_MAP _MD_CloseFileMap
-
-extern PRStatus _MD_SyncMemMap(
- PRFileDesc *fd,
- void *addr,
- PRUint32 len);
-#define _MD_SYNC_MEM_MAP _MD_SyncMemMap
-
-/* --- Named semaphores stuff --- */
-#define _PR_HAVE_NAMED_SEMAPHORES
-#define _MD_OPEN_SEMAPHORE _PR_MD_OPEN_SEMAPHORE
-#define _MD_WAIT_SEMAPHORE _PR_MD_WAIT_SEMAPHORE
-#define _MD_POST_SEMAPHORE _PR_MD_POST_SEMAPHORE
-#define _MD_CLOSE_SEMAPHORE _PR_MD_CLOSE_SEMAPHORE
-#define _MD_DELETE_SEMAPHORE(name) PR_SUCCESS /* no op */
-
-#endif /* nspr_win32_defs_h___ */
diff --git a/nspr/pr/include/md/prosdep.h b/nspr/pr/include/md/prosdep.h
deleted file mode 100644
index 94d8945..0000000
--- a/nspr/pr/include/md/prosdep.h
+++ /dev/null
@@ -1,113 +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/. */
-
-#ifndef prosdep_h___
-#define prosdep_h___
-
-/*
-** Get OS specific header information
-*/
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-#ifdef XP_PC
-
-#include "md/_pcos.h"
-#ifdef WINNT
-#include "md/_winnt.h"
-#include "md/_win32_errors.h"
-#elif defined(WIN95) || defined(WINCE)
-#include "md/_win95.h"
-#include "md/_win32_errors.h"
-#elif defined(OS2)
-#include "md/_os2.h"
-#include "md/_os2_errors.h"
-#else
-#error unknown Windows platform
-#endif
-
-#elif defined(XP_UNIX)
-
-#if defined(AIX)
-#include "md/_aix.h"
-
-#elif defined(FREEBSD)
-#include "md/_freebsd.h"
-
-#elif defined(NETBSD)
-#include "md/_netbsd.h"
-
-#elif defined(OPENBSD)
-#include "md/_openbsd.h"
-
-#elif defined(BSDI)
-#include "md/_bsdi.h"
-
-#elif defined(HPUX)
-#include "md/_hpux.h"
-
-#elif defined(IRIX)
-#include "md/_irix.h"
-
-#elif defined(LINUX) || defined(__GNU__) || defined(__GLIBC__)
-#include "md/_linux.h"
-
-#elif defined(OSF1)
-#include "md/_osf1.h"
-
-#elif defined(DARWIN)
-#include "md/_darwin.h"
-
-#elif defined(SOLARIS)
-#include "md/_solaris.h"
-
-#elif defined(SCO)
-#include "md/_scoos.h"
-
-#elif defined(UNIXWARE)
-#include "md/_unixware.h"
-
-#elif defined(DGUX)
-#include "md/_dgux.h"
-
-#elif defined(QNX)
-#include "md/_qnx.h"
-
-#elif defined(NTO)
-#include "md/_nto.h"
-
-#elif defined(RISCOS)
-#include "md/_riscos.h"
-
-#elif defined(SYMBIAN)
-#include "md/_symbian.h"
-
-#else
-#error unknown Unix flavor
-
-#endif
-
-#include "md/_unixos.h"
-#include "md/_unix_errors.h"
-
-#elif defined(XP_BEOS)
-
-#include "md/_beos.h"
-#include "md/_unix_errors.h"
-
-#else
-
-#error "The platform is not BeOS, Unix, Windows, or Mac"
-
-#endif
-
-#ifdef _PR_PTHREADS
-#include "md/_pth.h"
-#endif
-
-PR_END_EXTERN_C
-
-#endif /* prosdep_h___ */
diff --git a/nspr/pr/include/nspr.h b/nspr/pr/include/nspr.h
deleted file mode 100644
index 0cbc71c..0000000
--- a/nspr/pr/include/nspr.h
+++ /dev/null
@@ -1,43 +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/. */
-
-#ifndef nspr_h___
-#define nspr_h___
-
-#include "pratom.h"
-#include "prbit.h"
-#include "prclist.h"
-#include "prcmon.h"
-#include "prcvar.h"
-#include "prdtoa.h"
-#include "prenv.h"
-#include "prerror.h"
-#include "prinet.h"
-#include "prinit.h"
-#include "prinrval.h"
-#include "prio.h"
-#include "pripcsem.h"
-#include "prlink.h"
-#include "prlock.h"
-#include "prlog.h"
-#include "prlong.h"
-#include "prmem.h"
-#include "prmon.h"
-#include "prmwait.h"
-#include "prnetdb.h"
-#include "prprf.h"
-#include "prproces.h"
-#include "prrng.h"
-#include "prrwlock.h"
-#include "prshm.h"
-#include "prshma.h"
-#include "prsystem.h"
-#include "prthread.h"
-#include "prtime.h"
-#include "prtpool.h"
-#include "prtrace.h"
-#include "prtypes.h"
-
-#endif /* nspr_h___ */
diff --git a/nspr/pr/include/obsolete/pralarm.h b/nspr/pr/include/obsolete/pralarm.h
deleted file mode 100644
index 959e74b..0000000
--- a/nspr/pr/include/obsolete/pralarm.h
+++ /dev/null
@@ -1,162 +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/. */
-
-/*
-** File: pralarm.h
-** Description: API to periodic alarms.
-**
-**
-** Alarms are defined to invoke some client specified function at
-** a time in the future. The notification may be a one time event
-** or repeated at a fixed interval. The interval at which the next
-** notification takes place may be modified by the client code only
-** during the respective notification.
-**
-** The notification is delivered on a thread that is part of the
-** alarm context (PRAlarm). The thread will inherit the priority
-** of the Alarm creator.
-**
-** Any number of periodic alarms (PRAlarmID) may be created within
-** the context of a single alarm (PRAlarm). The notifications will be
-** scheduled as close to the desired time as possible.
-**
-** Repeating periodic notifies are expected to run at a fixed rate.
-** That rate is expressed as some number of notifies per period where
-** the period is much larger than a PRIntervalTime (see prinrval.h).
-*/
-
-#if !defined(pralarm_h)
-#define pralarm_h
-
-#include "prtypes.h"
-#include "prinrval.h"
-
-
-PR_BEGIN_EXTERN_C
-
-/**********************************************************************/
-/************************* TYPES AND CONSTANTS ************************/
-/**********************************************************************/
-
-typedef struct PRAlarm PRAlarm;
-typedef struct PRAlarmID PRAlarmID;
-
-typedef PRBool (PR_CALLBACK *PRPeriodicAlarmFn)(
- PRAlarmID *id, void *clientData, PRUint32 late);
-
-/**********************************************************************/
-/****************************** FUNCTIONS *****************************/
-/**********************************************************************/
-
-/***********************************************************************
-** FUNCTION: PR_CreateAlarm
-** DESCRIPTION:
-** Create an alarm context.
-** INPUTS: void
-** OUTPUTS: None
-** RETURN: PRAlarm*
-**
-** SIDE EFFECTS:
-** This creates an alarm context, which is an object used for subsequent
-** notification creations. It also creates a thread that will be used to
-** deliver the notifications that are expected to be defined. The client
-** is resposible for destroying the context when appropriate.
-** RESTRICTIONS:
-** None.
-** MEMORY: The object (PRAlarm) and a thread to support notifications.
-** ALGORITHM: N/A
-***********************************************************************/
-NSPR_API(PRAlarm*) PR_CreateAlarm(void);
-
-/***********************************************************************
-** FUNCTION: PR_DestroyAlarm
-** DESCRIPTION:
-** Destroys the context created by PR_CreateAlarm().
-** INPUTS: PRAlarm*
-** OUTPUTS: None
-** RETURN: PRStatus
-**
-** SIDE EFFECTS:
-** This destroys the context that was created by PR_CreateAlarm().
-** If there are any active alarms (PRAlarmID), they will be cancelled.
-** Once that is done, the thread that was used to deliver the alarms
-** will be joined.
-** RESTRICTIONS:
-** None.
-** MEMORY: N/A
-** ALGORITHM: N/A
-***********************************************************************/
-NSPR_API(PRStatus) PR_DestroyAlarm(PRAlarm *alarm);
-
-/***********************************************************************
-** FUNCTION: PR_SetAlarm
-** DESCRIPTION:
-** Creates a periodic notifier that is to be delivered to a specified
-** function at some fixed interval.
-** INPUTS: PRAlarm *alarm Parent alarm context
-** PRIntervalTime period Interval over which the notifies
-** are delivered.
-** PRUint32 rate The rate within the interval that
-** the notifies will be delivered.
-** PRPeriodicAlarmFn function Entry point where the notifies
-** will be delivered.
-** OUTPUTS: None
-** RETURN: PRAlarmID* Handle to the notifier just created
-** or NULL if the request failed.
-**
-** SIDE EFFECTS:
-** A periodic notifier is created. The notifications will be delivered
-** by the alarm's internal thread at a fixed interval whose rate is the
-** number of interrupts per interval specified. The first notification
-** will be delivered as soon as possible, and they will continue until
-** the notifier routine indicates that they should cease of the alarm
-** context is destroyed (PR_DestroyAlarm).
-** RESTRICTIONS:
-** None.
-** MEMORY: Memory for the notifier object.
-** ALGORITHM: The rate at which notifications are delivered are stated
-** to be "'rate' notifies per 'interval'". The exact time of
-** the notification is computed based on a epoch established
-** when the notifier was set. Each notification is delivered
-** not ealier than the epoch plus the fixed rate times the
-** notification sequence number. Such notifications have the
-** potential to be late by not more than 'interval'/'rate'.
-** The amount of lateness of one notification is taken into
-** account on the next in an attempt to avoid long term slew.
-***********************************************************************/
-NSPR_API(PRAlarmID*) PR_SetAlarm(
- PRAlarm *alarm, PRIntervalTime period, PRUint32 rate,
- PRPeriodicAlarmFn function, void *clientData);
-
-/***********************************************************************
-** FUNCTION: PR_ResetAlarm
-** DESCRIPTION:
-** Resets an existing alarm.
-** INPUTS: PRAlarmID *id Identify of the notifier.
-** PRIntervalTime period Interval over which the notifies
-** are delivered.
-** PRUint32 rate The rate within the interval that
-** the notifies will be delivered.
-** OUTPUTS: None
-** RETURN: PRStatus Indication of completion.
-**
-** SIDE EFFECTS:
-** An existing alarm may have its period and rate redefined. The
-** additional side effect is that the notifier's epoch is recomputed.
-** The first notification delivered by the newly refreshed alarm is
-** defined to be 'interval'/'rate' from the time of the reset.
-** RESTRICTIONS:
-** This function may only be called in the notifier for that alarm.
-** MEMORY: N/A.
-** ALGORITHM: See PR_SetAlarm().
-***********************************************************************/
-NSPR_API(PRStatus) PR_ResetAlarm(
- PRAlarmID *id, PRIntervalTime period, PRUint32 rate);
-
-PR_END_EXTERN_C
-
-#endif /* !defined(pralarm_h) */
-
-/* prinrval.h */
diff --git a/nspr/pr/include/obsolete/probslet.h b/nspr/pr/include/obsolete/probslet.h
deleted file mode 100644
index 2eff0ba..0000000
--- a/nspr/pr/include/obsolete/probslet.h
+++ /dev/null
@@ -1,149 +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/. */
-
-/*
-** A collection of things thought to be obsolete
-*/
-
-#if defined(PROBSLET_H)
-#else
-#define PROBSLET_H
-
-#include "prio.h"
-#include "private/pprio.h" /* for PROsfd */
-
-PR_BEGIN_EXTERN_C
-
-/*
-** Yield the current thread. The proper function to use in place of
-** PR_Yield() is PR_Sleep() with an argument of PR_INTERVAL_NO_WAIT.
-*/
-NSPR_API(PRStatus) PR_Yield(void);
-
-/************************************************************************/
-/************* The following definitions are for select *****************/
-/************************************************************************/
-
-/*
-** The following is obsolete and will be deleted in the next release!
-** These are provided for compatibility, but are GUARANTEED to be slow.
-**
-** Override PR_MAX_SELECT_DESC if you need more space in the select set.
-*/
-#ifndef PR_MAX_SELECT_DESC
-#define PR_MAX_SELECT_DESC 1024
-#endif
-typedef struct PR_fd_set {
- PRUint32 hsize;
- PRFileDesc *harray[PR_MAX_SELECT_DESC];
- PRUint32 nsize;
- PROsfd narray[PR_MAX_SELECT_DESC];
-} PR_fd_set;
-
-/*
-*************************************************************************
-** FUNCTION: PR_Select
-** DESCRIPTION:
-**
-** The call returns as soon as I/O is ready on one or more of the underlying
-** file/socket descriptors or an exceptional condition is pending. A count of the
-** number of ready descriptors is returned unless a timeout occurs in which case
-** zero is returned. On return, PR_Select replaces the given descriptor sets with
-** subsets consisting of those descriptors that are ready for the requested condition.
-** The total number of ready descriptors in all the sets is the return value.
-**
-** INPUTS:
-** PRInt32 num
-** This argument is unused but is provided for select(unix) interface
-** compatability. All input PR_fd_set arguments are self-describing
-** with its own maximum number of elements in the set.
-**
-** PR_fd_set *readfds
-** A set describing the io descriptors for which ready for reading
-** condition is of interest.
-**
-** PR_fd_set *writefds
-** A set describing the io descriptors for which ready for writing
-** condition is of interest.
-**
-** PR_fd_set *exceptfds
-** A set describing the io descriptors for which exception pending
-** condition is of interest.
-**
-** Any of the above readfds, writefds or exceptfds may be given as NULL
-** pointers if no descriptors are of interest for that particular condition.
-**
-** PRIntervalTime timeout
-** Amount of time the call will block waiting for I/O to become ready.
-** If this time expires without any I/O becoming ready, the result will
-** be zero.
-**
-** OUTPUTS:
-** PR_fd_set *readfds
-** A set describing the io descriptors which are ready for reading.
-**
-** PR_fd_set *writefds
-** A set describing the io descriptors which are ready for writing.
-**
-** PR_fd_set *exceptfds
-** A set describing the io descriptors which have pending exception.
-**
-** RETURN:PRInt32
-** Number of io descriptors with asked for conditions or zero if the function
-** timed out or -1 on failure. The reason for the failure is obtained by
-** calling PR_GetError().
-** XXX can we implement this on windoze and mac?
-**************************************************************************
-*/
-NSPR_API(PRInt32) PR_Select(
- PRInt32 num, PR_fd_set *readfds, PR_fd_set *writefds,
- PR_fd_set *exceptfds, PRIntervalTime timeout);
-
-/*
-** The following are not thread safe for two threads operating on them at the
-** same time.
-**
-** The following routines are provided for manipulating io descriptor sets.
-** PR_FD_ZERO(&fdset) initializes a descriptor set fdset to the null set.
-** PR_FD_SET(fd, &fdset) includes a particular file descriptor fd in fdset.
-** PR_FD_CLR(fd, &fdset) removes a file descriptor fd from fdset.
-** PR_FD_ISSET(fd, &fdset) is nonzero if file descriptor fd is a member of
-** fdset, zero otherwise.
-**
-** PR_FD_NSET(osfd, &fdset) includes a particular native file descriptor osfd
-** in fdset.
-** PR_FD_NCLR(osfd, &fdset) removes a native file descriptor osfd from fdset.
-** PR_FD_NISSET(osfd, &fdset) is nonzero if native file descriptor osfd is a member of
-** fdset, zero otherwise.
-*/
-
-NSPR_API(void) PR_FD_ZERO(PR_fd_set *set);
-NSPR_API(void) PR_FD_SET(PRFileDesc *fd, PR_fd_set *set);
-NSPR_API(void) PR_FD_CLR(PRFileDesc *fd, PR_fd_set *set);
-NSPR_API(PRInt32) PR_FD_ISSET(PRFileDesc *fd, PR_fd_set *set);
-NSPR_API(void) PR_FD_NSET(PROsfd osfd, PR_fd_set *set);
-NSPR_API(void) PR_FD_NCLR(PROsfd osfd, PR_fd_set *set);
-NSPR_API(PRInt32) PR_FD_NISSET(PROsfd osfd, PR_fd_set *set);
-
-/*
-** The next two entry points should not be in the API, but they are
-** declared here for historical reasons.
-*/
-
-NSPR_API(PRInt32) PR_GetSysfdTableMax(void);
-
-NSPR_API(PRInt32) PR_SetSysfdTableSize(PRIntn table_size);
-
-#ifndef NO_NSPR_10_SUPPORT
-#include <sys/stat.h>
-
-NSPR_API(PRInt32) PR_Stat(const char *path, struct stat *buf);
-#endif /* NO_NSPR_10_SUPPORT */
-
-PR_END_EXTERN_C
-
-#endif /* defined(PROBSLET_H) */
-
-/* probslet.h */
diff --git a/nspr/pr/include/obsolete/protypes.h b/nspr/pr/include/obsolete/protypes.h
deleted file mode 100644
index 2275bce..0000000
--- a/nspr/pr/include/obsolete/protypes.h
+++ /dev/null
@@ -1,199 +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/. */
-
-/*
- * This header typedefs the old 'native' types to the new PR<type>s.
- * These definitions are scheduled to be eliminated at the earliest
- * possible time. The NSPR API is implemented and documented using
- * the new definitions.
- */
-
-#if !defined(PROTYPES_H)
-#define PROTYPES_H
-
-typedef PRUintn uintn;
-#ifndef _XP_Core_
-typedef PRIntn intn;
-#endif
-
-/*
- * It is trickier to define uint, int8, uint8, int16, uint16,
- * int32, uint32, int64, and uint64 because some of these int
- * types are defined by standard header files on some platforms.
- * Our strategy here is to include all such standard headers
- * first, and then define these int types only if they are not
- * defined by those standard headers.
- */
-
-/*
- * BeOS defines all the int types below in its standard header
- * file SupportDefs.h.
- */
-#ifdef XP_BEOS
-#include <support/SupportDefs.h>
-#endif
-
-/*
- * SVR4 typedef of uint is commonly found on UNIX machines.
- *
- * On AIX 4.3, sys/inttypes.h (which is included by sys/types.h)
- * defines the types int8, int16, int32, and int64.
- *
- * On OS/2, sys/types.h defines uint.
- */
-#if defined(XP_UNIX) || defined(XP_OS2)
-#include <sys/types.h>
-#endif
-
-/* model.h on HP-UX defines int8, int16, and int32. */
-#ifdef HPUX
-#include <model.h>
-#endif
-
-/*
- * uint
- */
-
-#if !defined(XP_BEOS) && !defined(XP_OS2) && !defined(XP_UNIX) || defined(NTO)
-typedef PRUintn uint;
-#endif
-
-/*
- * uint64
- */
-
-#if !defined(XP_BEOS)
-typedef PRUint64 uint64;
-#endif
-
-/*
- * uint32
- */
-
-#if !defined(XP_BEOS)
-#if !defined(_WIN32) && !defined(XP_OS2) && !defined(NTO)
-typedef PRUint32 uint32;
-#else
-typedef unsigned long uint32;
-#endif
-#endif
-
-/*
- * uint16
- */
-
-#if !defined(XP_BEOS)
-typedef PRUint16 uint16;
-#endif
-
-/*
- * uint8
- */
-
-#if !defined(XP_BEOS)
-typedef PRUint8 uint8;
-#endif
-
-/*
- * int64
- */
-
-#if !defined(XP_BEOS) && !defined(_PR_AIX_HAVE_BSD_INT_TYPES)
-typedef PRInt64 int64;
-#endif
-
-/*
- * int32
- */
-
-#if !defined(XP_BEOS) && !defined(_PR_AIX_HAVE_BSD_INT_TYPES) \
- && !defined(HPUX)
-#if !defined(_WIN32) && !defined(XP_OS2) && !defined(NTO)
-typedef PRInt32 int32;
-#else
-typedef long int32;
-#endif
-#endif
-
-/*
- * int16
- */
-
-#if !defined(XP_BEOS) && !defined(_PR_AIX_HAVE_BSD_INT_TYPES) \
- && !defined(HPUX)
-typedef PRInt16 int16;
-#endif
-
-/*
- * int8
- */
-
-#if !defined(XP_BEOS) && !defined(_PR_AIX_HAVE_BSD_INT_TYPES) \
- && !defined(HPUX)
-typedef PRInt8 int8;
-#endif
-
-typedef PRFloat64 float64;
-typedef PRUptrdiff uptrdiff_t;
-typedef PRUword uprword_t;
-typedef PRWord prword_t;
-
-
-/* Re: prbit.h */
-#define TEST_BIT PR_TEST_BIT
-#define SET_BIT PR_SET_BIT
-#define CLEAR_BIT PR_CLEAR_BIT
-
-/* Re: prarena.h->plarena.h */
-#define PRArena PLArena
-#define PRArenaPool PLArenaPool
-#define PRArenaStats PLArenaStats
-#define PR_ARENA_ALIGN PL_ARENA_ALIGN
-#define PR_INIT_ARENA_POOL PL_INIT_ARENA_POOL
-#define PR_ARENA_ALLOCATE PL_ARENA_ALLOCATE
-#define PR_ARENA_GROW PL_ARENA_GROW
-#define PR_ARENA_MARK PL_ARENA_MARK
-#define PR_CLEAR_UNUSED PL_CLEAR_UNUSED
-#define PR_CLEAR_ARENA PL_CLEAR_ARENA
-#define PR_ARENA_RELEASE PL_ARENA_RELEASE
-#define PR_COUNT_ARENA PL_COUNT_ARENA
-#define PR_ARENA_DESTROY PL_ARENA_DESTROY
-#define PR_InitArenaPool PL_InitArenaPool
-#define PR_FreeArenaPool PL_FreeArenaPool
-#define PR_FinishArenaPool PL_FinishArenaPool
-#define PR_CompactArenaPool PL_CompactArenaPool
-#define PR_ArenaFinish PL_ArenaFinish
-#define PR_ArenaAllocate PL_ArenaAllocate
-#define PR_ArenaGrow PL_ArenaGrow
-#define PR_ArenaRelease PL_ArenaRelease
-#define PR_ArenaCountAllocation PL_ArenaCountAllocation
-#define PR_ArenaCountInplaceGrowth PL_ArenaCountInplaceGrowth
-#define PR_ArenaCountGrowth PL_ArenaCountGrowth
-#define PR_ArenaCountRelease PL_ArenaCountRelease
-#define PR_ArenaCountRetract PL_ArenaCountRetract
-
-/* Re: prhash.h->plhash.h */
-#define PRHashEntry PLHashEntry
-#define PRHashTable PLHashTable
-#define PRHashNumber PLHashNumber
-#define PRHashFunction PLHashFunction
-#define PRHashComparator PLHashComparator
-#define PRHashEnumerator PLHashEnumerator
-#define PRHashAllocOps PLHashAllocOps
-#define PR_NewHashTable PL_NewHashTable
-#define PR_HashTableDestroy PL_HashTableDestroy
-#define PR_HashTableRawLookup PL_HashTableRawLookup
-#define PR_HashTableRawAdd PL_HashTableRawAdd
-#define PR_HashTableRawRemove PL_HashTableRawRemove
-#define PR_HashTableAdd PL_HashTableAdd
-#define PR_HashTableRemove PL_HashTableRemove
-#define PR_HashTableEnumerateEntries PL_HashTableEnumerateEntries
-#define PR_HashTableLookup PL_HashTableLookup
-#define PR_HashTableDump PL_HashTableDump
-#define PR_HashString PL_HashString
-#define PR_CompareStrings PL_CompareStrings
-#define PR_CompareValues PL_CompareValues
-
-#endif /* !defined(PROTYPES_H) */
diff --git a/nspr/pr/include/obsolete/prsem.h b/nspr/pr/include/obsolete/prsem.h
deleted file mode 100644
index ee313cb..0000000
--- a/nspr/pr/include/obsolete/prsem.h
+++ /dev/null
@@ -1,64 +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/. */
-
-#ifndef prsem_h___
-#define prsem_h___
-
-/*
-** API for counting semaphores. Semaphores are counting synchronizing
-** variables based on a lock and a condition variable. They are lightweight
-** contention control for a given count of resources.
-*/
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-typedef struct PRSemaphore PRSemaphore;
-
-/*
-** Create a new semaphore object.
-*/
-NSPR_API(PRSemaphore*) PR_NewSem(PRUintn value);
-
-/*
-** Destroy the given semaphore object.
-**
-*/
-NSPR_API(void) PR_DestroySem(PRSemaphore *sem);
-
-/*
-** Wait on a Semaphore.
-**
-** This routine allows a calling thread to wait or proceed depending upon the
-** state of the semahore sem. The thread can proceed only if the counter value
-** of the semaphore sem is currently greater than 0. If the value of semaphore
-** sem is positive, it is decremented by one and the routine returns immediately
-** allowing the calling thread to continue. If the value of semaphore sem is 0,
-** the calling thread blocks awaiting the semaphore to be released by another
-** thread.
-**
-** This routine can return PR_PENDING_INTERRUPT if the waiting thread
-** has been interrupted.
-*/
-NSPR_API(PRStatus) PR_WaitSem(PRSemaphore *sem);
-
-/*
-** This routine increments the counter value of the semaphore. If other threads
-** are blocked for the semaphore, then the scheduler will determine which ONE
-** thread will be unblocked.
-*/
-NSPR_API(void) PR_PostSem(PRSemaphore *sem);
-
-/*
-** Returns the value of the semaphore referenced by sem without affecting
-** the state of the semaphore. The value represents the semaphore vaule
-F** at the time of the call, but may not be the actual value when the
-** caller inspects it.
-*/
-NSPR_API(PRUintn) PR_GetValueSem(PRSemaphore *sem);
-
-PR_END_EXTERN_C
-
-#endif /* prsem_h___ */
diff --git a/nspr/pr/include/pratom.h b/nspr/pr/include/pratom.h
deleted file mode 100644
index dff9d6c..0000000
--- a/nspr/pr/include/pratom.h
+++ /dev/null
@@ -1,198 +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/. */
-
-/* GLOBAL FUNCTIONS:
-** DESCRIPTION:
-** PR Atomic operations
-*/
-
-#ifndef pratom_h___
-#define pratom_h___
-
-#include "prtypes.h"
-#include "prlock.h"
-
-PR_BEGIN_EXTERN_C
-
-/*
-** FUNCTION: PR_AtomicIncrement
-** DESCRIPTION:
-** Atomically increment a 32 bit value.
-** INPUTS:
-** val: a pointer to the value to increment
-** RETURN:
-** the returned value is the result of the increment
-*/
-NSPR_API(PRInt32) PR_AtomicIncrement(PRInt32 *val);
-
-/*
-** FUNCTION: PR_AtomicDecrement
-** DESCRIPTION:
-** Atomically decrement a 32 bit value.
-** INPUTS:
-** val: a pointer to the value to decrement
-** RETURN:
-** the returned value is the result of the decrement
-*/
-NSPR_API(PRInt32) PR_AtomicDecrement(PRInt32 *val);
-
-/*
-** FUNCTION: PR_AtomicSet
-** DESCRIPTION:
-** Atomically set a 32 bit value.
-** INPUTS:
-** val: A pointer to a 32 bit value to be set
-** newval: The newvalue to assign to val
-** RETURN:
-** Returns the prior value
-*/
-NSPR_API(PRInt32) PR_AtomicSet(PRInt32 *val, PRInt32 newval);
-
-/*
-** FUNCTION: PR_AtomicAdd
-** DESCRIPTION:
-** Atomically add a 32 bit value.
-** INPUTS:
-** ptr: a pointer to the value to increment
-** val: value to be added
-** RETURN:
-** the returned value is the result of the addition
-*/
-NSPR_API(PRInt32) PR_AtomicAdd(PRInt32 *ptr, PRInt32 val);
-
-/*
-** MACRO: PR_ATOMIC_INCREMENT
-** MACRO: PR_ATOMIC_DECREMENT
-** MACRO: PR_ATOMIC_SET
-** MACRO: PR_ATOMIC_ADD
-** DESCRIPTION:
-** Macro versions of the atomic operations. They may be implemented
-** as compiler intrinsics.
-**
-** IMPORTANT NOTE TO NSPR MAINTAINERS:
-** Implement these macros with compiler intrinsics only on platforms
-** where the PR_AtomicXXX functions are truly atomic (i.e., where the
-** configuration macro _PR_HAVE_ATOMIC_OPS is defined). Otherwise,
-** the macros and functions won't be compatible and can't be used
-** interchangeably.
-*/
-#if defined(_WIN32) && !defined(_WIN32_WCE) && \
- (!defined(_MSC_VER) || (_MSC_VER >= 1310))
-
-#include <intrin.h>
-
-#ifdef _MSC_VER
-#pragma intrinsic(_InterlockedIncrement)
-#pragma intrinsic(_InterlockedDecrement)
-#pragma intrinsic(_InterlockedExchange)
-#pragma intrinsic(_InterlockedExchangeAdd)
-#endif
-
-#define PR_ATOMIC_INCREMENT(val) _InterlockedIncrement((long volatile *)(val))
-#define PR_ATOMIC_DECREMENT(val) _InterlockedDecrement((long volatile *)(val))
-#define PR_ATOMIC_SET(val, newval) \
- _InterlockedExchange((long volatile *)(val), (long)(newval))
-#define PR_ATOMIC_ADD(ptr, val) \
- (_InterlockedExchangeAdd((long volatile *)(ptr), (long)(val)) + (val))
-
-#elif ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) && \
- ((defined(__APPLE__) && \
- (defined(__ppc__) || defined(__i386__) || defined(__x86_64__))) || \
- (defined(__linux__) && \
- ((defined(__i386__) && \
- defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)) || \
- defined(__ia64__) || defined(__x86_64__) || \
- defined(__powerpc__) || \
- (defined(__arm__) && \
- defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)) || \
- defined(__aarch64__) || defined(__alpha) || \
- (defined(__mips__) && \
- defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)))))
-
-/*
- * Because the GCC manual warns that some processors may support
- * reduced functionality of __sync_lock_test_and_set, we test for the
- * processors that we believe support a full atomic exchange operation.
- */
-
-#define PR_ATOMIC_INCREMENT(val) __sync_add_and_fetch(val, 1)
-#define PR_ATOMIC_DECREMENT(val) __sync_sub_and_fetch(val, 1)
-#define PR_ATOMIC_SET(val, newval) __sync_lock_test_and_set(val, newval)
-#define PR_ATOMIC_ADD(ptr, val) __sync_add_and_fetch(ptr, val)
-
-#else
-
-#define PR_ATOMIC_INCREMENT(val) PR_AtomicIncrement(val)
-#define PR_ATOMIC_DECREMENT(val) PR_AtomicDecrement(val)
-#define PR_ATOMIC_SET(val, newval) PR_AtomicSet(val, newval)
-#define PR_ATOMIC_ADD(ptr, val) PR_AtomicAdd(ptr, val)
-
-#endif
-
-/*
-** LIFO linked-list (stack)
-*/
-typedef struct PRStackElemStr PRStackElem;
-
-struct PRStackElemStr {
- PRStackElem *prstk_elem_next; /* next pointer MUST be at offset 0;
- assembly language code relies on this */
-};
-
-typedef struct PRStackStr PRStack;
-
-/*
-** FUNCTION: PR_CreateStack
-** DESCRIPTION:
-** Create a stack, a LIFO linked list
-** INPUTS:
-** stack_name: a pointer to string containing the name of the stack
-** RETURN:
-** A pointer to the created stack, if successful, else NULL.
-*/
-NSPR_API(PRStack *) PR_CreateStack(const char *stack_name);
-
-/*
-** FUNCTION: PR_StackPush
-** DESCRIPTION:
-** Push an element on the top of the stack
-** INPUTS:
-** stack: pointer to the stack
-** stack_elem: pointer to the stack element
-** RETURN:
-** None
-*/
-NSPR_API(void) PR_StackPush(PRStack *stack, PRStackElem *stack_elem);
-
-/*
-** FUNCTION: PR_StackPop
-** DESCRIPTION:
-** Remove the element on the top of the stack
-** INPUTS:
-** stack: pointer to the stack
-** RETURN:
-** A pointer to the stack element removed from the top of the stack,
-** if non-empty,
-** else NULL
-*/
-NSPR_API(PRStackElem *) PR_StackPop(PRStack *stack);
-
-/*
-** FUNCTION: PR_DestroyStack
-** DESCRIPTION:
-** Destroy the stack
-** INPUTS:
-** stack: pointer to the stack
-** RETURN:
-** PR_SUCCESS - if successfully deleted
-** PR_FAILURE - if the stack is not empty
-** PR_GetError will return
-** PR_INVALID_STATE_ERROR - stack is not empty
-*/
-NSPR_API(PRStatus) PR_DestroyStack(PRStack *stack);
-
-PR_END_EXTERN_C
-
-#endif /* pratom_h___ */
diff --git a/nspr/pr/include/prbit.h b/nspr/pr/include/prbit.h
deleted file mode 100644
index 0434fc6..0000000
--- a/nspr/pr/include/prbit.h
+++ /dev/null
@@ -1,150 +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/. */
-
-#ifndef prbit_h___
-#define prbit_h___
-
-#include "prtypes.h"
-PR_BEGIN_EXTERN_C
-
-/*
-** Replace compare/jump/add/shift sequence with compiler built-in/intrinsic
-** functions.
-*/
-#if defined(_WIN32) && (_MSC_VER >= 1300) && \
- (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_ARM))
-# include <intrin.h>
-# pragma intrinsic(_BitScanForward,_BitScanReverse)
- __forceinline static int __prBitScanForward32(unsigned int val)
- {
- unsigned long idx;
- _BitScanForward(&idx, (unsigned long)val);
- return( (int)idx );
- }
- __forceinline static int __prBitScanReverse32(unsigned int val)
- {
- unsigned long idx;
- _BitScanReverse(&idx, (unsigned long)val);
- return( (int)(31-idx) );
- }
-# define pr_bitscan_ctz32(val) __prBitScanForward32(val)
-# define pr_bitscan_clz32(val) __prBitScanReverse32(val)
-# define PR_HAVE_BUILTIN_BITSCAN32
-#elif ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) && \
- (defined(__i386__) || defined(__x86_64__) || defined(__arm__))
-# define pr_bitscan_ctz32(val) __builtin_ctz(val)
-# define pr_bitscan_clz32(val) __builtin_clz(val)
-# define PR_HAVE_BUILTIN_BITSCAN32
-#endif /* MSVC || GCC */
-
-/*
-** A prbitmap_t is a long integer that can be used for bitmaps
-*/
-typedef unsigned long prbitmap_t;
-
-#define PR_TEST_BIT(_map,_bit) \
- ((_map)[(_bit)>>PR_BITS_PER_LONG_LOG2] & (1L << ((_bit) & (PR_BITS_PER_LONG-1))))
-#define PR_SET_BIT(_map,_bit) \
- ((_map)[(_bit)>>PR_BITS_PER_LONG_LOG2] |= (1L << ((_bit) & (PR_BITS_PER_LONG-1))))
-#define PR_CLEAR_BIT(_map,_bit) \
- ((_map)[(_bit)>>PR_BITS_PER_LONG_LOG2] &= ~(1L << ((_bit) & (PR_BITS_PER_LONG-1))))
-
-/*
-** Compute the log of the least power of 2 greater than or equal to n
-*/
-NSPR_API(PRIntn) PR_CeilingLog2(PRUint32 i);
-
-/*
-** Compute the log of the greatest power of 2 less than or equal to n
-*/
-NSPR_API(PRIntn) PR_FloorLog2(PRUint32 i);
-
-/*
-** Macro version of PR_CeilingLog2: Compute the log of the least power of
-** 2 greater than or equal to _n. The result is returned in _log2.
-*/
-#ifdef PR_HAVE_BUILTIN_BITSCAN32
-#define PR_CEILING_LOG2(_log2,_n) \
- PR_BEGIN_MACRO \
- PRUint32 j_ = (PRUint32)(_n); \
- (_log2) = (j_ <= 1 ? 0 : 32 - pr_bitscan_clz32(j_ - 1)); \
- PR_END_MACRO
-#else
-#define PR_CEILING_LOG2(_log2,_n) \
- PR_BEGIN_MACRO \
- PRUint32 j_ = (PRUint32)(_n); \
- (_log2) = 0; \
- if ((j_) & ((j_)-1)) \
- (_log2) += 1; \
- if ((j_) >> 16) \
- (_log2) += 16, (j_) >>= 16; \
- if ((j_) >> 8) \
- (_log2) += 8, (j_) >>= 8; \
- if ((j_) >> 4) \
- (_log2) += 4, (j_) >>= 4; \
- if ((j_) >> 2) \
- (_log2) += 2, (j_) >>= 2; \
- if ((j_) >> 1) \
- (_log2) += 1; \
- PR_END_MACRO
-#endif /* PR_HAVE_BUILTIN_BITSCAN32 */
-
-/*
-** Macro version of PR_FloorLog2: Compute the log of the greatest power of
-** 2 less than or equal to _n. The result is returned in _log2.
-**
-** This is equivalent to finding the highest set bit in the word.
-*/
-#ifdef PR_HAVE_BUILTIN_BITSCAN32
-#define PR_FLOOR_LOG2(_log2,_n) \
- PR_BEGIN_MACRO \
- PRUint32 j_ = (PRUint32)(_n); \
- (_log2) = 31 - pr_bitscan_clz32((j_) | 1); \
- PR_END_MACRO
-#else
-#define PR_FLOOR_LOG2(_log2,_n) \
- PR_BEGIN_MACRO \
- PRUint32 j_ = (PRUint32)(_n); \
- (_log2) = 0; \
- if ((j_) >> 16) \
- (_log2) += 16, (j_) >>= 16; \
- if ((j_) >> 8) \
- (_log2) += 8, (j_) >>= 8; \
- if ((j_) >> 4) \
- (_log2) += 4, (j_) >>= 4; \
- if ((j_) >> 2) \
- (_log2) += 2, (j_) >>= 2; \
- if ((j_) >> 1) \
- (_log2) += 1; \
- PR_END_MACRO
-#endif /* PR_HAVE_BUILTIN_BITSCAN32 */
-
-/*
-** Macros for rotate left and right. The argument 'a' must be an unsigned
-** 32-bit integer type such as PRUint32.
-**
-** There is no rotate operation in the C Language, so the construct
-** (a << 4) | (a >> 28) is frequently used instead. Most compilers convert
-** this to a rotate instruction, but MSVC doesn't without a little help.
-** To get MSVC to generate a rotate instruction, we have to use the _rotl
-** or _rotr intrinsic and use a pragma to make it inline.
-**
-** Note: MSVC in VS2005 will do an inline rotate instruction on the above
-** construct.
-*/
-
-#if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_AMD64) || \
- defined(_M_X64) || defined(_M_ARM))
-#include <stdlib.h>
-#pragma intrinsic(_rotl, _rotr)
-#define PR_ROTATE_LEFT32(a, bits) _rotl(a, bits)
-#define PR_ROTATE_RIGHT32(a, bits) _rotr(a, bits)
-#else
-#define PR_ROTATE_LEFT32(a, bits) (((a) << (bits)) | ((a) >> (32 - (bits))))
-#define PR_ROTATE_RIGHT32(a, bits) (((a) >> (bits)) | ((a) << (32 - (bits))))
-#endif
-
-PR_END_EXTERN_C
-#endif /* prbit_h___ */
diff --git a/nspr/pr/include/prclist.h b/nspr/pr/include/prclist.h
deleted file mode 100644
index 2324722..0000000
--- a/nspr/pr/include/prclist.h
+++ /dev/null
@@ -1,108 +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/. */
-
-#ifndef prclist_h___
-#define prclist_h___
-
-#include "prtypes.h"
-
-typedef struct PRCListStr PRCList;
-
-/*
-** Circular linked list
-*/
-struct PRCListStr {
- PRCList *next;
- PRCList *prev;
-};
-
-/*
-** Insert element "_e" into the list, before "_l".
-*/
-#define PR_INSERT_BEFORE(_e,_l) \
- PR_BEGIN_MACRO \
- (_e)->next = (_l); \
- (_e)->prev = (_l)->prev; \
- (_l)->prev->next = (_e); \
- (_l)->prev = (_e); \
- PR_END_MACRO
-
-/*
-** Insert element "_e" into the list, after "_l".
-*/
-#define PR_INSERT_AFTER(_e,_l) \
- PR_BEGIN_MACRO \
- (_e)->next = (_l)->next; \
- (_e)->prev = (_l); \
- (_l)->next->prev = (_e); \
- (_l)->next = (_e); \
- PR_END_MACRO
-
-/*
-** Return the element following element "_e"
-*/
-#define PR_NEXT_LINK(_e) \
- ((_e)->next)
-/*
-** Return the element preceding element "_e"
-*/
-#define PR_PREV_LINK(_e) \
- ((_e)->prev)
-
-/*
-** Append an element "_e" to the end of the list "_l"
-*/
-#define PR_APPEND_LINK(_e,_l) PR_INSERT_BEFORE(_e,_l)
-
-/*
-** Insert an element "_e" at the head of the list "_l"
-*/
-#define PR_INSERT_LINK(_e,_l) PR_INSERT_AFTER(_e,_l)
-
-/* Return the head/tail of the list */
-#define PR_LIST_HEAD(_l) (_l)->next
-#define PR_LIST_TAIL(_l) (_l)->prev
-
-/*
-** Remove the element "_e" from it's circular list.
-*/
-#define PR_REMOVE_LINK(_e) \
- PR_BEGIN_MACRO \
- (_e)->prev->next = (_e)->next; \
- (_e)->next->prev = (_e)->prev; \
- PR_END_MACRO
-
-/*
-** Remove the element "_e" from it's circular list. Also initializes the
-** linkage.
-*/
-#define PR_REMOVE_AND_INIT_LINK(_e) \
- PR_BEGIN_MACRO \
- (_e)->prev->next = (_e)->next; \
- (_e)->next->prev = (_e)->prev; \
- (_e)->next = (_e); \
- (_e)->prev = (_e); \
- PR_END_MACRO
-
-/*
-** Return non-zero if the given circular list "_l" is empty, zero if the
-** circular list is not empty
-*/
-#define PR_CLIST_IS_EMPTY(_l) \
- ((_l)->next == (_l))
-
-/*
-** Initialize a circular list
-*/
-#define PR_INIT_CLIST(_l) \
- PR_BEGIN_MACRO \
- (_l)->next = (_l); \
- (_l)->prev = (_l); \
- PR_END_MACRO
-
-#define PR_INIT_STATIC_CLIST(_l) \
- {(_l), (_l)}
-
-#endif /* prclist_h___ */
diff --git a/nspr/pr/include/prcmon.h b/nspr/pr/include/prcmon.h
deleted file mode 100644
index 6917113..0000000
--- a/nspr/pr/include/prcmon.h
+++ /dev/null
@@ -1,66 +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/. */
-
-#ifndef prcmon_h___
-#define prcmon_h___
-
-/*
-** Interface to cached monitors. Cached monitors use an address to find a
-** given PR monitor. In this way a monitor can be associated with another
-** object without preallocating a monitor for all objects.
-**
-** A hash table is used to quickly map addresses to individual monitors
-** and the system automatically grows the hash table as needed.
-**
-** Cache monitors are about 5 times slower to use than uncached monitors.
-*/
-#include "prmon.h"
-#include "prinrval.h"
-
-PR_BEGIN_EXTERN_C
-
-/**
-** Like PR_EnterMonitor except use the "address" to find a monitor in the
-** monitor cache. If successful, returns the PRMonitor now associated
-** with "address". Note that you must PR_CExitMonitor the address to
-** release the monitor cache entry (otherwise the monitor cache will fill
-** up). This call will return NULL if the monitor cache needs to be
-** expanded and the system is out of memory.
-*/
-NSPR_API(PRMonitor*) PR_CEnterMonitor(void *address);
-
-/*
-** Like PR_ExitMonitor except use the "address" to find a monitor in the
-** monitor cache.
-*/
-NSPR_API(PRStatus) PR_CExitMonitor(void *address);
-
-/*
-** Like PR_Wait except use the "address" to find a monitor in the
-** monitor cache.
-*/
-NSPR_API(PRStatus) PR_CWait(void *address, PRIntervalTime timeout);
-
-/*
-** Like PR_Notify except use the "address" to find a monitor in the
-** monitor cache.
-*/
-NSPR_API(PRStatus) PR_CNotify(void *address);
-
-/*
-** Like PR_NotifyAll except use the "address" to find a monitor in the
-** monitor cache.
-*/
-NSPR_API(PRStatus) PR_CNotifyAll(void *address);
-
-/*
-** Set a callback to be invoked each time a monitor is recycled from the cache
-** freelist, with the monitor's cache-key passed in address.
-*/
-NSPR_API(void) PR_CSetOnMonitorRecycle(void (PR_CALLBACK *callback)(void *address));
-
-PR_END_EXTERN_C
-
-#endif /* prcmon_h___ */
diff --git a/nspr/pr/include/prcountr.h b/nspr/pr/include/prcountr.h
deleted file mode 100644
index 53b6176..0000000
--- a/nspr/pr/include/prcountr.h
+++ /dev/null
@@ -1,525 +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/. */
-
-#ifndef prcountr_h___
-#define prcountr_h___
-
-/*----------------------------------------------------------------------------
-** prcountr.h -- NSPR Instrumentation counters
-**
-** The NSPR Counter Feature provides a means to "count
-** something." Counters can be dynamically defined, incremented,
-** decremented, set, and deleted under application program
-** control.
-**
-** The Counter Feature is intended to be used as instrumentation,
-** not as operational data. If you need a counter for operational
-** data, use native integral types.
-**
-** Counters are 32bit unsigned intergers. On overflow, a counter
-** will wrap. No exception is recognized or reported.
-**
-** A counter can be dynamically created using a two level naming
-** convention. A "handle" is returned when the counter is
-** created. The counter can subsequently be addressed by its
-** handle. An API is provided to get an existing counter's handle
-** given the names with which it was originally created.
-** Similarly, a counter's name can be retrieved given its handle.
-**
-** The counter naming convention is a two-level hierarchy. The
-** QName is the higher level of the hierarchy; RName is the
-** lower level. RNames can be thought of as existing within a
-** QName. The same RName can exist within multiple QNames. QNames
-** are unique. The NSPR Counter is not a near-zero overhead
-** feature. Application designers should be aware of
-** serialization issues when using the Counter API. Creating a
-** counter locks a large asset, potentially causing a stall. This
-** suggest that applications should create counters at component
-** initialization, for example, and not create and destroy them
-** willy-nilly. ... You have been warned.
-**
-** Incrementing and Adding to counters uses atomic operations.
-** The performance of these operations will vary from platform
-** to platform. On platforms where atomic operations are not
-** supported the overhead may be substantial.
-**
-** When traversing the counter database with FindNext functions,
-** the instantaneous values of any given counter is that at the
-** moment of extraction. The state of the entire counter database
-** may not be viewed as atomic.
-**
-** The counter interface may be disabled (No-Op'd) at compile
-** time. When DEBUG is defined at compile time, the Counter
-** Feature is compiled into NSPR and applications invoking it.
-** When DEBUG is not defined, the counter macros compile to
-** nothing. To force the Counter Feature to be compiled into an
-** optimized build, define FORCE_NSPR_COUNTERS at compile time
-** for both NSPR and the application intending to use it.
-**
-** Application designers should use the macro form of the Counter
-** Feature methods to minimize performance impact in optimized
-** builds. The macros normally compile to nothing on optimized
-** builds.
-**
-** Application designers should be aware of the effects of
-** debug and optimized build differences when using result of the
-** Counter Feature macros in expressions.
-**
-** The Counter Feature is thread-safe and SMP safe.
-**
-** /lth. 09-Jun-1998.
-*/
-
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-/*
-** Opaque counter handle type.
-** ... don't even think of looking in here.
-**
-*/
-typedef void * PRCounterHandle;
-
-#define PRCOUNTER_NAME_MAX 31
-#define PRCOUNTER_DESC_MAX 255
-
-
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_DEFINE_COUNTER() -- Define a PRCounterHandle
-**
-** DESCRIPTION: PR_DEFINE_COUNTER() is used to define a counter
-** handle.
-**
-*/
-#define PR_DEFINE_COUNTER(name) PRCounterHandle name
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_INIT_COUNTER_HANDLE() -- Set the value of a PRCounterHandle
-**
-** DESCRIPTION:
-** PR_INIT_COUNTER_HANDLE() sets the value of a PRCounterHandle
-** to value.
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS)
-#define PR_INIT_COUNTER_HANDLE(handle,value)\
- (handle) = (PRCounterHandle)(value)
-#else
-#define PR_INIT_COUNTER_HANDLE(handle,value)
-#endif
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_CreateCounter() -- Create a counter
-**
-** DESCRIPTION: PR_CreateCounter() creates a counter object and
-** initializes it to zero.
-**
-** The macro form takes as its first argument the name of the
-** PRCounterHandle to receive the handle returned from
-** PR_CreateCounter().
-**
-** INPUTS:
-** qName: The QName for the counter object. The maximum length
-** of qName is defined by PRCOUNTER_NAME_MAX
-**
-** rName: The RName for the counter object. The maximum length
-** of qName is defined by PRCOUNTER_NAME_MAX
-**
-** descrioption: The description of the counter object. The
-** maximum length of description is defined by
-** PRCOUNTER_DESC_MAX.
-**
-** OUTPUTS:
-**
-** RETURNS:
-** PRCounterHandle.
-**
-** RESTRICTIONS:
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS)
-#define PR_CREATE_COUNTER(handle,qName,rName,description)\
- (handle) = PR_CreateCounter((qName),(rName),(description))
-#else
-#define PR_CREATE_COUNTER(handle,qName,rName,description)
-#endif
-
-NSPR_API(PRCounterHandle)
- PR_CreateCounter(
- const char *qName,
- const char *rName,
- const char *description
-);
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_DestroyCounter() -- Destroy a counter object.
-**
-** DESCRIPTION: PR_DestroyCounter() removes a counter and
-** unregisters its handle from the counter database.
-**
-** INPUTS:
-** handle: the PRCounterHandle of the counter to be destroyed.
-**
-** OUTPUTS:
-** The counter is destroyed.
-**
-** RETURNS: void
-**
-** RESTRICTIONS:
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS)
-#define PR_DESTROY_COUNTER(handle) PR_DestroyCounter((handle))
-#else
-#define PR_DESTROY_COUNTER(handle)
-#endif
-
-NSPR_API(void)
- PR_DestroyCounter(
- PRCounterHandle handle
-);
-
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_GetCounterHandleFromName() -- Retreive a
-** counter's handle give its name.
-**
-** DESCRIPTION: PR_GetCounterHandleFromName() retreives a
-** counter's handle from the counter database, given the name
-** the counter was originally created with.
-**
-** INPUTS:
-** qName: Counter's original QName.
-** rName: Counter's original RName.
-**
-** OUTPUTS:
-**
-** RETURNS:
-** PRCounterHandle or PRCounterError.
-**
-** RESTRICTIONS:
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS)
-#define PR_GET_COUNTER_HANDLE_FROM_NAME(handle,qName,rName)\
- (handle) = PR_GetCounterHandleFromName((qName),(rName))
-#else
-#define PR_GET_COUNTER_HANDLE_FROM_NAME(handle,qName,rName)
-#endif
-
-NSPR_API(PRCounterHandle)
- PR_GetCounterHandleFromName(
- const char *qName,
- const char *rName
-);
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_GetCounterNameFromHandle() -- Retreive a
-** counter's name, given its handle.
-**
-** DESCRIPTION: PR_GetCounterNameFromHandle() retreives a
-** counter's name given its handle.
-**
-** INPUTS:
-** qName: Where to store a pointer to qName.
-** rName: Where to store a pointer to rName.
-** description: Where to store a pointer to description.
-**
-** OUTPUTS: Pointers to the Counter Feature's copies of the names
-** used when the counters were created.
-**
-** RETURNS: void
-**
-** RESTRICTIONS:
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS)
-#define PR_GET_COUNTER_NAME_FROM_HANDLE(handle,qName,rName,description)\
- PR_GetCounterNameFromHandle((handle),(qName),(rName),(description))
-#else
-#define PR_GET_COUNTER_NAME_FROM_HANDLE(handle,qName,rName,description )
-#endif
-
-NSPR_API(void)
- PR_GetCounterNameFromHandle(
- PRCounterHandle handle,
- const char **qName,
- const char **rName,
- const char **description
-);
-
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_IncrementCounter() -- Add one to the referenced
-** counter.
-**
-** DESCRIPTION: Add one to the referenced counter.
-**
-** INPUTS:
-** handle: The PRCounterHandle of the counter to be incremented
-**
-** OUTPUTS: The counter is incrementd.
-**
-** RETURNS: void
-**
-** RESTRICTIONS:
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS)
-#define PR_INCREMENT_COUNTER(handle) PR_IncrementCounter(handle)
-#else
-#define PR_INCREMENT_COUNTER(handle)
-#endif
-
-NSPR_API(void)
- PR_IncrementCounter(
- PRCounterHandle handle
-);
-
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_DecrementCounter() -- Subtract one from the
-** referenced counter
-**
-** DESCRIPTION: Subtract one from the referenced counter.
-**
-** INPUTS:
-** handle: The PRCounterHandle of the coutner to be
-** decremented.
-**
-** OUTPUTS: the counter is decremented.
-**
-** RETURNS: void
-**
-** RESTRICTIONS:
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS)
-#define PR_DECREMENT_COUNTER(handle) PR_DecrementCounter(handle)
-#else
-#define PR_DECREMENT_COUNTER(handle)
-#endif
-
-NSPR_API(void)
- PR_DecrementCounter(
- PRCounterHandle handle
-);
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_AddToCounter() -- Add a value to a counter.
-**
-** DESCRIPTION: Add value to the counter referenced by handle.
-**
-** INPUTS:
-** handle: the PRCounterHandle of the counter to be added to.
-**
-** value: the value to be added to the counter.
-**
-** OUTPUTS: new value for counter.
-**
-** RETURNS: void
-**
-** RESTRICTIONS:
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS)
-#define PR_ADD_TO_COUNTER(handle,value)\
- PR_AddToCounter((handle),(value))
-#else
-#define PR_ADD_TO_COUNTER(handle,value)
-#endif
-
-NSPR_API(void)
- PR_AddToCounter(
- PRCounterHandle handle,
- PRUint32 value
-);
-
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_SubtractFromCounter() -- A value is subtracted
-** from a counter.
-**
-** DESCRIPTION:
-** Subtract a value from a counter.
-**
-** INPUTS:
-** handle: the PRCounterHandle of the counter to be subtracted
-** from.
-**
-** value: the value to be subtracted from the counter.
-**
-** OUTPUTS: new value for counter
-**
-** RETURNS: void
-**
-** RESTRICTIONS:
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS)
-#define PR_SUBTRACT_FROM_COUNTER(handle,value)\
- PR_SubtractFromCounter((handle),(value))
-#else
-#define PR_SUBTRACT_FROM_COUNTER(handle,value)
-#endif
-
-NSPR_API(void)
- PR_SubtractFromCounter(
- PRCounterHandle handle,
- PRUint32 value
-);
-
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_GetCounter() -- Retreive the value of a counter
-**
-** DESCRIPTION:
-** Retreive the value of a counter.
-**
-** INPUTS:
-** handle: the PR_CounterHandle of the counter to be retreived
-**
-** OUTPUTS:
-**
-** RETURNS: The value of the referenced counter
-**
-** RESTRICTIONS:
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS)
-#define PR_GET_COUNTER(counter,handle)\
- (counter) = PR_GetCounter((handle))
-#else
-#define PR_GET_COUNTER(counter,handle) 0
-#endif
-
-NSPR_API(PRUint32)
- PR_GetCounter(
- PRCounterHandle handle
-);
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_SetCounter() -- Replace the content of counter
-** with value.
-**
-** DESCRIPTION: The contents of the referenced counter are
-** replaced by value.
-**
-** INPUTS:
-** handle: the PRCounterHandle of the counter whose contents
-** are to be replaced.
-**
-** value: the new value of the counter.
-**
-** OUTPUTS:
-**
-** RETURNS: void
-**
-** RESTRICTIONS:
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS)
-#define PR_SET_COUNTER(handle,value) PR_SetCounter((handle),(value))
-#else
-#define PR_SET_COUNTER(handle,value)
-#endif
-
-NSPR_API(void)
- PR_SetCounter(
- PRCounterHandle handle,
- PRUint32 value
-);
-
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_FindNextCounterQname() -- Retreive the next QName counter
-** handle iterator
-**
-** DESCRIPTION:
-** PR_FindNextCounterQname() retreives the first or next Qname
-** the counter data base, depending on the value of handle. When
-** handle is NULL, the function attempts to retreive the first
-** QName handle in the database. When handle is a handle previosly
-** retreived QName handle, then the function attempts to retreive
-** the next QName handle.
-**
-** INPUTS:
-** handle: PRCounterHandle or NULL.
-**
-** OUTPUTS: returned
-**
-** RETURNS: PRCounterHandle or NULL when no more QName counter
-** handles are present.
-**
-** RESTRICTIONS:
-** A concurrent PR_CreateCounter() or PR_DestroyCounter() may
-** cause unpredictable results.
-**
-** A PRCounterHandle returned from this function may only be used
-** in another PR_FindNextCounterQname() function call; other
-** operations may cause unpredictable results.
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS)
-#define PR_FIND_NEXT_COUNTER_QNAME(next,handle)\
- (next) = PR_FindNextCounterQname((handle))
-#else
-#define PR_FIND_NEXT_COUNTER_QNAME(next,handle) NULL
-#endif
-
-NSPR_API(PRCounterHandle)
- PR_FindNextCounterQname(
- PRCounterHandle handle
-);
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_FindNextCounterRname() -- Retreive the next RName counter
-** handle iterator
-**
-** DESCRIPTION:
-** PR_FindNextCounterRname() retreives the first or next RNname
-** handle from the counter data base, depending on the
-** value of handle. When handle is NULL, the function attempts to
-** retreive the first RName handle in the database. When handle is
-** a handle previosly retreived RName handle, then the function
-** attempts to retreive the next RName handle.
-**
-** INPUTS:
-** handle: PRCounterHandle or NULL.
-** qhandle: PRCounterHandle of a previously aquired via
-** PR_FIND_NEXT_QNAME_HANDLE()
-**
-** OUTPUTS: returned
-**
-** RETURNS: PRCounterHandle or NULL when no more RName counter
-** handles are present.
-**
-** RESTRICTIONS:
-** A concurrent PR_CreateCounter() or PR_DestroyCounter() may
-** cause unpredictable results.
-**
-** A PRCounterHandle returned from this function may only be used
-** in another PR_FindNextCounterRname() function call; other
-** operations may cause unpredictable results.
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS)
-#define PR_FIND_NEXT_COUNTER_RNAME(next,rhandle,qhandle)\
- (next) = PR_FindNextCounterRname((rhandle),(qhandle))
-#else
-#define PR_FIND_NEXT_COUNTER_RNAME(next,rhandle,qhandle)
-#endif
-
-NSPR_API(PRCounterHandle)
- PR_FindNextCounterRname(
- PRCounterHandle rhandle,
- PRCounterHandle qhandle
-);
-
-PR_END_EXTERN_C
-
-#endif /* prcountr_h___ */
diff --git a/nspr/pr/include/prcpucfg.h b/nspr/pr/include/prcpucfg.h
deleted file mode 100644
index c1c37cc..0000000
--- a/nspr/pr/include/prcpucfg.h
+++ /dev/null
@@ -1,14 +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/. */
-
-#if defined(_WIN32)
-#include "md/_win95.cfg"
-#elif defined(__APPLE__)
-#include "md/_darwin.cfg"
-#elif defined(__linux__)
-#include "md/_linux.cfg"
-#else
-#error Add a case for your platform
-#endif
diff --git a/nspr/pr/include/prcvar.h b/nspr/pr/include/prcvar.h
deleted file mode 100644
index 3e30ce1..0000000
--- a/nspr/pr/include/prcvar.h
+++ /dev/null
@@ -1,94 +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/. */
-
-#ifndef prcvar_h___
-#define prcvar_h___
-
-#include "prlock.h"
-#include "prinrval.h"
-
-PR_BEGIN_EXTERN_C
-
-typedef struct PRCondVar PRCondVar;
-
-/*
-** Create a new condition variable.
-**
-** "lock" is the lock used to protect the condition variable.
-**
-** Condition variables are synchronization objects that threads can use
-** to wait for some condition to occur.
-**
-** This may fail if memory is tight or if some operating system resource
-** is low. In such cases, a NULL will be returned.
-*/
-NSPR_API(PRCondVar*) PR_NewCondVar(PRLock *lock);
-
-/*
-** Destroy a condition variable. There must be no thread
-** waiting on the condvar. The caller is responsible for guaranteeing
-** that the condvar is no longer in use.
-**
-*/
-NSPR_API(void) PR_DestroyCondVar(PRCondVar *cvar);
-
-/*
-** The thread that waits on a condition is blocked in a "waiting on
-** condition" state until another thread notifies the condition or a
-** caller specified amount of time expires. The lock associated with
-** the condition variable will be released, which must have be held
-** prior to the call to wait.
-**
-** Logically a notified thread is moved from the "waiting on condition"
-** state and made "ready." When scheduled, it will attempt to reacquire
-** the lock that it held when wait was called.
-**
-** The timeout has two well known values, PR_INTERVAL_NO_TIMEOUT and
-** PR_INTERVAL_NO_WAIT. The former value requires that a condition be
-** notified (or the thread interrupted) before it will resume from the
-** wait. If the timeout has a value of PR_INTERVAL_NO_WAIT, the effect
-** is to release the lock, possibly causing a rescheduling within the
-** runtime, then immediately attempting to reacquire the lock and resume.
-**
-** Any other value for timeout will cause the thread to be rescheduled
-** either due to explicit notification or an expired interval. The latter
-** must be determined by treating time as one part of the monitored data
-** being protected by the lock and tested explicitly for an expired
-** interval.
-**
-** Returns PR_FAILURE if the caller has not locked the lock associated
-** with the condition variable or the thread was interrupted (PR_Interrupt()).
-** The particular reason can be extracted with PR_GetError().
-*/
-NSPR_API(PRStatus) PR_WaitCondVar(PRCondVar *cvar, PRIntervalTime timeout);
-
-/*
-** Notify ONE thread that is currently waiting on 'cvar'. Which thread is
-** dependent on the implementation of the runtime. Common sense would dictate
-** that all threads waiting on a single condition have identical semantics,
-** therefore which one gets notified is not significant.
-**
-** The calling thead must hold the lock that protects the condition, as
-** well as the invariants that are tightly bound to the condition, when
-** notify is called.
-**
-** Returns PR_FAILURE if the caller has not locked the lock associated
-** with the condition variable.
-*/
-NSPR_API(PRStatus) PR_NotifyCondVar(PRCondVar *cvar);
-
-/*
-** Notify all of the threads waiting on the condition variable. The order
-** that the threads are notified is indeterminant. The lock that protects
-** the condition must be held.
-**
-** Returns PR_FAILURE if the caller has not locked the lock associated
-** with the condition variable.
-*/
-NSPR_API(PRStatus) PR_NotifyAllCondVar(PRCondVar *cvar);
-
-PR_END_EXTERN_C
-
-#endif /* prcvar_h___ */
diff --git a/nspr/pr/include/prdtoa.h b/nspr/pr/include/prdtoa.h
deleted file mode 100644
index 191b6c7..0000000
--- a/nspr/pr/include/prdtoa.h
+++ /dev/null
@@ -1,51 +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/. */
-
-#ifndef prdtoa_h___
-#define prdtoa_h___
-
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-/*
-** PR_strtod() returns as a double-precision floating-point number
-** the value represented by the character string pointed to by
-** s00. The string is scanned up to the first unrecognized
-** character.
-**a
-** If the value of se is not (char **)NULL, a pointer to
-** the character terminating the scan is returned in the location pointed
-** to by se. If no number can be formed, se is set to s00, and
-** zero is returned.
-*/
-NSPR_API(PRFloat64)
-PR_strtod(const char *s00, char **se);
-
-/*
-** PR_cnvtf()
-** conversion routines for floating point
-** prcsn - number of digits of precision to generate floating
-** point value.
-*/
-NSPR_API(void) PR_cnvtf(char *buf, PRIntn bufsz, PRIntn prcsn, PRFloat64 fval);
-
-/*
-** PR_dtoa() converts double to a string.
-**
-** ARGUMENTS:
-** If rve is not null, *rve is set to point to the end of the return value.
-** If d is +-Infinity or NaN, then *decpt is set to 9999.
-**
-** mode:
-** 0 ==> shortest string that yields d when read in
-** and rounded to nearest.
-*/
-NSPR_API(PRStatus) PR_dtoa(PRFloat64 d, PRIntn mode, PRIntn ndigits,
- PRIntn *decpt, PRIntn *sign, char **rve, char *buf, PRSize bufsize);
-
-PR_END_EXTERN_C
-
-#endif /* prdtoa_h___ */
diff --git a/nspr/pr/include/prenv.h b/nspr/pr/include/prenv.h
deleted file mode 100644
index 468c7d5..0000000
--- a/nspr/pr/include/prenv.h
+++ /dev/null
@@ -1,162 +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/. */
-
-#ifndef prenv_h___
-#define prenv_h___
-
-#include "prtypes.h"
-
-/*******************************************************************************/
-/*******************************************************************************/
-/****************** THESE FUNCTIONS MAY NOT BE THREAD SAFE *********************/
-/*******************************************************************************/
-/*******************************************************************************/
-
-PR_BEGIN_EXTERN_C
-
-/*
-** PR_GetEnv() -- Retrieve value of environment variable
-**
-** Description:
-** PR_GetEnv() is modeled on Unix getenv().
-**
-**
-** Inputs:
-** var -- The name of the environment variable
-**
-** Returns:
-** The value of the environment variable 'var' or NULL if
-** the variable is undefined.
-**
-** Restrictions:
-** You'd think that a POSIX getenv(), putenv() would be
-** consistently implemented everywhere. Surprise! It is not. On
-** some platforms, a putenv() where the argument is of
-** the form "name" causes the named environment variable to
-** be un-set; that is: a subsequent getenv() returns NULL. On
-** other platforms, the putenv() fails, on others, it is a
-** no-op. Similarly, a putenv() where the argument is of the
-** form "name=" causes the named environment variable to be
-** un-set; a subsequent call to getenv() returns NULL. On
-** other platforms, a subsequent call to getenv() returns a
-** pointer to a null-string (a byte of zero).
-**
-** PR_GetEnv(), PR_SetEnv() provide a consistent behavior
-** across all supported platforms. There are, however, some
-** restrictions and some practices you must use to achieve
-** consistent results everywhere.
-**
-** When manipulating the environment there is no way to un-set
-** an environment variable across all platforms. We suggest
-** you interpret the return of a pointer to null-string to
-** mean the same as a return of NULL from PR_GetEnv().
-**
-** A call to PR_SetEnv() where the parameter is of the form
-** "name" will return PR_FAILURE; the environment remains
-** unchanged. A call to PR_SetEnv() where the parameter is
-** of the form "name=" may un-set the envrionment variable on
-** some platforms; on others it may set the value of the
-** environment variable to the null-string.
-**
-** For example, to test for NULL return or return of the
-** null-string from PR_GetEnv(), use the following code
-** fragment:
-**
-** char *val = PR_GetEnv("foo");
-** if ((NULL == val) || ('\0' == *val)) {
-** ... interpret this as un-set ...
-** }
-**
-** The caller must ensure that the string passed
-** to PR_SetEnv() is persistent. That is: The string should
-** not be on the stack, where it can be overwritten
-** on return from the function calling PR_SetEnv().
-** Similarly, the string passed to PR_SetEnv() must not be
-** overwritten by other actions of the process. ... Some
-** platforms use the string by reference rather than copying
-** it into the environment space. ... You have been warned!
-**
-** Use of platform-native functions that manipulate the
-** environment (getenv(), putenv(),
-** SetEnvironmentVariable(), etc.) must not be used with
-** NSPR's similar functions. The platform-native functions
-** may not be thread safe and/or may operate on different
-** conceptual environment space than that operated upon by
-** NSPR's functions or other environment manipulating
-** functions on the same platform. (!)
-**
-*/
-NSPR_API(char*) PR_GetEnv(const char *var);
-
-/*
-** PR_GetEnvSecure() -- get a security-sensitive environment variable
-**
-** Description:
-**
-** PR_GetEnvSecure() is similar to PR_GetEnv(), but it returns NULL if
-** the program was run with elevated privilege (e.g., setuid or setgid
-** on Unix). This can be used for cases like log file paths which
-** could otherwise be used for privilege escalation. Note that some
-** platforms may have platform-specific privilege elevation mechanisms
-** not recognized by this function; see the implementation for details.
-*/
-NSPR_API(char*) PR_GetEnvSecure(const char *var);
-
-/*
-** PR_SetEnv() -- set, unset or change an environment variable
-**
-** Description:
-** PR_SetEnv() is modeled on the Unix putenv() function.
-**
-** Inputs:
-** string -- pointer to a caller supplied
-** constant, persistent string of the form name=value. Where
-** name is the name of the environment variable to be set or
-** changed; value is the value assigned to the variable.
-**
-** Returns:
-** PRStatus.
-**
-** Restrictions:
-** See the Restrictions documented in the description of
-** PR_GetEnv() in this header file.
-**
-**
-*/
-NSPR_API(PRStatus) PR_SetEnv(const char *string);
-
-/*
-** PR_DuplicateEnvironment() -- Obtain a copy of the environment.
-**
-** Description:
-** PR_DuplicateEnvironment() copies the environment so that it can be
-** modified without changing the current process's environment, and
-** then passed to interfaces such as POSIX execve(). In particular,
-** this avoids needing to allocate memory or take locks in the child
-** after a fork(); neither of these is allowed by POSIX after a
-** multithreaded process calls fork(), and PR_SetEnv does both.
-**
-** Inputs:
-** none
-**
-** Returns:
-** A pointer to a null-terminated array of null-terminated strings,
-** like the traditional global variable "environ". The array and
-** the strings are allocated with PR_Malloc(), and it is the
-** caller's responsibility to free them.
-**
-** In case of memory allocation failure, or if the operating system
-** doesn't support reading the entire environment through the global
-** variable "environ" or similar, returns NULL instead.
-**
-** Restrictions:
-** Similarly to PR_GetEnv(), this function may not interoperate as
-** expected with the operating system's native environment accessors.
-*/
-NSPR_API(char **) PR_DuplicateEnvironment(void);
-
-PR_END_EXTERN_C
-
-#endif /* prenv_h___ */
diff --git a/nspr/pr/include/prerr.h b/nspr/pr/include/prerr.h
deleted file mode 100644
index 8512329..0000000
--- a/nspr/pr/include/prerr.h
+++ /dev/null
@@ -1,249 +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/. */
-
-#ifndef prerr_h___
-#define prerr_h___
-
-/*
- *
- * prerr.h
- * This file is automatically generated; please do not edit it.
- */
-
-/* Memory allocation attempt failed */
-#define PR_OUT_OF_MEMORY_ERROR (-6000L)
-
-/* Invalid file descriptor */
-#define PR_BAD_DESCRIPTOR_ERROR (-5999L)
-
-/* The operation would have blocked */
-#define PR_WOULD_BLOCK_ERROR (-5998L)
-
-/* Invalid memory address argument */
-#define PR_ACCESS_FAULT_ERROR (-5997L)
-
-/* Invalid function for file type */
-#define PR_INVALID_METHOD_ERROR (-5996L)
-
-/* Invalid memory address argument */
-#define PR_ILLEGAL_ACCESS_ERROR (-5995L)
-
-/* Some unknown error has occurred */
-#define PR_UNKNOWN_ERROR (-5994L)
-
-/* Operation interrupted by another thread */
-#define PR_PENDING_INTERRUPT_ERROR (-5993L)
-
-/* function not implemented */
-#define PR_NOT_IMPLEMENTED_ERROR (-5992L)
-
-/* I/O function error */
-#define PR_IO_ERROR (-5991L)
-
-/* I/O operation timed out */
-#define PR_IO_TIMEOUT_ERROR (-5990L)
-
-/* I/O operation on busy file descriptor */
-#define PR_IO_PENDING_ERROR (-5989L)
-
-/* The directory could not be opened */
-#define PR_DIRECTORY_OPEN_ERROR (-5988L)
-
-/* Invalid function argument */
-#define PR_INVALID_ARGUMENT_ERROR (-5987L)
-
-/* Network address not available (in use?) */
-#define PR_ADDRESS_NOT_AVAILABLE_ERROR (-5986L)
-
-/* Network address type not supported */
-#define PR_ADDRESS_NOT_SUPPORTED_ERROR (-5985L)
-
-/* Already connected */
-#define PR_IS_CONNECTED_ERROR (-5984L)
-
-/* Network address is invalid */
-#define PR_BAD_ADDRESS_ERROR (-5983L)
-
-/* Local Network address is in use */
-#define PR_ADDRESS_IN_USE_ERROR (-5982L)
-
-/* Connection refused by peer */
-#define PR_CONNECT_REFUSED_ERROR (-5981L)
-
-/* Network address is presently unreachable */
-#define PR_NETWORK_UNREACHABLE_ERROR (-5980L)
-
-/* Connection attempt timed out */
-#define PR_CONNECT_TIMEOUT_ERROR (-5979L)
-
-/* Network file descriptor is not connected */
-#define PR_NOT_CONNECTED_ERROR (-5978L)
-
-/* Failure to load dynamic library */
-#define PR_LOAD_LIBRARY_ERROR (-5977L)
-
-/* Failure to unload dynamic library */
-#define PR_UNLOAD_LIBRARY_ERROR (-5976L)
-
-/* Symbol not found in any of the loaded dynamic libraries */
-#define PR_FIND_SYMBOL_ERROR (-5975L)
-
-/* Insufficient system resources */
-#define PR_INSUFFICIENT_RESOURCES_ERROR (-5974L)
-
-/* A directory lookup on a network address has failed */
-#define PR_DIRECTORY_LOOKUP_ERROR (-5973L)
-
-/* Attempt to access a TPD key that is out of range */
-#define PR_TPD_RANGE_ERROR (-5972L)
-
-/* Process open FD table is full */
-#define PR_PROC_DESC_TABLE_FULL_ERROR (-5971L)
-
-/* System open FD table is full */
-#define PR_SYS_DESC_TABLE_FULL_ERROR (-5970L)
-
-/* Network operation attempted on non-network file descriptor */
-#define PR_NOT_SOCKET_ERROR (-5969L)
-
-/* TCP-specific function attempted on a non-TCP file descriptor */
-#define PR_NOT_TCP_SOCKET_ERROR (-5968L)
-
-/* TCP file descriptor is already bound */
-#define PR_SOCKET_ADDRESS_IS_BOUND_ERROR (-5967L)
-
-/* Access Denied */
-#define PR_NO_ACCESS_RIGHTS_ERROR (-5966L)
-
-/* The requested operation is not supported by the platform */
-#define PR_OPERATION_NOT_SUPPORTED_ERROR (-5965L)
-
-/* The host operating system does not support the protocol requested */
-#define PR_PROTOCOL_NOT_SUPPORTED_ERROR (-5964L)
-
-/* Access to the remote file has been severed */
-#define PR_REMOTE_FILE_ERROR (-5963L)
-
-/* The value requested is too large to be stored in the data buffer provided */
-#define PR_BUFFER_OVERFLOW_ERROR (-5962L)
-
-/* TCP connection reset by peer */
-#define PR_CONNECT_RESET_ERROR (-5961L)
-
-/* Unused */
-#define PR_RANGE_ERROR (-5960L)
-
-/* The operation would have deadlocked */
-#define PR_DEADLOCK_ERROR (-5959L)
-
-/* The file is already locked */
-#define PR_FILE_IS_LOCKED_ERROR (-5958L)
-
-/* Write would result in file larger than the system allows */
-#define PR_FILE_TOO_BIG_ERROR (-5957L)
-
-/* The device for storing the file is full */
-#define PR_NO_DEVICE_SPACE_ERROR (-5956L)
-
-/* Unused */
-#define PR_PIPE_ERROR (-5955L)
-
-/* Unused */
-#define PR_NO_SEEK_DEVICE_ERROR (-5954L)
-
-/* Cannot perform a normal file operation on a directory */
-#define PR_IS_DIRECTORY_ERROR (-5953L)
-
-/* Symbolic link loop */
-#define PR_LOOP_ERROR (-5952L)
-
-/* File name is too long */
-#define PR_NAME_TOO_LONG_ERROR (-5951L)
-
-/* File not found */
-#define PR_FILE_NOT_FOUND_ERROR (-5950L)
-
-/* Cannot perform directory operation on a normal file */
-#define PR_NOT_DIRECTORY_ERROR (-5949L)
-
-/* Cannot write to a read-only file system */
-#define PR_READ_ONLY_FILESYSTEM_ERROR (-5948L)
-
-/* Cannot delete a directory that is not empty */
-#define PR_DIRECTORY_NOT_EMPTY_ERROR (-5947L)
-
-/* Cannot delete or rename a file object while the file system is busy */
-#define PR_FILESYSTEM_MOUNTED_ERROR (-5946L)
-
-/* Cannot rename a file to a file system on another device */
-#define PR_NOT_SAME_DEVICE_ERROR (-5945L)
-
-/* The directory object in the file system is corrupted */
-#define PR_DIRECTORY_CORRUPTED_ERROR (-5944L)
-
-/* Cannot create or rename a filename that already exists */
-#define PR_FILE_EXISTS_ERROR (-5943L)
-
-/* Directory is full. No additional filenames may be added */
-#define PR_MAX_DIRECTORY_ENTRIES_ERROR (-5942L)
-
-/* The required device was in an invalid state */
-#define PR_INVALID_DEVICE_STATE_ERROR (-5941L)
-
-/* The device is locked */
-#define PR_DEVICE_IS_LOCKED_ERROR (-5940L)
-
-/* No more entries in the directory */
-#define PR_NO_MORE_FILES_ERROR (-5939L)
-
-/* Encountered end of file */
-#define PR_END_OF_FILE_ERROR (-5938L)
-
-/* Seek error */
-#define PR_FILE_SEEK_ERROR (-5937L)
-
-/* The file is busy */
-#define PR_FILE_IS_BUSY_ERROR (-5936L)
-
-/* The I/O operation was aborted */
-#define PR_OPERATION_ABORTED_ERROR (-5935L)
-
-/* Operation is still in progress (probably a non-blocking connect) */
-#define PR_IN_PROGRESS_ERROR (-5934L)
-
-/* Operation has already been initiated (probably a non-blocking connect) */
-#define PR_ALREADY_INITIATED_ERROR (-5933L)
-
-/* The wait group is empty */
-#define PR_GROUP_EMPTY_ERROR (-5932L)
-
-/* Object state improper for request */
-#define PR_INVALID_STATE_ERROR (-5931L)
-
-/* Network is down */
-#define PR_NETWORK_DOWN_ERROR (-5930L)
-
-/* Socket shutdown */
-#define PR_SOCKET_SHUTDOWN_ERROR (-5929L)
-
-/* Connection aborted */
-#define PR_CONNECT_ABORTED_ERROR (-5928L)
-
-/* Host is unreachable */
-#define PR_HOST_UNREACHABLE_ERROR (-5927L)
-
-/* The library is not loaded */
-#define PR_LIBRARY_NOT_LOADED_ERROR (-5926L)
-
-/* The one-time function was previously called and failed. Its error code is no longer available */
-#define PR_CALL_ONCE_ERROR (-5925L)
-
-/* Placeholder for the end of the list */
-#define PR_MAX_ERROR (-5924L)
-
-extern void nspr_InitializePRErrorTable(void);
-#define ERROR_TABLE_BASE_nspr (-6000L)
-
-#endif /* prerr_h___ */
diff --git a/nspr/pr/include/prerror.h b/nspr/pr/include/prerror.h
deleted file mode 100644
index 3d6baf6..0000000
--- a/nspr/pr/include/prerror.h
+++ /dev/null
@@ -1,294 +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/. */
-
-#ifndef prerror_h___
-#define prerror_h___
-
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-typedef PRInt32 PRErrorCode;
-
-#define PR_NSPR_ERROR_BASE -6000
-
-#include "prerr.h"
-
-/*
-** Set error will preserve an error condition within a thread context.
-** The values stored are the NSPR (platform independent) translation of
-** the error. Also, if available, the platform specific oserror is stored.
-** If there is no appropriate OS error number, a zero my be supplied.
-*/
-NSPR_API(void) PR_SetError(PRErrorCode errorCode, PRInt32 oserr);
-
-/*
-** The text value specified may be NULL. If it is not NULL and the text length
-** is zero, the string is assumed to be a null terminated C string. Otherwise
-** the text is assumed to be the length specified and possibly include NULL
-** characters (e.g., a multi-national string).
-**
-** The text will be copied into to thread structure and remain there
-** until the next call to PR_SetError.
-*/
-NSPR_API(void) PR_SetErrorText(
- PRIntn textLength, const char *text);
-
-/*
-** Return the current threads last set error code.
-*/
-NSPR_API(PRErrorCode) PR_GetError(void);
-
-/*
-** Return the current threads last set os error code. This is used for
-** machine specific code that desires the underlying os error.
-*/
-NSPR_API(PRInt32) PR_GetOSError(void);
-
-/*
-** Get the length of the error text. If a zero is returned, then there
-** is no text. Otherwise, the value returned is sufficient to contain
-** the error text currently available.
-*/
-NSPR_API(PRInt32) PR_GetErrorTextLength(void);
-
-/*
-** Copy the current threads current error text. Then actual number of bytes
-** copied is returned as the result. If the result is zero, the 'text' area
-** is unaffected.
-*/
-NSPR_API(PRInt32) PR_GetErrorText(char *text);
-
-
-/*
-Copyright (C) 1987, 1988 Student Information Processing Board of the
-Massachusetts Institute of Technology.
-
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted, provided
-that the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation, and that the names of M.I.T. and the M.I.T. S.I.P.B. not be
-used in advertising or publicity pertaining to distribution of the software
-without specific, written prior permission. M.I.T. and the M.I.T. S.I.P.B.
-make no representations about the suitability of this software for any
-purpose. It is provided "as is" without express or implied warranty.
-*/
-
-
-/*
- * NOTE:
- * The interfaces for error-code-translation described in the rest of
- * this file are preliminary in the 3.1 release of nspr and are subject
- * to change in future releases.
- */
-
-/*
-** Description: Localizable error code to string function.
-**
-**
-** NSPR provides a mechanism for converting an error code to a
-** descriptive string, in a caller-specified language.
-**
-** Error codes themselves are 32 bit (signed) integers. Typically,
-** the high order 24 bits are an identifier of which error table the
-** error code is from, and the low order 8 bits are a sequential error
-** number within the table. NSPR supports error tables whose first
-** error code is not a multiple of 256, such error code assignments
-** should be avoided when possible.
-**
-** Error table 0 is defined to match the UNIX system call error table
-** (sys_errlist); this allows errno values to be used directly in the
-** library. Other error table numbers are typically formed by
-** compacting together the first four characters of the error table
-** name. The mapping between characters in the name and numeric
-** values in the error code are defined in a system-independent
-** fashion, so that two systems that can pass integral values between
-** them can reliably pass error codes without loss of meaning; this
-** should work even if the character sets used are not the
-** same. (However, if this is to be done, error table 0 should be
-** avoided, since the local system call error tables may differ.)
-**
-** Libraries defining error codes need only provide a table mapping
-** error code numbers to names and default English descriptions,
-** calling a routine to install the table, making it ``known'' to NSPR
-** library. Once installed, a table may not be removed. Any error
-** code the library generates can be converted to the corresponding
-** error message. There is also a default format for error codes
-** accidentally returned before making the table known, which is of
-** the form "unknown code foo 32", where "foo" would be the name of
-** the table.
-**
-** Normally, the error code conversion routine only supports the
-** languages "i-default" and "en", returning the error-table-provided
-** English description for both languages. The application may
-** provide a localization plugin, allowing support for additional
-** languages.
-**
-**/
-
-/**********************************************************************/
-/************************* TYPES AND CONSTANTS ************************/
-/**********************************************************************/
-
-/*
- * PRLanguageCode --
- *
- * NSPR represents a language code as a non-negative integer.
- * Languages 0 is always "i-default" the language you get without
- * explicit negotiation. Language 1 is always "en", English
- * which has been explicitly negotiated. Additional language
- * codes are defined by an application-provided localization plugin.
- */
-typedef PRUint32 PRLanguageCode;
-#define PR_LANGUAGE_I_DEFAULT 0 /* i-default, the default language */
-#define PR_LANGUAGE_EN 1 /* English, explicitly negotiated */
-
-/*
- * struct PRErrorMessage --
- *
- * An error message in an error table.
- */
-struct PRErrorMessage {
- const char * name; /* Macro name for error */
- const char * en_text; /* Default English text */
-};
-
-/*
- * struct PRErrorTable --
- *
- * An error table, provided by a library.
- */
-struct PRErrorTable {
- const struct PRErrorMessage * msgs; /* Array of error information */
- const char *name; /* Name of error table source */
- PRErrorCode base; /* Error code for first error in table */
- int n_msgs; /* Number of codes in table */
-};
-
-/*
- * struct PRErrorCallbackPrivate --
- *
- * A private structure for the localization plugin
- */
-struct PRErrorCallbackPrivate;
-
-/*
- * struct PRErrorCallbackTablePrivate --
- *
- * A data structure under which the localization plugin may store information,
- * associated with an error table, that is private to itself.
- */
-struct PRErrorCallbackTablePrivate;
-
-/*
- * PRErrorCallbackLookupFn --
- *
- * A function of PRErrorCallbackLookupFn type is a localization
- * plugin callback which converts an error code into a description
- * in the requested language. The callback is provided the
- * appropriate error table, private data for the plugin and the table.
- * The callback returns the appropriate UTF-8 encoded description, or NULL
- * if no description can be found.
- */
-typedef const char *
-PRErrorCallbackLookupFn(PRErrorCode code, PRLanguageCode language,
- const struct PRErrorTable *table,
- struct PRErrorCallbackPrivate *cb_private,
- struct PRErrorCallbackTablePrivate *table_private);
-
-/*
- * PRErrorCallbackNewTableFn --
- *
- * A function PRErrorCallbackNewTableFn type is a localization plugin
- * callback which is called once with each error table registered
- * with NSPR. The callback is provided with the error table and
- * the plugin's private structure. The callback returns any table private
- * data it wishes to associate with the error table. Does not need to be thread
- * safe.
- */
-typedef struct PRErrorCallbackTablePrivate *
-PRErrorCallbackNewTableFn(const struct PRErrorTable *table,
- struct PRErrorCallbackPrivate *cb_private);
-
-/**********************************************************************/
-/****************************** FUNCTIONS *****************************/
-/**********************************************************************/
-
-/***********************************************************************
-** FUNCTION: PR_ErrorToString
-** DESCRIPTION:
-** Returns the UTF-8 message for an error code in
-** the requested language. May return the message
-** in the default language if a translation in the requested
-** language is not available. The returned string is
-** valid for the duration of the process. Never returns NULL.
-**
-***********************************************************************/
-NSPR_API(const char *) PR_ErrorToString(PRErrorCode code,
- PRLanguageCode language);
-
-
-/***********************************************************************
-** FUNCTION: PR_ErrorToName
-** DESCRIPTION:
-** Returns the macro name for an error code, or NULL
-** if the error code is not known. The returned string is
-** valid for the duration of the process.
-**
-** Does not work for error table 0, the system error codes.
-**
-***********************************************************************/
-NSPR_API(const char *) PR_ErrorToName(PRErrorCode code);
-
-
-/***********************************************************************
-** FUNCTION: PR_ErrorLanguages
-** DESCRIPTION:
-** Returns the RFC 1766 language tags for the language
-** codes PR_ErrorToString() supports. The returned array is valid
-** for the duration of the process. Never returns NULL. The first
-** item in the returned array is the language tag for PRLanguageCode 0,
-** the second is for PRLanguageCode 1, and so on. The array is terminated
-** with a null pointer.
-**
-***********************************************************************/
-NSPR_API(const char * const *) PR_ErrorLanguages(void);
-
-
-/***********************************************************************
-** FUNCTION: PR_ErrorInstallTable
-** DESCRIPTION:
-** Registers an error table with NSPR. Must be done exactly once per
-** table. Memory pointed to by `table' must remain valid for the life
-** of the process.
-**
-** NOT THREAD SAFE!
-**
-***********************************************************************/
-NSPR_API(PRErrorCode) PR_ErrorInstallTable(const struct PRErrorTable *table);
-
-
-/***********************************************************************
-** FUNCTION: PR_ErrorInstallCallback
-** DESCRIPTION:
-** Registers an error localization plugin with NSPR. May be called
-** at most one time. `languages' contains the language codes supported
-** by this plugin. Languages 0 and 1 must be "i-default" and "en"
-** respectively. `lookup' and `newtable' contain pointers to
-** the plugin callback functions. `cb_private' contains any information
-** private to the plugin functions.
-**
-** NOT THREAD SAFE!
-**
-***********************************************************************/
-NSPR_API(void) PR_ErrorInstallCallback(const char * const * languages,
- PRErrorCallbackLookupFn *lookup,
- PRErrorCallbackNewTableFn *newtable,
- struct PRErrorCallbackPrivate *cb_private);
-
-PR_END_EXTERN_C
-
-#endif /* prerror_h___ */
diff --git a/nspr/pr/include/prinet.h b/nspr/pr/include/prinet.h
deleted file mode 100644
index 15d229f..0000000
--- a/nspr/pr/include/prinet.h
+++ /dev/null
@@ -1,99 +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/. */
-
-/*
- * File: prinet.h
- * Description:
- * Header file used to find the system header files for socket support[1].
- * This file serves the following purposes:
- * - A cross-platform, "get-everything" socket header file. On
- * Unix, socket support is scattered in several header files,
- * while Windows has a "get-everything" socket header file[2].
- * - NSPR needs the following macro definitions and function
- * prototype declarations from these header files:
- * AF_INET
- * INADDR_ANY, INADDR_LOOPBACK, INADDR_BROADCAST
- * ntohl(), ntohs(), htonl(), ntons().
- * NSPR does not define its own versions of these macros and
- * functions. It simply uses the native versions, which have
- * the same names on all supported platforms.
- * This file is intended to be included by NSPR public header
- * files, such as prio.h. One should not include this file directly.
- *
- * Notes:
- * 1. This file should have been an internal header. Please do not
- * depend on it to pull in the system header files you need.
- * 2. WARNING: This file is no longer cross-platform as it is a no-op
- * for WIN32! See the comment in the WIN32 section for details.
- */
-
-#ifndef prinet_h__
-#define prinet_h__
-
-#if defined(XP_UNIX) || defined(XP_OS2) || defined(XP_BEOS)
-#include <sys/types.h>
-#include <sys/socket.h> /* AF_INET */
-#include <netinet/in.h> /* INADDR_ANY, ..., ntohl(), ... */
-#ifdef XP_OS2
-#include <sys/ioctl.h>
-#endif
-#ifdef XP_UNIX
-#ifdef AIX
-/*
- * On AIX 4.3, the header <arpa/inet.h> refers to struct
- * ether_addr and struct sockaddr_dl that are not declared.
- * The following struct declarations eliminate the compiler
- * warnings.
- */
-struct ether_addr;
-struct sockaddr_dl;
-#endif /* AIX */
-#include <arpa/inet.h>
-#endif /* XP_UNIX */
-#include <netdb.h>
-
-#if defined(FREEBSD) || defined(BSDI) || defined(QNX)
-#include <rpc/types.h> /* the only place that defines INADDR_LOOPBACK */
-#endif
-
-/*
- * OS/2 hack. For some reason INADDR_LOOPBACK is not defined in the
- * socket headers.
- */
-#if defined(OS2) && !defined(INADDR_LOOPBACK)
-#define INADDR_LOOPBACK 0x7f000001
-#endif
-
-/*
- * Prototypes of ntohl() etc. are declared in <machine/endian.h>
- * on these platforms.
- */
-#if defined(BSDI) || defined(OSF1)
-#include <machine/endian.h>
-#endif
-
-/* On Android, ntohl() etc. are declared in <sys/endian.h>. */
-#ifdef __ANDROID__
-#include <sys/endian.h>
-#endif
-
-#elif defined(WIN32)
-
-/*
- * Do not include any system header files.
- *
- * Originally we were including <windows.h>. It slowed down the
- * compilation of files that included NSPR headers, so we removed
- * the <windows.h> inclusion at customer's request, which created
- * an unfortunate inconsistency with other platforms.
- */
-
-#else
-
-#error Unknown platform
-
-#endif
-
-#endif /* prinet_h__ */
diff --git a/nspr/pr/include/prinit.h b/nspr/pr/include/prinit.h
deleted file mode 100644
index 523c2b9..0000000
--- a/nspr/pr/include/prinit.h
+++ /dev/null
@@ -1,215 +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/. */
-
-#ifndef prinit_h___
-#define prinit_h___
-
-#include "prthread.h"
-#include "prtypes.h"
-#include "prwin16.h"
-#include <stdio.h>
-
-PR_BEGIN_EXTERN_C
-
-/************************************************************************/
-/**************************IDENTITY AND VERSIONING***********************/
-/************************************************************************/
-
-/*
-** NSPR's name, this should persist until at least the turn of the
-** century.
-*/
-#define PR_NAME "NSPR"
-
-/*
-** NSPR's version is used to determine the likelihood that the version you
-** used to build your component is anywhere close to being compatible with
-** what is in the underlying library.
-**
-** The format of the version string is
-** "<major version>.<minor version>[.<patch level>] [<Beta>]"
-*/
-#define PR_VERSION "4.12"
-#define PR_VMAJOR 4
-#define PR_VMINOR 12
-#define PR_VPATCH 0
-#define PR_BETA PR_FALSE
-
-/*
-** PRVersionCheck
-**
-** The basic signature of the function that is called to provide version
-** checking. The result will be a boolean that indicates the likelihood
-** that the underling library will perform as the caller expects.
-**
-** The only argument is a string, which should be the verson identifier
-** of the library in question. That string will be compared against an
-** equivalent string that represents the actual build version of the
-** exporting library.
-**
-** The result will be the logical union of the directly called library
-** and all dependent libraries.
-*/
-
-typedef PRBool (*PRVersionCheck)(const char*);
-
-/*
-** PR_VersionCheck
-**
-** NSPR's existance proof of the version check function.
-**
-** Note that NSPR has no cooperating dependencies.
-*/
-
-NSPR_API(PRBool) PR_VersionCheck(const char *importedVersion);
-
-/*
- * Returns a const string of the NSPR library version.
- */
-NSPR_API(const char*) PR_GetVersion(void);
-
-
-/************************************************************************/
-/*******************************INITIALIZATION***************************/
-/************************************************************************/
-
-/*
-** Initialize the runtime. Attach a thread object to the currently
-** executing native thread of type "type".
-**
-** The specificaiton of 'maxPTDs' is ignored.
-*/
-NSPR_API(void) PR_Init(
- PRThreadType type, PRThreadPriority priority, PRUintn maxPTDs);
-
-/*
-** And alternate form of initialization, one that may become the default if
-** not the only mechanism, provides a method to get the NSPR runtime init-
-** ialized and place NSPR between the caller and the runtime library. This
-** allows main() to be treated as any other thread root function, signalling
-** its compeletion by returning and allowing the runtime to coordinate the
-** completion of the other threads of the runtime.
-**
-** The priority of the main (or primordial) thread will be PR_PRIORITY_NORMAL.
-** The thread may adjust its own priority by using PR_SetPriority(), though
-** at this time the support for priorities is somewhat weak.
-**
-** The specificaiton of 'maxPTDs' is ignored.
-**
-** The value returned by PR_Initialize is the value returned from the root
-** function, 'prmain'.
-*/
-
-typedef PRIntn (PR_CALLBACK *PRPrimordialFn)(PRIntn argc, char **argv);
-
-NSPR_API(PRIntn) PR_Initialize(
- PRPrimordialFn prmain, PRIntn argc, char **argv, PRUintn maxPTDs);
-
-/*
-** Return PR_TRUE if PR_Init has already been called.
-*/
-NSPR_API(PRBool) PR_Initialized(void);
-
-/*
- * Perform a graceful shutdown of NSPR. PR_Cleanup() may be called by
- * the primordial thread near the end of the main() function.
- *
- * PR_Cleanup() attempts to synchronize the natural termination of
- * process. It does that by blocking the caller, if and only if it is
- * the primordial thread, until the number of user threads has dropped
- * to zero. When the primordial thread returns from main(), the process
- * will immediately and silently exit. That is, it will (if necessary)
- * forcibly terminate any existing threads and exit without significant
- * blocking and there will be no error messages or core files.
- *
- * PR_Cleanup() returns PR_SUCCESS if NSPR is successfully shutdown,
- * or PR_FAILURE if the calling thread of this function is not the
- * primordial thread.
- */
-NSPR_API(PRStatus) PR_Cleanup(void);
-
-/*
-** Disable Interrupts
-** Disables timer signals used for pre-emptive scheduling.
-*/
-NSPR_API(void) PR_DisableClockInterrupts(void);
-
-/*
-** Enables Interrupts
-** Enables timer signals used for pre-emptive scheduling.
-*/
-NSPR_API(void) PR_EnableClockInterrupts(void);
-
-/*
-** Block Interrupts
-** Blocks the timer signal used for pre-emptive scheduling
-*/
-NSPR_API(void) PR_BlockClockInterrupts(void);
-
-/*
-** Unblock Interrupts
-** Unblocks the timer signal used for pre-emptive scheduling
-*/
-NSPR_API(void) PR_UnblockClockInterrupts(void);
-
-/*
-** Create extra virtual processor threads. Generally used with MP systems.
-*/
-NSPR_API(void) PR_SetConcurrency(PRUintn numCPUs);
-
-/*
-** Control the method and size of the file descriptor (PRFileDesc*)
-** cache used by the runtime. Setting 'high' to zero is for performance,
-** any other value probably for debugging (see memo on FD caching).
-*/
-NSPR_API(PRStatus) PR_SetFDCacheSize(PRIntn low, PRIntn high);
-
-/*
- * Cause an immediate, nongraceful, forced termination of the process.
- * It takes a PRIntn argument, which is the exit status code of the
- * process.
- */
-NSPR_API(void) PR_ProcessExit(PRIntn status);
-
-/*
-** Abort the process in a non-graceful manner. This will cause a core file,
-** call to the debugger or other moral equivalent as well as causing the
-** entire process to stop.
-*/
-NSPR_API(void) PR_Abort(void);
-
-/*
- ****************************************************************
- *
- * Module initialization:
- *
- ****************************************************************
- */
-
-typedef struct PRCallOnceType {
- PRIntn initialized;
- PRInt32 inProgress;
- PRStatus status;
-} PRCallOnceType;
-
-typedef PRStatus (PR_CALLBACK *PRCallOnceFN)(void);
-
-typedef PRStatus (PR_CALLBACK *PRCallOnceWithArgFN)(void *arg);
-
-NSPR_API(PRStatus) PR_CallOnce(
- PRCallOnceType *once,
- PRCallOnceFN func
-);
-
-NSPR_API(PRStatus) PR_CallOnceWithArg(
- PRCallOnceType *once,
- PRCallOnceWithArgFN func,
- void *arg
-);
-
-
-PR_END_EXTERN_C
-
-#endif /* prinit_h___ */
diff --git a/nspr/pr/include/prinrval.h b/nspr/pr/include/prinrval.h
deleted file mode 100644
index 14cd39b..0000000
--- a/nspr/pr/include/prinrval.h
+++ /dev/null
@@ -1,146 +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/. */
-
-/*
-** File: prinrval.h
-** Description: API to interval timing functions of NSPR.
-**
-**
-** NSPR provides interval times that are independent of network time
-** of day values. Interval times are (in theory) accurate regardless
-** of host processing requirements and also very cheap to acquire. It
-** is expected that getting an interval time while in a synchronized
-** function (holding one's lock).
-**/
-
-#if !defined(prinrval_h)
-#define prinrval_h
-
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-/**********************************************************************/
-/************************* TYPES AND CONSTANTS ************************/
-/**********************************************************************/
-
-typedef PRUint32 PRIntervalTime;
-
-/***********************************************************************
-** DEFINES: PR_INTERVAL_MIN
-** PR_INTERVAL_MAX
-** DESCRIPTION:
-** These two constants define the range (in ticks / second) of the
-** platform dependent type, PRIntervalTime. These constants bound both
-** the period and the resolution of a PRIntervalTime.
-***********************************************************************/
-#define PR_INTERVAL_MIN 1000UL
-#define PR_INTERVAL_MAX 100000UL
-
-/***********************************************************************
-** DEFINES: PR_INTERVAL_NO_WAIT
-** PR_INTERVAL_NO_TIMEOUT
-** DESCRIPTION:
-** Two reserved constants are defined in the PRIntervalTime namespace.
-** They are used to indicate that the process should wait no time (return
-** immediately) or wait forever (never time out), respectively.
-** Note: PR_INTERVAL_NO_TIMEOUT passed as input to PR_Connect is
-** interpreted as use the OS's connect timeout.
-**
-***********************************************************************/
-#define PR_INTERVAL_NO_WAIT 0UL
-#define PR_INTERVAL_NO_TIMEOUT 0xffffffffUL
-
-/**********************************************************************/
-/****************************** FUNCTIONS *****************************/
-/**********************************************************************/
-
-/***********************************************************************
-** FUNCTION: PR_IntervalNow
-** DESCRIPTION:
-** Return the value of NSPR's free running interval timer. That timer
-** can be used to establish epochs and determine intervals (be computing
-** the difference between two times).
-** INPUTS: void
-** OUTPUTS: void
-** RETURN: PRIntervalTime
-**
-** SIDE EFFECTS:
-** None
-** RESTRICTIONS:
-** The units of PRIntervalTime are platform dependent. They are chosen
-** such that they are appropriate for the host OS, yet provide sufficient
-** resolution and period to be useful to clients.
-** MEMORY: N/A
-** ALGORITHM: Platform dependent
-***********************************************************************/
-NSPR_API(PRIntervalTime) PR_IntervalNow(void);
-
-/***********************************************************************
-** FUNCTION: PR_TicksPerSecond
-** DESCRIPTION:
-** Return the number of ticks per second for PR_IntervalNow's clock.
-** The value will be in the range [PR_INTERVAL_MIN..PR_INTERVAL_MAX].
-** INPUTS: void
-** OUTPUTS: void
-** RETURN: PRUint32
-**
-** SIDE EFFECTS:
-** None
-** RESTRICTIONS:
-** None
-** MEMORY: N/A
-** ALGORITHM: N/A
-***********************************************************************/
-NSPR_API(PRUint32) PR_TicksPerSecond(void);
-
-/***********************************************************************
-** FUNCTION: PR_SecondsToInterval
-** PR_MillisecondsToInterval
-** PR_MicrosecondsToInterval
-** DESCRIPTION:
-** Convert standard clock units to platform dependent intervals.
-** INPUTS: PRUint32
-** OUTPUTS: void
-** RETURN: PRIntervalTime
-**
-** SIDE EFFECTS:
-** None
-** RESTRICTIONS:
-** Conversion may cause overflow, which is not reported.
-** MEMORY: N/A
-** ALGORITHM: N/A
-***********************************************************************/
-NSPR_API(PRIntervalTime) PR_SecondsToInterval(PRUint32 seconds);
-NSPR_API(PRIntervalTime) PR_MillisecondsToInterval(PRUint32 milli);
-NSPR_API(PRIntervalTime) PR_MicrosecondsToInterval(PRUint32 micro);
-
-/***********************************************************************
-** FUNCTION: PR_IntervalToSeconds
-** PR_IntervalToMilliseconds
-** PR_IntervalToMicroseconds
-** DESCRIPTION:
-** Convert platform dependent intervals to standard clock units.
-** INPUTS: PRIntervalTime
-** OUTPUTS: void
-** RETURN: PRUint32
-**
-** SIDE EFFECTS:
-** None
-** RESTRICTIONS:
-** Conversion may cause overflow, which is not reported.
-** MEMORY: N/A
-** ALGORITHM: N/A
-***********************************************************************/
-NSPR_API(PRUint32) PR_IntervalToSeconds(PRIntervalTime ticks);
-NSPR_API(PRUint32) PR_IntervalToMilliseconds(PRIntervalTime ticks);
-NSPR_API(PRUint32) PR_IntervalToMicroseconds(PRIntervalTime ticks);
-
-PR_END_EXTERN_C
-
-
-#endif /* !defined(prinrval_h) */
-
-/* prinrval.h */
diff --git a/nspr/pr/include/prio.h b/nspr/pr/include/prio.h
deleted file mode 100644
index c7e85db..0000000
--- a/nspr/pr/include/prio.h
+++ /dev/null
@@ -1,2022 +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/. */
-
-/*
- * File: prio.h
- *
- * Description: PR i/o related stuff, such as file system access, file
- * i/o, socket i/o, etc.
- */
-
-#ifndef prio_h___
-#define prio_h___
-
-#include "prlong.h"
-#include "prtime.h"
-#include "prinrval.h"
-#include "prinet.h"
-
-PR_BEGIN_EXTERN_C
-
-/* Typedefs */
-typedef struct PRDir PRDir;
-typedef struct PRDirEntry PRDirEntry;
-#ifdef MOZ_UNICODE
-typedef struct PRDirUTF16 PRDirUTF16;
-typedef struct PRDirEntryUTF16 PRDirEntryUTF16;
-#endif /* MOZ_UNICODE */
-typedef struct PRFileDesc PRFileDesc;
-typedef struct PRFileInfo PRFileInfo;
-typedef struct PRFileInfo64 PRFileInfo64;
-typedef union PRNetAddr PRNetAddr;
-typedef struct PRIOMethods PRIOMethods;
-typedef struct PRPollDesc PRPollDesc;
-typedef struct PRFilePrivate PRFilePrivate;
-typedef struct PRSendFileData PRSendFileData;
-
-/*
-***************************************************************************
-** The file descriptor.
-** This is the primary structure to represent any active open socket,
-** whether it be a normal file or a network connection. Such objects
-** are stackable (or layerable). Each layer may have its own set of
-** method pointers and context private to that layer. All each layer
-** knows about its neighbors is how to get to their method table.
-***************************************************************************
-*/
-
-typedef PRIntn PRDescIdentity; /* see: Layering file descriptors */
-
-struct PRFileDesc {
- const PRIOMethods *methods; /* the I/O methods table */
- PRFilePrivate *secret; /* layer dependent data */
- PRFileDesc *lower, *higher; /* pointers to adjacent layers */
- void (PR_CALLBACK *dtor)(PRFileDesc *fd);
- /* A destructor function for layer */
- PRDescIdentity identity; /* Identity of this particular layer */
-};
-
-/*
-***************************************************************************
-** PRTransmitFileFlags
-**
-** Flags for PR_TransmitFile. Pass PR_TRANSMITFILE_CLOSE_SOCKET to
-** PR_TransmitFile if the connection should be closed after the file
-** is transmitted.
-***************************************************************************
-*/
-typedef enum PRTransmitFileFlags {
- PR_TRANSMITFILE_KEEP_OPEN = 0, /* socket is left open after file
- * is transmitted. */
- PR_TRANSMITFILE_CLOSE_SOCKET = 1 /* socket is closed after file
- * is transmitted. */
-} PRTransmitFileFlags;
-
-/*
-**************************************************************************
-** Macros for PRNetAddr
-**
-** Address families: PR_AF_INET, PR_AF_INET6, PR_AF_LOCAL
-** IP addresses: PR_INADDR_ANY, PR_INADDR_LOOPBACK, PR_INADDR_BROADCAST
-**************************************************************************
-*/
-
-#ifdef WIN32
-
-#define PR_AF_INET 2
-#define PR_AF_LOCAL 1
-#define PR_INADDR_ANY (unsigned long)0x00000000
-#define PR_INADDR_LOOPBACK 0x7f000001
-#define PR_INADDR_BROADCAST (unsigned long)0xffffffff
-
-#else /* WIN32 */
-
-#define PR_AF_INET AF_INET
-#define PR_AF_LOCAL AF_UNIX
-#define PR_INADDR_ANY INADDR_ANY
-#define PR_INADDR_LOOPBACK INADDR_LOOPBACK
-#define PR_INADDR_BROADCAST INADDR_BROADCAST
-
-#endif /* WIN32 */
-
-/*
-** Define PR_AF_INET6 in prcpucfg.h with the same
-** value as AF_INET6 on platforms with IPv6 support.
-** Otherwise define it here.
-*/
-#ifndef PR_AF_INET6
-#define PR_AF_INET6 100
-#endif
-
-#define PR_AF_INET_SDP 101
-#define PR_AF_INET6_SDP 102
-
-#ifndef PR_AF_UNSPEC
-#define PR_AF_UNSPEC 0
-#endif
-
-/*
-**************************************************************************
-** A network address
-**
-** Only Internet Protocol (IPv4 and IPv6) addresses are supported.
-** The address family must always represent IPv4 (AF_INET, probably == 2)
-** or IPv6 (AF_INET6).
-**************************************************************************
-*************************************************************************/
-
-struct PRIPv6Addr {
- union {
- PRUint8 _S6_u8[16];
- PRUint16 _S6_u16[8];
- PRUint32 _S6_u32[4];
- PRUint64 _S6_u64[2];
- } _S6_un;
-};
-#define pr_s6_addr _S6_un._S6_u8
-#define pr_s6_addr16 _S6_un._S6_u16
-#define pr_s6_addr32 _S6_un._S6_u32
-#define pr_s6_addr64 _S6_un._S6_u64
-
-typedef struct PRIPv6Addr PRIPv6Addr;
-
-union PRNetAddr {
- struct {
- PRUint16 family; /* address family (0x00ff maskable) */
-#ifdef XP_BEOS
- char data[10]; /* Be has a smaller structure */
-#else
- char data[14]; /* raw address data */
-#endif
- } raw;
- struct {
- PRUint16 family; /* address family (AF_INET) */
- PRUint16 port; /* port number */
- PRUint32 ip; /* The actual 32 bits of address */
-#ifdef XP_BEOS
- char pad[4]; /* Be has a smaller structure */
-#else
- char pad[8];
-#endif
- } inet;
- struct {
- PRUint16 family; /* address family (AF_INET6) */
- PRUint16 port; /* port number */
- PRUint32 flowinfo; /* routing information */
- PRIPv6Addr ip; /* the actual 128 bits of address */
- PRUint32 scope_id; /* set of interfaces for a scope */
- } ipv6;
-#if defined(XP_UNIX) || defined(XP_OS2)
- struct { /* Unix domain socket address */
- PRUint16 family; /* address family (AF_UNIX) */
-#ifdef XP_OS2
- char path[108]; /* null-terminated pathname */
- /* bind fails if size is not 108. */
-#else
- char path[104]; /* null-terminated pathname */
-#endif
- } local;
-#endif
-};
-
-/*
-***************************************************************************
-** PRSockOption
-**
-** The file descriptors can have predefined options set after they file
-** descriptor is created to change their behavior. Only the options in
-** the following enumeration are supported.
-***************************************************************************
-*/
-typedef enum PRSockOption
-{
- PR_SockOpt_Nonblocking, /* nonblocking io */
- PR_SockOpt_Linger, /* linger on close if data present */
- PR_SockOpt_Reuseaddr, /* allow local address reuse */
- PR_SockOpt_Keepalive, /* keep connections alive */
- PR_SockOpt_RecvBufferSize, /* send buffer size */
- PR_SockOpt_SendBufferSize, /* receive buffer size */
-
- PR_SockOpt_IpTimeToLive, /* time to live */
- PR_SockOpt_IpTypeOfService, /* type of service and precedence */
-
- PR_SockOpt_AddMember, /* add an IP group membership */
- PR_SockOpt_DropMember, /* drop an IP group membership */
- PR_SockOpt_McastInterface, /* multicast interface address */
- PR_SockOpt_McastTimeToLive, /* multicast timetolive */
- PR_SockOpt_McastLoopback, /* multicast loopback */
-
- PR_SockOpt_NoDelay, /* don't delay send to coalesce packets */
- PR_SockOpt_MaxSegment, /* maximum segment size */
- PR_SockOpt_Broadcast, /* enable broadcast */
- PR_SockOpt_Reuseport, /* allow local address & port reuse on
- * platforms that support it */
- PR_SockOpt_Last
-} PRSockOption;
-
-typedef struct PRLinger {
- PRBool polarity; /* Polarity of the option's setting */
- PRIntervalTime linger; /* Time to linger before closing */
-} PRLinger;
-
-typedef struct PRMcastRequest {
- PRNetAddr mcaddr; /* IP multicast address of group */
- PRNetAddr ifaddr; /* local IP address of interface */
-} PRMcastRequest;
-
-typedef struct PRSocketOptionData
-{
- PRSockOption option;
- union
- {
- PRUintn ip_ttl; /* IP time to live */
- PRUintn mcast_ttl; /* IP multicast time to live */
- PRUintn tos; /* IP type of service and precedence */
- PRBool non_blocking; /* Non-blocking (network) I/O */
- PRBool reuse_addr; /* Allow local address reuse */
- PRBool reuse_port; /* Allow local address & port reuse on
- * platforms that support it */
- PRBool keep_alive; /* Keep connections alive */
- PRBool mcast_loopback; /* IP multicast loopback */
- PRBool no_delay; /* Don't delay send to coalesce packets */
- PRBool broadcast; /* Enable broadcast */
- PRSize max_segment; /* Maximum segment size */
- PRSize recv_buffer_size; /* Receive buffer size */
- PRSize send_buffer_size; /* Send buffer size */
- PRLinger linger; /* Time to linger on close if data present */
- PRMcastRequest add_member; /* add an IP group membership */
- PRMcastRequest drop_member; /* Drop an IP group membership */
- PRNetAddr mcast_if; /* multicast interface address */
- } value;
-} PRSocketOptionData;
-
-/*
-***************************************************************************
-** PRIOVec
-**
-** The I/O vector is used by the write vector method to describe the areas
-** that are affected by the ouput operation.
-***************************************************************************
-*/
-typedef struct PRIOVec {
- char *iov_base;
- int iov_len;
-} PRIOVec;
-
-/*
-***************************************************************************
-** Discover what type of socket is being described by the file descriptor.
-***************************************************************************
-*/
-typedef enum PRDescType
-{
- PR_DESC_FILE = 1,
- PR_DESC_SOCKET_TCP = 2,
- PR_DESC_SOCKET_UDP = 3,
- PR_DESC_LAYERED = 4,
- PR_DESC_PIPE = 5
-} PRDescType;
-
-typedef enum PRSeekWhence {
- PR_SEEK_SET = 0,
- PR_SEEK_CUR = 1,
- PR_SEEK_END = 2
-} PRSeekWhence;
-
-NSPR_API(PRDescType) PR_GetDescType(PRFileDesc *file);
-
-/*
-***************************************************************************
-** PRIOMethods
-**
-** The I/O methods table provides procedural access to the functions of
-** the file descriptor. It is the responsibility of a layer implementor
-** to provide suitable functions at every entry point. If a layer provides
-** no functionality, it should call the next lower(higher) function of the
-** same name (e.g., return fd->lower->method->close(fd->lower));
-**
-** Not all functions are implemented for all types of files. In cases where
-** that is true, the function will return a error indication with an error
-** code of PR_INVALID_METHOD_ERROR.
-***************************************************************************
-*/
-
-typedef PRStatus (PR_CALLBACK *PRCloseFN)(PRFileDesc *fd);
-typedef PRInt32 (PR_CALLBACK *PRReadFN)(PRFileDesc *fd, void *buf, PRInt32 amount);
-typedef PRInt32 (PR_CALLBACK *PRWriteFN)(PRFileDesc *fd, const void *buf, PRInt32 amount);
-typedef PRInt32 (PR_CALLBACK *PRAvailableFN)(PRFileDesc *fd);
-typedef PRInt64 (PR_CALLBACK *PRAvailable64FN)(PRFileDesc *fd);
-typedef PRStatus (PR_CALLBACK *PRFsyncFN)(PRFileDesc *fd);
-typedef PROffset32 (PR_CALLBACK *PRSeekFN)(PRFileDesc *fd, PROffset32 offset, PRSeekWhence how);
-typedef PROffset64 (PR_CALLBACK *PRSeek64FN)(PRFileDesc *fd, PROffset64 offset, PRSeekWhence how);
-typedef PRStatus (PR_CALLBACK *PRFileInfoFN)(PRFileDesc *fd, PRFileInfo *info);
-typedef PRStatus (PR_CALLBACK *PRFileInfo64FN)(PRFileDesc *fd, PRFileInfo64 *info);
-typedef PRInt32 (PR_CALLBACK *PRWritevFN)(
- PRFileDesc *fd, const PRIOVec *iov, PRInt32 iov_size,
- PRIntervalTime timeout);
-typedef PRStatus (PR_CALLBACK *PRConnectFN)(
- PRFileDesc *fd, const PRNetAddr *addr, PRIntervalTime timeout);
-typedef PRFileDesc* (PR_CALLBACK *PRAcceptFN) (
- PRFileDesc *fd, PRNetAddr *addr, PRIntervalTime timeout);
-typedef PRStatus (PR_CALLBACK *PRBindFN)(PRFileDesc *fd, const PRNetAddr *addr);
-typedef PRStatus (PR_CALLBACK *PRListenFN)(PRFileDesc *fd, PRIntn backlog);
-typedef PRStatus (PR_CALLBACK *PRShutdownFN)(PRFileDesc *fd, PRIntn how);
-typedef PRInt32 (PR_CALLBACK *PRRecvFN)(
- PRFileDesc *fd, void *buf, PRInt32 amount,
- PRIntn flags, PRIntervalTime timeout);
-typedef PRInt32 (PR_CALLBACK *PRSendFN) (
- PRFileDesc *fd, const void *buf, PRInt32 amount,
- PRIntn flags, PRIntervalTime timeout);
-typedef PRInt32 (PR_CALLBACK *PRRecvfromFN)(
- PRFileDesc *fd, void *buf, PRInt32 amount,
- PRIntn flags, PRNetAddr *addr, PRIntervalTime timeout);
-typedef PRInt32 (PR_CALLBACK *PRSendtoFN)(
- PRFileDesc *fd, const void *buf, PRInt32 amount,
- PRIntn flags, const PRNetAddr *addr, PRIntervalTime timeout);
-typedef PRInt16 (PR_CALLBACK *PRPollFN)(
- PRFileDesc *fd, PRInt16 in_flags, PRInt16 *out_flags);
-typedef PRInt32 (PR_CALLBACK *PRAcceptreadFN)(
- PRFileDesc *sd, PRFileDesc **nd, PRNetAddr **raddr,
- void *buf, PRInt32 amount, PRIntervalTime t);
-typedef PRInt32 (PR_CALLBACK *PRTransmitfileFN)(
- PRFileDesc *sd, PRFileDesc *fd, const void *headers,
- PRInt32 hlen, PRTransmitFileFlags flags, PRIntervalTime t);
-typedef PRStatus (PR_CALLBACK *PRGetsocknameFN)(PRFileDesc *fd, PRNetAddr *addr);
-typedef PRStatus (PR_CALLBACK *PRGetpeernameFN)(PRFileDesc *fd, PRNetAddr *addr);
-typedef PRStatus (PR_CALLBACK *PRGetsocketoptionFN)(
- PRFileDesc *fd, PRSocketOptionData *data);
-typedef PRStatus (PR_CALLBACK *PRSetsocketoptionFN)(
- PRFileDesc *fd, const PRSocketOptionData *data);
-typedef PRInt32 (PR_CALLBACK *PRSendfileFN)(
- PRFileDesc *networkSocket, PRSendFileData *sendData,
- PRTransmitFileFlags flags, PRIntervalTime timeout);
-typedef PRStatus (PR_CALLBACK *PRConnectcontinueFN)(
- PRFileDesc *fd, PRInt16 out_flags);
-typedef PRIntn (PR_CALLBACK *PRReservedFN)(PRFileDesc *fd);
-
-struct PRIOMethods {
- PRDescType file_type; /* Type of file represented (tos) */
- PRCloseFN close; /* close file and destroy descriptor */
- PRReadFN read; /* read up to specified bytes into buffer */
- PRWriteFN write; /* write specified bytes from buffer */
- PRAvailableFN available; /* determine number of bytes available */
- PRAvailable64FN available64; /* ditto, 64 bit */
- PRFsyncFN fsync; /* flush all buffers to permanent store */
- PRSeekFN seek; /* position the file to the desired place */
- PRSeek64FN seek64; /* ditto, 64 bit */
- PRFileInfoFN fileInfo; /* Get information about an open file */
- PRFileInfo64FN fileInfo64; /* ditto, 64 bit */
- PRWritevFN writev; /* Write segments as described by iovector */
- PRConnectFN connect; /* Connect to the specified (net) address */
- PRAcceptFN accept; /* Accept a connection for a (net) peer */
- PRBindFN bind; /* Associate a (net) address with the fd */
- PRListenFN listen; /* Prepare to listen for (net) connections */
- PRShutdownFN shutdown; /* Shutdown a (net) connection */
- PRRecvFN recv; /* Solicit up the the specified bytes */
- PRSendFN send; /* Send all the bytes specified */
- PRRecvfromFN recvfrom; /* Solicit (net) bytes and report source */
- PRSendtoFN sendto; /* Send bytes to (net) address specified */
- PRPollFN poll; /* Test the fd to see if it is ready */
- PRAcceptreadFN acceptread; /* Accept and read on a new (net) fd */
- PRTransmitfileFN transmitfile; /* Transmit at entire file */
- PRGetsocknameFN getsockname; /* Get (net) address associated with fd */
- PRGetpeernameFN getpeername; /* Get peer's (net) address */
- PRReservedFN reserved_fn_6; /* reserved for future use */
- PRReservedFN reserved_fn_5; /* reserved for future use */
- PRGetsocketoptionFN getsocketoption;
- /* Get current setting of specified option */
- PRSetsocketoptionFN setsocketoption;
- /* Set value of specified option */
- PRSendfileFN sendfile; /* Send a (partial) file with header/trailer*/
- PRConnectcontinueFN connectcontinue;
- /* Continue a nonblocking connect */
- PRReservedFN reserved_fn_3; /* reserved for future use */
- PRReservedFN reserved_fn_2; /* reserved for future use */
- PRReservedFN reserved_fn_1; /* reserved for future use */
- PRReservedFN reserved_fn_0; /* reserved for future use */
-};
-
-/*
- **************************************************************************
- * FUNCTION: PR_GetSpecialFD
- * DESCRIPTION: Get the file descriptor that represents the standard input,
- * output, or error stream.
- * INPUTS:
- * PRSpecialFD id
- * A value indicating the type of stream desired:
- * PR_StandardInput: standard input
- * PR_StandardOuput: standard output
- * PR_StandardError: standard error
- * OUTPUTS: none
- * RETURNS: PRFileDesc *
- * If the argument is valid, PR_GetSpecialFD returns a file descriptor
- * that represents the corresponding standard I/O stream. Otherwise,
- * PR_GetSpecialFD returns NULL and sets error PR_INVALID_ARGUMENT_ERROR.
- **************************************************************************
- */
-
-typedef enum PRSpecialFD
-{
- PR_StandardInput, /* standard input */
- PR_StandardOutput, /* standard output */
- PR_StandardError /* standard error */
-} PRSpecialFD;
-
-NSPR_API(PRFileDesc*) PR_GetSpecialFD(PRSpecialFD id);
-
-#define PR_STDIN PR_GetSpecialFD(PR_StandardInput)
-#define PR_STDOUT PR_GetSpecialFD(PR_StandardOutput)
-#define PR_STDERR PR_GetSpecialFD(PR_StandardError)
-
-/*
- **************************************************************************
- * Layering file descriptors
- *
- * File descriptors may be layered. Each layer has it's own identity.
- * Identities are allocated by the runtime and are to be associated
- * (by the layer implementor) with all layers that are of that type.
- * It is then possible to scan the chain of layers and find a layer
- * that one recongizes and therefore predict that it will implement
- * a desired protocol.
- *
- * There are three well-known identities:
- * PR_INVALID_IO_LAYER => an invalid layer identity, for error return
- * PR_TOP_IO_LAYER => the identity of the top of the stack
- * PR_NSPR_IO_LAYER => the identity used by NSPR proper
- * PR_TOP_IO_LAYER may be used as a shorthand for identifying the topmost
- * layer of an existing stack. Ie., the following two constructs are
- * equivalent.
- *
- * rv = PR_PushIOLayer(stack, PR_TOP_IO_LAYER, my_layer);
- * rv = PR_PushIOLayer(stack, PR_GetLayersIdentity(stack), my_layer)
- *
- * A string may be associated with the creation of the identity. It
- * will be copied by the runtime. If queried the runtime will return
- * a reference to that copied string (not yet another copy). There
- * is no facility for deleting an identity.
- **************************************************************************
- */
-
-#define PR_IO_LAYER_HEAD (PRDescIdentity)-3
-#define PR_INVALID_IO_LAYER (PRDescIdentity)-1
-#define PR_TOP_IO_LAYER (PRDescIdentity)-2
-#define PR_NSPR_IO_LAYER (PRDescIdentity)0
-
-NSPR_API(PRDescIdentity) PR_GetUniqueIdentity(const char *layer_name);
-NSPR_API(const char*) PR_GetNameForIdentity(PRDescIdentity ident);
-NSPR_API(PRDescIdentity) PR_GetLayersIdentity(PRFileDesc* fd);
-NSPR_API(PRFileDesc*) PR_GetIdentitiesLayer(PRFileDesc* fd_stack, PRDescIdentity id);
-
-/*
- **************************************************************************
- * PR_GetDefaultIOMethods: Accessing the default methods table.
- * You may get a pointer to the default methods table by calling this function.
- * You may then select any elements from that table with which to build your
- * layer's methods table. You may NOT modify the table directly.
- **************************************************************************
- */
-NSPR_API(const PRIOMethods *) PR_GetDefaultIOMethods(void);
-
-/*
- **************************************************************************
- * Creating a layer
- *
- * A new layer may be allocated by calling PR_CreateIOLayerStub(). The
- * file descriptor returned will contain the pointer to the methods table
- * provided. The runtime will not modify the table nor test its correctness.
- **************************************************************************
- */
-NSPR_API(PRFileDesc*) PR_CreateIOLayerStub(
- PRDescIdentity ident, const PRIOMethods *methods);
-
-/*
- **************************************************************************
- * Creating a layer
- *
- * A new stack may be created by calling PR_CreateIOLayer(). The
- * file descriptor returned will point to the top of the stack, which has
- * the layer 'fd' as the topmost layer.
- *
- * NOTE: This function creates a new style stack, which has a fixed, dummy
- * header. The old style stack, created by a call to PR_PushIOLayer,
- * results in modifying contents of the top layer of the stack, when
- * pushing and popping layers of the stack.
- **************************************************************************
- */
-NSPR_API(PRFileDesc*) PR_CreateIOLayer(PRFileDesc* fd);
-
-/*
- **************************************************************************
- * Pushing a layer
- *
- * A file descriptor (perhaps allocated using PR_CreateIOLayerStub()) may
- * be pushed into an existing stack of file descriptors at any point the
- * caller deems appropriate. The new layer will be inserted into the stack
- * just above the layer with the indicated identity.
- *
- * Note: Even if the identity parameter indicates the top-most layer of
- * the stack, the value of the file descriptor describing the original
- * stack will not change.
- **************************************************************************
- */
-NSPR_API(PRStatus) PR_PushIOLayer(
- PRFileDesc *fd_stack, PRDescIdentity id, PRFileDesc *layer);
-
-/*
- **************************************************************************
- * Popping a layer
- *
- * A layer may be popped from a stack by indicating the identity of the
- * layer to be removed. If found, a pointer to the removed object will
- * be returned to the caller. The object then becomes the responsibility
- * of the caller.
- *
- * Note: Even if the identity indicates the top layer of the stack, the
- * reference returned will not be the file descriptor for the stack and
- * that file descriptor will remain valid.
- **************************************************************************
- */
-NSPR_API(PRFileDesc*) PR_PopIOLayer(PRFileDesc *fd_stack, PRDescIdentity id);
-
-/*
- **************************************************************************
- * FUNCTION: PR_Open
- * DESCRIPTION: Open a file for reading, writing, or both.
- * INPUTS:
- * const char *name
- * The path name of the file to be opened
- * PRIntn flags
- * The file status flags.
- * It is a bitwise OR of the following bit flags (only one of
- * the first three flags below may be used):
- * PR_RDONLY Open for reading only.
- * PR_WRONLY Open for writing only.
- * PR_RDWR Open for reading and writing.
- * PR_CREATE_FILE If the file does not exist, the file is created
- * If the file exists, this flag has no effect.
- * PR_SYNC If set, each write will wait for both the file data
- * and file status to be physically updated.
- * PR_APPEND The file pointer is set to the end of
- * the file prior to each write.
- * PR_TRUNCATE If the file exists, its length is truncated to 0.
- * PR_EXCL With PR_CREATE_FILE, if the file does not exist,
- * the file is created. If the file already
- * exists, no action and NULL is returned
- *
- * PRIntn mode
- * The access permission bits of the file mode, if the file is
- * created when PR_CREATE_FILE is on.
- * OUTPUTS: None
- * RETURNS: PRFileDesc *
- * If the file is successfully opened,
- * returns a pointer to the PRFileDesc
- * created for the newly opened file.
- * Returns a NULL pointer if the open
- * failed.
- * SIDE EFFECTS:
- * RESTRICTIONS:
- * MEMORY:
- * The return value, if not NULL, points to a dynamically allocated
- * PRFileDesc object.
- * ALGORITHM:
- **************************************************************************
- */
-
-/* Open flags */
-#define PR_RDONLY 0x01
-#define PR_WRONLY 0x02
-#define PR_RDWR 0x04
-#define PR_CREATE_FILE 0x08
-#define PR_APPEND 0x10
-#define PR_TRUNCATE 0x20
-#define PR_SYNC 0x40
-#define PR_EXCL 0x80
-
-/*
-** File modes ....
-**
-** CAVEAT: 'mode' is currently only applicable on UNIX platforms.
-** The 'mode' argument may be ignored by PR_Open on other platforms.
-**
-** 00400 Read by owner.
-** 00200 Write by owner.
-** 00100 Execute (search if a directory) by owner.
-** 00040 Read by group.
-** 00020 Write by group.
-** 00010 Execute by group.
-** 00004 Read by others.
-** 00002 Write by others
-** 00001 Execute by others.
-**
-*/
-
-NSPR_API(PRFileDesc*) PR_Open(const char *name, PRIntn flags, PRIntn mode);
-
-/*
- **************************************************************************
- * FUNCTION: PR_OpenFile
- * DESCRIPTION:
- * Open a file for reading, writing, or both.
- * PR_OpenFile has the same prototype as PR_Open but implements
- * the specified file mode where possible.
- **************************************************************************
- */
-
-/* File mode bits */
-#define PR_IRWXU 00700 /* read, write, execute/search by owner */
-#define PR_IRUSR 00400 /* read permission, owner */
-#define PR_IWUSR 00200 /* write permission, owner */
-#define PR_IXUSR 00100 /* execute/search permission, owner */
-#define PR_IRWXG 00070 /* read, write, execute/search by group */
-#define PR_IRGRP 00040 /* read permission, group */
-#define PR_IWGRP 00020 /* write permission, group */
-#define PR_IXGRP 00010 /* execute/search permission, group */
-#define PR_IRWXO 00007 /* read, write, execute/search by others */
-#define PR_IROTH 00004 /* read permission, others */
-#define PR_IWOTH 00002 /* write permission, others */
-#define PR_IXOTH 00001 /* execute/search permission, others */
-
-NSPR_API(PRFileDesc*) PR_OpenFile(
- const char *name, PRIntn flags, PRIntn mode);
-
-#ifdef MOZ_UNICODE
-/*
- * EXPERIMENTAL: This function may be removed in a future release.
- */
-NSPR_API(PRFileDesc*) PR_OpenFileUTF16(
- const PRUnichar *name, PRIntn flags, PRIntn mode);
-#endif /* MOZ_UNICODE */
-
-/*
- **************************************************************************
- * FUNCTION: PR_Close
- * DESCRIPTION:
- * Close a file or socket.
- * INPUTS:
- * PRFileDesc *fd
- * a pointer to a PRFileDesc.
- * OUTPUTS:
- * None.
- * RETURN:
- * PRStatus
- * SIDE EFFECTS:
- * RESTRICTIONS:
- * None.
- * MEMORY:
- * The dynamic memory pointed to by the argument fd is freed.
- **************************************************************************
- */
-
-NSPR_API(PRStatus) PR_Close(PRFileDesc *fd);
-
-/*
- **************************************************************************
- * FUNCTION: PR_Read
- * DESCRIPTION:
- * Read bytes from a file or socket.
- * The operation will block until either an end of stream indication is
- * encountered, some positive number of bytes are transferred, or there
- * is an error. No more than 'amount' bytes will be transferred.
- * INPUTS:
- * PRFileDesc *fd
- * pointer to the PRFileDesc object for the file or socket
- * void *buf
- * pointer to a buffer to hold the data read in.
- * PRInt32 amount
- * the size of 'buf' (in bytes)
- * OUTPUTS:
- * RETURN:
- * PRInt32
- * a positive number indicates the number of bytes actually read in.
- * 0 means end of file is reached or the network connection is closed.
- * -1 indicates a failure. The reason for the failure is obtained
- * by calling PR_GetError().
- * SIDE EFFECTS:
- * data is written into the buffer pointed to by 'buf'.
- * RESTRICTIONS:
- * None.
- * MEMORY:
- * N/A
- * ALGORITHM:
- * N/A
- **************************************************************************
- */
-
-NSPR_API(PRInt32) PR_Read(PRFileDesc *fd, void *buf, PRInt32 amount);
-
-/*
- ***************************************************************************
- * FUNCTION: PR_Write
- * DESCRIPTION:
- * Write a specified number of bytes to a file or socket. The thread
- * invoking this function blocks until all the data is written.
- * INPUTS:
- * PRFileDesc *fd
- * pointer to a PRFileDesc object that refers to a file or socket
- * const void *buf
- * pointer to the buffer holding the data
- * PRInt32 amount
- * amount of data in bytes to be written from the buffer
- * OUTPUTS:
- * None.
- * RETURN: PRInt32
- * A positive number indicates the number of bytes successfully written.
- * A -1 is an indication that the operation failed. The reason
- * for the failure is obtained by calling PR_GetError().
- ***************************************************************************
- */
-
-NSPR_API(PRInt32) PR_Write(PRFileDesc *fd,const void *buf,PRInt32 amount);
-
-/*
- ***************************************************************************
- * FUNCTION: PR_Writev
- * DESCRIPTION:
- * Write data to a socket. The data is organized in a PRIOVec array. The
- * operation will block until all the data is written or the operation
- * fails.
- * INPUTS:
- * PRFileDesc *fd
- * Pointer that points to a PRFileDesc object for a socket.
- * const PRIOVec *iov
- * An array of PRIOVec. PRIOVec is a struct with the following
- * two fields:
- * char *iov_base;
- * int iov_len;
- * PRInt32 iov_size
- * Number of elements in the iov array. The value of this
- * argument must not be greater than PR_MAX_IOVECTOR_SIZE.
- * If it is, the method will fail (PR_BUFFER_OVERFLOW_ERROR).
- * PRIntervalTime timeout
- * Time limit for completion of the entire write operation.
- * OUTPUTS:
- * None
- * RETURN:
- * A positive number indicates the number of bytes successfully written.
- * A -1 is an indication that the operation failed. The reason
- * for the failure is obtained by calling PR_GetError().
- ***************************************************************************
- */
-
-#define PR_MAX_IOVECTOR_SIZE 16 /* 'iov_size' must be <= */
-
-NSPR_API(PRInt32) PR_Writev(
- PRFileDesc *fd, const PRIOVec *iov, PRInt32 iov_size,
- PRIntervalTime timeout);
-
-/*
- ***************************************************************************
- * FUNCTION: PR_Delete
- * DESCRIPTION:
- * Delete a file from the filesystem. The operation may fail if the
- * file is open.
- * INPUTS:
- * const char *name
- * Path name of the file to be deleted.
- * OUTPUTS:
- * None.
- * RETURN: PRStatus
- * The function returns PR_SUCCESS if the file is successfully
- * deleted, otherwise it returns PR_FAILURE.
- ***************************************************************************
- */
-
-NSPR_API(PRStatus) PR_Delete(const char *name);
-
-/**************************************************************************/
-
-typedef enum PRFileType
-{
- PR_FILE_FILE = 1,
- PR_FILE_DIRECTORY = 2,
- PR_FILE_OTHER = 3
-} PRFileType;
-
-struct PRFileInfo {
- PRFileType type; /* Type of file */
- PROffset32 size; /* Size, in bytes, of file's contents */
- PRTime creationTime; /* Creation time per definition of PRTime */
- PRTime modifyTime; /* Last modification time per definition of PRTime */
-};
-
-struct PRFileInfo64 {
- PRFileType type; /* Type of file */
- PROffset64 size; /* Size, in bytes, of file's contents */
- PRTime creationTime; /* Creation time per definition of PRTime */
- PRTime modifyTime; /* Last modification time per definition of PRTime */
-};
-
-/****************************************************************************
- * FUNCTION: PR_GetFileInfo, PR_GetFileInfo64
- * DESCRIPTION:
- * Get the information about the file with the given path name. This is
- * applicable only to NSFileDesc describing 'file' types (see
- * INPUTS:
- * const char *fn
- * path name of the file
- * OUTPUTS:
- * PRFileInfo *info
- * Information about the given file is written into the file
- * information object pointer to by 'info'.
- * RETURN: PRStatus
- * PR_GetFileInfo returns PR_SUCCESS if file information is successfully
- * obtained, otherwise it returns PR_FAILURE.
- ***************************************************************************
- */
-
-NSPR_API(PRStatus) PR_GetFileInfo(const char *fn, PRFileInfo *info);
-NSPR_API(PRStatus) PR_GetFileInfo64(const char *fn, PRFileInfo64 *info);
-
-#ifdef MOZ_UNICODE
-/*
- * EXPERIMENTAL: This function may be removed in a future release.
- */
-NSPR_API(PRStatus) PR_GetFileInfo64UTF16(const PRUnichar *fn, PRFileInfo64 *info);
-#endif /* MOZ_UNICODE */
-
-/*
- **************************************************************************
- * FUNCTION: PR_GetOpenFileInfo, PR_GetOpenFileInfo64
- * DESCRIPTION:
- * Get information about an open file referred to by the
- * given PRFileDesc object.
- * INPUTS:
- * const PRFileDesc *fd
- * A reference to a valid, open file.
- * OUTPUTS:
- * Same as PR_GetFileInfo, PR_GetFileInfo64
- * RETURN: PRStatus
- * PR_GetFileInfo returns PR_SUCCESS if file information is successfully
- * obtained, otherwise it returns PR_FAILURE.
- ***************************************************************************
- */
-
-NSPR_API(PRStatus) PR_GetOpenFileInfo(PRFileDesc *fd, PRFileInfo *info);
-NSPR_API(PRStatus) PR_GetOpenFileInfo64(PRFileDesc *fd, PRFileInfo64 *info);
-
-/*
- **************************************************************************
- * FUNCTION: PR_Rename
- * DESCRIPTION:
- * Rename a file from the old name 'from' to the new name 'to'.
- * INPUTS:
- * const char *from
- * The old name of the file to be renamed.
- * const char *to
- * The new name of the file.
- * OUTPUTS:
- * None.
- * RETURN: PRStatus
- **************************************************************************
- */
-
-NSPR_API(PRStatus) PR_Rename(const char *from, const char *to);
-
-/*
- *************************************************************************
- * FUNCTION: PR_Access
- * DESCRIPTION:
- * Determine accessibility of a file.
- * INPUTS:
- * const char *name
- * path name of the file
- * PRAccessHow how
- * specifies which access permission to check for.
- * It can be one of the following values:
- * PR_ACCESS_READ_OK Test for read permission
- * PR_ACCESS_WRITE_OK Test for write permission
- * PR_ACCESS_EXISTS Check existence of file
- * OUTPUTS:
- * None.
- * RETURN: PRStatus
- * PR_SUCCESS is returned if the requested access is permitted.
- * Otherwise, PR_FAILURE is returned. Additional information
- * regarding the reason for the failure may be retrieved from
- * PR_GetError().
- *************************************************************************
- */
-
-typedef enum PRAccessHow {
- PR_ACCESS_EXISTS = 1,
- PR_ACCESS_WRITE_OK = 2,
- PR_ACCESS_READ_OK = 3
-} PRAccessHow;
-
-NSPR_API(PRStatus) PR_Access(const char *name, PRAccessHow how);
-
-/*
- *************************************************************************
- * FUNCTION: PR_Seek, PR_Seek64
- * DESCRIPTION:
- * Moves read-write file offset
- * INPUTS:
- * PRFileDesc *fd
- * Pointer to a PRFileDesc object.
- * PROffset32, PROffset64 offset
- * Specifies a value, in bytes, that is used in conjunction
- * with the 'whence' parameter to set the file pointer. A
- * negative value causes seeking in the reverse direction.
- * PRSeekWhence whence
- * Specifies how to interpret the 'offset' parameter in setting
- * the file pointer associated with the 'fd' parameter.
- * Values for the 'whence' parameter are:
- * PR_SEEK_SET Sets the file pointer to the value of the
- * 'offset' parameter
- * PR_SEEK_CUR Sets the file pointer to its current location
- * plus the value of the offset parameter.
- * PR_SEEK_END Sets the file pointer to the size of the
- * file plus the value of the offset parameter.
- * OUTPUTS:
- * None.
- * RETURN: PROffset32, PROffset64
- * Upon successful completion, the resulting pointer location,
- * measured in bytes from the beginning of the file, is returned.
- * If the PR_Seek() function fails, the file offset remains
- * unchanged, and the returned value is -1. The error code can
- * then be retrieved via PR_GetError().
- *************************************************************************
- */
-
-NSPR_API(PROffset32) PR_Seek(PRFileDesc *fd, PROffset32 offset, PRSeekWhence whence);
-NSPR_API(PROffset64) PR_Seek64(PRFileDesc *fd, PROffset64 offset, PRSeekWhence whence);
-
-/*
- ************************************************************************
- * FUNCTION: PR_Available
- * DESCRIPTION:
- * Determine the amount of data in bytes available for reading
- * in the given file or socket.
- * INPUTS:
- * PRFileDesc *fd
- * Pointer to a PRFileDesc object that refers to a file or
- * socket.
- * OUTPUTS:
- * None
- * RETURN: PRInt32, PRInt64
- * Upon successful completion, PR_Available returns the number of
- * bytes beyond the current read pointer that is available for
- * reading. Otherwise, it returns a -1 and the reason for the
- * failure can be retrieved via PR_GetError().
- ************************************************************************
- */
-
-NSPR_API(PRInt32) PR_Available(PRFileDesc *fd);
-NSPR_API(PRInt64) PR_Available64(PRFileDesc *fd);
-
-/*
- ************************************************************************
- * FUNCTION: PR_Sync
- * DESCRIPTION:
- * Sync any buffered data for a fd to its backing device (disk).
- * INPUTS:
- * PRFileDesc *fd
- * Pointer to a PRFileDesc object that refers to a file or
- * socket
- * OUTPUTS:
- * None
- * RETURN: PRStatus
- * PR_SUCCESS is returned if the requested access is permitted.
- * Otherwise, PR_FAILURE is returned.
- ************************************************************************
- */
-
-NSPR_API(PRStatus) PR_Sync(PRFileDesc *fd);
-
-/************************************************************************/
-
-struct PRDirEntry {
- const char *name; /* name of entry, relative to directory name */
-};
-
-#ifdef MOZ_UNICODE
-struct PRDirEntryUTF16 {
- const PRUnichar *name; /* name of entry in UTF16, relative to
- * directory name */
-};
-#endif /* MOZ_UNICODE */
-
-#if !defined(NO_NSPR_10_SUPPORT)
-#define PR_DirName(dirEntry) (dirEntry->name)
-#endif
-
-/*
- *************************************************************************
- * FUNCTION: PR_OpenDir
- * DESCRIPTION:
- * Open the directory by the given name
- * INPUTS:
- * const char *name
- * path name of the directory to be opened
- * OUTPUTS:
- * None
- * RETURN: PRDir *
- * If the directory is sucessfully opened, a PRDir object is
- * dynamically allocated and a pointer to it is returned.
- * If the directory cannot be opened, a NULL pointer is returned.
- * MEMORY:
- * Upon successful completion, the return value points to
- * dynamically allocated memory.
- *************************************************************************
- */
-
-NSPR_API(PRDir*) PR_OpenDir(const char *name);
-
-#ifdef MOZ_UNICODE
-/*
- * EXPERIMENTAL: This function may be removed in a future release.
- */
-NSPR_API(PRDirUTF16*) PR_OpenDirUTF16(const PRUnichar *name);
-#endif /* MOZ_UNICODE */
-
-/*
- *************************************************************************
- * FUNCTION: PR_ReadDir
- * DESCRIPTION:
- * INPUTS:
- * PRDir *dir
- * pointer to a PRDir object that designates an open directory
- * PRDirFlags flags
- * PR_SKIP_NONE Do not skip any files
- * PR_SKIP_DOT Skip the directory entry "." that
- * represents the current directory
- * PR_SKIP_DOT_DOT Skip the directory entry ".." that
- * represents the parent directory.
- * PR_SKIP_BOTH Skip both '.' and '..'
- * PR_SKIP_HIDDEN Skip hidden files
- * OUTPUTS:
- * RETURN: PRDirEntry*
- * Returns a pointer to the next entry in the directory. Returns
- * a NULL pointer upon reaching the end of the directory or when an
- * error occurs. The actual reason can be retrieved via PR_GetError().
- *************************************************************************
- */
-
-typedef enum PRDirFlags {
- PR_SKIP_NONE = 0x0,
- PR_SKIP_DOT = 0x1,
- PR_SKIP_DOT_DOT = 0x2,
- PR_SKIP_BOTH = 0x3,
- PR_SKIP_HIDDEN = 0x4
-} PRDirFlags;
-
-NSPR_API(PRDirEntry*) PR_ReadDir(PRDir *dir, PRDirFlags flags);
-
-#ifdef MOZ_UNICODE
-/*
- * EXPERIMENTAL: This function may be removed in a future release.
- */
-NSPR_API(PRDirEntryUTF16*) PR_ReadDirUTF16(PRDirUTF16 *dir, PRDirFlags flags);
-#endif /* MOZ_UNICODE */
-
-/*
- *************************************************************************
- * FUNCTION: PR_CloseDir
- * DESCRIPTION:
- * Close the specified directory.
- * INPUTS:
- * PRDir *dir
- * The directory to be closed.
- * OUTPUTS:
- * None
- * RETURN: PRStatus
- * If successful, will return a status of PR_SUCCESS. Otherwise
- * a value of PR_FAILURE. The reason for the failure may be re-
- * trieved using PR_GetError().
- *************************************************************************
- */
-
-NSPR_API(PRStatus) PR_CloseDir(PRDir *dir);
-
-#ifdef MOZ_UNICODE
-/*
- * EXPERIMENTAL: This function may be removed in a future release.
- */
-NSPR_API(PRStatus) PR_CloseDirUTF16(PRDirUTF16 *dir);
-#endif /* MOZ_UNICODE */
-
-/*
- *************************************************************************
- * FUNCTION: PR_MkDir
- * DESCRIPTION:
- * Create a new directory with the given name and access mode.
- * INPUTS:
- * const char *name
- * The name of the directory to be created. All the path components
- * up to but not including the leaf component must already exist.
- * PRIntn mode
- * See 'mode' definiton in PR_Open().
- * OUTPUTS:
- * None
- * RETURN: PRStatus
- * If successful, will return a status of PR_SUCCESS. Otherwise
- * a value of PR_FAILURE. The reason for the failure may be re-
- * trieved using PR_GetError().
- *************************************************************************
- */
-
-NSPR_API(PRStatus) PR_MkDir(const char *name, PRIntn mode);
-
-/*
- *************************************************************************
- * FUNCTION: PR_MakeDir
- * DESCRIPTION:
- * Create a new directory with the given name and access mode.
- * PR_MakeDir has the same prototype as PR_MkDir but implements
- * the specified access mode where possible.
- *************************************************************************
- */
-
-NSPR_API(PRStatus) PR_MakeDir(const char *name, PRIntn mode);
-
-/*
- *************************************************************************
- * FUNCTION: PR_RmDir
- * DESCRIPTION:
- * Remove a directory by the given name.
- * INPUTS:
- * const char *name
- * The name of the directory to be removed. All the path components
- * must already exist. Only the leaf component will be removed.
- * OUTPUTS:
- * None
- * RETURN: PRStatus
- * If successful, will return a status of PR_SUCCESS. Otherwise
- * a value of PR_FAILURE. The reason for the failure may be re-
- * trieved using PR_GetError().
- **************************************************************************
- */
-
-NSPR_API(PRStatus) PR_RmDir(const char *name);
-
-/*
- *************************************************************************
- * FUNCTION: PR_NewUDPSocket
- * DESCRIPTION:
- * Create a new UDP socket.
- * INPUTS:
- * None
- * OUTPUTS:
- * None
- * RETURN: PRFileDesc*
- * Upon successful completion, PR_NewUDPSocket returns a pointer
- * to the PRFileDesc created for the newly opened UDP socket.
- * Returns a NULL pointer if the creation of a new UDP socket failed.
- *
- **************************************************************************
- */
-
-NSPR_API(PRFileDesc*) PR_NewUDPSocket(void);
-
-/*
- *************************************************************************
- * FUNCTION: PR_NewTCPSocket
- * DESCRIPTION:
- * Create a new TCP socket.
- * INPUTS:
- * None
- * OUTPUTS:
- * None
- * RETURN: PRFileDesc*
- * Upon successful completion, PR_NewTCPSocket returns a pointer
- * to the PRFileDesc created for the newly opened TCP socket.
- * Returns a NULL pointer if the creation of a new TCP socket failed.
- *
- **************************************************************************
- */
-
-NSPR_API(PRFileDesc*) PR_NewTCPSocket(void);
-
-/*
- *************************************************************************
- * FUNCTION: PR_OpenUDPSocket
- * DESCRIPTION:
- * Create a new UDP socket of the specified address family.
- * INPUTS:
- * PRIntn af
- * Address family
- * OUTPUTS:
- * None
- * RETURN: PRFileDesc*
- * Upon successful completion, PR_OpenUDPSocket returns a pointer
- * to the PRFileDesc created for the newly opened UDP socket.
- * Returns a NULL pointer if the creation of a new UDP socket failed.
- *
- **************************************************************************
- */
-
-NSPR_API(PRFileDesc*) PR_OpenUDPSocket(PRIntn af);
-
-/*
- *************************************************************************
- * FUNCTION: PR_OpenTCPSocket
- * DESCRIPTION:
- * Create a new TCP socket of the specified address family.
- * INPUTS:
- * PRIntn af
- * Address family
- * OUTPUTS:
- * None
- * RETURN: PRFileDesc*
- * Upon successful completion, PR_NewTCPSocket returns a pointer
- * to the PRFileDesc created for the newly opened TCP socket.
- * Returns a NULL pointer if the creation of a new TCP socket failed.
- *
- **************************************************************************
- */
-
-NSPR_API(PRFileDesc*) PR_OpenTCPSocket(PRIntn af);
-
-/*
- *************************************************************************
- * FUNCTION: PR_Connect
- * DESCRIPTION:
- * Initiate a connection on a socket.
- * INPUTS:
- * PRFileDesc *fd
- * Points to a PRFileDesc object representing a socket
- * PRNetAddr *addr
- * Specifies the address of the socket in its own communication
- * space.
- * PRIntervalTime timeout
- * The function uses the lesser of the provided timeout and
- * the OS's connect timeout. In particular, if you specify
- * PR_INTERVAL_NO_TIMEOUT as the timeout, the OS's connection
- * time limit will be used.
- *
- * OUTPUTS:
- * None
- * RETURN: PRStatus
- * Upon successful completion of connection initiation, PR_Connect
- * returns PR_SUCCESS. Otherwise, it returns PR_FAILURE. Further
- * failure information can be obtained by calling PR_GetError().
- **************************************************************************
- */
-
-NSPR_API(PRStatus) PR_Connect(
- PRFileDesc *fd, const PRNetAddr *addr, PRIntervalTime timeout);
-
-/*
- *************************************************************************
- * FUNCTION: PR_ConnectContinue
- * DESCRIPTION:
- * Continue a nonblocking connect. After a nonblocking connect
- * is initiated with PR_Connect() (which fails with
- * PR_IN_PROGRESS_ERROR), one should call PR_Poll() on the socket,
- * with the in_flags PR_POLL_WRITE | PR_POLL_EXCEPT. When
- * PR_Poll() returns, one calls PR_ConnectContinue() on the
- * socket to determine whether the nonblocking connect has
- * completed or is still in progress. Repeat the PR_Poll(),
- * PR_ConnectContinue() sequence until the nonblocking connect
- * has completed.
- * INPUTS:
- * PRFileDesc *fd
- * the file descriptor representing a socket
- * PRInt16 out_flags
- * the out_flags field of the poll descriptor returned by
- * PR_Poll()
- * RETURN: PRStatus
- * If the nonblocking connect has successfully completed,
- * PR_ConnectContinue returns PR_SUCCESS. If PR_ConnectContinue()
- * returns PR_FAILURE, call PR_GetError():
- * - PR_IN_PROGRESS_ERROR: the nonblocking connect is still in
- * progress and has not completed yet. The caller should poll
- * on the file descriptor for the in_flags
- * PR_POLL_WRITE|PR_POLL_EXCEPT and retry PR_ConnectContinue
- * later when PR_Poll() returns.
- * - Other errors: the nonblocking connect has failed with this
- * error code.
- */
-
-NSPR_API(PRStatus) PR_ConnectContinue(PRFileDesc *fd, PRInt16 out_flags);
-
-/*
- *************************************************************************
- * THIS FUNCTION IS DEPRECATED. USE PR_ConnectContinue INSTEAD.
- *
- * FUNCTION: PR_GetConnectStatus
- * DESCRIPTION:
- * Get the completion status of a nonblocking connect. After
- * a nonblocking connect is initiated with PR_Connect() (which
- * fails with PR_IN_PROGRESS_ERROR), one should call PR_Poll()
- * on the socket, with the in_flags PR_POLL_WRITE | PR_POLL_EXCEPT.
- * When PR_Poll() returns, one calls PR_GetConnectStatus on the
- * PRPollDesc structure to determine whether the nonblocking
- * connect has succeeded or failed.
- * INPUTS:
- * const PRPollDesc *pd
- * Pointer to a PRPollDesc whose fd member is the socket,
- * and in_flags must contain PR_POLL_WRITE and PR_POLL_EXCEPT.
- * PR_Poll() should have been called and set the out_flags.
- * RETURN: PRStatus
- * If the nonblocking connect has successfully completed,
- * PR_GetConnectStatus returns PR_SUCCESS. If PR_GetConnectStatus()
- * returns PR_FAILURE, call PR_GetError():
- * - PR_IN_PROGRESS_ERROR: the nonblocking connect is still in
- * progress and has not completed yet.
- * - Other errors: the nonblocking connect has failed with this
- * error code.
- */
-
-NSPR_API(PRStatus) PR_GetConnectStatus(const PRPollDesc *pd);
-
-/*
- *************************************************************************
- * FUNCTION: PR_Accept
- * DESCRIPTION:
- * Accept a connection on a socket.
- * INPUTS:
- * PRFileDesc *fd
- * Points to a PRFileDesc object representing the rendezvous socket
- * on which the caller is willing to accept new connections.
- * PRIntervalTime timeout
- * Time limit for completion of the accept operation.
- * OUTPUTS:
- * PRNetAddr *addr
- * Returns the address of the connecting entity in its own
- * communication space. It may be NULL.
- * RETURN: PRFileDesc*
- * Upon successful acceptance of a connection, PR_Accept
- * returns a valid file descriptor. Otherwise, it returns NULL.
- * Further failure information can be obtained by calling PR_GetError().
- **************************************************************************
- */
-
-NSPR_API(PRFileDesc*) PR_Accept(
- PRFileDesc *fd, PRNetAddr *addr, PRIntervalTime timeout);
-
-/*
- *************************************************************************
- * FUNCTION: PR_Bind
- * DESCRIPTION:
- * Bind an address to a socket.
- * INPUTS:
- * PRFileDesc *fd
- * Points to a PRFileDesc object representing a socket.
- * PRNetAddr *addr
- * Specifies the address to which the socket will be bound.
- * OUTPUTS:
- * None
- * RETURN: PRStatus
- * Upon successful binding of an address to a socket, PR_Bind
- * returns PR_SUCCESS. Otherwise, it returns PR_FAILURE. Further
- * failure information can be obtained by calling PR_GetError().
- **************************************************************************
- */
-
-NSPR_API(PRStatus) PR_Bind(PRFileDesc *fd, const PRNetAddr *addr);
-
-/*
- *************************************************************************
- * FUNCTION: PR_Listen
- * DESCRIPTION:
- * Listen for connections on a socket.
- * INPUTS:
- * PRFileDesc *fd
- * Points to a PRFileDesc object representing a socket that will be
- * used to listen for new connections.
- * PRIntn backlog
- * Specifies the maximum length of the queue of pending connections.
- * OUTPUTS:
- * None
- * RETURN: PRStatus
- * Upon successful completion of listen request, PR_Listen
- * returns PR_SUCCESS. Otherwise, it returns PR_FAILURE. Further
- * failure information can be obtained by calling PR_GetError().
- **************************************************************************
- */
-
-NSPR_API(PRStatus) PR_Listen(PRFileDesc *fd, PRIntn backlog);
-
-/*
- *************************************************************************
- * FUNCTION: PR_Shutdown
- * DESCRIPTION:
- * Shut down part of a full-duplex connection on a socket.
- * INPUTS:
- * PRFileDesc *fd
- * Points to a PRFileDesc object representing a connected socket.
- * PRIntn how
- * Specifies the kind of disallowed operations on the socket.
- * PR_SHUTDOWN_RCV - Further receives will be disallowed
- * PR_SHUTDOWN_SEND - Further sends will be disallowed
- * PR_SHUTDOWN_BOTH - Further sends and receives will be disallowed
- * OUTPUTS:
- * None
- * RETURN: PRStatus
- * Upon successful completion of shutdown request, PR_Shutdown
- * returns PR_SUCCESS. Otherwise, it returns PR_FAILURE. Further
- * failure information can be obtained by calling PR_GetError().
- **************************************************************************
- */
-
-typedef enum PRShutdownHow
-{
- PR_SHUTDOWN_RCV = 0, /* disallow further receives */
- PR_SHUTDOWN_SEND = 1, /* disallow further sends */
- PR_SHUTDOWN_BOTH = 2 /* disallow further receives and sends */
-} PRShutdownHow;
-
-NSPR_API(PRStatus) PR_Shutdown(PRFileDesc *fd, PRShutdownHow how);
-
-/*
- *************************************************************************
- * FUNCTION: PR_Recv
- * DESCRIPTION:
- * Receive a specified number of bytes from a connected socket.
- * The operation will block until some positive number of bytes are
- * transferred, a time out has occurred, or there is an error.
- * No more than 'amount' bytes will be transferred.
- * INPUTS:
- * PRFileDesc *fd
- * points to a PRFileDesc object representing a socket.
- * void *buf
- * pointer to a buffer to hold the data received.
- * PRInt32 amount
- * the size of 'buf' (in bytes)
- * PRIntn flags
- * must be zero or PR_MSG_PEEK.
- * PRIntervalTime timeout
- * Time limit for completion of the receive operation.
- * OUTPUTS:
- * None
- * RETURN: PRInt32
- * a positive number indicates the number of bytes actually received.
- * 0 means the network connection is closed.
- * -1 indicates a failure. The reason for the failure is obtained
- * by calling PR_GetError().
- **************************************************************************
- */
-
-#define PR_MSG_PEEK 0x2
-
-NSPR_API(PRInt32) PR_Recv(PRFileDesc *fd, void *buf, PRInt32 amount,
- PRIntn flags, PRIntervalTime timeout);
-
-/*
- *************************************************************************
- * FUNCTION: PR_Send
- * DESCRIPTION:
- * Send a specified number of bytes from a connected socket.
- * The operation will block until all bytes are
- * processed, a time out has occurred, or there is an error.
- * INPUTS:
- * PRFileDesc *fd
- * points to a PRFileDesc object representing a socket.
- * void *buf
- * pointer to a buffer from where the data is sent.
- * PRInt32 amount
- * the size of 'buf' (in bytes)
- * PRIntn flags
- * (OBSOLETE - must always be zero)
- * PRIntervalTime timeout
- * Time limit for completion of the send operation.
- * OUTPUTS:
- * None
- * RETURN: PRInt32
- * A positive number indicates the number of bytes successfully processed.
- * This number must always equal 'amount'. A -1 is an indication that the
- * operation failed. The reason for the failure is obtained by calling
- * PR_GetError().
- **************************************************************************
- */
-
-NSPR_API(PRInt32) PR_Send(PRFileDesc *fd, const void *buf, PRInt32 amount,
- PRIntn flags, PRIntervalTime timeout);
-
-/*
- *************************************************************************
- * FUNCTION: PR_RecvFrom
- * DESCRIPTION:
- * Receive up to a specified number of bytes from socket which may
- * or may not be connected.
- * The operation will block until one or more bytes are
- * transferred, a time out has occurred, or there is an error.
- * No more than 'amount' bytes will be transferred.
- * INPUTS:
- * PRFileDesc *fd
- * points to a PRFileDesc object representing a socket.
- * void *buf
- * pointer to a buffer to hold the data received.
- * PRInt32 amount
- * the size of 'buf' (in bytes)
- * PRIntn flags
- * (OBSOLETE - must always be zero)
- * PRNetAddr *addr
- * Specifies the address of the sending peer. It may be NULL.
- * PRIntervalTime timeout
- * Time limit for completion of the receive operation.
- * OUTPUTS:
- * None
- * RETURN: PRInt32
- * a positive number indicates the number of bytes actually received.
- * 0 means the network connection is closed.
- * -1 indicates a failure. The reason for the failure is obtained
- * by calling PR_GetError().
- **************************************************************************
- */
-
-NSPR_API(PRInt32) PR_RecvFrom(
- PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags,
- PRNetAddr *addr, PRIntervalTime timeout);
-
-/*
- *************************************************************************
- * FUNCTION: PR_SendTo
- * DESCRIPTION:
- * Send a specified number of bytes from an unconnected socket.
- * The operation will block until all bytes are
- * sent, a time out has occurred, or there is an error.
- * INPUTS:
- * PRFileDesc *fd
- * points to a PRFileDesc object representing an unconnected socket.
- * void *buf
- * pointer to a buffer from where the data is sent.
- * PRInt32 amount
- * the size of 'buf' (in bytes)
- * PRIntn flags
- * (OBSOLETE - must always be zero)
- * PRNetAddr *addr
- * Specifies the address of the peer.
-.* PRIntervalTime timeout
- * Time limit for completion of the send operation.
- * OUTPUTS:
- * None
- * RETURN: PRInt32
- * A positive number indicates the number of bytes successfully sent.
- * -1 indicates a failure. The reason for the failure is obtained
- * by calling PR_GetError().
- **************************************************************************
- */
-
-NSPR_API(PRInt32) PR_SendTo(
- PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
- const PRNetAddr *addr, PRIntervalTime timeout);
-
-/*
-*************************************************************************
-** FUNCTION: PR_TransmitFile
-** DESCRIPTION:
-** Transmitfile sends a complete file (sourceFile) across a socket
-** (networkSocket). If headers is non-NULL, the headers will be sent across
-** the socket prior to sending the file.
-**
-** Optionally, the PR_TRANSMITFILE_CLOSE_SOCKET flag may be passed to
-** transmitfile. This flag specifies that transmitfile should close the
-** socket after sending the data.
-**
-** INPUTS:
-** PRFileDesc *networkSocket
-** The socket to send data over
-** PRFileDesc *sourceFile
-** The file to send
-** const void *headers
-** A pointer to headers to be sent before sending data
-** PRInt32 hlen
-** length of header buffers in bytes.
-** PRTransmitFileFlags flags
-** If the flags indicate that the connection should be closed,
-** it will be done immediately after transferring the file, unless
-** the operation is unsuccessful.
-.* PRIntervalTime timeout
- * Time limit for completion of the transmit operation.
-**
-** RETURNS:
-** Returns the number of bytes written or -1 if the operation failed.
-** If an error occurs while sending the file, the PR_TRANSMITFILE_CLOSE_
-** SOCKET flag is ignored. The reason for the failure is obtained
-** by calling PR_GetError().
-**************************************************************************
-*/
-
-NSPR_API(PRInt32) PR_TransmitFile(
- PRFileDesc *networkSocket, PRFileDesc *sourceFile,
- const void *headers, PRInt32 hlen, PRTransmitFileFlags flags,
- PRIntervalTime timeout);
-
-/*
-*************************************************************************
-** FUNCTION: PR_SendFile
-** DESCRIPTION:
-** PR_SendFile sends data from a file (sendData->fd) across a socket
-** (networkSocket). If specified, a header and/or trailer buffer are sent
-** before and after the file, respectively. The file offset, number of bytes
-** of file data to send, the header and trailer buffers are specified in the
-** sendData argument.
-**
-** Optionally, if the PR_TRANSMITFILE_CLOSE_SOCKET flag is passed, the
-** socket is closed after successfully sending the data.
-**
-** INPUTS:
-** PRFileDesc *networkSocket
-** The socket to send data over
-** PRSendFileData *sendData
-** Contains the FD, file offset and length, header and trailer
-** buffer specifications.
-** PRTransmitFileFlags flags
-** If the flags indicate that the connection should be closed,
-** it will be done immediately after transferring the file, unless
-** the operation is unsuccessful.
-.* PRIntervalTime timeout
- * Time limit for completion of the send operation.
-**
-** RETURNS:
-** Returns the number of bytes written or -1 if the operation failed.
-** If an error occurs while sending the file, the PR_TRANSMITFILE_CLOSE_
-** SOCKET flag is ignored. The reason for the failure is obtained
-** by calling PR_GetError().
-**************************************************************************
-*/
-
-struct PRSendFileData {
- PRFileDesc *fd; /* file to send */
- PRUint32 file_offset; /* file offset */
- PRSize file_nbytes; /* number of bytes of file data to send */
- /* if 0, send data from file_offset to */
- /* end-of-file. */
- const void *header; /* header buffer */
- PRInt32 hlen; /* header len */
- const void *trailer; /* trailer buffer */
- PRInt32 tlen; /* trailer len */
-};
-
-
-NSPR_API(PRInt32) PR_SendFile(
- PRFileDesc *networkSocket, PRSendFileData *sendData,
- PRTransmitFileFlags flags, PRIntervalTime timeout);
-
-/*
-*************************************************************************
-** FUNCTION: PR_AcceptRead
-** DESCRIPTION:
-** AcceptRead accepts a new connection, returns the newly created
-** socket's descriptor and also returns the connecting peer's address.
-** AcceptRead, as its name suggests, also receives the first block of data
-** sent by the peer.
-**
-** INPUTS:
-** PRFileDesc *listenSock
-** A socket descriptor that has been called with the PR_Listen()
-** function, also known as the rendezvous socket.
-** void *buf
-** A pointer to a buffer to receive data sent by the client. This
-** buffer must be large enough to receive <amount> bytes of data
-** and two PRNetAddr structures, plus an extra 32 bytes. See:
-** PR_ACCEPT_READ_BUF_OVERHEAD.
-** PRInt32 amount
-** The number of bytes of client data to receive. Does not include
-** the size of the PRNetAddr structures. If 0, no data will be read
-** from the client.
-** PRIntervalTime timeout
-** The timeout interval only applies to the read portion of the
-** operation. PR_AcceptRead will block indefinitely until the
-** connection is accepted; the read will timeout after the timeout
-** interval elapses.
-** OUTPUTS:
-** PRFileDesc **acceptedSock
-** The file descriptor for the newly connected socket. This parameter
-** will only be valid if the function return does not indicate failure.
-** PRNetAddr **peerAddr,
-** The address of the remote socket. This parameter will only be
-** valid if the function return does not indicate failure. The
-** returned address is not guaranteed to be properly aligned.
-**
-** RETURNS:
-** The number of bytes read from the client or -1 on failure. The reason
-** for the failure is obtained by calling PR_GetError().
-**************************************************************************
-**/
-/* define buffer overhead constant. Add this value to the user's
-** data length when allocating a buffer to accept data.
-** Example:
-** #define USER_DATA_SIZE 10
-** char buf[USER_DATA_SIZE + PR_ACCEPT_READ_BUF_OVERHEAD];
-** bytesRead = PR_AcceptRead( s, fd, &a, &p, USER_DATA_SIZE, ...);
-*/
-#define PR_ACCEPT_READ_BUF_OVERHEAD (32+(2*sizeof(PRNetAddr)))
-
-NSPR_API(PRInt32) PR_AcceptRead(
- PRFileDesc *listenSock, PRFileDesc **acceptedSock,
- PRNetAddr **peerAddr, void *buf, PRInt32 amount, PRIntervalTime timeout);
-
-/*
-*************************************************************************
-** FUNCTION: PR_NewTCPSocketPair
-** DESCRIPTION:
-** Create a new TCP socket pair. The returned descriptors can be used
-** interchangeably; they are interconnected full-duplex descriptors: data
-** written to one can be read from the other and vice-versa.
-**
-** INPUTS:
-** None
-** OUTPUTS:
-** PRFileDesc *fds[2]
-** The file descriptor pair for the newly created TCP sockets.
-** RETURN: PRStatus
-** Upon successful completion of TCP socket pair, PR_NewTCPSocketPair
-** returns PR_SUCCESS. Otherwise, it returns PR_FAILURE. Further
-** failure information can be obtained by calling PR_GetError().
-** XXX can we implement this on windoze and mac?
-**************************************************************************
-**/
-NSPR_API(PRStatus) PR_NewTCPSocketPair(PRFileDesc *fds[2]);
-
-/*
-*************************************************************************
-** FUNCTION: PR_GetSockName
-** DESCRIPTION:
-** Get socket name. Return the network address for this socket.
-**
-** INPUTS:
-** PRFileDesc *fd
-** Points to a PRFileDesc object representing the socket.
-** OUTPUTS:
-** PRNetAddr *addr
-** Returns the address of the socket in its own communication space.
-** RETURN: PRStatus
-** Upon successful completion, PR_GetSockName returns PR_SUCCESS.
-** Otherwise, it returns PR_FAILURE. Further failure information can
-** be obtained by calling PR_GetError().
-**************************************************************************
-**/
-NSPR_API(PRStatus) PR_GetSockName(PRFileDesc *fd, PRNetAddr *addr);
-
-/*
-*************************************************************************
-** FUNCTION: PR_GetPeerName
-** DESCRIPTION:
-** Get name of the connected peer. Return the network address for the
-** connected peer socket.
-**
-** INPUTS:
-** PRFileDesc *fd
-** Points to a PRFileDesc object representing the connected peer.
-** OUTPUTS:
-** PRNetAddr *addr
-** Returns the address of the connected peer in its own communication
-** space.
-** RETURN: PRStatus
-** Upon successful completion, PR_GetPeerName returns PR_SUCCESS.
-** Otherwise, it returns PR_FAILURE. Further failure information can
-** be obtained by calling PR_GetError().
-**************************************************************************
-**/
-NSPR_API(PRStatus) PR_GetPeerName(PRFileDesc *fd, PRNetAddr *addr);
-
-NSPR_API(PRStatus) PR_GetSocketOption(
- PRFileDesc *fd, PRSocketOptionData *data);
-
-NSPR_API(PRStatus) PR_SetSocketOption(
- PRFileDesc *fd, const PRSocketOptionData *data);
-
-/*
- *********************************************************************
- *
- * File descriptor inheritance
- *
- *********************************************************************
- */
-
-/*
- ************************************************************************
- * FUNCTION: PR_SetFDInheritable
- * DESCRIPTION:
- * Set the inheritance attribute of a file descriptor.
- *
- * INPUTS:
- * PRFileDesc *fd
- * Points to a PRFileDesc object.
- * PRBool inheritable
- * If PR_TRUE, the file descriptor fd is set to be inheritable
- * by a child process. If PR_FALSE, the file descriptor is set
- * to be not inheritable by a child process.
- * RETURN: PRStatus
- * Upon successful completion, PR_SetFDInheritable returns PR_SUCCESS.
- * Otherwise, it returns PR_FAILURE. Further failure information can
- * be obtained by calling PR_GetError().
- *************************************************************************
- */
-NSPR_API(PRStatus) PR_SetFDInheritable(
- PRFileDesc *fd,
- PRBool inheritable);
-
-/*
- ************************************************************************
- * FUNCTION: PR_GetInheritedFD
- * DESCRIPTION:
- * Get an inherited file descriptor with the specified name.
- *
- * INPUTS:
- * const char *name
- * The name of the inherited file descriptor.
- * RETURN: PRFileDesc *
- * Upon successful completion, PR_GetInheritedFD returns the
- * inherited file descriptor with the specified name. Otherwise,
- * it returns NULL. Further failure information can be obtained
- * by calling PR_GetError().
- *************************************************************************
- */
-NSPR_API(PRFileDesc *) PR_GetInheritedFD(const char *name);
-
-/*
- *********************************************************************
- *
- * Memory-mapped files
- *
- *********************************************************************
- */
-
-typedef struct PRFileMap PRFileMap;
-
-/*
- * protection options for read and write accesses of a file mapping
- */
-typedef enum PRFileMapProtect {
- PR_PROT_READONLY, /* read only */
- PR_PROT_READWRITE, /* readable, and write is shared */
- PR_PROT_WRITECOPY /* readable, and write is private (copy-on-write) */
-} PRFileMapProtect;
-
-NSPR_API(PRFileMap *) PR_CreateFileMap(
- PRFileDesc *fd,
- PRInt64 size,
- PRFileMapProtect prot);
-
-/*
- * return the alignment (in bytes) of the offset argument to PR_MemMap
- */
-NSPR_API(PRInt32) PR_GetMemMapAlignment(void);
-
-NSPR_API(void *) PR_MemMap(
- PRFileMap *fmap,
- PROffset64 offset, /* must be aligned and sized according to the
- * return value of PR_GetMemMapAlignment() */
- PRUint32 len);
-
-NSPR_API(PRStatus) PR_MemUnmap(void *addr, PRUint32 len);
-
-NSPR_API(PRStatus) PR_CloseFileMap(PRFileMap *fmap);
-
-/*
- * Synchronously flush the given memory-mapped address range of the given open
- * file to disk. The function does not return until all modified data have
- * been written to disk.
- *
- * On some platforms, the function will call PR_Sync(fd) internally if it is
- * necessary for flushing modified data to disk synchronously.
- */
-NSPR_API(PRStatus) PR_SyncMemMap(
- PRFileDesc *fd,
- void *addr,
- PRUint32 len);
-
-/*
- ******************************************************************
- *
- * Interprocess communication
- *
- ******************************************************************
- */
-
-/*
- * Creates an anonymous pipe and returns file descriptors for the
- * read and write ends of the pipe.
- */
-
-NSPR_API(PRStatus) PR_CreatePipe(
- PRFileDesc **readPipe,
- PRFileDesc **writePipe
-);
-
-/************************************************************************/
-/************** The following definitions are for poll ******************/
-/************************************************************************/
-
-struct PRPollDesc {
- PRFileDesc* fd;
- PRInt16 in_flags;
- PRInt16 out_flags;
-};
-
-/*
-** Bit values for PRPollDesc.in_flags or PRPollDesc.out_flags. Binary-or
-** these together to produce the desired poll request.
-*/
-
-#if defined(_PR_POLL_BACKCOMPAT)
-
-#include <poll.h>
-#define PR_POLL_READ POLLIN
-#define PR_POLL_WRITE POLLOUT
-#define PR_POLL_EXCEPT POLLPRI
-#define PR_POLL_ERR POLLERR /* only in out_flags */
-#define PR_POLL_NVAL POLLNVAL /* only in out_flags when fd is bad */
-#define PR_POLL_HUP POLLHUP /* only in out_flags */
-
-#else /* _PR_POLL_BACKCOMPAT */
-
-#define PR_POLL_READ 0x1
-#define PR_POLL_WRITE 0x2
-#define PR_POLL_EXCEPT 0x4
-#define PR_POLL_ERR 0x8 /* only in out_flags */
-#define PR_POLL_NVAL 0x10 /* only in out_flags when fd is bad */
-#define PR_POLL_HUP 0x20 /* only in out_flags */
-
-#endif /* _PR_POLL_BACKCOMPAT */
-
-/*
-*************************************************************************
-** FUNCTION: PR_Poll
-** DESCRIPTION:
-**
-** The call returns as soon as I/O is ready on one or more of the underlying
-** socket objects. A count of the number of ready descriptors is
-** returned unless a timeout occurs in which case zero is returned.
-**
-** PRPollDesc.fd should be set to a pointer to a PRFileDesc object
-** representing a socket. This field can be set to NULL to indicate to
-** PR_Poll that this PRFileDesc object should be ignored.
-** PRPollDesc.in_flags should be set to the desired request
-** (read/write/except or some combination). Upon successful return from
-** this call PRPollDesc.out_flags will be set to indicate what kind of
-** i/o can be performed on the respective descriptor. PR_Poll() uses the
-** out_flags fields as scratch variables during the call. If PR_Poll()
-** returns 0 or -1, the out_flags fields do not contain meaningful values
-** and must not be used.
-**
-** INPUTS:
-** PRPollDesc *pds A pointer to an array of PRPollDesc
-**
-** PRIntn npds The number of elements in the array
-** If this argument is zero PR_Poll is
-** equivalent to a PR_Sleep(timeout).
-**
-** PRIntervalTime timeout Amount of time the call will block waiting
-** for I/O to become ready. If this time expires
-** w/o any I/O becoming ready, the result will
-** be zero.
-**
-** OUTPUTS: None
-** RETURN:
-** PRInt32 Number of PRPollDesc's with events or zero
-** if the function timed out or -1 on failure.
-** The reason for the failure is obtained by
-** calling PR_GetError().
-**************************************************************************
-*/
-NSPR_API(PRInt32) PR_Poll(
- PRPollDesc *pds, PRIntn npds, PRIntervalTime timeout);
-
-/*
-**************************************************************************
-**
-** Pollable events
-**
-** A pollable event is a special kind of file descriptor.
-** The only I/O operation you can perform on a pollable event
-** is to poll it with the PR_POLL_READ flag. You can't
-** read from or write to a pollable event.
-**
-** The purpose of a pollable event is to combine event waiting
-** with I/O waiting in a single PR_Poll call. Pollable events
-** are implemented using a pipe or a pair of TCP sockets
-** connected via the loopback address, therefore setting and
-** waiting for pollable events are expensive operating system
-** calls. Do not use pollable events for general thread
-** synchronization. Use condition variables instead.
-**
-** A pollable event has two states: set and unset. Events
-** are not queued, so there is no notion of an event count.
-** A pollable event is either set or unset.
-**
-** A new pollable event is created by a PR_NewPollableEvent
-** call and is initially in the unset state.
-**
-** PR_WaitForPollableEvent blocks the calling thread until
-** the pollable event is set, and then it atomically unsets
-** the pollable event before it returns.
-**
-** To set a pollable event, call PR_SetPollableEvent.
-**
-** One can call PR_Poll with the PR_POLL_READ flag on a pollable
-** event. When the pollable event is set, PR_Poll returns with
-** the PR_POLL_READ flag set in the out_flags.
-**
-** To close a pollable event, call PR_DestroyPollableEvent
-** (not PR_Close).
-**
-**************************************************************************
-*/
-
-NSPR_API(PRFileDesc *) PR_NewPollableEvent(void);
-
-NSPR_API(PRStatus) PR_DestroyPollableEvent(PRFileDesc *event);
-
-NSPR_API(PRStatus) PR_SetPollableEvent(PRFileDesc *event);
-
-NSPR_API(PRStatus) PR_WaitForPollableEvent(PRFileDesc *event);
-
-PR_END_EXTERN_C
-
-#endif /* prio_h___ */
diff --git a/nspr/pr/include/pripcsem.h b/nspr/pr/include/pripcsem.h
deleted file mode 100644
index f5a524d..0000000
--- a/nspr/pr/include/pripcsem.h
+++ /dev/null
@@ -1,101 +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/. */
-
-/*
- * File: pripcsem.h
- *
- * Description: named semaphores for interprocess
- * synchronization
- *
- * Unrelated processes obtain access to a shared semaphore
- * by specifying its name.
- *
- * Our goal is to support named semaphores on at least
- * Unix and Win32 platforms. The implementation will use
- * one of the three native semaphore APIs: POSIX, System V,
- * and Win32.
- *
- * Because POSIX named semaphores have kernel persistence,
- * we are forced to have a delete function in this API.
- */
-
-#ifndef pripcsem_h___
-#define pripcsem_h___
-
-#include "prtypes.h"
-#include "prio.h"
-
-PR_BEGIN_EXTERN_C
-
-/*
- * PRSem is an opaque structure that represents a named
- * semaphore.
- */
-typedef struct PRSem PRSem;
-
-/*
- * PR_OpenSemaphore --
- *
- * Create or open a named semaphore with the specified name.
- * A handle to the semaphore is returned.
- *
- * If the named semaphore doesn't exist and the PR_SEM_CREATE
- * flag is specified, the named semaphore is created. The
- * created semaphore needs to be removed from the system with
- * a PR_DeleteSemaphore call.
- *
- * If PR_SEM_CREATE is specified, the third argument is the
- * access permission bits of the new semaphore (same
- * interpretation as the mode argument to PR_Open) and the
- * fourth argument is the initial value of the new semaphore.
- * If PR_SEM_CREATE is not specified, the third and fourth
- * arguments are ignored.
- */
-
-#define PR_SEM_CREATE 0x1 /* create if not exist */
-#define PR_SEM_EXCL 0x2 /* fail if already exists */
-
-NSPR_API(PRSem *) PR_OpenSemaphore(
- const char *name, PRIntn flags, PRIntn mode, PRUintn value);
-
-/*
- * PR_WaitSemaphore --
- *
- * If the value of the semaphore is > 0, decrement the value and return.
- * If the value is 0, sleep until the value becomes > 0, then decrement
- * the value and return.
- *
- * The "test and decrement" operation is performed atomically.
- */
-
-NSPR_API(PRStatus) PR_WaitSemaphore(PRSem *sem);
-
-/*
- * PR_PostSemaphore --
- *
- * Increment the value of the named semaphore by 1.
- */
-
-NSPR_API(PRStatus) PR_PostSemaphore(PRSem *sem);
-
-/*
- * PR_CloseSemaphore --
- *
- * Close a named semaphore handle.
- */
-
-NSPR_API(PRStatus) PR_CloseSemaphore(PRSem *sem);
-
-/*
- * PR_DeleteSemaphore --
- *
- * Remove a named semaphore from the system.
- */
-
-NSPR_API(PRStatus) PR_DeleteSemaphore(const char *name);
-
-PR_END_EXTERN_C
-
-#endif /* pripcsem_h___ */
diff --git a/nspr/pr/include/private/pprio.h b/nspr/pr/include/private/pprio.h
deleted file mode 100644
index 26bcd0d..0000000
--- a/nspr/pr/include/private/pprio.h
+++ /dev/null
@@ -1,242 +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/. */
-
-/*
-** File: pprio.h
-**
-** Description: Private definitions for I/O related structures
-*/
-
-#ifndef pprio_h___
-#define pprio_h___
-
-#include "prtypes.h"
-#include "prio.h"
-
-PR_BEGIN_EXTERN_C
-
-/************************************************************************/
-/************************************************************************/
-
-#ifdef _WIN64
-typedef __int64 PROsfd;
-#else
-typedef PRInt32 PROsfd;
-#endif
-
-/* Return the method tables for files, tcp sockets and udp sockets */
-NSPR_API(const PRIOMethods*) PR_GetFileMethods(void);
-NSPR_API(const PRIOMethods*) PR_GetTCPMethods(void);
-NSPR_API(const PRIOMethods*) PR_GetUDPMethods(void);
-NSPR_API(const PRIOMethods*) PR_GetPipeMethods(void);
-
-/*
-** Convert a NSPR socket handle to a native socket handle.
-**
-** Using this function makes your code depend on the properties of the
-** current NSPR implementation, which may change (although extremely
-** unlikely because of NSPR's backward compatibility requirement). Avoid
-** using it if you can.
-**
-** If you use this function, you need to understand what NSPR does to
-** the native handle. For example, NSPR puts native socket handles in
-** non-blocking mode or associates them with an I/O completion port (the
-** WINNT build configuration only). Your use of the native handle should
-** not interfere with NSPR's use of the native handle. If your code
-** changes the configuration of the native handle, (e.g., changes it to
-** blocking or closes it), NSPR will not work correctly.
-*/
-NSPR_API(PROsfd) PR_FileDesc2NativeHandle(PRFileDesc *);
-NSPR_API(void) PR_ChangeFileDescNativeHandle(PRFileDesc *, PROsfd);
-NSPR_API(PRFileDesc*) PR_AllocFileDesc(PROsfd osfd,
- const PRIOMethods *methods);
-NSPR_API(void) PR_FreeFileDesc(PRFileDesc *fd);
-/*
-** Import an existing OS file to NSPR.
-*/
-NSPR_API(PRFileDesc*) PR_ImportFile(PROsfd osfd);
-NSPR_API(PRFileDesc*) PR_ImportPipe(PROsfd osfd);
-NSPR_API(PRFileDesc*) PR_ImportTCPSocket(PROsfd osfd);
-NSPR_API(PRFileDesc*) PR_ImportUDPSocket(PROsfd osfd);
-
-
-/*
- *************************************************************************
- * FUNCTION: PR_CreateSocketPollFd
- * DESCRIPTION:
- * Create a PRFileDesc wrapper for a native socket handle, for use with
- * PR_Poll only
- * INPUTS:
- * None
- * OUTPUTS:
- * None
- * RETURN: PRFileDesc*
- * Upon successful completion, PR_CreateSocketPollFd returns a pointer
- * to the PRFileDesc created for the native socket handle
- * Returns a NULL pointer if the create of a new PRFileDesc failed
- *
- **************************************************************************
- */
-
-NSPR_API(PRFileDesc*) PR_CreateSocketPollFd(PROsfd osfd);
-
-/*
- *************************************************************************
- * FUNCTION: PR_DestroySocketPollFd
- * DESCRIPTION:
- * Destroy the PRFileDesc wrapper created by PR_CreateSocketPollFd
- * INPUTS:
- * None
- * OUTPUTS:
- * None
- * RETURN: PRFileDesc*
- * Upon successful completion, PR_DestroySocketPollFd returns
- * PR_SUCCESS, else PR_FAILURE
- *
- **************************************************************************
- */
-
-NSPR_API(PRStatus) PR_DestroySocketPollFd(PRFileDesc *fd);
-
-
-/*
-** Macros for PR_Socket
-**
-** Socket types: PR_SOCK_STREAM, PR_SOCK_DGRAM
-*/
-
-#ifdef WIN32
-
-#define PR_SOCK_STREAM 1
-#define PR_SOCK_DGRAM 2
-
-#else /* WIN32 */
-
-#define PR_SOCK_STREAM SOCK_STREAM
-#define PR_SOCK_DGRAM SOCK_DGRAM
-
-#endif /* WIN32 */
-
-/*
-** Create a new Socket; this function is obsolete.
-*/
-NSPR_API(PRFileDesc*) PR_Socket(PRInt32 domain, PRInt32 type, PRInt32 proto);
-
-/* FUNCTION: PR_LockFile
-** DESCRIPTION:
-** Lock a file for exclusive access.
-** RETURNS:
-** PR_SUCCESS when the lock is held
-** PR_FAILURE otherwise
-*/
-NSPR_API(PRStatus) PR_LockFile(PRFileDesc *fd);
-
-/* FUNCTION: PR_TLockFile
-** DESCRIPTION:
-** Test and Lock a file for exclusive access. Do not block if the
-** file cannot be locked immediately.
-** RETURNS:
-** PR_SUCCESS when the lock is held
-** PR_FAILURE otherwise
-*/
-NSPR_API(PRStatus) PR_TLockFile(PRFileDesc *fd);
-
-/* FUNCTION: PR_UnlockFile
-** DESCRIPTION:
-** Unlock a file which has been previously locked successfully by this
-** process.
-** RETURNS:
-** PR_SUCCESS when the lock is released
-** PR_FAILURE otherwise
-*/
-NSPR_API(PRStatus) PR_UnlockFile(PRFileDesc *fd);
-
-/*
-** Emulate acceptread by accept and recv.
-*/
-NSPR_API(PRInt32) PR_EmulateAcceptRead(PRFileDesc *sd, PRFileDesc **nd,
- PRNetAddr **raddr, void *buf, PRInt32 amount, PRIntervalTime timeout);
-
-/*
-** Emulate sendfile by reading from the file and writing to the socket.
-** The file is memory-mapped if memory-mapped files are supported.
-*/
-NSPR_API(PRInt32) PR_EmulateSendFile(
- PRFileDesc *networkSocket, PRSendFileData *sendData,
- PRTransmitFileFlags flags, PRIntervalTime timeout);
-
-#ifdef WIN32
-/* FUNCTION: PR_NTFast_AcceptRead
-** DESCRIPTION:
-** NT has the notion of an "accept context", which is only needed in
-** order to make certain calls. By default, a socket connected via
-** AcceptEx can only do a limited number of things without updating
-** the acceptcontext. The generic version of PR_AcceptRead always
-** updates the accept context. This version does not.
-**/
-NSPR_API(PRInt32) PR_NTFast_AcceptRead(PRFileDesc *sd, PRFileDesc **nd,
- PRNetAddr **raddr, void *buf, PRInt32 amount, PRIntervalTime t);
-
-typedef void (*_PR_AcceptTimeoutCallback)(void *);
-
-/* FUNCTION: PR_NTFast_AcceptRead_WithTimeoutCallback
-** DESCRIPTION:
-** The AcceptEx call combines the accept with the read function. However,
-** our daemon threads need to be able to wakeup and reliably flush their
-** log buffers if the Accept times out. However, with the current blocking
-** interface to AcceptRead, there is no way for us to timeout the Accept;
-** this is because when we timeout the Read, we can close the newly
-** socket and continue; but when we timeout the accept itself, there is no
-** new socket to timeout. So instead, this version of the function is
-** provided. After the initial timeout period elapses on the accept()
-** portion of the function, it will call the callback routine and then
-** continue the accept. If the timeout occurs on the read, it will
-** close the connection and return error.
-*/
-NSPR_API(PRInt32) PR_NTFast_AcceptRead_WithTimeoutCallback(
- PRFileDesc *sd,
- PRFileDesc **nd,
- PRNetAddr **raddr,
- void *buf,
- PRInt32 amount,
- PRIntervalTime t,
- _PR_AcceptTimeoutCallback callback,
- void *callback_arg);
-
-/* FUNCTION: PR_NTFast_Accept
-** DESCRIPTION:
-** NT has the notion of an "accept context", which is only needed in
-** order to make certain calls. By default, a socket connected via
-** AcceptEx can only do a limited number of things without updating
-** the acceptcontext. The generic version of PR_Accept always
-** updates the accept context. This version does not.
-**/
-NSPR_API(PRFileDesc*) PR_NTFast_Accept(PRFileDesc *fd, PRNetAddr *addr,
- PRIntervalTime timeout);
-
-/* FUNCTION: PR_NTFast_Update
-** DESCRIPTION:
-** For sockets accepted with PR_NTFast_Accept or PR_NTFastAcceptRead,
-** this function will update the accept context for those sockets,
-** so that the socket can make general purpose socket calls.
-** Without calling this, the only operations supported on the socket
-** Are PR_Read, PR_Write, PR_Transmitfile, and PR_Close.
-*/
-NSPR_API(void) PR_NTFast_UpdateAcceptContext(PRFileDesc *acceptSock,
- PRFileDesc *listenSock);
-
-
-/* FUNCTION: PR_NT_CancelIo
-** DESCRIPTION:
-** Cancel IO operations on fd.
-*/
-NSPR_API(PRStatus) PR_NT_CancelIo(PRFileDesc *fd);
-
-
-#endif /* WIN32 */
-
-PR_END_EXTERN_C
-
-#endif /* pprio_h___ */
diff --git a/nspr/pr/include/private/pprmwait.h b/nspr/pr/include/private/pprmwait.h
deleted file mode 100644
index 3e4057c..0000000
--- a/nspr/pr/include/private/pprmwait.h
+++ /dev/null
@@ -1,103 +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/. */
-
-#if defined(_PPRMWAIT_H)
-#else
-#define _PPRMWAIT_H
-
-#include "prlock.h"
-#include "prcvar.h"
-#include "prclist.h"
-#include "prthread.h"
-
-#define MAX_POLLING_INTERVAL 100
-#define _PR_POLL_COUNT_FUDGE 64
-#define _PR_DEFAULT_HASH_LENGTH 59
-
-/*
- * Our hash table resolves collisions by open addressing with
- * double hashing. See Cormen, Leiserson, and Rivest,
- * Introduction to Algorithms, p. 232, The MIT Press, 1990.
- */
-
-#define _MW_HASH(a, m) ((((PRUptrdiff)(a) >> 4) ^ ((PRUptrdiff)(a) >> 10)) % (m))
-#define _MW_HASH2(a, m) (1 + ((((PRUptrdiff)(a) >> 4) ^ ((PRUptrdiff)(a) >> 10)) % (m - 2)))
-#define _MW_ABORTED(_rv) \
- ((PR_FAILURE == (_rv)) && (PR_PENDING_INTERRUPT_ERROR == PR_GetError()))
-
-typedef enum {_prmw_success, _prmw_rehash, _prmw_error} _PR_HashStory;
-
-typedef struct _PRWaiterHash
-{
- PRUint16 count; /* current number in hash table */
- PRUint16 length; /* current size of the hash table */
- PRRecvWait *recv_wait; /* hash table of receive wait objects */
-} _PRWaiterHash;
-
-typedef enum {_prmw_running, _prmw_stopping, _prmw_stopped} PRMWGroupState;
-
-struct PRWaitGroup
-{
- PRCList group_link; /* all groups are linked to each other */
- PRCList io_ready; /* list of I/O requests that are ready */
- PRMWGroupState state; /* state of this group (so we can shut down) */
-
- PRLock *ml; /* lock for synchronizing this wait group */
- PRCondVar *io_taken; /* calling threads notify when they take I/O */
- PRCondVar *io_complete; /* calling threads wait here for completions */
- PRCondVar *new_business; /* polling thread waits here more work */
- PRCondVar *mw_manage; /* used to manage group lists */
- PRThread* poller; /* thread that's actually doing the poll() */
- PRUint16 waiting_threads; /* number of threads waiting for recv */
- PRUint16 polling_count; /* number of elements in the polling list */
- PRUint32 p_timestamp; /* pseudo-time group had element removed */
- PRPollDesc *polling_list; /* list poller builds for polling */
- PRIntervalTime last_poll; /* last time we polled */
- _PRWaiterHash *waiter; /* pointer to hash table of wait receive objects */
-
-#ifdef WINNT
- /*
- * On NT, idle threads are responsible for getting completed i/o.
- * They need to add completed i/o to the io_ready list. Since
- * idle threads cannot use nspr locks, we have to use an md lock
- * to protect the io_ready list.
- */
- _MDLock mdlock; /* protect io_ready, waiter, and wait_list */
- PRCList wait_list; /* used in place of io_complete. reuse
- * waitQLinks in the PRThread structure. */
-#endif /* WINNT */
-};
-
-/**********************************************************************
-***********************************************************************
-******************** Wait group enumerations **************************
-***********************************************************************
-**********************************************************************/
-typedef struct _PRGlobalState
-{
- PRCList group_list; /* master of the group list */
- PRWaitGroup *group; /* the default (NULL) group */
-} _PRGlobalState;
-
-#ifdef WINNT
-extern PRStatus NT_HashRemoveInternal(PRWaitGroup *group, PRFileDesc *fd);
-#endif
-
-typedef enum {_PR_ENUM_UNSEALED=0, _PR_ENUM_SEALED=0x0eadface} _PREnumSeal;
-
-struct PRMWaitEnumerator
-{
- PRWaitGroup *group; /* group this enumerator is bound to */
- PRThread *thread; /* thread in midst of an enumeration */
- _PREnumSeal seal; /* trying to detect deleted objects */
- PRUint32 p_timestamp; /* when enumeration was (re)started */
- PRRecvWait **waiter; /* pointer into hash table */
- PRUintn index; /* position in hash table */
- void *pad[4]; /* some room to grow */
-};
-
-#endif /* defined(_PPRMWAIT_H) */
-
-/* pprmwait.h */
diff --git a/nspr/pr/include/private/pprthred.h b/nspr/pr/include/private/pprthred.h
deleted file mode 100644
index eb60bae..0000000
--- a/nspr/pr/include/private/pprthred.h
+++ /dev/null
@@ -1,331 +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/. */
-
-#ifndef pprthred_h___
-#define pprthred_h___
-
-/*
-** API for PR private functions. These calls are to be used by internal
-** developers only.
-*/
-#include "nspr.h"
-
-#if defined(XP_OS2)
-#define INCL_DOS
-#define INCL_DOSERRORS
-#define INCL_WIN
-#include <os2.h>
-#endif
-
-PR_BEGIN_EXTERN_C
-
-/*---------------------------------------------------------------------------
-** THREAD PRIVATE FUNCTIONS
----------------------------------------------------------------------------*/
-
-/*
-** Associate a thread object with an existing native thread.
-** "type" is the type of thread object to attach
-** "priority" is the priority to assign to the thread
-** "stack" defines the shape of the threads stack
-**
-** This can return NULL if some kind of error occurs, or if memory is
-** tight. This call invokes "start(obj,arg)" and returns when the
-** function returns. The thread object is automatically destroyed.
-**
-** This call is not normally needed unless you create your own native
-** thread. PR_Init does this automatically for the primordial thread.
-*/
-NSPR_API(PRThread*) PR_AttachThread(PRThreadType type,
- PRThreadPriority priority,
- PRThreadStack *stack);
-
-/*
-** Detach the nspr thread from the currently executing native thread.
-** The thread object will be destroyed and all related data attached
-** to it. The exit procs will be invoked.
-**
-** This call is not normally needed unless you create your own native
-** thread. PR_Exit will automatially detach the nspr thread object
-** created by PR_Init for the primordial thread.
-**
-** This call returns after the nspr thread object is destroyed.
-*/
-NSPR_API(void) PR_DetachThread(void);
-
-/*
-** Get the id of the named thread. Each thread is assigned a unique id
-** when it is created or attached.
-*/
-NSPR_API(PRUint32) PR_GetThreadID(PRThread *thread);
-
-/*
-** Set the procedure that is called when a thread is dumped. The procedure
-** will be applied to the argument, arg, when called. Setting the procedure
-** to NULL effectively removes it.
-*/
-typedef void (*PRThreadDumpProc)(PRFileDesc *fd, PRThread *t, void *arg);
-NSPR_API(void) PR_SetThreadDumpProc(
- PRThread* thread, PRThreadDumpProc dump, void *arg);
-
-/*
-** Get this thread's affinity mask. The affinity mask is a 32 bit quantity
-** marking a bit for each processor this process is allowed to run on.
-** The processor mask is returned in the mask argument.
-** The least-significant-bit represents processor 0.
-**
-** Returns 0 on success, -1 on failure.
-*/
-NSPR_API(PRInt32) PR_GetThreadAffinityMask(PRThread *thread, PRUint32 *mask);
-
-/*
-** Set this thread's affinity mask.
-**
-** Returns 0 on success, -1 on failure.
-*/
-NSPR_API(PRInt32) PR_SetThreadAffinityMask(PRThread *thread, PRUint32 mask );
-
-/*
-** Set the default CPU Affinity mask.
-**
-*/
-NSPR_API(PRInt32) PR_SetCPUAffinityMask(PRUint32 mask);
-
-/*
-** Show status of all threads to standard error output.
-*/
-NSPR_API(void) PR_ShowStatus(void);
-
-/*
-** Set thread recycle mode to on (1) or off (0)
-*/
-NSPR_API(void) PR_SetThreadRecycleMode(PRUint32 flag);
-
-
-/*---------------------------------------------------------------------------
-** THREAD PRIVATE FUNCTIONS FOR GARBAGE COLLECTIBLE THREADS
----------------------------------------------------------------------------*/
-
-/*
-** Only Garbage collectible threads participate in resume all, suspend all and
-** enumeration operations. They are also different during creation when
-** platform specific action may be needed (For example, all Solaris GC able
-** threads are bound threads).
-*/
-
-/*
-** Same as PR_CreateThread except that the thread is marked as garbage
-** collectible.
-*/
-NSPR_API(PRThread*) PR_CreateThreadGCAble(PRThreadType type,
- void (*start)(void *arg),
- void *arg,
- PRThreadPriority priority,
- PRThreadScope scope,
- PRThreadState state,
- PRUint32 stackSize);
-
-/*
-** Same as PR_AttachThread except that the thread being attached is marked as
-** garbage collectible.
-*/
-NSPR_API(PRThread*) PR_AttachThreadGCAble(PRThreadType type,
- PRThreadPriority priority,
- PRThreadStack *stack);
-
-/*
-** Mark the thread as garbage collectible.
-*/
-NSPR_API(void) PR_SetThreadGCAble(void);
-
-/*
-** Unmark the thread as garbage collectible.
-*/
-NSPR_API(void) PR_ClearThreadGCAble(void);
-
-/*
-** This routine prevents all other GC able threads from running. This call is needed by
-** the garbage collector.
-*/
-NSPR_API(void) PR_SuspendAll(void);
-
-/*
-** This routine unblocks all other GC able threads that were suspended from running by
-** PR_SuspendAll(). This call is needed by the garbage collector.
-*/
-NSPR_API(void) PR_ResumeAll(void);
-
-/*
-** Return the thread stack pointer of the given thread.
-** Needed by the garbage collector.
-*/
-NSPR_API(void *) PR_GetSP(PRThread *thread);
-
-/*
-** Save the registers that the GC would find interesting into the thread
-** "t". isCurrent will be non-zero if the thread state that is being
-** saved is the currently executing thread. Return the address of the
-** first register to be scanned as well as the number of registers to
-** scan in "np".
-**
-** If "isCurrent" is non-zero then it is allowed for the thread context
-** area to be used as scratch storage to hold just the registers
-** necessary for scanning.
-**
-** This function simply calls the internal function _MD_HomeGCRegisters().
-*/
-NSPR_API(PRWord *) PR_GetGCRegisters(PRThread *t, int isCurrent, int *np);
-
-/*
-** (Get|Set)ExecutionEnvironent
-**
-** Used by Java to associate it's execution environment so garbage collector
-** can find it. If return is NULL, then it's probably not a collectable thread.
-**
-** There's no locking required around these calls.
-*/
-NSPR_API(void*) GetExecutionEnvironment(PRThread *thread);
-NSPR_API(void) SetExecutionEnvironment(PRThread* thread, void *environment);
-
-/*
-** Enumeration function that applies "func(thread,i,arg)" to each active
-** thread in the process. The enumerator returns PR_SUCCESS if the enumeration
-** should continue, any other value is considered failure, and enumeration
-** stops, returning the failure value from PR_EnumerateThreads.
-** Needed by the garbage collector.
-*/
-typedef PRStatus (PR_CALLBACK *PREnumerator)(PRThread *t, int i, void *arg);
-NSPR_API(PRStatus) PR_EnumerateThreads(PREnumerator func, void *arg);
-
-/*
-** Signature of a thread stack scanning function. It is applied to every
-** contiguous group of potential pointers within a thread. Count denotes the
-** number of pointers.
-*/
-typedef PRStatus
-(PR_CALLBACK *PRScanStackFun)(PRThread* t,
- void** baseAddr, PRUword count, void* closure);
-
-/*
-** Applies scanFun to all contiguous groups of potential pointers
-** within a thread. This includes the stack, registers, and thread-local
-** data. If scanFun returns a status value other than PR_SUCCESS the scan
-** is aborted, and the status value is returned.
-*/
-NSPR_API(PRStatus)
-PR_ThreadScanStackPointers(PRThread* t,
- PRScanStackFun scanFun, void* scanClosure);
-
-/*
-** Calls PR_ThreadScanStackPointers for every thread.
-*/
-NSPR_API(PRStatus)
-PR_ScanStackPointers(PRScanStackFun scanFun, void* scanClosure);
-
-/*
-** Returns a conservative estimate on the amount of stack space left
-** on a thread in bytes, sufficient for making decisions about whether
-** to continue recursing or not.
-*/
-NSPR_API(PRUword)
-PR_GetStackSpaceLeft(PRThread* t);
-
-/*---------------------------------------------------------------------------
-** THREAD CPU PRIVATE FUNCTIONS
----------------------------------------------------------------------------*/
-
-/*
-** Get a pointer to the primordial CPU.
-*/
-NSPR_API(struct _PRCPU *) _PR_GetPrimordialCPU(void);
-
-/*---------------------------------------------------------------------------
-** THREAD SYNCHRONIZATION PRIVATE FUNCTIONS
----------------------------------------------------------------------------*/
-
-/*
-** Create a new named monitor (named for debugging purposes).
-** Monitors are re-entrant locks with a built-in condition variable.
-**
-** This may fail if memory is tight or if some operating system resource
-** is low.
-*/
-NSPR_API(PRMonitor*) PR_NewNamedMonitor(const char* name);
-
-/*
-** Test and then lock the lock if it's not already locked by some other
-** thread. Return PR_FALSE if some other thread owned the lock at the
-** time of the call.
-*/
-NSPR_API(PRBool) PR_TestAndLock(PRLock *lock);
-
-/*
-** Test and then enter the mutex associated with the monitor if it's not
-** already entered by some other thread. Return PR_FALSE if some other
-** thread owned the mutex at the time of the call.
-*/
-NSPR_API(PRBool) PR_TestAndEnterMonitor(PRMonitor *mon);
-
-/*
-** Return the number of times that the current thread has entered the
-** mutex. Returns zero if the current thread has not entered the mutex.
-*/
-NSPR_API(PRIntn) PR_GetMonitorEntryCount(PRMonitor *mon);
-
-/*
-** Just like PR_CEnterMonitor except that if the monitor is owned by
-** another thread NULL is returned.
-*/
-NSPR_API(PRMonitor*) PR_CTestAndEnterMonitor(void *address);
-
-/*---------------------------------------------------------------------------
-** PLATFORM-SPECIFIC INITIALIZATION FUNCTIONS
----------------------------------------------------------------------------*/
-#if defined(IRIX)
-/*
-** Irix specific initialization funtion to be called before PR_Init
-** is called by the application. Sets the CONF_INITUSERS and CONF_INITSIZE
-** attributes of the shared arena set up by nspr.
-**
-** The environment variables _NSPR_IRIX_INITUSERS and _NSPR_IRIX_INITSIZE
-** can also be used to set these arena attributes. If _NSPR_IRIX_INITUSERS
-** is set, but not _NSPR_IRIX_INITSIZE, the value of the CONF_INITSIZE
-** attribute of the nspr arena is scaled as a function of the
-** _NSPR_IRIX_INITUSERS value.
-**
-** If the _PR_Irix_Set_Arena_Params() is called in addition to setting the
-** environment variables, the values of the environment variables are used.
-**
-*/
-NSPR_API(void) _PR_Irix_Set_Arena_Params(PRInt32 initusers, PRInt32 initsize);
-
-#endif /* IRIX */
-
-#if defined(XP_OS2)
-/*
-** These functions need to be called at the start and end of a thread.
-** An EXCEPTIONREGISTRATIONRECORD must be declared on the stack and its
-** address passed to the two functions.
-*/
-NSPR_API(void) PR_OS2_SetFloatExcpHandler(EXCEPTIONREGISTRATIONRECORD* e);
-NSPR_API(void) PR_OS2_UnsetFloatExcpHandler(EXCEPTIONREGISTRATIONRECORD* e);
-#endif /* XP_OS2 */
-
-/* I think PR_GetMonitorEntryCount is useless. All you really want is this... */
-#define PR_InMonitor(m) (PR_GetMonitorEntryCount(m) > 0)
-
-/*---------------------------------------------------------------------------
-** Special X-Lock hack for client
----------------------------------------------------------------------------*/
-
-#ifdef XP_UNIX
-extern void PR_XLock(void);
-extern void PR_XUnlock(void);
-extern PRBool PR_XIsLocked(void);
-#endif /* XP_UNIX */
-
-PR_END_EXTERN_C
-
-#endif /* pprthred_h___ */
diff --git a/nspr/pr/include/private/primpl.h b/nspr/pr/include/private/primpl.h
deleted file mode 100644
index 63ba3ee..0000000
--- a/nspr/pr/include/private/primpl.h
+++ /dev/null
@@ -1,2151 +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/. */
-
-#ifndef primpl_h___
-#define primpl_h___
-
-/*
- * HP-UX 10.10's pthread.h (DCE threads) includes dce/cma.h, which
- * has:
- * #define sigaction _sigaction_sys
- * This macro causes chaos if signal.h gets included before pthread.h.
- * To be safe, we include pthread.h first.
- */
-
-#if defined(_PR_PTHREADS)
-#include <pthread.h>
-#endif
-
-#if defined(_PR_BTHREADS)
-#include <kernel/OS.h>
-#endif
-
-#ifdef WIN32
-/*
- * Allow use of functions and symbols first defined in Win2k.
- */
-#if !defined(WINVER) || (WINVER < 0x0500)
-#undef WINVER
-#define WINVER 0x0500
-#endif
-#if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
-#undef _WIN32_WINNT
-#define _WIN32_WINNT 0x0500
-#endif
-#endif /* WIN32 */
-
-#include "nspr.h"
-#include "prpriv.h"
-
-typedef struct PRSegment PRSegment;
-
-#include "md/prosdep.h"
-#include "obsolete/probslet.h"
-
-#ifdef _PR_HAVE_POSIX_SEMAPHORES
-#include <semaphore.h>
-#elif defined(_PR_HAVE_SYSV_SEMAPHORES)
-#include <sys/sem.h>
-#endif
-
-#ifdef HAVE_SYSCALL
-#include <sys/syscall.h>
-#endif
-
-/*************************************************************************
-***** A Word about Model Dependent Function Naming Convention ***********
-*************************************************************************/
-
-/*
-NSPR 2.0 must implement its function across a range of platforms
-including: MAC, Windows/16, Windows/95, Windows/NT, and several
-variants of Unix. Each implementation shares common code as well
-as having platform dependent portions. This standard describes how
-the model dependent portions are to be implemented.
-
-In header file pr/include/primpl.h, each publicly declared
-platform dependent function is declared as:
-
-NSPR_API void _PR_MD_FUNCTION( long arg1, long arg2 );
-#define _PR_MD_FUNCTION _MD_FUNCTION
-
-In header file pr/include/md/<platform>/_<platform>.h,
-each #define'd macro is redefined as one of:
-
-#define _MD_FUNCTION <blanks>
-#define _MD_FUNCTION <expanded macro>
-#define _MD_FUNCTION <osFunction>
-#define _MD_FUNCTION <_MD_Function>
-
-Where:
-
-<blanks> is no definition at all. In this case, the function is not implemented
-and is never called for this platform.
-For example:
-#define _MD_INIT_CPUS()
-
-<expanded macro> is a C language macro expansion.
-For example:
-#define _MD_CLEAN_THREAD(_thread) \
- PR_BEGIN_MACRO \
- PR_DestroyCondVar(_thread->md.asyncIOCVar); \
- PR_DestroyLock(_thread->md.asyncIOLock); \
- PR_END_MACRO
-
-<osFunction> is some function implemented by the host operating system.
-For example:
-#define _MD_EXIT exit
-
-<_MD_function> is the name of a function implemented for this platform in
-pr/src/md/<platform>/<soruce>.c file.
-For example:
-#define _MD_GETFILEINFO _MD_GetFileInfo
-
-In <source>.c, the implementation is:
-PR_IMPLEMENT(PRInt32) _MD_GetFileInfo(const char *fn, PRFileInfo *info);
-*/
-
-PR_BEGIN_EXTERN_C
-
-typedef struct _MDLock _MDLock;
-typedef struct _MDCVar _MDCVar;
-typedef struct _MDSegment _MDSegment;
-typedef struct _MDThread _MDThread;
-typedef struct _MDThreadStack _MDThreadStack;
-typedef struct _MDSemaphore _MDSemaphore;
-typedef struct _MDDir _MDDir;
-#ifdef MOZ_UNICODE
-typedef struct _MDDirUTF16 _MDDirUTF16;
-#endif /* MOZ_UNICODE */
-typedef struct _MDFileDesc _MDFileDesc;
-typedef struct _MDProcess _MDProcess;
-typedef struct _MDFileMap _MDFileMap;
-
-#if defined(_PR_PTHREADS)
-
-/*
-** The following definitions are unique to implementing NSPR using pthreads.
-** Since pthreads defines most of the thread and thread synchronization
-** stuff, this is a pretty small set.
-*/
-
-#define PT_CV_NOTIFIED_LENGTH 6
-typedef struct _PT_Notified _PT_Notified;
-struct _PT_Notified
-{
- PRIntn length; /* # of used entries in this structure */
- struct
- {
- PRCondVar *cv; /* the condition variable notified */
- PRIntn times; /* and the number of times notified */
- } cv[PT_CV_NOTIFIED_LENGTH];
- _PT_Notified *link; /* link to another of these | NULL */
-};
-
-/*
- * bits defined for pthreads 'state' field
- */
-#define PT_THREAD_DETACHED 0x01 /* thread can't be joined */
-#define PT_THREAD_GLOBAL 0x02 /* a global thread (unlikely) */
-#define PT_THREAD_SYSTEM 0x04 /* system (not user) thread */
-#define PT_THREAD_PRIMORD 0x08 /* this is the primordial thread */
-#define PT_THREAD_ABORTED 0x10 /* thread has been interrupted */
-#define PT_THREAD_GCABLE 0x20 /* thread is garbage collectible */
-#define PT_THREAD_SUSPENDED 0x40 /* thread has been suspended */
-#define PT_THREAD_FOREIGN 0x80 /* thread is not one of ours */
-#define PT_THREAD_BOUND 0x100 /* a bound-global thread */
-
-#define _PT_THREAD_INTERRUPTED(thr) \
- (!(thr->interrupt_blocked) && (thr->state & PT_THREAD_ABORTED))
-#define _PT_THREAD_BLOCK_INTERRUPT(thr) \
- (thr->interrupt_blocked = 1)
-#define _PT_THREAD_UNBLOCK_INTERRUPT(thr) \
- (thr->interrupt_blocked = 0)
-
-#define _PT_IS_GCABLE_THREAD(thr) ((thr)->state & PT_THREAD_GCABLE)
-
-/*
-** Possible values for thread's suspend field
-** Note that the first two can be the same as they are really mutually exclusive,
-** i.e. both cannot be happening at the same time. We have two symbolic names
-** just as a mnemonic.
-**/
-#define PT_THREAD_RESUMED 0x80 /* thread has been resumed */
-#define PT_THREAD_SETGCABLE 0x100 /* set the GCAble flag */
-
-#if defined(DEBUG)
-
-typedef struct PTDebug
-{
- PRTime timeStarted;
- PRUintn locks_created, locks_destroyed;
- PRUintn locks_acquired, locks_released;
- PRUintn cvars_created, cvars_destroyed;
- PRUintn cvars_notified, delayed_cv_deletes;
-} PTDebug;
-
-#endif /* defined(DEBUG) */
-
-NSPR_API(void) PT_FPrintStats(PRFileDesc *fd, const char *msg);
-
-/*
- * On Linux and its derivatives POSIX priority scheduling works only for
- * real-time threads. On those platforms we set thread's nice values
- * instead which requires us to track kernel thread IDs for each POSIX
- * thread we create.
- */
-#if defined(LINUX) && defined(HAVE_SETPRIORITY) && \
- ((defined(HAVE_SYSCALL) && defined(SYS_gettid)) || defined(HAVE_GETTID))
-#define _PR_NICE_PRIORITY_SCHEDULING
-#endif
-
-#else /* defined(_PR_PTHREADS) */
-
-NSPR_API(void) PT_FPrintStats(PRFileDesc *fd, const char *msg);
-
-/*
-** This section is contains those parts needed to implement NSPR on
-** platforms in general. One would assume that the pthreads implementation
-** included lots of the same types, at least conceptually.
-*/
-
-/*
- * Local threads only. No multiple CPU support and hence all the
- * following routines are no-op.
- */
-#ifdef _PR_LOCAL_THREADS_ONLY
-
-#define _PR_MD_SUSPEND_THREAD(thread)
-#define _PR_MD_RESUME_THREAD(thread)
-#define _PR_MD_SUSPEND_CPU(cpu)
-#define _PR_MD_RESUME_CPU(cpu)
-#define _PR_MD_BEGIN_SUSPEND_ALL()
-#define _PR_MD_END_SUSPEND_ALL()
-#define _PR_MD_BEGIN_RESUME_ALL()
-#define _PR_MD_END_RESUME_ALL()
-#define _PR_MD_INIT_ATTACHED_THREAD(thread) PR_FAILURE
-
-#endif
-
-typedef struct _PRCPUQueue _PRCPUQueue;
-typedef struct _PRCPU _PRCPU;
-typedef struct _MDCPU _MDCPU;
-
-struct _PRCPUQueue {
- _MDLock runQLock; /* lock for the run + wait queues */
- _MDLock sleepQLock; /* lock for the run + wait queues */
- _MDLock miscQLock; /* lock for the run + wait queues */
-
- PRCList runQ[PR_PRIORITY_LAST + 1]; /* run queue for this CPU */
- PRUint32 runQReadyMask;
- PRCList sleepQ;
- PRIntervalTime sleepQmax;
- PRCList pauseQ;
- PRCList suspendQ;
- PRCList waitingToJoinQ;
-
- PRUintn numCPUs; /* number of CPUs using this Q */
-};
-
-struct _PRCPU {
- PRCList links; /* link list of CPUs */
- PRUint32 id; /* id for this CPU */
-
- union {
- PRInt32 bits;
- PRUint8 missed[4];
- } u;
- PRIntn where; /* index into u.missed */
- PRPackedBool paused; /* cpu is paused */
- PRPackedBool exit; /* cpu should exit */
-
- PRThread *thread; /* native thread for this CPUThread */
- PRThread *idle_thread; /* user-level idle thread for this CPUThread */
-
- PRIntervalTime last_clock; /* the last time we went into
- * _PR_ClockInterrupt() on this CPU
- */
-
- _PRCPUQueue *queue;
-
- _MDCPU md;
-};
-
-typedef struct _PRInterruptTable {
- const char *name;
- PRUintn missed_bit;
- void (*handler)(void);
-} _PRInterruptTable;
-
-#define _PR_CPU_PTR(_qp) \
- ((_PRCPU*) ((char*) (_qp) - offsetof(_PRCPU,links)))
-
-#if !defined(IRIX) && !defined(WIN32) && !defined(XP_OS2) \
- && !(defined(SOLARIS) && defined(_PR_GLOBAL_THREADS_ONLY))
-#define _MD_GET_ATTACHED_THREAD() (_PR_MD_CURRENT_THREAD())
-#endif
-
-#ifdef _PR_LOCAL_THREADS_ONLY
-
-NSPR_API(struct _PRCPU *) _pr_currentCPU;
-NSPR_API(PRThread *) _pr_currentThread;
-NSPR_API(PRThread *) _pr_lastThread;
-NSPR_API(PRInt32) _pr_intsOff;
-
-#define _MD_CURRENT_CPU() (_pr_currentCPU)
-#define _MD_SET_CURRENT_CPU(_cpu) (_pr_currentCPU = (_cpu))
-#define _MD_CURRENT_THREAD() (_pr_currentThread)
-#define _MD_SET_CURRENT_THREAD(_thread) (_pr_currentThread = (_thread))
-#define _MD_LAST_THREAD() (_pr_lastThread)
-#define _MD_SET_LAST_THREAD(t) (_pr_lastThread = t)
-
-#define _MD_GET_INTSOFF() (_pr_intsOff)
-#define _MD_SET_INTSOFF(_val) (_pr_intsOff = _val)
-
-
-/* The unbalanced curly braces in these two macros are intentional */
-#define _PR_LOCK_HEAP() { PRIntn _is; if (_pr_currentCPU) _PR_INTSOFF(_is);
-#define _PR_UNLOCK_HEAP() if (_pr_currentCPU) _PR_INTSON(_is); }
-
-#endif /* _PR_LOCAL_THREADS_ONLY */
-
-extern PRInt32 _native_threads_only;
-
-#if defined(_PR_GLOBAL_THREADS_ONLY)
-
-#define _MD_GET_INTSOFF() 0
-#define _MD_SET_INTSOFF(_val)
-#define _PR_INTSOFF(_is)
-#define _PR_FAST_INTSON(_is)
-#define _PR_INTSON(_is)
-#define _PR_THREAD_LOCK(_thread)
-#define _PR_THREAD_UNLOCK(_thread)
-#define _PR_RUNQ_LOCK(cpu)
-#define _PR_RUNQ_UNLOCK(cpu)
-#define _PR_SLEEPQ_LOCK(thread)
-#define _PR_SLEEPQ_UNLOCK(thread)
-#define _PR_MISCQ_LOCK(thread)
-#define _PR_MISCQ_UNLOCK(thread)
-#define _PR_CPU_LIST_LOCK()
-#define _PR_CPU_LIST_UNLOCK()
-
-#define _PR_ADD_RUNQ(_thread, _cpu, _pri)
-#define _PR_DEL_RUNQ(_thread)
-#define _PR_ADD_SLEEPQ(_thread, _timeout)
-#define _PR_DEL_SLEEPQ(_thread, _propogate)
-#define _PR_ADD_JOINQ(_thread, _cpu)
-#define _PR_DEL_JOINQ(_thread)
-#define _PR_ADD_SUSPENDQ(_thread, _cpu)
-#define _PR_DEL_SUSPENDQ(_thread)
-
-#define _PR_THREAD_SWITCH_CPU(_thread, _newCPU)
-
-#define _PR_IS_NATIVE_THREAD(thread) 1
-#define _PR_IS_NATIVE_THREAD_SUPPORTED() 1
-
-#else
-
-#define _PR_INTSOFF(_is) \
- PR_BEGIN_MACRO \
- (_is) = _PR_MD_GET_INTSOFF(); \
- _PR_MD_SET_INTSOFF(1); \
- PR_END_MACRO
-
-#define _PR_FAST_INTSON(_is) \
- PR_BEGIN_MACRO \
- _PR_MD_SET_INTSOFF(_is); \
- PR_END_MACRO
-
-#define _PR_INTSON(_is) \
- PR_BEGIN_MACRO \
- if ((_is == 0) && (_PR_MD_CURRENT_CPU())->u.bits) \
- _PR_IntsOn((_PR_MD_CURRENT_CPU())); \
- _PR_MD_SET_INTSOFF(_is); \
- PR_END_MACRO
-
-#ifdef _PR_LOCAL_THREADS_ONLY
-
-#define _PR_IS_NATIVE_THREAD(thread) 0
-#define _PR_THREAD_LOCK(_thread)
-#define _PR_THREAD_UNLOCK(_thread)
-#define _PR_RUNQ_LOCK(cpu)
-#define _PR_RUNQ_UNLOCK(cpu)
-#define _PR_SLEEPQ_LOCK(thread)
-#define _PR_SLEEPQ_UNLOCK(thread)
-#define _PR_MISCQ_LOCK(thread)
-#define _PR_MISCQ_UNLOCK(thread)
-#define _PR_CPU_LIST_LOCK()
-#define _PR_CPU_LIST_UNLOCK()
-
-#define _PR_ADD_RUNQ(_thread, _cpu, _pri) \
- PR_BEGIN_MACRO \
- PR_APPEND_LINK(&(_thread)->links, &_PR_RUNQ(_cpu)[_pri]); \
- _PR_RUNQREADYMASK(_cpu) |= (1L << _pri); \
- PR_END_MACRO
-
-#define _PR_DEL_RUNQ(_thread) \
- PR_BEGIN_MACRO \
- _PRCPU *_cpu = _thread->cpu; \
- PRInt32 _pri = _thread->priority; \
- PR_REMOVE_LINK(&(_thread)->links); \
- if (PR_CLIST_IS_EMPTY(&_PR_RUNQ(_cpu)[_pri])) \
- _PR_RUNQREADYMASK(_cpu) &= ~(1L << _pri); \
- PR_END_MACRO
-
-#define _PR_ADD_SLEEPQ(_thread, _timeout) \
- _PR_AddSleepQ(_thread, _timeout);
-
-#define _PR_DEL_SLEEPQ(_thread, _propogate) \
- _PR_DelSleepQ(_thread, _propogate);
-
-#define _PR_ADD_JOINQ(_thread, _cpu) \
- PR_APPEND_LINK(&(_thread)->links, &_PR_WAITINGTOJOINQ(_cpu));
-
-#define _PR_DEL_JOINQ(_thread) \
- PR_REMOVE_LINK(&(_thread)->links);
-
-#define _PR_ADD_SUSPENDQ(_thread, _cpu) \
- PR_APPEND_LINK(&(_thread)->links, &_PR_SUSPENDQ(_cpu));
-
-#define _PR_DEL_SUSPENDQ(_thread) \
- PR_REMOVE_LINK(&(_thread)->links);
-
-#define _PR_THREAD_SWITCH_CPU(_thread, _newCPU)
-
-#define _PR_IS_NATIVE_THREAD_SUPPORTED() 0
-
-#else /* _PR_LOCAL_THREADS_ONLY */
-
-/* These are for the "combined" thread model */
-
-#define _PR_THREAD_LOCK(_thread) \
- _PR_MD_LOCK(&(_thread)->threadLock);
-
-#define _PR_THREAD_UNLOCK(_thread) \
- _PR_MD_UNLOCK(&(_thread)->threadLock);
-
-#define _PR_RUNQ_LOCK(_cpu) \
- PR_BEGIN_MACRO \
- _PR_MD_LOCK(&(_cpu)->queue->runQLock );\
- PR_END_MACRO
-
-#define _PR_RUNQ_UNLOCK(_cpu) \
- PR_BEGIN_MACRO \
- _PR_MD_UNLOCK(&(_cpu)->queue->runQLock );\
- PR_END_MACRO
-
-#define _PR_SLEEPQ_LOCK(_cpu) \
- _PR_MD_LOCK(&(_cpu)->queue->sleepQLock );
-
-#define _PR_SLEEPQ_UNLOCK(_cpu) \
- _PR_MD_UNLOCK(&(_cpu)->queue->sleepQLock );
-
-#define _PR_MISCQ_LOCK(_cpu) \
- _PR_MD_LOCK(&(_cpu)->queue->miscQLock );
-
-#define _PR_MISCQ_UNLOCK(_cpu) \
- _PR_MD_UNLOCK(&(_cpu)->queue->miscQLock );
-
-#define _PR_CPU_LIST_LOCK() _PR_MD_LOCK(&_pr_cpuLock)
-#define _PR_CPU_LIST_UNLOCK() _PR_MD_UNLOCK(&_pr_cpuLock)
-
-#define QUEUE_RUN 0x1
-#define QUEUE_SLEEP 0x2
-#define QUEUE_JOIN 0x4
-#define QUEUE_SUSPEND 0x8
-#define QUEUE_LOCK 0x10
-
-#define _PR_ADD_RUNQ(_thread, _cpu, _pri) \
- PR_BEGIN_MACRO \
- PR_APPEND_LINK(&(_thread)->links, &_PR_RUNQ(_cpu)[_pri]); \
- _PR_RUNQREADYMASK(_cpu) |= (1L << _pri); \
- PR_ASSERT((_thread)->queueCount == 0); \
- (_thread)->queueCount = QUEUE_RUN; \
- PR_END_MACRO
-
-#define _PR_DEL_RUNQ(_thread) \
- PR_BEGIN_MACRO \
- _PRCPU *_cpu = _thread->cpu; \
- PRInt32 _pri = _thread->priority; \
- PR_REMOVE_LINK(&(_thread)->links); \
- if (PR_CLIST_IS_EMPTY(&_PR_RUNQ(_cpu)[_pri])) \
- _PR_RUNQREADYMASK(_cpu) &= ~(1L << _pri); \
- PR_ASSERT((_thread)->queueCount == QUEUE_RUN);\
- (_thread)->queueCount = 0; \
- PR_END_MACRO
-
-#define _PR_ADD_SLEEPQ(_thread, _timeout) \
- PR_ASSERT((_thread)->queueCount == 0); \
- (_thread)->queueCount = QUEUE_SLEEP; \
- _PR_AddSleepQ(_thread, _timeout);
-
-#define _PR_DEL_SLEEPQ(_thread, _propogate) \
- PR_ASSERT((_thread)->queueCount == QUEUE_SLEEP);\
- (_thread)->queueCount = 0; \
- _PR_DelSleepQ(_thread, _propogate);
-
-#define _PR_ADD_JOINQ(_thread, _cpu) \
- PR_ASSERT((_thread)->queueCount == 0); \
- (_thread)->queueCount = QUEUE_JOIN; \
- PR_APPEND_LINK(&(_thread)->links, &_PR_WAITINGTOJOINQ(_cpu));
-
-#define _PR_DEL_JOINQ(_thread) \
- PR_ASSERT((_thread)->queueCount == QUEUE_JOIN);\
- (_thread)->queueCount = 0; \
- PR_REMOVE_LINK(&(_thread)->links);
-
-#define _PR_ADD_SUSPENDQ(_thread, _cpu) \
- PR_ASSERT((_thread)->queueCount == 0); \
- (_thread)->queueCount = QUEUE_SUSPEND; \
- PR_APPEND_LINK(&(_thread)->links, &_PR_SUSPENDQ(_cpu));
-
-#define _PR_DEL_SUSPENDQ(_thread) \
- PR_ASSERT((_thread)->queueCount == QUEUE_SUSPEND);\
- (_thread)->queueCount = 0; \
- PR_REMOVE_LINK(&(_thread)->links);
-
-#define _PR_THREAD_SWITCH_CPU(_thread, _newCPU) \
- (_thread)->cpu = (_newCPU);
-
-#define _PR_IS_NATIVE_THREAD(thread) (thread->flags & _PR_GLOBAL_SCOPE)
-#define _PR_IS_NATIVE_THREAD_SUPPORTED() 1
-
-#endif /* _PR_LOCAL_THREADS_ONLY */
-
-#endif /* _PR_GLOBAL_THREADS_ONLY */
-
-#define _PR_SET_RESCHED_FLAG() _PR_MD_CURRENT_CPU()->u.missed[3] = 1
-#define _PR_CLEAR_RESCHED_FLAG() _PR_MD_CURRENT_CPU()->u.missed[3] = 0
-
-extern _PRInterruptTable _pr_interruptTable[];
-
-/* Bits for _pr_interruptState.u.missed[0,1] */
-#define _PR_MISSED_CLOCK 0x1
-#define _PR_MISSED_IO 0x2
-#define _PR_MISSED_CHILD 0x4
-
-extern void _PR_IntsOn(_PRCPU *cpu);
-
-NSPR_API(void) _PR_WakeupCPU(void);
-NSPR_API(void) _PR_PauseCPU(void);
-
-/************************************************************************/
-
-#define _PR_LOCK_LOCK(_lock) \
- _PR_MD_LOCK(&(_lock)->ilock);
-#define _PR_LOCK_UNLOCK(_lock) \
- _PR_MD_UNLOCK(&(_lock)->ilock);
-
-extern void _PR_UnblockLockWaiter(PRLock *lock);
-extern PRStatus _PR_InitLock(PRLock *lock);
-extern void _PR_FreeLock(PRLock *lock);
-
-#define _PR_LOCK_PTR(_qp) \
- ((PRLock*) ((char*) (_qp) - offsetof(PRLock,links)))
-
-/************************************************************************/
-
-#define _PR_CVAR_LOCK(_cvar) \
- _PR_MD_LOCK(&(_cvar)->ilock);
-#define _PR_CVAR_UNLOCK(_cvar) \
- _PR_MD_UNLOCK(&(_cvar)->ilock);
-
-extern PRStatus _PR_InitCondVar(PRCondVar *cvar, PRLock *lock);
-extern void _PR_FreeCondVar(PRCondVar *cvar);
-extern PRStatus _PR_WaitCondVar(
- PRThread *thread, PRCondVar *cvar, PRLock *lock, PRIntervalTime timeout);
-extern void _PR_NotifyCondVar(PRCondVar *cvar, PRThread *me);
-extern PRUint32 _PR_CondVarToString(PRCondVar *cvar, char *buf, PRUint32 buflen);
-
-NSPR_API(void) _PR_Notify(PRMonitor *mon, PRBool all, PRBool sticky);
-
-/* PRThread.flags */
-#define _PR_SYSTEM 0x01
-#define _PR_INTERRUPT 0x02
-#define _PR_ATTACHED 0x04 /* created via PR_AttachThread */
-#define _PR_PRIMORDIAL 0x08 /* the thread that called PR_Init */
-#define _PR_ON_SLEEPQ 0x10 /* thread is on the sleepQ */
-#define _PR_ON_PAUSEQ 0x20 /* thread is on the pauseQ */
-#define _PR_SUSPENDING 0x40 /* thread wants to suspend */
-#define _PR_GLOBAL_SCOPE 0x80 /* thread is global scope */
-#define _PR_IDLE_THREAD 0x200 /* this is an idle thread */
-#define _PR_GCABLE_THREAD 0x400 /* this is a collectable thread */
-#define _PR_BOUND_THREAD 0x800 /* a bound thread */
-#define _PR_INTERRUPT_BLOCKED 0x1000 /* interrupts blocked */
-
-/* PRThread.state */
-#define _PR_UNBORN 0
-#define _PR_RUNNABLE 1
-#define _PR_RUNNING 2
-#define _PR_LOCK_WAIT 3
-#define _PR_COND_WAIT 4
-#define _PR_JOIN_WAIT 5
-#define _PR_IO_WAIT 6
-#define _PR_SUSPENDED 7
-#define _PR_DEAD_STATE 8 /* for debugging */
-
-/* PRThreadStack.flags */
-#define _PR_STACK_VM 0x1 /* using vm instead of malloc */
-#define _PR_STACK_MAPPED 0x2 /* vm is mapped */
-#define _PR_STACK_PRIMORDIAL 0x4 /* stack for primordial thread */
-
-/*
-** If the default stcksize from the client is zero, we need to pick a machine
-** dependent value. This is only for standard user threads. For custom threads,
-** 0 has a special meaning.
-** Adjust stackSize. Round up to a page boundary.
-*/
-
-#ifndef _MD_MINIMUM_STACK_SIZE
-#define _MD_MINIMUM_STACK_SIZE 0
-#endif
-
-#if (!defined(HAVE_CUSTOM_USER_THREADS))
-#define _PR_ADJUST_STACKSIZE(stackSize) \
- PR_BEGIN_MACRO \
- if (stackSize == 0) \
- stackSize = _MD_DEFAULT_STACK_SIZE; \
- if (stackSize < _MD_MINIMUM_STACK_SIZE) \
- stackSize = _MD_MINIMUM_STACK_SIZE; \
- stackSize = (stackSize + (1 << _pr_pageShift) - 1) >> _pr_pageShift; \
- stackSize <<= _pr_pageShift; \
- PR_END_MACRO
-#else
-#define _PR_ADJUST_STACKSIZE(stackSize)
-#endif
-
-#define _PR_IS_GCABLE_THREAD(thr) ((thr)->flags & _PR_GCABLE_THREAD)
-
-#define _PR_PENDING_INTERRUPT(thr) \
- (!((thr)->flags & _PR_INTERRUPT_BLOCKED) && ((thr)->flags & _PR_INTERRUPT))
-#define _PR_THREAD_BLOCK_INTERRUPT(thr) \
- (thr->flags |= _PR_INTERRUPT_BLOCKED)
-#define _PR_THREAD_UNBLOCK_INTERRUPT(thr) \
- (thr->flags &= ~_PR_INTERRUPT_BLOCKED)
-
-#define _PR_THREAD_PTR(_qp) \
- ((PRThread*) ((char*) (_qp) - offsetof(PRThread,links)))
-
-#define _PR_ACTIVE_THREAD_PTR(_qp) \
- ((PRThread*) ((char*) (_qp) - offsetof(PRThread,active)))
-
-#define _PR_THREAD_CONDQ_PTR(_qp) \
- ((PRThread*) ((char*) (_qp) - offsetof(PRThread,waitQLinks)))
-
-#define _PR_THREAD_MD_TO_PTR(_md) \
- ((PRThread*) ((char*) (_md) - offsetof(PRThread,md)))
-
-#define _PR_THREAD_STACK_TO_PTR(_stack) \
- ((PRThread*) (_stack->thr))
-
-extern PRCList _pr_active_local_threadQ;
-extern PRCList _pr_active_global_threadQ;
-extern PRCList _pr_cpuQ;
-extern _MDLock _pr_cpuLock;
-extern PRInt32 _pr_md_idle_cpus;
-
-#define _PR_ACTIVE_LOCAL_THREADQ() _pr_active_local_threadQ
-#define _PR_ACTIVE_GLOBAL_THREADQ() _pr_active_global_threadQ
-#define _PR_CPUQ() _pr_cpuQ
-#define _PR_RUNQ(_cpu) ((_cpu)->queue->runQ)
-#define _PR_RUNQREADYMASK(_cpu) ((_cpu)->queue->runQReadyMask)
-#define _PR_SLEEPQ(_cpu) ((_cpu)->queue->sleepQ)
-#define _PR_SLEEPQMAX(_cpu) ((_cpu)->queue->sleepQmax)
-#define _PR_PAUSEQ(_cpu) ((_cpu)->queue->pauseQ)
-#define _PR_SUSPENDQ(_cpu) ((_cpu)->queue->suspendQ)
-#define _PR_WAITINGTOJOINQ(_cpu) ((_cpu)->queue->waitingToJoinQ)
-
-extern PRUint32 _pr_recycleThreads; /* Flag for behavior on thread cleanup */
-extern PRLock *_pr_deadQLock;
-extern PRUint32 _pr_numNativeDead;
-extern PRUint32 _pr_numUserDead;
-extern PRCList _pr_deadNativeQ;
-extern PRCList _pr_deadUserQ;
-#define _PR_DEADNATIVEQ _pr_deadNativeQ
-#define _PR_DEADUSERQ _pr_deadUserQ
-#define _PR_DEADQ_LOCK PR_Lock(_pr_deadQLock);
-#define _PR_DEADQ_UNLOCK PR_Unlock(_pr_deadQLock);
-#define _PR_INC_DEADNATIVE (_pr_numNativeDead++)
-#define _PR_DEC_DEADNATIVE (_pr_numNativeDead--)
-#define _PR_NUM_DEADNATIVE (_pr_numNativeDead)
-#define _PR_INC_DEADUSER (_pr_numUserDead++)
-#define _PR_DEC_DEADUSER (_pr_numUserDead--)
-#define _PR_NUM_DEADUSER (_pr_numUserDead)
-
-extern PRUint32 _pr_utid;
-
-extern struct _PRCPU *_pr_primordialCPU;
-
-extern PRLock *_pr_activeLock; /* lock for userActive and systemActive */
-extern PRInt32 _pr_userActive; /* number of active user threads */
-extern PRInt32 _pr_systemActive; /* number of active system threads */
-extern PRInt32 _pr_primordialExitCount; /* number of user threads left
- * before the primordial thread
- * can exit. */
-extern PRCondVar *_pr_primordialExitCVar; /* the condition variable for
- * notifying the primordial thread
- * when all other user threads
- * have terminated. */
-
-extern PRUintn _pr_maxPTDs;
-
-extern PRLock *_pr_terminationCVLock;
-
-/*************************************************************************
-* Internal routines either called by PR itself or from machine-dependent *
-* code. *
-*************************************************************************/
-
-extern void _PR_ClockInterrupt(void);
-
-extern void _PR_Schedule(void);
-extern void _PR_SetThreadPriority(
- PRThread* thread, PRThreadPriority priority);
-
-/***********************************************************************
-** FUNCTION: _PR_NewSegment()
-** DESCRIPTION:
-** Allocate a memory segment. The "size" value is rounded up to the
-** native system page size and a page aligned portion of memory is
-** returned. This memory is not part of the malloc heap. If "vaddr" is
-** not NULL then PR tries to allocate the segment at the desired virtual
-** address.
-** INPUTS: size: size of the desired memory segment
-** vaddr: address at which the newly aquired segment is to be
-** mapped into memory.
-** OUTPUTS: a memory segment is allocated, a PRSegment is allocated
-** RETURN: pointer to PRSegment
-***********************************************************************/
-extern PRSegment* _PR_NewSegment(PRUint32 size, void *vaddr);
-
-/***********************************************************************
-** FUNCTION: _PR_DestroySegment()
-** DESCRIPTION:
-** The memory segment and the PRSegment are freed
-** INPUTS: seg: pointer to PRSegment to be freed
-** OUTPUTS: the the PRSegment and its associated memory segment are freed
-** RETURN: void
-***********************************************************************/
-extern void _PR_DestroySegment(PRSegment *seg);
-
-extern PRThreadStack * _PR_NewStack(PRUint32 stackSize);
-extern void _PR_FreeStack(PRThreadStack *stack);
-extern PRBool _PR_NotifyThread (PRThread *thread, PRThread *me);
-extern void _PR_NotifyLockedThread (PRThread *thread);
-
-NSPR_API(void) _PR_AddSleepQ(PRThread *thread, PRIntervalTime timeout);
-NSPR_API(void) _PR_DelSleepQ(PRThread *thread, PRBool propogate_time);
-
-extern void _PR_AddThreadToRunQ(PRThread *me, PRThread *thread);
-
-NSPR_API(PRThread*) _PR_CreateThread(PRThreadType type,
- void (*start)(void *arg),
- void *arg,
- PRThreadPriority priority,
- PRThreadScope scope,
- PRThreadState state,
- PRUint32 stackSize,
- PRUint32 flags);
-
-extern void _PR_NativeDestroyThread(PRThread *thread);
-extern void _PR_UserDestroyThread(PRThread *thread);
-
-extern PRThread* _PRI_AttachThread(
- PRThreadType type, PRThreadPriority priority,
- PRThreadStack *stack, PRUint32 flags);
-
-extern void _PRI_DetachThread(void);
-
-
-#define _PR_IO_PENDING(_thread) ((_thread)->io_pending)
-
-NSPR_API(void) _PR_MD_INIT_CPUS();
-#define _PR_MD_INIT_CPUS _MD_INIT_CPUS
-
-NSPR_API(void) _PR_MD_WAKEUP_CPUS();
-#define _PR_MD_WAKEUP_CPUS _MD_WAKEUP_CPUS
-
-/* Interrupts related */
-
-NSPR_API(void) _PR_MD_START_INTERRUPTS(void);
-#define _PR_MD_START_INTERRUPTS _MD_START_INTERRUPTS
-
-NSPR_API(void) _PR_MD_STOP_INTERRUPTS(void);
-#define _PR_MD_STOP_INTERRUPTS _MD_STOP_INTERRUPTS
-
-NSPR_API(void) _PR_MD_ENABLE_CLOCK_INTERRUPTS(void);
-#define _PR_MD_ENABLE_CLOCK_INTERRUPTS _MD_ENABLE_CLOCK_INTERRUPTS
-
-NSPR_API(void) _PR_MD_DISABLE_CLOCK_INTERRUPTS(void);
-#define _PR_MD_DISABLE_CLOCK_INTERRUPTS _MD_DISABLE_CLOCK_INTERRUPTS
-
-NSPR_API(void) _PR_MD_BLOCK_CLOCK_INTERRUPTS(void);
-#define _PR_MD_BLOCK_CLOCK_INTERRUPTS _MD_BLOCK_CLOCK_INTERRUPTS
-
-NSPR_API(void) _PR_MD_UNBLOCK_CLOCK_INTERRUPTS(void);
-#define _PR_MD_UNBLOCK_CLOCK_INTERRUPTS _MD_UNBLOCK_CLOCK_INTERRUPTS
-
-/* The _PR_MD_WAIT_LOCK and _PR_MD_WAKEUP_WAITER functions put to sleep and
- * awaken a thread which is waiting on a lock or cvar.
- */
-extern PRStatus _PR_MD_WAIT(PRThread *, PRIntervalTime timeout);
-#define _PR_MD_WAIT _MD_WAIT
-
-extern PRStatus _PR_MD_WAKEUP_WAITER(PRThread *);
-#define _PR_MD_WAKEUP_WAITER _MD_WAKEUP_WAITER
-
-#ifndef _PR_LOCAL_THREADS_ONLY /* not if only local threads supported */
-NSPR_API(void) _PR_MD_CLOCK_INTERRUPT(void);
-#define _PR_MD_CLOCK_INTERRUPT _MD_CLOCK_INTERRUPT
-#endif
-
-/* Stack debugging */
-NSPR_API(void) _PR_MD_INIT_STACK(PRThreadStack *ts, PRIntn redzone);
-#define _PR_MD_INIT_STACK _MD_INIT_STACK
-
-NSPR_API(void) _PR_MD_CLEAR_STACK(PRThreadStack* ts);
-#define _PR_MD_CLEAR_STACK _MD_CLEAR_STACK
-
-/* CPU related */
-NSPR_API(PRInt32) _PR_MD_GET_INTSOFF(void);
-#define _PR_MD_GET_INTSOFF _MD_GET_INTSOFF
-
-NSPR_API(void) _PR_MD_SET_INTSOFF(PRInt32 _val);
-#define _PR_MD_SET_INTSOFF _MD_SET_INTSOFF
-
-NSPR_API(_PRCPU*) _PR_MD_CURRENT_CPU(void);
-#define _PR_MD_CURRENT_CPU _MD_CURRENT_CPU
-
-NSPR_API(void) _PR_MD_SET_CURRENT_CPU(_PRCPU *cpu);
-#define _PR_MD_SET_CURRENT_CPU _MD_SET_CURRENT_CPU
-
-NSPR_API(void) _PR_MD_INIT_RUNNING_CPU(_PRCPU *cpu);
-#define _PR_MD_INIT_RUNNING_CPU _MD_INIT_RUNNING_CPU
-
-/*
- * Returns the number of threads awoken or 0 if a timeout occurred;
- */
-extern PRInt32 _PR_MD_PAUSE_CPU(PRIntervalTime timeout);
-#define _PR_MD_PAUSE_CPU _MD_PAUSE_CPU
-
-extern void _PR_MD_CLEANUP_BEFORE_EXIT(void);
-#define _PR_MD_CLEANUP_BEFORE_EXIT _MD_CLEANUP_BEFORE_EXIT
-
-extern void _PR_MD_EXIT(PRIntn status);
-#define _PR_MD_EXIT _MD_EXIT
-
-/* Locks related */
-
-NSPR_API(void) _PR_MD_INIT_LOCKS(void);
-#define _PR_MD_INIT_LOCKS _MD_INIT_LOCKS
-
-NSPR_API(PRStatus) _PR_MD_NEW_LOCK(_MDLock *md);
-#define _PR_MD_NEW_LOCK _MD_NEW_LOCK
-
-NSPR_API(void) _PR_MD_FREE_LOCK(_MDLock *md);
-#define _PR_MD_FREE_LOCK _MD_FREE_LOCK
-
-NSPR_API(void) _PR_MD_LOCK(_MDLock *md);
-#define _PR_MD_LOCK _MD_LOCK
-
-/* Return 0 on success, a nonzero value on failure. */
-NSPR_API(PRIntn) _PR_MD_TEST_AND_LOCK(_MDLock *md);
-#define _PR_MD_TEST_AND_LOCK _MD_TEST_AND_LOCK
-
-NSPR_API(void) _PR_MD_UNLOCK(_MDLock *md);
-#define _PR_MD_UNLOCK _MD_UNLOCK
-
-NSPR_API(void) _PR_MD_IOQ_LOCK(void);
-#define _PR_MD_IOQ_LOCK _MD_IOQ_LOCK
-
-NSPR_API(void) _PR_MD_IOQ_UNLOCK(void);
-#define _PR_MD_IOQ_UNLOCK _MD_IOQ_UNLOCK
-
-#ifndef _PR_LOCAL_THREADS_ONLY /* not if only local threads supported */
-/* Semaphore related -- only for native threads */
-#ifdef HAVE_CVAR_BUILT_ON_SEM
-NSPR_API(void) _PR_MD_NEW_SEM(_MDSemaphore *md, PRUintn value);
-#define _PR_MD_NEW_SEM _MD_NEW_SEM
-
-NSPR_API(void) _PR_MD_DESTROY_SEM(_MDSemaphore *md);
-#define _PR_MD_DESTROY_SEM _MD_DESTROY_SEM
-
-NSPR_API(PRStatus) _PR_MD_TIMED_WAIT_SEM(
- _MDSemaphore *md, PRIntervalTime timeout);
-#define _PR_MD_TIMED_WAIT_SEM _MD_TIMED_WAIT_SEM
-
-NSPR_API(PRStatus) _PR_MD_WAIT_SEM(_MDSemaphore *md);
-#define _PR_MD_WAIT_SEM _MD_WAIT_SEM
-
-NSPR_API(void) _PR_MD_POST_SEM(_MDSemaphore *md);
-#define _PR_MD_POST_SEM _MD_POST_SEM
-#endif /* HAVE_CVAR_BUILT_ON_SEM */
-
-#endif
-
-/* Condition Variables related -- only for native threads */
-
-#ifndef _PR_LOCAL_THREADS_ONLY /* not if only local threads supported */
-NSPR_API(PRInt32) _PR_MD_NEW_CV(_MDCVar *md);
-#define _PR_MD_NEW_CV _MD_NEW_CV
-
-NSPR_API(void) _PR_MD_FREE_CV(_MDCVar *md);
-#define _PR_MD_FREE_CV _MD_FREE_CV
-
-NSPR_API(void) _PR_MD_WAIT_CV(
- _MDCVar *mdCVar,_MDLock *mdLock,PRIntervalTime timeout);
-#define _PR_MD_WAIT_CV _MD_WAIT_CV
-
-NSPR_API(void) _PR_MD_NOTIFY_CV(_MDCVar *md, _MDLock *lock);
-#define _PR_MD_NOTIFY_CV _MD_NOTIFY_CV
-
-NSPR_API(void) _PR_MD_NOTIFYALL_CV(_MDCVar *md, _MDLock *lock);
-#define _PR_MD_NOTIFYALL_CV _MD_NOTIFYALL_CV
-#endif /* _PR_LOCAL_THREADS_ONLY */
-
-/* Threads related */
-NSPR_API(PRThread*) _PR_MD_CURRENT_THREAD(void);
-#define _PR_MD_CURRENT_THREAD _MD_CURRENT_THREAD
-
-NSPR_API(PRThread*) _PR_MD_GET_ATTACHED_THREAD(void);
-#define _PR_MD_GET_ATTACHED_THREAD _MD_GET_ATTACHED_THREAD
-
-NSPR_API(PRThread*) _PR_MD_LAST_THREAD(void);
-#define _PR_MD_LAST_THREAD _MD_LAST_THREAD
-
-NSPR_API(void) _PR_MD_SET_CURRENT_THREAD(PRThread *thread);
-#define _PR_MD_SET_CURRENT_THREAD _MD_SET_CURRENT_THREAD
-
-NSPR_API(void) _PR_MD_SET_LAST_THREAD(PRThread *thread);
-#define _PR_MD_SET_LAST_THREAD _MD_SET_LAST_THREAD
-
-extern PRStatus _PR_MD_INIT_THREAD(PRThread *thread);
-#define _PR_MD_INIT_THREAD _MD_INIT_THREAD
-
-extern void _PR_MD_EXIT_THREAD(PRThread *thread);
-#define _PR_MD_EXIT_THREAD _MD_EXIT_THREAD
-
-#ifndef _PR_LOCAL_THREADS_ONLY /* not if only local threads supported */
-
-NSPR_API(PRStatus) _PR_MD_INIT_ATTACHED_THREAD(PRThread *thread);
-#define _PR_MD_INIT_ATTACHED_THREAD _MD_INIT_ATTACHED_THREAD
-
-extern void _PR_MD_SUSPEND_THREAD(PRThread *thread);
-#define _PR_MD_SUSPEND_THREAD _MD_SUSPEND_THREAD
-
-extern void _PR_MD_RESUME_THREAD(PRThread *thread);
-#define _PR_MD_RESUME_THREAD _MD_RESUME_THREAD
-
-extern void _PR_MD_SUSPEND_CPU(_PRCPU *cpu);
-#define _PR_MD_SUSPEND_CPU _MD_SUSPEND_CPU
-
-extern void _PR_MD_RESUME_CPU(_PRCPU *cpu);
-#define _PR_MD_RESUME_CPU _MD_RESUME_CPU
-
-extern void _PR_MD_BEGIN_SUSPEND_ALL(void);
-#define _PR_MD_BEGIN_SUSPEND_ALL _MD_BEGIN_SUSPEND_ALL
-
-extern void _PR_MD_END_SUSPEND_ALL(void);
-#define _PR_MD_END_SUSPEND_ALL _MD_END_SUSPEND_ALL
-
-extern void _PR_MD_BEGIN_RESUME_ALL(void);
-#define _PR_MD_BEGIN_RESUME_ALL _MD_BEGIN_RESUME_ALL
-
-extern void _PR_MD_END_RESUME_ALL(void);
-#define _PR_MD_END_RESUME_ALL _MD_END_RESUME_ALL
-
-#if defined(IRIX)
-NSPR_API(void) _PR_IRIX_CHILD_PROCESS(void);
-#endif /* IRIX */
-
-#endif /* !_PR_LOCAL_THREADS_ONLY */
-
-extern void _PR_MD_CLEAN_THREAD(PRThread *thread);
-#define _PR_MD_CLEAN_THREAD _MD_CLEAN_THREAD
-
-#ifdef HAVE_CUSTOM_USER_THREADS
-extern void _PR_MD_CREATE_PRIMORDIAL_USER_THREAD(PRThread *);
-#define _PR_MD_CREATE_PRIMORDIAL_USER_THREAD _MD_CREATE_PRIMORDIAL_USER_THREAD
-
-extern PRThread* _PR_MD_CREATE_USER_THREAD(
- PRUint32 stacksize,
- void (*start)(void *),
- void *arg);
-#define _PR_MD_CREATE_USER_THREAD _MD_CREATE_USER_THREAD
-#endif
-
-extern PRStatus _PR_MD_CREATE_THREAD(
- PRThread *thread,
- void (*start) (void *),
- PRThreadPriority priority,
- PRThreadScope scope,
- PRThreadState state,
- PRUint32 stackSize);
-#define _PR_MD_CREATE_THREAD _MD_CREATE_THREAD
-
-extern void _PR_MD_JOIN_THREAD(_MDThread *md);
-#define _PR_MD_JOIN_THREAD _MD_JOIN_THREAD
-
-extern void _PR_MD_END_THREAD(void);
-#define _PR_MD_END_THREAD _MD_END_THREAD
-
-extern void _PR_MD_YIELD(void);
-#define _PR_MD_YIELD _MD_YIELD
-
-extern void _PR_MD_SET_PRIORITY(_MDThread *md, PRThreadPriority newPri);
-#define _PR_MD_SET_PRIORITY _MD_SET_PRIORITY
-
-extern void _PR_MD_SET_CURRENT_THREAD_NAME(const char *name);
-#define _PR_MD_SET_CURRENT_THREAD_NAME _MD_SET_CURRENT_THREAD_NAME
-
-NSPR_API(void) _PR_MD_SUSPENDALL(void);
-#define _PR_MD_SUSPENDALL _MD_SUSPENDALL
-
-NSPR_API(void) _PR_MD_RESUMEALL(void);
-#define _PR_MD_RESUMEALL _MD_RESUMEALL
-
-extern void _PR_MD_INIT_CONTEXT(
- PRThread *thread, char *top, void (*start) (void), PRBool *status);
-#define _PR_MD_INIT_CONTEXT _MD_INIT_CONTEXT
-
-extern void _PR_MD_SWITCH_CONTEXT(PRThread *thread);
-#define _PR_MD_SWITCH_CONTEXT _MD_SWITCH_CONTEXT
-
-extern void _PR_MD_RESTORE_CONTEXT(PRThread *thread);
-#define _PR_MD_RESTORE_CONTEXT _MD_RESTORE_CONTEXT
-
-/* Segment related */
-extern void _PR_MD_INIT_SEGS(void);
-#define _PR_MD_INIT_SEGS _MD_INIT_SEGS
-
-extern PRStatus _PR_MD_ALLOC_SEGMENT(PRSegment *seg, PRUint32 size, void *vaddr);
-#define _PR_MD_ALLOC_SEGMENT _MD_ALLOC_SEGMENT
-
-extern void _PR_MD_FREE_SEGMENT(PRSegment *seg);
-#define _PR_MD_FREE_SEGMENT _MD_FREE_SEGMENT
-
-/* Directory enumeration related */
-extern PRStatus _PR_MD_OPEN_DIR(_MDDir *md,const char *name);
-#define _PR_MD_OPEN_DIR _MD_OPEN_DIR
-
-extern char * _PR_MD_READ_DIR(_MDDir *md, PRIntn flags);
-#define _PR_MD_READ_DIR _MD_READ_DIR
-
-extern PRInt32 _PR_MD_CLOSE_DIR(_MDDir *md);
-#define _PR_MD_CLOSE_DIR _MD_CLOSE_DIR
-
-/* Named semaphores related */
-extern PRSem * _PR_MD_OPEN_SEMAPHORE(
- const char *osname, PRIntn flags, PRIntn mode, PRUintn value);
-#define _PR_MD_OPEN_SEMAPHORE _MD_OPEN_SEMAPHORE
-
-extern PRStatus _PR_MD_WAIT_SEMAPHORE(PRSem *sem);
-#define _PR_MD_WAIT_SEMAPHORE _MD_WAIT_SEMAPHORE
-
-extern PRStatus _PR_MD_POST_SEMAPHORE(PRSem *sem);
-#define _PR_MD_POST_SEMAPHORE _MD_POST_SEMAPHORE
-
-extern PRStatus _PR_MD_CLOSE_SEMAPHORE(PRSem *sem);
-#define _PR_MD_CLOSE_SEMAPHORE _MD_CLOSE_SEMAPHORE
-
-extern PRStatus _PR_MD_DELETE_SEMAPHORE(const char *osname);
-#define _PR_MD_DELETE_SEMAPHORE _MD_DELETE_SEMAPHORE
-
-/* I/O related */
-extern void _PR_MD_INIT_FILEDESC(PRFileDesc *fd);
-#define _PR_MD_INIT_FILEDESC _MD_INIT_FILEDESC
-
-extern void _PR_MD_MAKE_NONBLOCK(PRFileDesc *fd);
-#define _PR_MD_MAKE_NONBLOCK _MD_MAKE_NONBLOCK
-
-/* File I/O related */
-extern PROsfd _PR_MD_OPEN(const char *name, PRIntn osflags, PRIntn mode);
-#define _PR_MD_OPEN _MD_OPEN
-
-extern PROsfd _PR_MD_OPEN_FILE(const char *name, PRIntn osflags, PRIntn mode);
-#define _PR_MD_OPEN_FILE _MD_OPEN_FILE
-
-extern PRInt32 _PR_MD_CLOSE_FILE(PROsfd osfd);
-#define _PR_MD_CLOSE_FILE _MD_CLOSE_FILE
-
-extern PRInt32 _PR_MD_READ(PRFileDesc *fd, void *buf, PRInt32 amount);
-#define _PR_MD_READ _MD_READ
-
-extern PRInt32 _PR_MD_WRITE(PRFileDesc *fd, const void *buf, PRInt32 amount);
-#define _PR_MD_WRITE _MD_WRITE
-
-extern PRInt32 _PR_MD_WRITEV(
- PRFileDesc *fd, const struct PRIOVec *iov,
- PRInt32 iov_size, PRIntervalTime timeout);
-#define _PR_MD_WRITEV _MD_WRITEV
-
-extern PRInt32 _PR_MD_FSYNC(PRFileDesc *fd);
-#define _PR_MD_FSYNC _MD_FSYNC
-
-extern PRInt32 _PR_MD_DELETE(const char *name);
-#define _PR_MD_DELETE _MD_DELETE
-
-extern PRInt32 _PR_MD_RENAME(const char *from, const char *to);
-#define _PR_MD_RENAME _MD_RENAME
-
-extern PRInt32 _PR_MD_ACCESS(const char *name, PRAccessHow how);
-#define _PR_MD_ACCESS _MD_ACCESS
-
-extern PRInt32 _PR_MD_STAT(const char *name, struct stat *buf);
-#define _PR_MD_STAT _MD_STAT
-
-extern PRInt32 _PR_MD_MKDIR(const char *name, PRIntn mode);
-#define _PR_MD_MKDIR _MD_MKDIR
-
-extern PRInt32 _PR_MD_MAKE_DIR(const char *name, PRIntn mode);
-#define _PR_MD_MAKE_DIR _MD_MAKE_DIR
-
-extern PRInt32 _PR_MD_RMDIR(const char *name);
-#define _PR_MD_RMDIR _MD_RMDIR
-
-#ifdef MOZ_UNICODE
-/* UTF16 File I/O related */
-extern PRStatus _PR_MD_OPEN_DIR_UTF16(_MDDirUTF16 *md, const PRUnichar *name);
-#define _PR_MD_OPEN_DIR_UTF16 _MD_OPEN_DIR_UTF16
-
-extern PROsfd _PR_MD_OPEN_FILE_UTF16(const PRUnichar *name, PRIntn osflags, PRIntn mode);
-#define _PR_MD_OPEN_FILE_UTF16 _MD_OPEN_FILE_UTF16
-
-extern PRUnichar * _PR_MD_READ_DIR_UTF16(_MDDirUTF16 *md, PRIntn flags);
-#define _PR_MD_READ_DIR_UTF16 _MD_READ_DIR_UTF16
-
-extern PRInt32 _PR_MD_CLOSE_DIR_UTF16(_MDDirUTF16 *md);
-#define _PR_MD_CLOSE_DIR_UTF16 _MD_CLOSE_DIR_UTF16
-
-extern PRInt32 _PR_MD_GETFILEINFO64_UTF16(const PRUnichar *fn, PRFileInfo64 *info);
-#define _PR_MD_GETFILEINFO64_UTF16 _MD_GETFILEINFO64_UTF16
-#endif /* MOZ_UNICODE */
-
-/* Socket I/O related */
-extern void _PR_MD_INIT_IO(void);
-#define _PR_MD_INIT_IO _MD_INIT_IO
-
-extern PRInt32 _PR_MD_CLOSE_SOCKET(PROsfd osfd);
-#define _PR_MD_CLOSE_SOCKET _MD_CLOSE_SOCKET
-
-extern PRInt32 _PR_MD_CONNECT(
- PRFileDesc *fd, const PRNetAddr *addr,
- PRUint32 addrlen, PRIntervalTime timeout);
-#define _PR_MD_CONNECT _MD_CONNECT
-
-extern PROsfd _PR_MD_ACCEPT(
- PRFileDesc *fd, PRNetAddr *addr,
- PRUint32 *addrlen, PRIntervalTime timeout);
-#define _PR_MD_ACCEPT _MD_ACCEPT
-
-extern PRInt32 _PR_MD_BIND(PRFileDesc *fd, const PRNetAddr *addr, PRUint32 addrlen);
-#define _PR_MD_BIND _MD_BIND
-
-extern PRInt32 _PR_MD_LISTEN(PRFileDesc *fd, PRIntn backlog);
-#define _PR_MD_LISTEN _MD_LISTEN
-
-extern PRInt32 _PR_MD_SHUTDOWN(PRFileDesc *fd, PRIntn how);
-#define _PR_MD_SHUTDOWN _MD_SHUTDOWN
-
-extern PRInt32 _PR_MD_RECV(PRFileDesc *fd, void *buf, PRInt32 amount,
- PRIntn flags, PRIntervalTime timeout);
-#define _PR_MD_RECV _MD_RECV
-
-extern PRInt32 _PR_MD_SEND(
- PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
- PRIntervalTime timeout);
-#define _PR_MD_SEND _MD_SEND
-
-extern PRInt32 _PR_MD_ACCEPT_READ(PRFileDesc *sd, PROsfd *newSock,
- PRNetAddr **raddr, void *buf, PRInt32 amount,
- PRIntervalTime timeout);
-#define _PR_MD_ACCEPT_READ _MD_ACCEPT_READ
-
-#ifdef WIN32
-extern PROsfd _PR_MD_FAST_ACCEPT(PRFileDesc *fd, PRNetAddr *addr,
- PRUint32 *addrlen, PRIntervalTime timeout,
- PRBool fast,
- _PR_AcceptTimeoutCallback callback,
- void *callbackArg);
-
-extern PRInt32 _PR_MD_FAST_ACCEPT_READ(PRFileDesc *sd, PROsfd *newSock,
- PRNetAddr **raddr, void *buf, PRInt32 amount,
- PRIntervalTime timeout, PRBool fast,
- _PR_AcceptTimeoutCallback callback,
- void *callbackArg);
-
-extern void _PR_MD_UPDATE_ACCEPT_CONTEXT(PROsfd s, PROsfd ls);
-#define _PR_MD_UPDATE_ACCEPT_CONTEXT _MD_UPDATE_ACCEPT_CONTEXT
-/*
- * The NSPR epoch (00:00:00 1 Jan 1970 UTC) in FILETIME.
- * We store the value in a PRTime variable for convenience.
- * This constant is used by _PR_FileTimeToPRTime().
- * This is defined in ntmisc.c
- */
-extern const PRTime _pr_filetime_offset;
-#endif /* WIN32 */
-
-extern PRInt32 _PR_MD_SENDFILE(
- PRFileDesc *sock, PRSendFileData *sfd,
- PRInt32 flags, PRIntervalTime timeout);
-#define _PR_MD_SENDFILE _MD_SENDFILE
-
-extern PRStatus _PR_MD_GETSOCKNAME(
- PRFileDesc *fd, PRNetAddr *addr, PRUint32 *addrlen);
-#define _PR_MD_GETSOCKNAME _MD_GETSOCKNAME
-
-extern PRStatus _PR_MD_GETPEERNAME(
- PRFileDesc *fd, PRNetAddr *addr, PRUint32 *addrlen);
-#define _PR_MD_GETPEERNAME _MD_GETPEERNAME
-
-extern PRStatus _PR_MD_GETSOCKOPT(
- PRFileDesc *fd, PRInt32 level, PRInt32 optname, char* optval, PRInt32* optlen);
-#define _PR_MD_GETSOCKOPT _MD_GETSOCKOPT
-
-extern PRStatus _PR_MD_SETSOCKOPT(
- PRFileDesc *fd, PRInt32 level, PRInt32 optname,
- const char* optval, PRInt32 optlen);
-#define _PR_MD_SETSOCKOPT _MD_SETSOCKOPT
-
-extern PRStatus PR_CALLBACK _PR_SocketGetSocketOption(
- PRFileDesc *fd, PRSocketOptionData *data);
-
-extern PRStatus PR_CALLBACK _PR_SocketSetSocketOption(
- PRFileDesc *fd, const PRSocketOptionData *data);
-
-extern PRInt32 _PR_MD_RECVFROM(
- PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags,
- PRNetAddr *addr, PRUint32 *addrlen, PRIntervalTime timeout);
-#define _PR_MD_RECVFROM _MD_RECVFROM
-
-extern PRInt32 _PR_MD_SENDTO(
- PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
- const PRNetAddr *addr, PRUint32 addrlen, PRIntervalTime timeout);
-#define _PR_MD_SENDTO _MD_SENDTO
-
-extern PRInt32 _PR_MD_SOCKETPAIR(int af, int type, int flags, PROsfd *osfd);
-#define _PR_MD_SOCKETPAIR _MD_SOCKETPAIR
-
-extern PROsfd _PR_MD_SOCKET(int af, int type, int flags);
-#define _PR_MD_SOCKET _MD_SOCKET
-
-extern PRInt32 _PR_MD_SOCKETAVAILABLE(PRFileDesc *fd);
-#define _PR_MD_SOCKETAVAILABLE _MD_SOCKETAVAILABLE
-
-extern PRInt32 _PR_MD_PIPEAVAILABLE(PRFileDesc *fd);
-#define _PR_MD_PIPEAVAILABLE _MD_PIPEAVAILABLE
-
-extern PRInt32 _PR_MD_PR_POLL(PRPollDesc *pds, PRIntn npds,
- PRIntervalTime timeout);
-#define _PR_MD_PR_POLL _MD_PR_POLL
-
-/*
- * Initialize fd->secret->inheritable for a newly created fd.
- * If 'imported' is false, the osfd (i.e., fd->secret->md.osfd)
- * was created by NSPR and hence has the OS-dependent default
- * inheritable attribute. If 'imported' is true, the osfd was
- * not created by NSPR and hence a system call is required to
- * query its inheritable attribute. Since we may never need to
- * know the inheritable attribute of a fd, a platform may choose
- * to initialize fd->secret->inheritable of an imported fd to
- * _PR_TRI_UNKNOWN and only pay the cost of the system call
- * (in _PR_MD_QUERY_FD_INHERITABLE) when necessary.
- */
-extern void _PR_MD_INIT_FD_INHERITABLE(PRFileDesc *fd, PRBool imported);
-#define _PR_MD_INIT_FD_INHERITABLE _MD_INIT_FD_INHERITABLE
-
-extern PRStatus _PR_MD_SET_FD_INHERITABLE(PRFileDesc *fd, PRBool inheritable);
-#define _PR_MD_SET_FD_INHERITABLE _MD_SET_FD_INHERITABLE
-
-
-#define _PR_PROCESS_TIMEOUT_INTERRUPT_ERRORS(me) \
- if (_PR_PENDING_INTERRUPT(me)) { \
- me->flags &= ~_PR_INTERRUPT; \
- PR_SetError( PR_PENDING_INTERRUPT_ERROR, 0); \
- } else { \
- PR_SetError(PR_IO_TIMEOUT_ERROR, 0); \
- }
-
-extern void *_PR_MD_GET_SP(PRThread *thread);
-#define _PR_MD_GET_SP _MD_GET_SP
-
-#endif /* defined(_PR_PTHREADS) */
-
-/************************************************************************/
-/*************************************************************************
-** The remainder of the definitions are shared by pthreads and the classic
-** NSPR code. These too may be conditionalized.
-*************************************************************************/
-/************************************************************************/
-
-extern PROffset32 _PR_MD_LSEEK(PRFileDesc *fd, PROffset32 offset, PRSeekWhence whence);
-#define _PR_MD_LSEEK _MD_LSEEK
-
-extern PROffset64 _PR_MD_LSEEK64(PRFileDesc *fd, PROffset64 offset, PRSeekWhence whence);
-#define _PR_MD_LSEEK64 _MD_LSEEK64
-
-extern PRInt32 _PR_MD_GETFILEINFO(const char *fn, PRFileInfo *info);
-#define _PR_MD_GETFILEINFO _MD_GETFILEINFO
-
-extern PRInt32 _PR_MD_GETFILEINFO64(const char *fn, PRFileInfo64 *info);
-#define _PR_MD_GETFILEINFO64 _MD_GETFILEINFO64
-
-extern PRInt32 _PR_MD_GETOPENFILEINFO(const PRFileDesc *fd, PRFileInfo *info);
-#define _PR_MD_GETOPENFILEINFO _MD_GETOPENFILEINFO
-
-extern PRInt32 _PR_MD_GETOPENFILEINFO64(const PRFileDesc *fd, PRFileInfo64 *info);
-#define _PR_MD_GETOPENFILEINFO64 _MD_GETOPENFILEINFO64
-
-
-/*****************************************************************************/
-/************************** File descriptor caching **************************/
-/*****************************************************************************/
-extern void _PR_InitFdCache(void);
-extern void _PR_CleanupFdCache(void);
-extern PRFileDesc *_PR_Getfd(void);
-extern void _PR_Putfd(PRFileDesc *fd);
-
-/*
- * These flags are used by NSPR temporarily in the poll
- * descriptor's out_flags field to record the mapping of
- * NSPR's poll flags to the system poll flags.
- *
- * If _PR_POLL_READ_SYS_WRITE bit is set, it means the
- * PR_POLL_READ flag specified by the topmost layer is
- * mapped to the WRITE flag at the system layer. Similarly
- * for the other three _PR_POLL_XXX_SYS_YYY flags. It is
- * assumed that the PR_POLL_EXCEPT flag doesn't get mapped
- * to other flags.
- */
-#define _PR_POLL_READ_SYS_READ 0x1
-#define _PR_POLL_READ_SYS_WRITE 0x2
-#define _PR_POLL_WRITE_SYS_READ 0x4
-#define _PR_POLL_WRITE_SYS_WRITE 0x8
-
-/*
-** These methods are coerced into file descriptor methods table
-** when the intended service is inappropriate for the particular
-** type of file descriptor.
-*/
-extern PRIntn _PR_InvalidInt(void);
-extern PRInt16 _PR_InvalidInt16(void);
-extern PRInt64 _PR_InvalidInt64(void);
-extern PRStatus _PR_InvalidStatus(void);
-extern PRFileDesc *_PR_InvalidDesc(void);
-
-extern PRIOMethods _pr_faulty_methods;
-
-/*
-** The PR_NETADDR_SIZE macro can only be called on a PRNetAddr union
-** whose 'family' field is set. It returns the size of the union
-** member corresponding to the specified address family.
-*/
-
-extern PRUintn _PR_NetAddrSize(const PRNetAddr* addr);
-
-#if defined(_PR_INET6)
-
-#define PR_NETADDR_SIZE(_addr) _PR_NetAddrSize(_addr)
-
-#elif defined(_PR_HAVE_MD_SOCKADDR_IN6)
-
-/*
-** Under the following conditions:
-** 1. _PR_INET6 is not defined;
-** 2. _PR_INET6_PROBE is defined;
-** 3. struct sockaddr_in6 has nonstandard fields at the end
-** (e.g., on Solaris 8),
-** (_addr)->ipv6 is smaller than struct sockaddr_in6, and
-** hence we can't pass sizeof((_addr)->ipv6) to socket
-** functions such as connect because they would fail with
-** EINVAL.
-**
-** To pass the correct socket address length to socket
-** functions, define the macro _PR_HAVE_MD_SOCKADDR_IN6 and
-** define struct _md_sockaddr_in6 to be isomorphic to
-** struct sockaddr_in6.
-*/
-
-#if defined(XP_UNIX) || defined(XP_OS2)
-#define PR_NETADDR_SIZE(_addr) \
- ((_addr)->raw.family == PR_AF_INET \
- ? sizeof((_addr)->inet) \
- : ((_addr)->raw.family == PR_AF_INET6 \
- ? sizeof(struct _md_sockaddr_in6) \
- : sizeof((_addr)->local)))
-#else
-#define PR_NETADDR_SIZE(_addr) \
- ((_addr)->raw.family == PR_AF_INET \
- ? sizeof((_addr)->inet) \
- : sizeof(struct _md_sockaddr_in6))
-#endif /* defined(XP_UNIX) */
-
-#else
-
-#if defined(XP_UNIX) || defined(XP_OS2)
-#define PR_NETADDR_SIZE(_addr) \
- ((_addr)->raw.family == PR_AF_INET \
- ? sizeof((_addr)->inet) \
- : ((_addr)->raw.family == PR_AF_INET6 \
- ? sizeof((_addr)->ipv6) \
- : sizeof((_addr)->local)))
-#else
-#define PR_NETADDR_SIZE(_addr) \
- ((_addr)->raw.family == PR_AF_INET \
- ? sizeof((_addr)->inet) \
- : sizeof((_addr)->ipv6))
-#endif /* defined(XP_UNIX) */
-
-#endif /* defined(_PR_INET6) */
-
-extern PRStatus _PR_MapOptionName(
- PRSockOption optname, PRInt32 *level, PRInt32 *name);
-extern void _PR_InitThreads(
- PRThreadType type, PRThreadPriority priority, PRUintn maxPTDs);
-
-struct PRLock {
-#if defined(_PR_PTHREADS)
- pthread_mutex_t mutex; /* the underlying lock */
- _PT_Notified notified; /* array of conditions notified */
- PRBool locked; /* whether the mutex is locked */
- pthread_t owner; /* if locked, current lock owner */
-#elif defined(_PR_BTHREADS)
- sem_id semaphoreID; /* the underlying lock */
- int32 benaphoreCount; /* number of people in lock */
- thread_id owner; /* current lock owner */
-#else /* not pthreads or Be threads */
- PRCList links; /* linkage for PRThread.lockList */
- struct PRThread *owner; /* current lock owner */
- PRCList waitQ; /* list of threads waiting for lock */
- PRThreadPriority priority; /* priority of lock */
- PRThreadPriority boostPriority; /* boosted priority of lock owner */
- _MDLock ilock; /* Internal Lock to protect user-level fields */
-#endif
-};
-
-struct PRCondVar {
- PRLock *lock; /* associated lock that protects the condition */
-#if defined(_PR_PTHREADS)
- pthread_cond_t cv; /* underlying pthreads condition */
- PRInt32 notify_pending; /* CV has destroy pending notification */
-#elif defined(_PR_BTHREADS)
- sem_id sem; /* the underlying lock */
- sem_id handshakeSem; /* the lock for 'notify'-threads waiting for confirmation */
- sem_id signalSem; /* the lock for threads waiting for someone to notify */
- volatile int32 nw; /* the number waiting */
- volatile int32 ns; /* the number signalling */
- long signalBenCount; /* the number waiting on the underlying sem */
-#else /* not pthreads or Be threads */
- PRCList condQ; /* Condition variable wait Q */
- _MDLock ilock; /* Internal Lock to protect condQ */
- _MDCVar md;
-#endif
-};
-
-/************************************************************************/
-
-struct PRMonitor {
- const char* name; /* monitor name for debugging */
-#if defined(_PR_PTHREADS)
- pthread_mutex_t lock; /* lock is only held when accessing fields
- * of the PRMonitor, instead of being held
- * while the monitor is entered. The only
- * exception is notifyTimes, which is
- * protected by the monitor. */
- pthread_t owner; /* the owner of the monitor or invalid */
- pthread_cond_t entryCV; /* for threads waiting to enter the monitor */
-
- pthread_cond_t waitCV; /* for threads waiting on the monitor */
- PRInt32 refCount; /* reference count, an atomic variable.
- * PR_NewMonitor adds a reference to the
- * newly created PRMonitor, and
- * PR_DestroyMonitor releases that reference.
- * PR_ExitMonitor adds a reference before
- * unlocking the internal lock if it needs to
- * signal entryCV, and releases the reference
- * after signaling entryCV. */
-#else /* defined(_PR_PTHREADS) */
- PRLock lock; /* lock is only held when accessing fields
- * of the PRMonitor, instead of being held
- * while the monitor is entered. The only
- * exception is notifyTimes, which is
- * protected by the monitor. */
- PRThread *owner; /* the owner of the monitor or invalid */
- PRCondVar entryCV; /* for threads waiting to enter the monitor */
-
- PRCondVar waitCV; /* for threads waiting on the monitor */
-#endif /* defined(_PR_PTHREADS) */
- PRUint32 entryCount; /* # of times re-entered */
- PRIntn notifyTimes; /* number of pending notifies for waitCV.
- * The special value -1 means a broadcast
- * (PR_NotifyAll). */
-};
-
-/************************************************************************/
-
-struct PRSemaphore {
-#if defined(_PR_BTHREADS)
- sem_id sem;
- int32 benaphoreCount;
-#else
- PRCondVar *cvar; /* associated lock and condition variable queue */
- PRUintn count; /* the value of the counting semaphore */
- PRUint32 waiters; /* threads waiting on the semaphore */
-#if defined(_PR_PTHREADS)
-#else /* defined(_PR_PTHREADS) */
- _MDSemaphore md;
-#endif /* defined(_PR_PTHREADS) */
-#endif /* defined(_PR_BTHREADS) */
-};
-
-/*************************************************************************/
-
-struct PRSem {
-#ifdef _PR_HAVE_POSIX_SEMAPHORES
- sem_t *sem;
-#elif defined(_PR_HAVE_SYSV_SEMAPHORES)
- int semid;
-#elif defined(WIN32)
- HANDLE sem;
-#else
- PRInt8 notused;
-#endif
-};
-
-/*************************************************************************/
-
-struct PRStackStr {
- /* head MUST be at offset 0; assembly language code relies on this */
-#if defined(AIX)
- volatile PRStackElem prstk_head;
-#else
- PRStackElem prstk_head;
-#endif
-
- PRLock *prstk_lock;
- char *prstk_name;
-};
-
-/************************************************************************/
-
-/* XXX this needs to be exported (sigh) */
-struct PRThreadStack {
- PRCList links;
- PRUintn flags;
-
- char *allocBase; /* base of stack's allocated memory */
- PRUint32 allocSize; /* size of stack's allocated memory */
- char *stackBottom; /* bottom of stack from C's point of view */
- char *stackTop; /* top of stack from C's point of view */
- PRUint32 stackSize; /* size of usable portion of the stack */
-
- PRSegment *seg;
- PRThread* thr; /* back pointer to thread owning this stack */
-
-#if defined(_PR_PTHREADS)
-#else /* defined(_PR_PTHREADS) */
- _MDThreadStack md;
-#endif /* defined(_PR_PTHREADS) */
-};
-
-extern void _PR_DestroyThreadPrivate(PRThread*);
-
-typedef void (PR_CALLBACK *_PRStartFn)(void *);
-
-struct PRThread {
- PRUint32 state; /* thread's creation state */
- PRThreadPriority priority; /* apparent priority, loosly defined */
-
- void *arg; /* argument to the client's entry point */
- _PRStartFn startFunc; /* the root of the client's thread */
-
- PRThreadStack *stack; /* info about thread's stack (for GC) */
- void *environment; /* pointer to execution environment */
-
- PRThreadDumpProc dump; /* dump thread info out */
- void *dumpArg; /* argument for the dump function */
-
- /*
- ** Per thread private data
- */
- PRUint32 tpdLength; /* thread's current vector length */
- void **privateData; /* private data vector or NULL */
- PRErrorCode errorCode; /* current NSPR error code | zero */
- PRInt32 osErrorCode; /* mapping of errorCode | zero */
- PRIntn errorStringLength; /* textLength from last call to PR_SetErrorText() */
- PRInt32 errorStringSize; /* malloc()'d size of buffer | zero */
- char *errorString; /* current error string | NULL */
- char *name; /* thread's name */
-
-#if defined(_PR_PTHREADS)
- pthread_t id; /* pthread identifier for the thread */
- PRBool idSet; /* whether 'id' has been set. Protected by
- * pt_book.ml. */
-#ifdef _PR_NICE_PRIORITY_SCHEDULING
- pid_t tid; /* Linux-specific kernel thread ID */
-#endif
- PRBool okToDelete; /* ok to delete the PRThread struct? */
- PRCondVar *waiting; /* where the thread is waiting | NULL */
- void *sp; /* recorded sp for garbage collection */
- PRThread *next, *prev; /* simple linked list of all threads */
- PRUint32 suspend; /* used to store suspend and resume flags */
-#ifdef PT_NO_SIGTIMEDWAIT
- pthread_mutex_t suspendResumeMutex;
- pthread_cond_t suspendResumeCV;
-#endif
- PRUint32 interrupt_blocked; /* interrupt blocked */
- struct pollfd *syspoll_list; /* Unix polling list used by PR_Poll */
- PRUint32 syspoll_count; /* number of elements in syspoll_list */
-#if defined(_PR_POLL_WITH_SELECT)
- int *selectfd_list; /* Unix fd's that PR_Poll selects on */
- PRUint32 selectfd_count; /* number of elements in selectfd_list */
-#endif
-#elif defined(_PR_BTHREADS)
- PRUint32 flags;
- _MDThread md;
- PRBool io_pending;
- PRInt32 io_fd;
- PRBool io_suspended;
-#else /* not pthreads or Be threads */
- _MDLock threadLock; /* Lock to protect thread state variables.
- * Protects the following fields:
- * state
- * priority
- * links
- * wait
- * cpu
- */
- PRUint32 queueCount;
- PRUint32 waitCount;
-
- PRCList active; /* on list of all active threads */
- PRCList links;
- PRCList waitQLinks; /* when thread is PR_Wait'ing */
- PRCList lockList; /* list of locks currently holding */
- PRIntervalTime sleep; /* sleep time when thread is sleeping */
- struct _wait {
- struct PRLock *lock;
- struct PRCondVar *cvar;
- } wait;
-
- PRUint32 id;
- PRUint32 flags;
- PRUint32 no_sched; /* Don't schedule the thread to run.
- * This flag has relevance only when
- * multiple NSPR CPUs are created.
- * When a thread is de-scheduled, there
- * is a narrow window of time in which
- * the thread is put on the run queue
- * but the scheduler is actually using
- * the stack of this thread. It is safe
- * to run this thread on a different CPU
- * only when its stack is not in use on
- * any other CPU. The no_sched flag is
- * set during this interval to prevent
- * the thread from being scheduled on a
- * different CPU.
- */
-
- /* thread termination condition variable for join */
- PRCondVar *term;
-
- _PRCPU *cpu; /* cpu to which this thread is bound */
- PRUint32 threadAllocatedOnStack;/* boolean */
-
- /* When an async IO is in progress and a second async IO cannot be
- * initiated, the io_pending flag is set to true. Some platforms will
- * not use the io_pending flag. If the io_pending flag is true, then
- * io_fd is the OS-file descriptor on which IO is pending.
- */
- PRBool io_pending;
- PRInt32 io_fd;
-
- /* If a timeout occurs or if an outstanding IO is interrupted and the
- * OS doesn't support a real cancellation (NT or MAC), then the
- * io_suspended flag will be set to true. The thread will be resumed
- * but may run into trouble issuing additional IOs until the io_pending
- * flag can be cleared
- */
- PRBool io_suspended;
-
- _MDThread md;
-#endif
-};
-
-struct PRProcessAttr {
- PRFileDesc *stdinFd;
- PRFileDesc *stdoutFd;
- PRFileDesc *stderrFd;
- char *currentDirectory;
- char *fdInheritBuffer;
- PRSize fdInheritBufferSize;
- PRSize fdInheritBufferUsed;
-};
-
-struct PRProcess {
- _MDProcess md;
-};
-
-struct PRFileMap {
- PRFileDesc *fd;
- PRFileMapProtect prot;
- _MDFileMap md;
-};
-
-/************************************************************************/
-
-/*
-** File descriptors of the NSPR layer can be in one of the
-** following states (stored in the 'state' field of struct
-** PRFilePrivate):
-** - _PR_FILEDESC_OPEN: The OS fd is open.
-** - _PR_FILEDESC_CLOSED: The OS fd is closed. The PRFileDesc
-** is still open but is unusable. The only operation allowed
-** on the PRFileDesc is PR_Close().
-** - _PR_FILEDESC_FREED: The OS fd is closed and the PRFileDesc
-** structure is freed.
-*/
-
-#define _PR_FILEDESC_OPEN 0xaaaaaaaa /* 1010101... */
-#define _PR_FILEDESC_CLOSED 0x55555555 /* 0101010... */
-#define _PR_FILEDESC_FREED 0x11111111
-
-/*
-** A boolean type with an additional "unknown" state
-*/
-
-typedef enum {
- _PR_TRI_TRUE = 1,
- _PR_TRI_FALSE = 0,
- _PR_TRI_UNKNOWN = -1
-} _PRTriStateBool;
-
-struct PRFilePrivate {
- PRInt32 state;
- PRBool nonblocking;
- _PRTriStateBool inheritable;
- PRFileDesc *next;
- PRIntn lockCount; /* 0: not locked
- * -1: a native lockfile call is in progress
- * > 0: # times the file is locked */
-#ifdef _PR_HAVE_PEEK_BUFFER
- char *peekBuffer;
- PRInt32 peekBufSize;
- PRInt32 peekBytes;
-#endif
-#if !defined(_PR_HAVE_O_APPEND)
- PRBool appendMode; /* Some platforms don't have O_APPEND or its
- * equivalent, so they have to seek to end of
- * file on write if the file was opened in
- * append mode. See Bugzilla 4090, 276330. */
-#endif
- _MDFileDesc md;
-#ifdef _PR_NEED_SECRET_AF
- PRUint16 af; /* If the platform's implementation of accept()
- * requires knowing the address family of the
- * socket, we save the address family here. */
-#endif
-};
-
-#ifdef _WIN64
-#define PR_PRIdOSFD "lld" /* for printing PROsfd */
-#define PR_PRIxOSFD "llx"
-#define PR_SCNdOSFD "lld" /* for scanning PROsfd */
-#define PR_SCNxOSFD "llx"
-#else
-#define PR_PRIdOSFD "ld" /* for printing PROsfd */
-#define PR_PRIxOSFD "lx"
-#define PR_SCNdOSFD "ld" /* for scanning PROsfd */
-#define PR_SCNxOSFD "lx"
-#endif
-
-struct PRDir {
- PRDirEntry d;
- _MDDir md;
-};
-
-#ifdef MOZ_UNICODE
-struct PRDirUTF16 {
- PRDirEntry d;
- _MDDirUTF16 md;
-};
-#endif /* MOZ_UNICODE */
-
-extern void _PR_InitLocks(void);
-extern void _PR_InitSegs(void);
-extern void _PR_InitStacks(void);
-extern void _PR_InitTPD(void);
-extern void _PR_InitMem(void);
-extern void _PR_InitEnv(void);
-extern void _PR_InitCMon(void);
-extern void _PR_InitIO(void);
-extern void _PR_InitLog(void);
-extern void _PR_InitNet(void);
-extern void _PR_InitClock(void);
-extern void _PR_InitLinker(void);
-extern void _PR_InitAtomic(void);
-extern void _PR_InitCPUs(void);
-extern void _PR_InitDtoa(void);
-extern void _PR_InitTime(void);
-extern void _PR_InitMW(void);
-extern void _PR_InitRWLocks(void);
-extern void _PR_CleanupThread(PRThread *thread);
-extern void _PR_CleanupCallOnce(void);
-extern void _PR_CleanupMW(void);
-extern void _PR_CleanupTime(void);
-extern void _PR_CleanupDtoa(void);
-extern void _PR_ShutdownLinker(void);
-extern void _PR_CleanupEnv(void);
-extern void _PR_CleanupIO(void);
-extern void _PR_CleanupCMon(void);
-extern void _PR_CleanupNet(void);
-extern void _PR_CleanupLayerCache(void);
-extern void _PR_CleanupStacks(void);
-#ifdef WINNT
-extern void _PR_CleanupCPUs(void);
-#endif
-extern void _PR_CleanupThreads(void);
-extern void _PR_CleanupTPD(void);
-extern void _PR_Cleanup(void);
-extern void _PR_LogCleanup(void);
-extern void _PR_InitLayerCache(void);
-
-extern PRBool _pr_initialized;
-extern void _PR_ImplicitInitialization(void);
-extern PRBool _PR_Obsolete(const char *obsolete, const char *preferred);
-
-/************************************************************************/
-
-struct PRSegment {
- void *vaddr;
- PRUint32 size;
- PRUintn flags;
-#if defined(_PR_PTHREADS)
-#else /* defined(_PR_PTHREADS) */
- _MDSegment md;
-#endif /* defined(_PR_PTHREADS) */
-};
-
-/* PRSegment.flags */
-#define _PR_SEG_VM 0x1
-
-/************************************************************************/
-
-extern PRInt32 _pr_pageSize;
-extern PRInt32 _pr_pageShift;
-
-extern PRLogModuleInfo *_pr_clock_lm;
-extern PRLogModuleInfo *_pr_cmon_lm;
-extern PRLogModuleInfo *_pr_io_lm;
-extern PRLogModuleInfo *_pr_cvar_lm;
-extern PRLogModuleInfo *_pr_mon_lm;
-extern PRLogModuleInfo *_pr_linker_lm;
-extern PRLogModuleInfo *_pr_sched_lm;
-extern PRLogModuleInfo *_pr_thread_lm;
-extern PRLogModuleInfo *_pr_gc_lm;
-
-extern PRFileDesc *_pr_stdin;
-extern PRFileDesc *_pr_stdout;
-extern PRFileDesc *_pr_stderr;
-
-/* Zone allocator */
-/*
-** The zone allocator code has hardcoded pthread types and
-** functions, so it can only be used in the pthreads version.
-** This can be fixed by replacing the hardcoded pthread types
-** and functions with macros that expand to the native thread
-** types and functions on each platform.
-*/
-#if defined(_PR_PTHREADS) && !defined(_PR_DCETHREADS)
-#define _PR_ZONE_ALLOCATOR
-#endif
-
-#ifdef _PR_ZONE_ALLOCATOR
-extern void _PR_InitZones(void);
-extern void _PR_DestroyZones(void);
-#endif
-
-/* Overriding malloc, free, etc. */
-#if !defined(_PR_NO_PREEMPT) && defined(XP_UNIX) \
- && !defined(_PR_PTHREADS) && !defined(_PR_GLOBAL_THREADS_ONLY) \
- && !defined(PURIFY) \
- && !defined(DARWIN) \
- && !defined(QNX) \
- && !(defined (UNIXWARE) && defined (USE_SVR4_THREADS))
-#define _PR_OVERRIDE_MALLOC
-#endif
-
-/*************************************************************************
-* External machine-dependent code provided by each OS. * *
-*************************************************************************/
-
-/* Initialization related */
-extern void _PR_MD_EARLY_INIT(void);
-#define _PR_MD_EARLY_INIT _MD_EARLY_INIT
-
-extern void _PR_MD_INTERVAL_INIT(void);
-#define _PR_MD_INTERVAL_INIT _MD_INTERVAL_INIT
-
-NSPR_API(void) _PR_MD_FINAL_INIT(void);
-#define _PR_MD_FINAL_INIT _MD_FINAL_INIT
-
-extern void _PR_MD_EARLY_CLEANUP(void);
-#define _PR_MD_EARLY_CLEANUP _MD_EARLY_CLEANUP
-
-/* Process control */
-
-extern PRProcess * _PR_MD_CREATE_PROCESS(
- const char *path,
- char *const *argv,
- char *const *envp,
- const PRProcessAttr *attr);
-#define _PR_MD_CREATE_PROCESS _MD_CREATE_PROCESS
-
-extern PRStatus _PR_MD_DETACH_PROCESS(PRProcess *process);
-#define _PR_MD_DETACH_PROCESS _MD_DETACH_PROCESS
-
-extern PRStatus _PR_MD_WAIT_PROCESS(PRProcess *process, PRInt32 *exitCode);
-#define _PR_MD_WAIT_PROCESS _MD_WAIT_PROCESS
-
-extern PRStatus _PR_MD_KILL_PROCESS(PRProcess *process);
-#define _PR_MD_KILL_PROCESS _MD_KILL_PROCESS
-
-/* Current Time */
-NSPR_API(PRTime) _PR_MD_NOW(void);
-#define _PR_MD_NOW _MD_NOW
-
-/* Environment related */
-extern char* _PR_MD_GET_ENV(const char *name);
-#define _PR_MD_GET_ENV _MD_GET_ENV
-
-extern PRIntn _PR_MD_PUT_ENV(const char *name);
-#define _PR_MD_PUT_ENV _MD_PUT_ENV
-
-/* Atomic operations */
-
-extern void _PR_MD_INIT_ATOMIC(void);
-#define _PR_MD_INIT_ATOMIC _MD_INIT_ATOMIC
-
-extern PRInt32 _PR_MD_ATOMIC_INCREMENT(PRInt32 *);
-#define _PR_MD_ATOMIC_INCREMENT _MD_ATOMIC_INCREMENT
-
-extern PRInt32 _PR_MD_ATOMIC_ADD(PRInt32 *, PRInt32);
-#define _PR_MD_ATOMIC_ADD _MD_ATOMIC_ADD
-
-extern PRInt32 _PR_MD_ATOMIC_DECREMENT(PRInt32 *);
-#define _PR_MD_ATOMIC_DECREMENT _MD_ATOMIC_DECREMENT
-
-extern PRInt32 _PR_MD_ATOMIC_SET(PRInt32 *, PRInt32);
-#define _PR_MD_ATOMIC_SET _MD_ATOMIC_SET
-
-/* Garbage collection */
-
-/*
-** Save the registers that the GC would find interesting into the thread
-** "t". isCurrent will be non-zero if the thread state that is being
-** saved is the currently executing thread. Return the address of the
-** first register to be scanned as well as the number of registers to
-** scan in "np".
-**
-** If "isCurrent" is non-zero then it is allowed for the thread context
-** area to be used as scratch storage to hold just the registers
-** necessary for scanning.
-*/
-extern PRWord *_MD_HomeGCRegisters(PRThread *t, int isCurrent, int *np);
-
-/* Time intervals */
-
-extern PRIntervalTime _PR_MD_GET_INTERVAL(void);
-#define _PR_MD_GET_INTERVAL _MD_GET_INTERVAL
-
-extern PRIntervalTime _PR_MD_INTERVAL_PER_SEC(void);
-#define _PR_MD_INTERVAL_PER_SEC _MD_INTERVAL_PER_SEC
-
-/* Affinity masks */
-
-extern PRInt32 _PR_MD_SETTHREADAFFINITYMASK(PRThread *thread, PRUint32 mask );
-#define _PR_MD_SETTHREADAFFINITYMASK _MD_SETTHREADAFFINITYMASK
-
-extern PRInt32 _PR_MD_GETTHREADAFFINITYMASK(PRThread *thread, PRUint32 *mask);
-#define _PR_MD_GETTHREADAFFINITYMASK _MD_GETTHREADAFFINITYMASK
-
-/* File locking */
-
-extern PRStatus _PR_MD_LOCKFILE(PROsfd osfd);
-#define _PR_MD_LOCKFILE _MD_LOCKFILE
-
-extern PRStatus _PR_MD_TLOCKFILE(PROsfd osfd);
-#define _PR_MD_TLOCKFILE _MD_TLOCKFILE
-
-extern PRStatus _PR_MD_UNLOCKFILE(PROsfd osfd);
-#define _PR_MD_UNLOCKFILE _MD_UNLOCKFILE
-
-/* Memory-mapped files */
-
-extern PRStatus _PR_MD_CREATE_FILE_MAP(PRFileMap *fmap, PRInt64 size);
-#define _PR_MD_CREATE_FILE_MAP _MD_CREATE_FILE_MAP
-
-extern PRInt32 _PR_MD_GET_MEM_MAP_ALIGNMENT(void);
-#define _PR_MD_GET_MEM_MAP_ALIGNMENT _MD_GET_MEM_MAP_ALIGNMENT
-
-extern void * _PR_MD_MEM_MAP(
- PRFileMap *fmap,
- PROffset64 offset,
- PRUint32 len);
-#define _PR_MD_MEM_MAP _MD_MEM_MAP
-
-extern PRStatus _PR_MD_MEM_UNMAP(void *addr, PRUint32 size);
-#define _PR_MD_MEM_UNMAP _MD_MEM_UNMAP
-
-extern PRStatus _PR_MD_CLOSE_FILE_MAP(PRFileMap *fmap);
-#define _PR_MD_CLOSE_FILE_MAP _MD_CLOSE_FILE_MAP
-
-extern PRStatus _PR_MD_SYNC_MEM_MAP(
- PRFileDesc *fd,
- void *addr,
- PRUint32 len);
-#define _PR_MD_SYNC_MEM_MAP _MD_SYNC_MEM_MAP
-
-/* Named Shared Memory */
-
-/*
-** Declare PRSharedMemory.
-*/
-struct PRSharedMemory
-{
- char *ipcname; /* after conversion to native */
- PRSize size; /* from open */
- PRIntn mode; /* from open */
- PRIntn flags; /* from open */
-#if defined(PR_HAVE_POSIX_NAMED_SHARED_MEMORY)
- int id;
-#elif defined(PR_HAVE_SYSV_NAMED_SHARED_MEMORY)
- int id;
-#elif defined(PR_HAVE_WIN32_NAMED_SHARED_MEMORY)
- HANDLE handle;
-#else
- PRUint32 nothing; /* placeholder, nothing behind here */
-#endif
- PRUint32 ident; /* guard word at end of struct */
-#define _PR_SHM_IDENT 0xdeadbad
-};
-
-extern PRSharedMemory * _MD_OpenSharedMemory(
- const char *name,
- PRSize size,
- PRIntn flags,
- PRIntn mode
-);
-#define _PR_MD_OPEN_SHARED_MEMORY _MD_OpenSharedMemory
-
-extern void * _MD_AttachSharedMemory( PRSharedMemory *shm, PRIntn flags );
-#define _PR_MD_ATTACH_SHARED_MEMORY _MD_AttachSharedMemory
-
-extern PRStatus _MD_DetachSharedMemory( PRSharedMemory *shm, void *addr );
-#define _PR_MD_DETACH_SHARED_MEMORY _MD_DetachSharedMemory
-
-extern PRStatus _MD_CloseSharedMemory( PRSharedMemory *shm );
-#define _PR_MD_CLOSE_SHARED_MEMORY _MD_CloseSharedMemory
-
-extern PRStatus _MD_DeleteSharedMemory( const char *name );
-#define _PR_MD_DELETE_SHARED_MEMORY _MD_DeleteSharedMemory
-
-extern PRFileMap* _md_OpenAnonFileMap(
- const char *dirName,
- PRSize size,
- PRFileMapProtect prot
-);
-#define _PR_MD_OPEN_ANON_FILE_MAP _md_OpenAnonFileMap
-
-extern PRStatus _md_ExportFileMapAsString(
- PRFileMap *fm,
- PRSize bufSize,
- char *buf
-);
-#define _PR_MD_EXPORT_FILE_MAP_AS_STRING _md_ExportFileMapAsString
-
-extern PRFileMap * _md_ImportFileMapFromString(
- const char *fmstring
-);
-#define _PR_MD_IMPORT_FILE_MAP_FROM_STRING _md_ImportFileMapFromString
-
-
-
-/* Interprocess communications (IPC) */
-
-/*
- * The maximum length of an NSPR IPC name, including the
- * terminating null byte.
- */
-#define PR_IPC_NAME_SIZE 1024
-
-/*
- * Types of NSPR IPC objects
- */
-typedef enum {
- _PRIPCSem, /* semaphores */
- _PRIPCShm /* shared memory segments */
-} _PRIPCType;
-
-/*
- * Make a native IPC name from an NSPR IPC name.
- */
-extern PRStatus _PR_MakeNativeIPCName(
- const char *name, /* NSPR IPC name */
- char *result, /* result buffer */
- PRIntn size, /* size of result buffer */
- _PRIPCType type /* type of IPC object */
-);
-
-/* Socket call error code */
-
-NSPR_API(PRInt32) _PR_MD_GET_SOCKET_ERROR(void);
-#define _PR_MD_GET_SOCKET_ERROR _MD_GET_SOCKET_ERROR
-
-/* Get name of current host */
-extern PRStatus _PR_MD_GETHOSTNAME(char *name, PRUint32 namelen);
-#define _PR_MD_GETHOSTNAME _MD_GETHOSTNAME
-
-extern PRStatus _PR_MD_GETSYSINFO(PRSysInfo cmd, char *name, PRUint32 namelen);
-#define _PR_MD_GETSYSINFO _MD_GETSYSINFO
-
-/* File descriptor inheritance */
-
-/*
- * If fd->secret->inheritable is _PR_TRI_UNKNOWN and we need to
- * know the inheritable attribute of the fd, call this function
- * to find that out. This typically requires a system call.
- */
-extern void _PR_MD_QUERY_FD_INHERITABLE(PRFileDesc *fd);
-#define _PR_MD_QUERY_FD_INHERITABLE _MD_QUERY_FD_INHERITABLE
-
-/* --- PR_GetRandomNoise() related things --- */
-
-extern PRSize _PR_MD_GetRandomNoise( void *buf, PRSize size );
-#define _PR_MD_GET_RANDOM_NOISE(buf,size) _PR_MD_GetRandomNoise((buf),(size))
-extern PRSize _pr_CopyLowBits( void *dest, PRSize dstlen, void *src, PRSize srclen );
-
-/* end PR_GetRandomNoise() related */
-
-#ifdef XP_BEOS
-
-extern PRLock *_connectLock;
-
-typedef struct _ConnectListNode {
- PRInt32 osfd;
- PRNetAddr addr;
- PRUint32 addrlen;
- PRIntervalTime timeout;
-} ConnectListNode;
-
-extern ConnectListNode connectList[64];
-
-extern PRUint32 connectCount;
-
-#endif /* XP_BEOS */
-
-PR_END_EXTERN_C
-
-#endif /* primpl_h___ */
diff --git a/nspr/pr/include/private/prpriv.h b/nspr/pr/include/private/prpriv.h
deleted file mode 100644
index f45eee4..0000000
--- a/nspr/pr/include/private/prpriv.h
+++ /dev/null
@@ -1,16 +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/. */
-
-#ifndef prpriv_h___
-#define prpriv_h___
-
-/*
- * NSPR 2.0 Private API
- */
-
-#include "private/pprio.h"
-#include "private/pprthred.h"
-
-#endif /* prpriv_h___ */
diff --git a/nspr/pr/include/prlink.h b/nspr/pr/include/prlink.h
deleted file mode 100644
index ea45ef8..0000000
--- a/nspr/pr/include/prlink.h
+++ /dev/null
@@ -1,230 +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/. */
-
-#ifndef prlink_h___
-#define prlink_h___
-
-/*
-** API to static and dynamic linking.
-*/
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-typedef struct PRLibrary PRLibrary;
-
-typedef struct PRStaticLinkTable {
- const char *name;
- void (*fp)(void);
-} PRStaticLinkTable;
-
-/*
-** Change the default library path to the given string. The string is
-** copied. This call will fail if it runs out of memory.
-**
-** The string provided as 'path' is copied. The caller can do whatever is
-** convenient with the argument when the function is complete.
-*/
-NSPR_API(PRStatus) PR_SetLibraryPath(const char *path);
-
-/*
-** Return a character string which contains the path used to search for
-** dynamically loadable libraries.
-**
-** The returned value is basically a copy of a PR_SetLibraryPath().
-** The storage is allocated by the runtime and becomes the responsibilty
-** of the caller.
-*/
-NSPR_API(char*) PR_GetLibraryPath(void);
-
-/*
-** Given a directory name "dir" and a library name "lib" construct a full
-** path name that will refer to the actual dynamically loaded
-** library. This does not test for existance of said file, it just
-** constructs the full filename. The name constructed is system dependent
-** and prepared for PR_LoadLibrary. The result must be free'd when the
-** caller is done with it.
-**
-** The storage for the result is allocated by the runtime and becomes the
-** responsibility of the caller.
-*/
-NSPR_API(char*) PR_GetLibraryName(const char *dir, const char *lib);
-
-/*
-**
-** Free the memory allocated, for the caller, by PR_GetLibraryName
-*/
-NSPR_API(void) PR_FreeLibraryName(char *mem);
-
-/*
-** Given a library "name" try to load the library. The argument "name"
-** is a machine-dependent name for the library, such as the full pathname
-** returned by PR_GetLibraryName. If the library is already loaded,
-** this function will avoid loading the library twice.
-**
-** If the library is loaded successfully, then a pointer to the PRLibrary
-** structure representing the library is returned. Otherwise, NULL is
-** returned.
-**
-** This increments the reference count of the library.
-*/
-NSPR_API(PRLibrary*) PR_LoadLibrary(const char *name);
-
-/*
-** Each operating system has its preferred way of specifying
-** a file in the file system. Most operating systems use
-** a pathname. Mac OS Classic, on the other hand, uses the FSSpec
-** structure to specify a file. PRLibSpec allows NSPR clients
-** to use the type of file specification that is most efficient
-** for a particular platform.
-**
-** On some operating systems such as Mac OS Classic, a shared library
-** may contain code fragments that can be individually loaded.
-** PRLibSpec also allows NSPR clients to identify a code fragment
-** in a library, if code fragments are supported by the OS.
-** A code fragment can be specified by name or by an integer index.
-**
-** Right now PRLibSpec supports four types of library specification:
-** a pathname in the native character encoding, a Mac code fragment
-** by name, a Mac code fragment by index, and a UTF-16 pathname.
-*/
-
-typedef enum PRLibSpecType {
- PR_LibSpec_Pathname,
- PR_LibSpec_MacNamedFragment, /* obsolete (for Mac OS Classic) */
- PR_LibSpec_MacIndexedFragment, /* obsolete (for Mac OS Classic) */
- PR_LibSpec_PathnameU /* supported only on Win32 */
-} PRLibSpecType;
-
-struct FSSpec; /* Mac OS Classic FSSpec */
-
-typedef struct PRLibSpec {
- PRLibSpecType type;
- union {
- /* if type is PR_LibSpec_Pathname */
- const char *pathname;
-
- /* if type is PR_LibSpec_MacNamedFragment */
- struct {
- const struct FSSpec *fsspec;
- const char *name;
- } mac_named_fragment; /* obsolete (for Mac OS Classic) */
-
- /* if type is PR_LibSpec_MacIndexedFragment */
- struct {
- const struct FSSpec *fsspec;
- PRUint32 index;
- } mac_indexed_fragment; /* obsolete (for Mac OS Classic) */
-
- /* if type is PR_LibSpec_PathnameU */
- const PRUnichar *pathname_u; /* supported only on Win32 */
- } value;
-} PRLibSpec;
-
-/*
-** The following bit flags may be or'd together and passed
-** as the 'flags' argument to PR_LoadLibraryWithFlags.
-** Flags not supported by the underlying OS are ignored.
-*/
-
-#define PR_LD_LAZY 0x1 /* equivalent to RTLD_LAZY on Unix */
-#define PR_LD_NOW 0x2 /* equivalent to RTLD_NOW on Unix */
-#define PR_LD_GLOBAL 0x4 /* equivalent to RTLD_GLOBAL on Unix */
-#define PR_LD_LOCAL 0x8 /* equivalent to RTLD_LOCAL on Unix */
-/* The following is equivalent to LOAD_WITH_ALTERED_SEARCH_PATH on Windows */
-#define PR_LD_ALT_SEARCH_PATH 0x10
-/* 0x8000 reserved for NSPR internal use */
-
-/*
-** Load the specified library, in the manner specified by 'flags'.
-*/
-
-NSPR_API(PRLibrary *)
-PR_LoadLibraryWithFlags(
- PRLibSpec libSpec, /* the shared library */
- PRIntn flags /* flags that affect the loading */
-);
-
-/*
-** Unload a previously loaded library. If the library was a static
-** library then the static link table will no longer be referenced. The
-** associated PRLibrary object is freed.
-**
-** PR_FAILURE is returned if the library cannot be unloaded.
-**
-** This function decrements the reference count of the library.
-*/
-NSPR_API(PRStatus) PR_UnloadLibrary(PRLibrary *lib);
-
-/*
-** Given the name of a procedure, return the address of the function that
-** implements the procedure, or NULL if no such function can be
-** found. This does not find symbols in the main program (the ".exe");
-** use PR_LoadStaticLibrary to register symbols in the main program.
-**
-** This function does not modify the reference count of the library.
-*/
-NSPR_API(void*) PR_FindSymbol(PRLibrary *lib, const char *name);
-
-/*
-** Similar to PR_FindSymbol, except that the return value is a pointer to
-** a function, and not a pointer to void. Casting between a data pointer
-** and a function pointer is not portable according to the C standard.
-** Any function pointer can be cast to any other function pointer.
-**
-** This function does not modify the reference count of the library.
-*/
-typedef void (*PRFuncPtr)(void);
-NSPR_API(PRFuncPtr) PR_FindFunctionSymbol(PRLibrary *lib, const char *name);
-
-/*
-** Finds a symbol in one of the currently loaded libraries. Given the
-** name of a procedure, return the address of the function that
-** implements the procedure, and return the library that contains that
-** symbol, or NULL if no such function can be found. This does not find
-** symbols in the main program (the ".exe"); use PR_AddStaticLibrary to
-** register symbols in the main program.
-**
-** This increments the reference count of the library.
-*/
-NSPR_API(void*) PR_FindSymbolAndLibrary(const char *name,
- PRLibrary* *lib);
-
-/*
-** Similar to PR_FindSymbolAndLibrary, except that the return value is
-** a pointer to a function, and not a pointer to void. Casting between a
-** data pointer and a function pointer is not portable according to the C
-** standard. Any function pointer can be cast to any other function pointer.
-**
-** This increments the reference count of the library.
-*/
-NSPR_API(PRFuncPtr) PR_FindFunctionSymbolAndLibrary(const char *name,
- PRLibrary* *lib);
-
-/*
-** Register a static link table with the runtime under the name
-** "name". The symbols present in the static link table will be made
-** available to PR_FindSymbol. If "name" is null then the symbols will be
-** made available to the library which represents the executable. The
-** tables are not copied.
-**
-** Returns the library object if successful, null otherwise.
-**
-** This increments the reference count of the library.
-*/
-NSPR_API(PRLibrary*) PR_LoadStaticLibrary(
- const char *name, const PRStaticLinkTable *table);
-
-/*
-** Return the pathname of the file that the library "name" was loaded
-** from. "addr" is the address of a function defined in the library.
-**
-** The caller is responsible for freeing the result with PR_Free.
-*/
-NSPR_API(char *) PR_GetLibraryFilePathname(const char *name, PRFuncPtr addr);
-
-PR_END_EXTERN_C
-
-#endif /* prlink_h___ */
diff --git a/nspr/pr/include/prlock.h b/nspr/pr/include/prlock.h
deleted file mode 100644
index bc76a0e..0000000
--- a/nspr/pr/include/prlock.h
+++ /dev/null
@@ -1,109 +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/. */
-
-/*
-** File: prlock.h
-** Description: API to basic locking functions of NSPR.
-**
-**
-** NSPR provides basic locking mechanisms for thread synchronization. Locks
-** are lightweight resource contention controls that prevent multiple threads
-** from accessing something (code/data) simultaneously.
-**/
-
-#ifndef prlock_h___
-#define prlock_h___
-
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-/**********************************************************************/
-/************************* TYPES AND CONSTANTS ************************/
-/**********************************************************************/
-
-/*
- * PRLock --
- *
- * NSPR represents the lock as an opaque entity to the client of the
- * API. All routines operate on a pointer to this opaque entity.
- */
-
-typedef struct PRLock PRLock;
-
-/**********************************************************************/
-/****************************** FUNCTIONS *****************************/
-/**********************************************************************/
-
-/***********************************************************************
-** FUNCTION: PR_NewLock
-** DESCRIPTION:
-** Returns a pointer to a newly created opaque lock object.
-** INPUTS: void
-** OUTPUTS: void
-** RETURN: PRLock*
-** If the lock can not be created because of resource constraints, NULL
-** is returned.
-**
-***********************************************************************/
-NSPR_API(PRLock*) PR_NewLock(void);
-
-/***********************************************************************
-** FUNCTION: PR_DestroyLock
-** DESCRIPTION:
-** Destroys a given opaque lock object.
-** INPUTS: PRLock *lock
-** Lock to be freed.
-** OUTPUTS: void
-** RETURN: None
-***********************************************************************/
-NSPR_API(void) PR_DestroyLock(PRLock *lock);
-
-/***********************************************************************
-** FUNCTION: PR_Lock
-** DESCRIPTION:
-** Lock a lock.
-** INPUTS: PRLock *lock
-** Lock to locked.
-** OUTPUTS: void
-** RETURN: None
-***********************************************************************/
-NSPR_API(void) PR_Lock(PRLock *lock);
-
-/***********************************************************************
-** FUNCTION: PR_Unlock
-** DESCRIPTION:
-** Unlock a lock. Unlocking an unlocked lock has undefined results.
-** INPUTS: PRLock *lock
-** Lock to unlocked.
-** OUTPUTS: void
-** RETURN: PR_STATUS
-** Returns PR_FAILURE if the caller does not own the lock.
-***********************************************************************/
-NSPR_API(PRStatus) PR_Unlock(PRLock *lock);
-
-/***********************************************************************
-** MACRO: PR_ASSERT_CURRENT_THREAD_OWNS_LOCK
-** DESCRIPTION:
-** If the current thread owns |lock|, this assertion is guaranteed to
-** succeed. Otherwise, the behavior of this function is undefined.
-** INPUTS: PRLock *lock
-** Lock to assert ownership of.
-** OUTPUTS: void
-** RETURN: None
-***********************************************************************/
-#if defined(DEBUG) || defined(FORCE_PR_ASSERT)
-#define PR_ASSERT_CURRENT_THREAD_OWNS_LOCK(/* PrLock* */ lock) \
- PR_AssertCurrentThreadOwnsLock(lock)
-#else
-#define PR_ASSERT_CURRENT_THREAD_OWNS_LOCK(/* PrLock* */ lock)
-#endif
-
-/* Don't call this function directly. */
-NSPR_API(void) PR_AssertCurrentThreadOwnsLock(PRLock *lock);
-
-PR_END_EXTERN_C
-
-#endif /* prlock_h___ */
diff --git a/nspr/pr/include/prlog.h b/nspr/pr/include/prlog.h
deleted file mode 100644
index 4a291dc..0000000
--- a/nspr/pr/include/prlog.h
+++ /dev/null
@@ -1,222 +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/. */
-
-#ifndef prlog_h___
-#define prlog_h___
-
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-/*
-** prlog.h -- Declare interfaces to NSPR's Logging service
-**
-** NSPR provides a logging service that is used by NSPR itself and is
-** available to client programs.
-**
-** To use the service from a client program, you should create a
-** PRLogModuleInfo structure by calling PR_NewLogModule(). After
-** creating the LogModule, you can write to the log using the PR_LOG()
-** macro.
-**
-** Initialization of the log service is handled by NSPR initialization.
-**
-** At execution time, you must enable the log service. To enable the
-** log service, set the environment variable: NSPR_LOG_MODULES
-** variable.
-**
-** NSPR_LOG_MODULES variable has the form:
-**
-** <moduleName>:<value>[, <moduleName>:<value>]*
-**
-** Where:
-** <moduleName> is the name passed to PR_NewLogModule().
-** <value> is a numeric constant, e.g. 5. This value is the maximum
-** value of a log event, enumerated by PRLogModuleLevel, that you want
-** written to the log.
-**
-** For example: to record all events of greater value than or equal to
-** PR_LOG_ERROR for a LogModule names "gizmo", say:
-**
-** set NSPR_LOG_MODULES=gizmo:2
-**
-** Note that you must specify the numeric value of PR_LOG_ERROR.
-**
-** Special LogModule names are provided for controlling NSPR's log
-** service at execution time. These controls should be set in the
-** NSPR_LOG_MODULES environment variable at execution time to affect
-** NSPR's log service for your application.
-**
-** The special LogModule "all" enables all LogModules. To enable all
-** LogModule calls to PR_LOG(), say:
-**
-** set NSPR_LOG_MODULES=all:5
-**
-** The special LogModule name "sync" tells the NSPR log service to do
-** unbuffered logging.
-**
-** The special LogModule name "bufsize:<size>" tells NSPR to set the
-** log buffer to <size>.
-**
-** The environment variable NSPR_LOG_FILE specifies the log file to use
-** unless the default of "stderr" is acceptable. For MS Windows
-** systems, NSPR_LOG_FILE can be set to a special value: "WinDebug"
-** (case sensitive). This value causes PR_LOG() output to be written
-** using the Windows API OutputDebugString(). OutputDebugString()
-** writes to the debugger window; some people find this helpful.
-**
-**
-** To put log messages in your programs, use the PR_LOG macro:
-**
-** PR_LOG(<module>, <level>, (<printfString>, <args>*));
-**
-** Where <module> is the address of a PRLogModuleInfo structure, and
-** <level> is one of the levels defined by the enumeration:
-** PRLogModuleLevel. <args> is a printf() style of argument list. That
-** is: (fmtstring, ...).
-**
-** Example:
-**
-** main() {
-** PRIntn one = 1;
-** PRLogModuleInfo * myLm = PR_NewLogModule("gizmo");
-** PR_LOG( myLm, PR_LOG_ALWAYS, ("Log this! %d\n", one));
-** return;
-** }
-**
-** Note the use of printf() style arguments as the third agrument(s) to
-** PR_LOG().
-**
-** After compiling and linking you application, set the environment:
-**
-** set NSPR_LOG_MODULES=gizmo:5
-** set NSPR_LOG_FILE=logfile.txt
-**
-** When you execute your application, the string "Log this! 1" will be
-** written to the file "logfile.txt".
-**
-** Note to NSPR engineers: a number of PRLogModuleInfo structures are
-** defined and initialized in prinit.c. See this module for ideas on
-** what to log where.
-**
-*/
-
-typedef enum PRLogModuleLevel {
- PR_LOG_NONE = 0, /* nothing */
- PR_LOG_ALWAYS = 1, /* always printed */
- PR_LOG_ERROR = 2, /* error messages */
- PR_LOG_WARNING = 3, /* warning messages */
- PR_LOG_DEBUG = 4, /* debug messages */
-
- PR_LOG_NOTICE = PR_LOG_DEBUG, /* notice messages */
- PR_LOG_WARN = PR_LOG_WARNING, /* warning messages */
- PR_LOG_MIN = PR_LOG_DEBUG, /* minimal debugging messages */
- PR_LOG_MAX = PR_LOG_DEBUG /* maximal debugging messages */
-} PRLogModuleLevel;
-
-/*
-** One of these structures is created for each module that uses logging.
-** "name" is the name of the module
-** "level" is the debugging level selected for that module
-*/
-typedef struct PRLogModuleInfo {
- const char *name;
- PRLogModuleLevel level;
- struct PRLogModuleInfo *next;
-} PRLogModuleInfo;
-
-/*
-** Create a new log module.
-*/
-NSPR_API(PRLogModuleInfo*) PR_NewLogModule(const char *name);
-
-/*
-** Set the file to use for logging. Returns PR_FALSE if the file cannot
-** be created
-*/
-NSPR_API(PRBool) PR_SetLogFile(const char *name);
-
-/*
-** Set the size of the logging buffer. If "buffer_size" is zero then the
-** logging becomes "synchronous" (or unbuffered).
-*/
-NSPR_API(void) PR_SetLogBuffering(PRIntn buffer_size);
-
-/*
-** Print a string to the log. "fmt" is a PR_snprintf format type. All
-** messages printed to the log are preceeded by the name of the thread
-** and a time stamp. Also, the routine provides a missing newline if one
-** is not provided.
-*/
-NSPR_API(void) PR_LogPrint(const char *fmt, ...);
-
-/*
-** Flush the log to its file.
-*/
-NSPR_API(void) PR_LogFlush(void);
-
-NSPR_API(void) PR_Assert(const char *s, const char *file, PRIntn ln)
- PR_PRETEND_NORETURN;
-
-#if defined(DEBUG) || defined(FORCE_PR_LOG)
-#define PR_LOGGING 1
-
-#define PR_LOG_TEST(_module,_level) \
- ((_module)->level >= (_level))
-
-/*
-** Log something.
-** "module" is the address of a PRLogModuleInfo structure
-** "level" is the desired logging level
-** "args" is a variable length list of arguments to print, in the following
-** format: ("printf style format string", ...)
-*/
-#define PR_LOG(_module,_level,_args) \
- PR_BEGIN_MACRO \
- if (PR_LOG_TEST(_module,_level)) { \
- PR_LogPrint _args; \
- } \
- PR_END_MACRO
-
-#else /* defined(DEBUG) || defined(FORCE_PR_LOG) */
-
-#undef PR_LOGGING
-#define PR_LOG_TEST(module,level) 0
-#define PR_LOG(module,level,args)
-
-#endif /* defined(DEBUG) || defined(FORCE_PR_LOG) */
-
-#ifndef NO_NSPR_10_SUPPORT
-
-#ifdef PR_LOGGING
-#define PR_LOG_BEGIN PR_LOG
-#define PR_LOG_END PR_LOG
-#define PR_LOG_DEFINE PR_NewLogModule
-#else
-#define PR_LOG_BEGIN(module,level,args)
-#define PR_LOG_END(module,level,args)
-#define PR_LOG_DEFINE(_name) NULL
-#endif /* PR_LOGGING */
-
-#endif /* NO_NSPR_10_SUPPORT */
-
-#if defined(DEBUG) || defined(FORCE_PR_ASSERT)
-
-#define PR_ASSERT(_expr) \
- ((_expr)?((void)0):PR_Assert(# _expr,__FILE__,__LINE__))
-
-#define PR_NOT_REACHED(_reasonStr) \
- PR_Assert(_reasonStr,__FILE__,__LINE__)
-
-#else
-
-#define PR_ASSERT(expr) ((void) 0)
-#define PR_NOT_REACHED(reasonStr)
-
-#endif /* defined(DEBUG) || defined(FORCE_PR_ASSERT) */
-
-PR_END_EXTERN_C
-
-#endif /* prlog_h___ */
diff --git a/nspr/pr/include/prlong.h b/nspr/pr/include/prlong.h
deleted file mode 100644
index df1f30b..0000000
--- a/nspr/pr/include/prlong.h
+++ /dev/null
@@ -1,403 +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/. */
-
-/*
-** File: prlong.h
-** Description: Portable access to 64 bit numerics
-**
-** Long-long (64-bit signed integer type) support. Some C compilers
-** don't support 64 bit integers yet, so we use these macros to
-** support both machines that do and don't.
-**/
-#ifndef prlong_h___
-#define prlong_h___
-
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-/***********************************************************************
-** DEFINES: LL_MaxInt
-** LL_MinInt
-** LL_Zero
-** LL_MaxUint
-** DESCRIPTION:
-** Various interesting constants and static variable
-** initializer
-***********************************************************************/
-NSPR_API(PRInt64) LL_MaxInt(void);
-NSPR_API(PRInt64) LL_MinInt(void);
-NSPR_API(PRInt64) LL_Zero(void);
-NSPR_API(PRUint64) LL_MaxUint(void);
-
-#if defined(HAVE_LONG_LONG)
-
-/* Keep this in sync with prtypes.h. */
-#if PR_BYTES_PER_LONG == 8 && !defined(PR_ALTERNATE_INT64_TYPEDEF)
-#define LL_MAXINT 9223372036854775807L
-#define LL_MININT (-LL_MAXINT - 1L)
-#define LL_ZERO 0L
-#define LL_MAXUINT 18446744073709551615UL
-#define LL_INIT(hi, lo) ((hi ## L << 32) + lo ## L)
-#elif defined(WIN32) && !defined(__GNUC__)
-#define LL_MAXINT 9223372036854775807i64
-#define LL_MININT (-LL_MAXINT - 1i64)
-#define LL_ZERO 0i64
-#define LL_MAXUINT 18446744073709551615ui64
-#define LL_INIT(hi, lo) ((hi ## i64 << 32) + lo ## i64)
-#else
-#define LL_MAXINT 9223372036854775807LL
-#define LL_MININT (-LL_MAXINT - 1LL)
-#define LL_ZERO 0LL
-#define LL_MAXUINT 18446744073709551615ULL
-#define LL_INIT(hi, lo) ((hi ## LL << 32) + lo ## LL)
-#endif
-
-/***********************************************************************
-** MACROS: LL_*
-** DESCRIPTION:
-** The following macros define portable access to the 64 bit
-** math facilities.
-**
-***********************************************************************/
-
-/***********************************************************************
-** MACROS: LL_<relational operators>
-**
-** LL_IS_ZERO Test for zero
-** LL_EQ Test for equality
-** LL_NE Test for inequality
-** LL_GE_ZERO Test for zero or positive
-** LL_CMP Compare two values
-***********************************************************************/
-#define LL_IS_ZERO(a) ((a) == 0)
-#define LL_EQ(a, b) ((a) == (b))
-#define LL_NE(a, b) ((a) != (b))
-#define LL_GE_ZERO(a) ((a) >= 0)
-#define LL_CMP(a, op, b) ((PRInt64)(a) op (PRInt64)(b))
-#define LL_UCMP(a, op, b) ((PRUint64)(a) op (PRUint64)(b))
-
-/***********************************************************************
-** MACROS: LL_<logical operators>
-**
-** LL_AND Logical and
-** LL_OR Logical or
-** LL_XOR Logical exclusion
-** LL_OR2 A disgusting deviation
-** LL_NOT Negation (one's complement)
-***********************************************************************/
-#define LL_AND(r, a, b) ((r) = (a) & (b))
-#define LL_OR(r, a, b) ((r) = (a) | (b))
-#define LL_XOR(r, a, b) ((r) = (a) ^ (b))
-#define LL_OR2(r, a) ((r) = (r) | (a))
-#define LL_NOT(r, a) ((r) = ~(a))
-
-/***********************************************************************
-** MACROS: LL_<mathematical operators>
-**
-** LL_NEG Negation (two's complement)
-** LL_ADD Summation (two's complement)
-** LL_SUB Difference (two's complement)
-***********************************************************************/
-#define LL_NEG(r, a) ((r) = -(a))
-#define LL_ADD(r, a, b) ((r) = (a) + (b))
-#define LL_SUB(r, a, b) ((r) = (a) - (b))
-
-/***********************************************************************
-** MACROS: LL_<mathematical operators>
-**
-** LL_MUL Product (two's complement)
-** LL_DIV Quotient (two's complement)
-** LL_MOD Modulus (two's complement)
-***********************************************************************/
-#define LL_MUL(r, a, b) ((r) = (a) * (b))
-#define LL_DIV(r, a, b) ((r) = (a) / (b))
-#define LL_MOD(r, a, b) ((r) = (a) % (b))
-
-/***********************************************************************
-** MACROS: LL_<shifting operators>
-**
-** LL_SHL Shift left [0..64] bits
-** LL_SHR Shift right [0..64] bits with sign extension
-** LL_USHR Unsigned shift right [0..64] bits
-** LL_ISHL Signed shift left [0..64] bits
-***********************************************************************/
-#define LL_SHL(r, a, b) ((r) = (PRInt64)(a) << (b))
-#define LL_SHR(r, a, b) ((r) = (PRInt64)(a) >> (b))
-#define LL_USHR(r, a, b) ((r) = (PRUint64)(a) >> (b))
-#define LL_ISHL(r, a, b) ((r) = (PRInt64)(a) << (b))
-
-/***********************************************************************
-** MACROS: LL_<conversion operators>
-**
-** LL_L2I Convert to signed 32 bit
-** LL_L2UI Convert to unsigned 32 bit
-** LL_L2F Convert to floating point
-** LL_L2D Convert to floating point
-** LL_I2L Convert signed to 64 bit
-** LL_UI2L Convert unsigned to 64 bit
-** LL_F2L Convert float to 64 bit
-** LL_D2L Convert float to 64 bit
-***********************************************************************/
-#define LL_L2I(i, l) ((i) = (PRInt32)(l))
-#define LL_L2UI(ui, l) ((ui) = (PRUint32)(l))
-#define LL_L2F(f, l) ((f) = (PRFloat64)(l))
-#define LL_L2D(d, l) ((d) = (PRFloat64)(l))
-
-#define LL_I2L(l, i) ((l) = (PRInt64)(i))
-#define LL_UI2L(l, ui) ((l) = (PRInt64)(ui))
-#define LL_F2L(l, f) ((l) = (PRInt64)(f))
-#define LL_D2L(l, d) ((l) = (PRInt64)(d))
-
-/***********************************************************************
-** MACROS: LL_UDIVMOD
-** DESCRIPTION:
-** Produce both a quotient and a remainder given an unsigned
-** INPUTS: PRUint64 a: The dividend of the operation
-** PRUint64 b: The quotient of the operation
-** OUTPUTS: PRUint64 *qp: pointer to quotient
-** PRUint64 *rp: pointer to remainder
-***********************************************************************/
-#define LL_UDIVMOD(qp, rp, a, b) \
- (*(qp) = ((PRUint64)(a) / (b)), \
- *(rp) = ((PRUint64)(a) % (b)))
-
-#else /* !HAVE_LONG_LONG */
-
-#define LL_MAXINT LL_MaxInt()
-#define LL_MININT LL_MinInt()
-#define LL_ZERO LL_Zero()
-#define LL_MAXUINT LL_MaxUint()
-
-#ifdef IS_LITTLE_ENDIAN
-#define LL_INIT(hi, lo) {PR_UINT32(lo), PR_UINT32(hi)}
-#else
-#define LL_INIT(hi, lo) {PR_UINT32(hi), PR_UINT32(lo)}
-#endif
-
-#define LL_IS_ZERO(a) (((a).hi == 0) && ((a).lo == 0))
-#define LL_EQ(a, b) (((a).hi == (b).hi) && ((a).lo == (b).lo))
-#define LL_NE(a, b) (((a).hi != (b).hi) || ((a).lo != (b).lo))
-#define LL_GE_ZERO(a) (((a).hi >> 31) == 0)
-
-#define LL_CMP(a, op, b) (((a).hi == (b).hi) ? ((a).lo op (b).lo) : \
- ((PRInt32)(a).hi op (PRInt32)(b).hi))
-#define LL_UCMP(a, op, b) (((a).hi == (b).hi) ? ((a).lo op (b).lo) : \
- ((a).hi op (b).hi))
-
-#define LL_AND(r, a, b) ((r).lo = (a).lo & (b).lo, \
- (r).hi = (a).hi & (b).hi)
-#define LL_OR(r, a, b) ((r).lo = (a).lo | (b).lo, \
- (r).hi = (a).hi | (b).hi)
-#define LL_XOR(r, a, b) ((r).lo = (a).lo ^ (b).lo, \
- (r).hi = (a).hi ^ (b).hi)
-#define LL_OR2(r, a) ((r).lo = (r).lo | (a).lo, \
- (r).hi = (r).hi | (a).hi)
-#define LL_NOT(r, a) ((r).lo = ~(a).lo, \
- (r).hi = ~(a).hi)
-
-#define LL_NEG(r, a) ((r).lo = -(PRInt32)(a).lo, \
- (r).hi = -(PRInt32)(a).hi - ((r).lo != 0))
-#define LL_ADD(r, a, b) { \
- PRInt64 _a, _b; \
- _a = a; _b = b; \
- (r).lo = _a.lo + _b.lo; \
- (r).hi = _a.hi + _b.hi + ((r).lo < _b.lo); \
-}
-
-#define LL_SUB(r, a, b) { \
- PRInt64 _a, _b; \
- _a = a; _b = b; \
- (r).lo = _a.lo - _b.lo; \
- (r).hi = _a.hi - _b.hi - (_a.lo < _b.lo); \
-}
-
-#define LL_MUL(r, a, b) { \
- PRInt64 _a, _b; \
- _a = a; _b = b; \
- LL_MUL32(r, _a.lo, _b.lo); \
- (r).hi += _a.hi * _b.lo + _a.lo * _b.hi; \
-}
-
-#define _lo16(a) ((a) & PR_BITMASK(16))
-#define _hi16(a) ((a) >> 16)
-
-#define LL_MUL32(r, a, b) { \
- PRUint32 _a1, _a0, _b1, _b0, _y0, _y1, _y2, _y3; \
- _a1 = _hi16(a), _a0 = _lo16(a); \
- _b1 = _hi16(b), _b0 = _lo16(b); \
- _y0 = _a0 * _b0; \
- _y1 = _a0 * _b1; \
- _y2 = _a1 * _b0; \
- _y3 = _a1 * _b1; \
- _y1 += _hi16(_y0); /* can't carry */ \
- _y1 += _y2; /* might carry */ \
- if (_y1 < _y2) \
- _y3 += (PRUint32)(PR_BIT(16)); /* propagate */ \
- (r).lo = (_lo16(_y1) << 16) + _lo16(_y0); \
- (r).hi = _y3 + _hi16(_y1); \
-}
-
-#define LL_UDIVMOD(qp, rp, a, b) ll_udivmod(qp, rp, a, b)
-
-NSPR_API(void) ll_udivmod(PRUint64 *qp, PRUint64 *rp, PRUint64 a, PRUint64 b);
-
-#define LL_DIV(r, a, b) { \
- PRInt64 _a, _b; \
- PRUint32 _negative = (PRInt32)(a).hi < 0; \
- if (_negative) { \
- LL_NEG(_a, a); \
- } else { \
- _a = a; \
- } \
- if ((PRInt32)(b).hi < 0) { \
- _negative ^= 1; \
- LL_NEG(_b, b); \
- } else { \
- _b = b; \
- } \
- LL_UDIVMOD(&(r), 0, _a, _b); \
- if (_negative) \
- LL_NEG(r, r); \
-}
-
-#define LL_MOD(r, a, b) { \
- PRInt64 _a, _b; \
- PRUint32 _negative = (PRInt32)(a).hi < 0; \
- if (_negative) { \
- LL_NEG(_a, a); \
- } else { \
- _a = a; \
- } \
- if ((PRInt32)(b).hi < 0) { \
- LL_NEG(_b, b); \
- } else { \
- _b = b; \
- } \
- LL_UDIVMOD(0, &(r), _a, _b); \
- if (_negative) \
- LL_NEG(r, r); \
-}
-
-#define LL_SHL(r, a, b) { \
- if (b) { \
- PRInt64 _a; \
- _a = a; \
- if ((b) < 32) { \
- (r).lo = _a.lo << ((b) & 31); \
- (r).hi = (_a.hi << ((b) & 31)) | (_a.lo >> (32 - (b))); \
- } else { \
- (r).lo = 0; \
- (r).hi = _a.lo << ((b) & 31); \
- } \
- } else { \
- (r) = (a); \
- } \
-}
-
-/* a is an PRInt32, b is PRInt32, r is PRInt64 */
-#define LL_ISHL(r, a, b) { \
- if (b) { \
- PRInt64 _a; \
- _a.lo = (a); \
- _a.hi = 0; \
- if ((b) < 32) { \
- (r).lo = (a) << ((b) & 31); \
- (r).hi = ((a) >> (32 - (b))); \
- } else { \
- (r).lo = 0; \
- (r).hi = (a) << ((b) & 31); \
- } \
- } else { \
- (r).lo = (a); \
- (r).hi = 0; \
- } \
-}
-
-#define LL_SHR(r, a, b) { \
- if (b) { \
- PRInt64 _a; \
- _a = a; \
- if ((b) < 32) { \
- (r).lo = (_a.hi << (32 - (b))) | (_a.lo >> ((b) & 31)); \
- (r).hi = (PRInt32)_a.hi >> ((b) & 31); \
- } else { \
- (r).lo = (PRInt32)_a.hi >> ((b) & 31); \
- (r).hi = (PRInt32)_a.hi >> 31; \
- } \
- } else { \
- (r) = (a); \
- } \
-}
-
-#define LL_USHR(r, a, b) { \
- if (b) { \
- PRInt64 _a; \
- _a = a; \
- if ((b) < 32) { \
- (r).lo = (_a.hi << (32 - (b))) | (_a.lo >> ((b) & 31)); \
- (r).hi = _a.hi >> ((b) & 31); \
- } else { \
- (r).lo = _a.hi >> ((b) & 31); \
- (r).hi = 0; \
- } \
- } else { \
- (r) = (a); \
- } \
-}
-
-#define LL_L2I(i, l) ((i) = (l).lo)
-#define LL_L2UI(ui, l) ((ui) = (l).lo)
-#define LL_L2F(f, l) { double _d; LL_L2D(_d, l); (f) = (PRFloat64)_d; }
-
-#define LL_L2D(d, l) { \
- int _negative; \
- PRInt64 _absval; \
- \
- _negative = (l).hi >> 31; \
- if (_negative) { \
- LL_NEG(_absval, l); \
- } else { \
- _absval = l; \
- } \
- (d) = (double)_absval.hi * 4.294967296e9 + _absval.lo; \
- if (_negative) \
- (d) = -(d); \
-}
-
-#define LL_I2L(l, i) { PRInt32 _i = ((PRInt32)(i)) >> 31; (l).lo = (i); (l).hi = _i; }
-#define LL_UI2L(l, ui) ((l).lo = (ui), (l).hi = 0)
-#define LL_F2L(l, f) { double _d = (double)f; LL_D2L(l, _d); }
-
-#define LL_D2L(l, d) { \
- int _negative; \
- double _absval, _d_hi; \
- PRInt64 _lo_d; \
- \
- _negative = ((d) < 0); \
- _absval = _negative ? -(d) : (d); \
- \
- (l).hi = _absval / 4.294967296e9; \
- (l).lo = 0; \
- LL_L2D(_d_hi, l); \
- _absval -= _d_hi; \
- _lo_d.hi = 0; \
- if (_absval < 0) { \
- _lo_d.lo = -_absval; \
- LL_SUB(l, l, _lo_d); \
- } else { \
- _lo_d.lo = _absval; \
- LL_ADD(l, l, _lo_d); \
- } \
- \
- if (_negative) \
- LL_NEG(l, l); \
-}
-
-#endif /* !HAVE_LONG_LONG */
-
-PR_END_EXTERN_C
-
-#endif /* prlong_h___ */
diff --git a/nspr/pr/include/prmem.h b/nspr/pr/include/prmem.h
deleted file mode 100644
index c7cb5fb..0000000
--- a/nspr/pr/include/prmem.h
+++ /dev/null
@@ -1,126 +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/. */
-
-/*
-** File: prmem.h
-** Description: API to NSPR memory management functions
-**
-*/
-#ifndef prmem_h___
-#define prmem_h___
-
-#include "prtypes.h"
-#include <stdlib.h>
-
-PR_BEGIN_EXTERN_C
-
-/*
-** Thread safe memory allocation.
-**
-** NOTE: pr wraps up malloc, free, calloc, realloc so they are already
-** thread safe (and are not declared here - look in stdlib.h).
-*/
-
-/*
-** PR_Malloc, PR_Calloc, PR_Realloc, and PR_Free have the same signatures
-** as their libc equivalent malloc, calloc, realloc, and free, and have
-** the same semantics. (Note that the argument type size_t is replaced
-** by PRUint32.) Memory allocated by PR_Malloc, PR_Calloc, or PR_Realloc
-** must be freed by PR_Free.
-*/
-
-NSPR_API(void *) PR_Malloc(PRUint32 size);
-
-NSPR_API(void *) PR_Calloc(PRUint32 nelem, PRUint32 elsize);
-
-NSPR_API(void *) PR_Realloc(void *ptr, PRUint32 size);
-
-NSPR_API(void) PR_Free(void *ptr);
-
-/*
-** The following are some convenience macros defined in terms of
-** PR_Malloc, PR_Calloc, PR_Realloc, and PR_Free.
-*/
-
-/***********************************************************************
-** FUNCTION: PR_MALLOC()
-** DESCRIPTION:
-** PR_NEW() allocates an untyped item of size _size from the heap.
-** INPUTS: _size: size in bytes of item to be allocated
-** OUTPUTS: untyped pointer to the node allocated
-** RETURN: pointer to node or error returned from malloc().
-***********************************************************************/
-#define PR_MALLOC(_bytes) (PR_Malloc((_bytes)))
-
-/***********************************************************************
-** FUNCTION: PR_NEW()
-** DESCRIPTION:
-** PR_NEW() allocates an item of type _struct from the heap.
-** INPUTS: _struct: a data type
-** OUTPUTS: pointer to _struct
-** RETURN: pointer to _struct or error returns from malloc().
-***********************************************************************/
-#define PR_NEW(_struct) ((_struct *) PR_MALLOC(sizeof(_struct)))
-
-/***********************************************************************
-** FUNCTION: PR_REALLOC()
-** DESCRIPTION:
-** PR_REALLOC() re-allocates _ptr bytes from the heap as a _size
-** untyped item.
-** INPUTS: _ptr: pointer to node to reallocate
-** _size: size of node to allocate
-** OUTPUTS: pointer to node allocated
-** RETURN: pointer to node allocated
-***********************************************************************/
-#define PR_REALLOC(_ptr, _size) (PR_Realloc((_ptr), (_size)))
-
-/***********************************************************************
-** FUNCTION: PR_CALLOC()
-** DESCRIPTION:
-** PR_CALLOC() allocates a _size bytes untyped item from the heap
-** and sets the allocated memory to all 0x00.
-** INPUTS: _size: size of node to allocate
-** OUTPUTS: pointer to node allocated
-** RETURN: pointer to node allocated
-***********************************************************************/
-#define PR_CALLOC(_size) (PR_Calloc(1, (_size)))
-
-/***********************************************************************
-** FUNCTION: PR_NEWZAP()
-** DESCRIPTION:
-** PR_NEWZAP() allocates an item of type _struct from the heap
-** and sets the allocated memory to all 0x00.
-** INPUTS: _struct: a data type
-** OUTPUTS: pointer to _struct
-** RETURN: pointer to _struct
-***********************************************************************/
-#define PR_NEWZAP(_struct) ((_struct*)PR_Calloc(1, sizeof(_struct)))
-
-/***********************************************************************
-** FUNCTION: PR_DELETE()
-** DESCRIPTION:
-** PR_DELETE() unallocates an object previosly allocated via PR_NEW()
-** or PR_NEWZAP() to the heap.
-** INPUTS: pointer to previously allocated object
-** OUTPUTS: the referenced object is returned to the heap
-** RETURN: void
-***********************************************************************/
-#define PR_DELETE(_ptr) { PR_Free(_ptr); (_ptr) = NULL; }
-
-/***********************************************************************
-** FUNCTION: PR_FREEIF()
-** DESCRIPTION:
-** PR_FREEIF() conditionally unallocates an object previously allocated
-** vial PR_NEW() or PR_NEWZAP(). If the pointer to the object is
-** equal to zero (0), the object is not released.
-** INPUTS: pointer to previously allocated object
-** OUTPUTS: the referenced object is conditionally returned to the heap
-** RETURN: void
-***********************************************************************/
-#define PR_FREEIF(_ptr) if (_ptr) PR_DELETE(_ptr)
-
-PR_END_EXTERN_C
-
-#endif /* prmem_h___ */
diff --git a/nspr/pr/include/prmon.h b/nspr/pr/include/prmon.h
deleted file mode 100644
index 374e298..0000000
--- a/nspr/pr/include/prmon.h
+++ /dev/null
@@ -1,96 +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/. */
-
-#ifndef prmon_h___
-#define prmon_h___
-
-#include "prtypes.h"
-#include "prinrval.h"
-
-PR_BEGIN_EXTERN_C
-
-typedef struct PRMonitor PRMonitor;
-
-/*
-** Create a new monitor. Monitors are re-entrant locks with a single built-in
-** condition variable.
-**
-** This may fail if memory is tight or if some operating system resource
-** is low.
-*/
-NSPR_API(PRMonitor*) PR_NewMonitor(void);
-
-/*
-** Destroy a monitor. The caller is responsible for guaranteeing that the
-** monitor is no longer in use. There must be no thread waiting on the monitor's
-** condition variable and that the lock is not held.
-**
-*/
-NSPR_API(void) PR_DestroyMonitor(PRMonitor *mon);
-
-/*
-** Enter the lock associated with the monitor. If the calling thread currently
-** is in the monitor, the call to enter will silently succeed. In either case,
-** it will increment the entry count by one.
-*/
-NSPR_API(void) PR_EnterMonitor(PRMonitor *mon);
-
-/*
-** Decrement the entry count associated with the monitor. If the decremented
-** entry count is zero, the monitor is exited. Returns PR_FAILURE if the
-** calling thread has not entered the monitor.
-*/
-NSPR_API(PRStatus) PR_ExitMonitor(PRMonitor *mon);
-
-/*
-** Wait for a notify on the monitor's condition variable. Sleep for "ticks"
-** amount of time (if "ticks" is PR_INTERVAL_NO_TIMEOUT then the sleep is
-** indefinite).
-**
-** While the thread is waiting it exits the monitor (as if it called
-** PR_ExitMonitor as many times as it had called PR_EnterMonitor). When
-** the wait has finished the thread regains control of the monitors lock
-** with the same entry count as before the wait began.
-**
-** The thread waiting on the monitor will be resumed when the monitor is
-** notified (assuming the thread is the next in line to receive the
-** notify) or when the "ticks" timeout elapses.
-**
-** Returns PR_FAILURE if the caller has not entered the monitor.
-*/
-NSPR_API(PRStatus) PR_Wait(PRMonitor *mon, PRIntervalTime ticks);
-
-/*
-** Notify a thread waiting on the monitor's condition variable. If a thread
-** is waiting on the condition variable (using PR_Wait) then it is awakened
-** and attempts to reenter the monitor.
-*/
-NSPR_API(PRStatus) PR_Notify(PRMonitor *mon);
-
-/*
-** Notify all of the threads waiting on the monitor's condition variable.
-** All of threads waiting on the condition are scheduled to reenter the
-** monitor.
-*/
-NSPR_API(PRStatus) PR_NotifyAll(PRMonitor *mon);
-
-/*
-** PR_ASSERT_CURRENT_THREAD_IN_MONITOR
-** If the current thread is in |mon|, this assertion is guaranteed to
-** succeed. Otherwise, the behavior of this function is undefined.
-*/
-#if defined(DEBUG) || defined(FORCE_PR_ASSERT)
-#define PR_ASSERT_CURRENT_THREAD_IN_MONITOR(/* PRMonitor* */ mon) \
- PR_AssertCurrentThreadInMonitor(mon)
-#else
-#define PR_ASSERT_CURRENT_THREAD_IN_MONITOR(/* PRMonitor* */ mon)
-#endif
-
-/* Don't call this function directly. */
-NSPR_API(void) PR_AssertCurrentThreadInMonitor(PRMonitor *mon);
-
-PR_END_EXTERN_C
-
-#endif /* prmon_h___ */
diff --git a/nspr/pr/include/prmwait.h b/nspr/pr/include/prmwait.h
deleted file mode 100644
index a902d90..0000000
--- a/nspr/pr/include/prmwait.h
+++ /dev/null
@@ -1,380 +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/. */
-
-#if defined(_PRMWAIT_H)
-#else
-#define _PRMWAIT_H
-
-#include "prio.h"
-#include "prtypes.h"
-#include "prclist.h"
-
-PR_BEGIN_EXTERN_C
-
-/********************************************************************************/
-/********************************************************************************/
-/********************************************************************************/
-/****************************** WARNING ****************************/
-/********************************************************************************/
-/**************************** This is work in progress. *************************/
-/************************** Do not make any assumptions *************************/
-/************************** about the stability of this *************************/
-/************************** API or the underlying imple- ************************/
-/************************** mentation. ************************/
-/********************************************************************************/
-/********************************************************************************/
-
-/*
-** STRUCTURE: PRWaitGroup
-** DESCRIPTION:
-** The client may define several wait groups in order to semantically
-** tie a collection of file descriptors for a single purpose. This allows
-** easier dispatching of threads that returned with active file descriptors
-** from the wait function.
-*/
-typedef struct PRWaitGroup PRWaitGroup;
-
-/*
-** ENUMERATION: PRMWStatus
-** DESCRIPTION:
-** This enumeration is used to indicate the completion status of
-** a receive wait object. Generally stated, a positive value indicates
-** that the operation is not yet complete. A zero value indicates
-** success (similar to PR_SUCCESS) and any negative value is an
-** indication of failure. The reason for the failure can be retrieved
-** by calling PR_GetError().
-**
-** PR_MW_PENDING The operation is still pending. None of the other
-** fields of the object are currently valid.
-** PR_MW_SUCCESS The operation is complete and it was successful.
-** PR_MW_FAILURE The operation failed. The reason for the failure
-** can be retrieved by calling PR_GetError().
-** PR_MW_TIMEOUT The amount of time allowed for by the object's
-** 'timeout' field has expired w/o the operation
-** otherwise coming to closure.
-** PR_MW_INTERRUPT The operation was cancelled, either by the client
-** calling PR_CancelWaitFileDesc() or destroying the
-** entire wait group (PR_DestroyWaitGroup()).
-*/
-typedef enum PRMWStatus
-{
- PR_MW_PENDING = 1,
- PR_MW_SUCCESS = 0,
- PR_MW_FAILURE = -1,
- PR_MW_TIMEOUT = -2,
- PR_MW_INTERRUPT = -3
-} PRMWStatus;
-
-/*
-** STRUCTURE: PRMemoryDescriptor
-** DESCRIPTION:
-** THis is a descriptor for an interval of memory. It contains a
-** pointer to the first byte of that memory and the length (in
-** bytes) of the interval.
-*/
-typedef struct PRMemoryDescriptor
-{
- void *start; /* pointer to first byte of memory */
- PRSize length; /* length (in bytes) of memory interval */
-} PRMemoryDescriptor;
-
-/*
-** STRUCTURE: PRMWaitClientData
-** DESCRIPTION:
-** An opague stucture for which a client MAY give provide a concrete
-** definition and associate with a receive descriptor. The NSPR runtime
-** does not manage this field. It is completely up to the client.
-*/
-typedef struct PRMWaitClientData PRMWaitClientData;
-
-/*
-** STRUCTURE: PRRecvWait
-** DESCRIPTION:
-** A receive wait object contains the file descriptor that is subject
-** to the wait and the amount of time (beginning epoch established
-** when the object is presented to the runtime) the the channel should
-** block before abandoning the process.
-**
-** The success of the wait operation will be noted in the object's
-** 'outcome' field. The fields are not valid when the NSPR runtime
-** is in possession of the object.
-**
-** The memory descriptor describes an interval of writable memory
-** in the caller's address space where data from an initial read
-** can be placed. The description may indicate a null interval.
-*/
-typedef struct PRRecvWait
-{
- PRCList internal; /* internal runtime linkages */
-
- PRFileDesc *fd; /* file descriptor associated w/ object */
- PRMWStatus outcome; /* outcome of the current/last operation */
- PRIntervalTime timeout; /* time allowed for entire operation */
-
- PRInt32 bytesRecv; /* number of bytes transferred into buffer */
- PRMemoryDescriptor buffer; /* where to store first segment of input data */
- PRMWaitClientData *client; /* pointer to arbitrary client defined data */
-} PRRecvWait;
-
-/*
-** STRUCTURE: PRMWaitEnumerator
-** DESCRIPTION:
-** An enumeration object is used to store the state of an existing
-** enumeration over a wait group. The opaque object must be allocated
-** by the client and the reference presented on each call to the
-** pseudo-stateless enumerator. The enumeration objects are sharable
-** only in serial fashion.
-*/
-typedef struct PRMWaitEnumerator PRMWaitEnumerator;
-
-
-/*
-** FUNCTION: PR_AddWaitFileDesc
-** DESCRIPTION:
-** This function will effectively add a file descriptor to the
-** list of those waiting for network receive. The new descriptor
-** will be semantically tied to the wait group specified.
-**
-** The ownership for the storage pointed to by 'desc' is temporarily
-** passed over the the NSPR runtime. It will be handed back by the
-** function PR_WaitRecvReady().
-**
-** INPUTS
-** group A reference to a PRWaitGroup or NULL. Wait groups are
-** created by calling PR_CreateWaitGroup() and are used
-** to semantically group various file descriptors by the
-** client's application.
-** desc A reference to a valid PRRecvWait. The object of the
-** reference must be preserved and not be modified
-** until its ownership is returned to the client.
-** RETURN
-** PRStatus An indication of success. If equal to PR_FAILUE details
-** of the failure are avaiable via PR_GetError().
-**
-** ERRORS
-** PR_INVALID_ARGUMENT_ERROR
-** Invalid 'group' identifier or duplicate 'desc' object.
-** PR_OUT_OF_MEMORY_ERROR
-** Insuffient memory for internal data structures.
-** PR_INVALID_STATE_ERROR
-** The group is being destroyed.
-*/
-NSPR_API(PRStatus) PR_AddWaitFileDesc(PRWaitGroup *group, PRRecvWait *desc);
-
-/*
-** FUNCTION: PR_WaitRecvReady
-** DESCRIPTION:
-** PR_WaitRecvReady will block the calling thread until one of the
-** file descriptors that have been added via PR_AddWaitFileDesc is
-** available for input I/O.
-** INPUT
-** group A pointer to a valid PRWaitGroup or NULL (the null
-** group. The function will block the caller until a
-** channel from the wait group becomes ready for receive
-** or there is some sort of error.
-** RETURN
-** PRReciveWait
-** When the caller is resumed it is either returned a
-** valid pointer to a previously added receive wait or
-** a NULL. If the latter, the function has terminated
-** for a reason that can be determined by calling
-** PR_GetError().
-** If a valid pointer is returned, the reference is to the
-** file descriptor contained in the receive wait object.
-** The outcome of the wait operation may still fail, and
-** if it has, that fact will be noted in the object's
-** outcome field. Details can be retrieved from PR_GetError().
-**
-** ERRORS
-** PR_INVALID_ARGUMENT_ERROR
-** The 'group' is not known by the runtime.
-** PR_PENDING_INTERRUPT_ERROR
- The thread was interrupted.
-** PR_INVALID_STATE_ERROR
-** The group is being destroyed.
-*/
-NSPR_API(PRRecvWait*) PR_WaitRecvReady(PRWaitGroup *group);
-
-/*
-** FUNCTION: PR_CancelWaitFileDesc
-** DESCRIPTION:
-** PR_CancelWaitFileDesc is provided as a means for cancelling operations
-** on objects previously submitted by use of PR_AddWaitFileDesc(). If
-** the runtime knows of the object, it will be marked as having failed
-** because it was interrupted (similar to PR_Interrupt()). The first
-** available thread waiting on the group will be made to return the
-** PRRecvWait object with the outcome noted.
-**
-** INPUTS
-** group The wait group under which the wait receive object was
-** added.
-** desc A pointer to the wait receive object that is to be
-** cancelled.
-** RETURN
-** PRStatus If the wait receive object was located and associated
-** with the specified wait group, the status returned will
-** be PR_SUCCESS. There is still a race condition that would
-** permit the offected object to complete normally, but it
-** is assured that it will complete in the near future.
-** If the receive object or wait group are invalid, the
-** function will return with a status of PR_FAILURE.
-**
-** ERRORS
-** PR_INVALID_ARGUMENT_ERROR
-** The 'group' argument is not recognized as a valid group.
-** PR_COLLECTION_EMPTY_ERROR
-** There are no more receive wait objects in the group's
-** collection.
-** PR_INVALID_STATE_ERROR
-** The group is being destroyed.
-*/
-NSPR_API(PRStatus) PR_CancelWaitFileDesc(PRWaitGroup *group, PRRecvWait *desc);
-
-/*
-** FUNCTION: PR_CancelWaitGroup
-** DESCRIPTION:
-** PR_CancelWaitGroup is provided as a means for cancelling operations
-** on objects previously submitted by use of PR_AddWaitFileDesc(). Each
-** successive call will return a pointer to a PRRecvWait object that
-** was previously registered via PR_AddWaitFileDesc(). If no wait
-** objects are associated with the wait group, a NULL will be returned.
-** This function should be called in a loop until a NULL is returned
-** to reclaim all the wait objects prior to calling PR_DestroyWaitGroup().
-**
-** INPUTS
-** group The wait group under which the wait receive object was
-** added.
-** RETURN
-** PRRecvWait* If the wait group is valid and at least one receive wait
-** object is present in the group, that object will be
-** marked as PR_MW_INTERRUPT'd and removed from the group's
-** queues. Otherwise a NULL will be returned and the reason
-** for the NULL may be retrieved by calling PR_GetError().
-**
-** ERRORS
-** PR_INVALID_ARGUMENT_ERROR
-** PR_GROUP_EMPTY_ERROR
-*/
-NSPR_API(PRRecvWait*) PR_CancelWaitGroup(PRWaitGroup *group);
-
-/*
-** FUNCTION: PR_CreateWaitGroup
-** DESCRIPTION:
-** A wait group is an opaque object that a client may create in order
-** to semantically group various wait requests. Each wait group is
-** unique, including the default wait group (NULL). A wait request
-** that was added under a wait group will only be serviced by a caller
-** that specified the same wait group.
-**
-** INPUT
-** size The size of the hash table to be used to contain the
-** receive wait objects. This is just the initial size.
-** It will grow as it needs to, but to avoid that hassle
-** one can suggest a suitable size initially. It should
-** be ~30% larger than the maximum number of receive wait
-** objects expected.
-** RETURN
-** PRWaitGroup If successful, the function will return a pointer to an
-** object that was allocated by and owned by the runtime.
-** The reference remains valid until it is explicitly destroyed
-** by calling PR_DestroyWaitGroup().
-**
-** ERRORS
-** PR_OUT_OF_MEMORY_ERROR
-*/
-NSPR_API(PRWaitGroup*) PR_CreateWaitGroup(PRInt32 size);
-
-/*
-** FUNCTION: PR_DestroyWaitGroup
-** DESCRIPTION:
-** Undo the effects of PR_CreateWaitGroup(). Any receive wait operations
-** on the group will be treated as if the each had been the target of a
-** PR_CancelWaitFileDesc().
-**
-** INPUT
-** group Reference to a wait group previously allocated using
-** PR_CreateWaitGroup().
-** RETURN
-** PRStatus Will be PR_SUCCESS if the wait group was valid and there
-** are no receive wait objects in that group. Otherwise
-** will indicate PR_FAILURE.
-**
-** ERRORS
-** PR_INVALID_ARGUMENT_ERROR
-** The 'group' argument does not reference a known object.
-** PR_INVALID_STATE_ERROR
-** The group still contains receive wait objects.
-*/
-NSPR_API(PRStatus) PR_DestroyWaitGroup(PRWaitGroup *group);
-
-/*
-** FUNCTION: PR_CreateMWaitEnumerator
-** DESCRIPTION:
-** The PR_CreateMWaitEnumerator() function returns a reference to an
-** opaque PRMWaitEnumerator object. The enumerator object is required
-** as an argument for each successive call in the stateless enumeration
-** of the indicated wait group.
-**
-** group The wait group that the enumeration is intended to
-** process. It may be be the default wait group (NULL).
-** RETURN
-** PRMWaitEnumerator* group
-** A reference to an object that will be used to store
-** intermediate state of enumerations.
-** ERRORS
-** Errors are indicated by the function returning a NULL.
-** PR_INVALID_ARGUMENT_ERROR
-** The 'group' argument does not reference a known object.
-** PR_OUT_OF_MEMORY_ERROR
-*/
-NSPR_API(PRMWaitEnumerator*) PR_CreateMWaitEnumerator(PRWaitGroup *group);
-
-/*
-** FUNCTION: PR_DestroyMWaitEnumerator
-** DESCRIPTION:
-** Destroys the object created by PR_CreateMWaitEnumerator(). The reference
-** used as an argument becomes invalid.
-**
-** INPUT
-** PRMWaitEnumerator* enumerator
-** The PRMWaitEnumerator object to destroy.
-** RETURN
-** PRStatus
-** PR_SUCCESS if successful, PR_FAILURE otherwise.
-** ERRORS
-** PR_INVALID_ARGUMENT_ERROR
-** The enumerator is invalid.
-*/
-NSPR_API(PRStatus) PR_DestroyMWaitEnumerator(PRMWaitEnumerator* enumerator);
-
-/*
-** FUNCTION: PR_EnumerateWaitGroup
-** DESCRIPTION:
-** PR_EnumerateWaitGroup is a thread safe enumerator over a wait group.
-** Each call to the enumerator must present a valid PRMWaitEnumerator
-** rererence and a pointer to the "previous" element returned from the
-** enumeration process or a NULL.
-**
-** An enumeration is started by passing a NULL as the "previous" value.
-** Subsequent calls to the enumerator must pass in the result of the
-** previous call. The enumeration end is signaled by the runtime returning
-** a NULL as the result.
-**
-** Modifications to the content of the wait group are allowed during
-** an enumeration. The effect is that the enumeration may have to be
-** "reset" and that may result in duplicates being returned from the
-** enumeration.
-**
-** An enumeration may be abandoned at any time. The runtime is not
-** keeping any state, so there are no issues in that regard.
-*/
-NSPR_API(PRRecvWait*) PR_EnumerateWaitGroup(
- PRMWaitEnumerator *enumerator, const PRRecvWait *previous);
-
-PR_END_EXTERN_C
-
-#endif /* defined(_PRMWAIT_H) */
-
-/* prmwait.h */
diff --git a/nspr/pr/include/prnetdb.h b/nspr/pr/include/prnetdb.h
deleted file mode 100644
index 49b77b1..0000000
--- a/nspr/pr/include/prnetdb.h
+++ /dev/null
@@ -1,467 +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/. */
-
-#ifndef prnetdb_h___
-#define prnetdb_h___
-
-#include "prtypes.h"
-#include "prio.h"
-
-PR_BEGIN_EXTERN_C
-
-
-/*
- *********************************************************************
- * Translate an Internet address to/from a character string
- *********************************************************************
- */
-NSPR_API(PRStatus) PR_StringToNetAddr(
- const char *string, PRNetAddr *addr);
-
-NSPR_API(PRStatus) PR_NetAddrToString(
- const PRNetAddr *addr, char *string, PRUint32 size);
-
-/*
-** Structures returned by network data base library. All addresses are
-** supplied in host order, and returned in network order (suitable for
-** use in system calls).
-*/
-/*
-** Beware that WINSOCK.H defines h_addrtype and h_length as short.
-** Client code does direct struct copies of hostent to PRHostEnt and
-** hence the ifdef.
-*/
-typedef struct PRHostEnt {
- char *h_name; /* official name of host */
- char **h_aliases; /* alias list */
-#ifdef WIN32
- PRInt16 h_addrtype; /* host address type */
- PRInt16 h_length; /* length of address */
-#else
- PRInt32 h_addrtype; /* host address type */
- PRInt32 h_length; /* length of address */
-#endif
- char **h_addr_list; /* list of addresses from name server */
-} PRHostEnt;
-
-/* A safe size to use that will mostly work... */
-#if (defined(AIX) && defined(_THREAD_SAFE)) || defined(OSF1)
-#define PR_NETDB_BUF_SIZE sizeof(struct protoent_data)
-#else
-#define PR_NETDB_BUF_SIZE 1024
-#endif
-
-/***********************************************************************
-** FUNCTION:
-** DESCRIPTION: PR_GetHostByName()
-** Lookup a host by name.
-**
-** INPUTS:
-** char *hostname Character string defining the host name of interest
-** char *buf A scratch buffer for the runtime to return result.
-** This buffer is allocated by the caller.
-** PRIntn bufsize Number of bytes in 'buf'. A recommnded value to
-** use is PR_NETDB_BUF_SIZE.
-** OUTPUTS:
-** PRHostEnt *hostentry
-** This structure is filled in by the runtime if
-** the function returns PR_SUCCESS. This structure
-** is allocated by the caller.
-** RETURN:
-** PRStatus PR_SUCCESS if the lookup succeeds. If it fails
-** the result will be PR_FAILURE and the reason
-** for the failure can be retrieved by PR_GetError().
-***********************************************************************/
-NSPR_API(PRStatus) PR_GetHostByName(
- const char *hostname, char *buf, PRIntn bufsize, PRHostEnt *hostentry);
-
-/***********************************************************************
-** FUNCTION:
-** DESCRIPTION: PR_GetIPNodeByName()
-** Lookup a host by name. Equivalent to getipnodebyname(AI_DEFAULT)
-** of RFC 2553.
-**
-** INPUTS:
-** char *hostname Character string defining the host name of interest
-** PRUint16 af Address family (either PR_AF_INET or PR_AF_INET6)
-** PRIntn flags Specifies the types of addresses that are searched
-** for and the types of addresses that are returned.
-** The only supported flag is PR_AI_DEFAULT.
-** char *buf A scratch buffer for the runtime to return result.
-** This buffer is allocated by the caller.
-** PRIntn bufsize Number of bytes in 'buf'. A recommnded value to
-** use is PR_NETDB_BUF_SIZE.
-** OUTPUTS:
-** PRHostEnt *hostentry
-** This structure is filled in by the runtime if
-** the function returns PR_SUCCESS. This structure
-** is allocated by the caller.
-** RETURN:
-** PRStatus PR_SUCCESS if the lookup succeeds. If it fails
-** the result will be PR_FAILURE and the reason
-** for the failure can be retrieved by PR_GetError().
-***********************************************************************/
-
-
-#define PR_AI_ALL 0x08
-#define PR_AI_V4MAPPED 0x10
-#define PR_AI_ADDRCONFIG 0x20
-#define PR_AI_NOCANONNAME 0x8000
-#define PR_AI_DEFAULT (PR_AI_V4MAPPED | PR_AI_ADDRCONFIG)
-
-NSPR_API(PRStatus) PR_GetIPNodeByName(
- const char *hostname,
- PRUint16 af,
- PRIntn flags,
- char *buf,
- PRIntn bufsize,
- PRHostEnt *hostentry);
-
-/***********************************************************************
-** FUNCTION:
-** DESCRIPTION: PR_GetHostByAddr()
-** Lookup a host entry by its network address.
-**
-** INPUTS:
-** char *hostaddr IP address of host in question
-** char *buf A scratch buffer for the runtime to return result.
-** This buffer is allocated by the caller.
-** PRIntn bufsize Number of bytes in 'buf'. A recommnded value to
-** use is PR_NETDB_BUF_SIZE.
-** OUTPUTS:
-** PRHostEnt *hostentry
-** This structure is filled in by the runtime if
-** the function returns PR_SUCCESS. This structure
-** is allocated by the caller.
-** RETURN:
-** PRStatus PR_SUCCESS if the lookup succeeds. If it fails
-** the result will be PR_FAILURE and the reason
-** for the failure can be retrieved by PR_GetError().
-***********************************************************************/
-NSPR_API(PRStatus) PR_GetHostByAddr(
- const PRNetAddr *hostaddr, char *buf, PRIntn bufsize, PRHostEnt *hostentry);
-
-/***********************************************************************
-** FUNCTION: PR_EnumerateHostEnt()
-** DESCRIPTION:
-** A stateless enumerator over a PRHostEnt structure acquired from
-** PR_GetHostByName() PR_GetHostByAddr() to evaluate the possible
-** network addresses.
-**
-** INPUTS:
-** PRIntn enumIndex Index of the enumeration. The enumeration starts
-** and ends with a value of zero.
-**
-** PRHostEnt *hostEnt A pointer to a host entry struct that was
-** previously returned by PR_GetHostByName() or
-** PR_GetHostByAddr().
-**
-** PRUint16 port The port number to be assigned as part of the
-** PRNetAddr.
-**
-** OUTPUTS:
-** PRNetAddr *address A pointer to an address structure that will be
-** filled in by the call to the enumeration if the
-** result of the call is greater than zero.
-**
-** RETURN:
-** PRIntn The value that should be used for the next call
-** of the enumerator ('enumIndex'). The enumeration
-** is ended if this value is returned zero.
-** If a value of -1 is returned, the enumeration
-** has failed. The reason for the failure can be
-** retrieved by calling PR_GetError().
-***********************************************************************/
-NSPR_API(PRIntn) PR_EnumerateHostEnt(
- PRIntn enumIndex, const PRHostEnt *hostEnt, PRUint16 port, PRNetAddr *address);
-
-/***********************************************************************
-** FUNCTION: PR_InitializeNetAddr(),
-** DESCRIPTION:
-** Initialize the fields of a PRNetAddr, assigning well known values as
-** appropriate.
-**
-** INPUTS
-** PRNetAddrValue val The value to be assigned to the IP Address portion
-** of the network address. This can only specify the
-** special well known values that are equivalent to
-** INADDR_ANY and INADDR_LOOPBACK.
-**
-** PRUint16 port The port number to be assigned in the structure.
-**
-** OUTPUTS:
-** PRNetAddr *addr The address to be manipulated.
-**
-** RETURN:
-** PRStatus To indicate success or failure. If the latter, the
-** reason for the failure can be retrieved by calling
-** PR_GetError();
-***********************************************************************/
-typedef enum PRNetAddrValue
-{
- PR_IpAddrNull, /* do NOT overwrite the IP address */
- PR_IpAddrAny, /* assign logical INADDR_ANY to IP address */
- PR_IpAddrLoopback, /* assign logical INADDR_LOOPBACK */
- PR_IpAddrV4Mapped /* IPv4 mapped address */
-} PRNetAddrValue;
-
-NSPR_API(PRStatus) PR_InitializeNetAddr(
- PRNetAddrValue val, PRUint16 port, PRNetAddr *addr);
-
-/***********************************************************************
-** FUNCTION: PR_SetNetAddr(),
-** DESCRIPTION:
-** Set the fields of a PRNetAddr, assigning well known values as
-** appropriate. This function is similar to PR_InitializeNetAddr
-** but differs in that the address family is specified.
-**
-** INPUTS
-** PRNetAddrValue val The value to be assigned to the IP Address portion
-** of the network address. This can only specify the
-** special well known values that are equivalent to
-** INADDR_ANY and INADDR_LOOPBACK.
-**
-** PRUint16 af The address family (either PR_AF_INET or PR_AF_INET6)
-**
-** PRUint16 port The port number to be assigned in the structure.
-**
-** OUTPUTS:
-** PRNetAddr *addr The address to be manipulated.
-**
-** RETURN:
-** PRStatus To indicate success or failure. If the latter, the
-** reason for the failure can be retrieved by calling
-** PR_GetError();
-***********************************************************************/
-NSPR_API(PRStatus) PR_SetNetAddr(
- PRNetAddrValue val, PRUint16 af, PRUint16 port, PRNetAddr *addr);
-
-/***********************************************************************
-** FUNCTION:
-** DESCRIPTION: PR_IsNetAddrType()
-** Determine if the network address is of the specified type.
-**
-** INPUTS:
-** const PRNetAddr *addr A network address.
-** PRNetAddrValue The type of network address
-**
-** RETURN:
-** PRBool PR_TRUE if the network address is of the
-** specified type, else PR_FALSE.
-***********************************************************************/
-NSPR_API(PRBool) PR_IsNetAddrType(const PRNetAddr *addr, PRNetAddrValue val);
-
-/***********************************************************************
-** FUNCTION:
-** DESCRIPTION: PR_ConvertIPv4AddrToIPv6()
-** Convert an IPv4 addr to an (IPv4-mapped) IPv6 addr
-**
-** INPUTS:
-** PRUint32 v4addr IPv4 address
-**
-** OUTPUTS:
-** PRIPv6Addr *v6addr The converted IPv6 address
-**
-** RETURN:
-** void
-**
-***********************************************************************/
-NSPR_API(void) PR_ConvertIPv4AddrToIPv6(PRUint32 v4addr, PRIPv6Addr *v6addr);
-
-/***********************************************************************
-** MACRO:
-** DESCRIPTION: PR_NetAddrFamily()
-** Get the 'family' field of a PRNetAddr union.
-**
-** INPUTS:
-** const PRNetAddr *addr A network address.
-**
-** RETURN:
-** PRUint16 The 'family' field of 'addr'.
-***********************************************************************/
-#define PR_NetAddrFamily(addr) ((addr)->raw.family)
-
-/***********************************************************************
-** MACRO:
-** DESCRIPTION: PR_NetAddrInetPort()
-** Get the 'port' field of a PRNetAddr union.
-**
-** INPUTS:
-** const PRNetAddr *addr A network address.
-**
-** RETURN:
-** PRUint16 The 'port' field of 'addr'.
-***********************************************************************/
-#define PR_NetAddrInetPort(addr) \
- ((addr)->raw.family == PR_AF_INET6 ? (addr)->ipv6.port : (addr)->inet.port)
-
-/***********************************************************************
-** FUNCTION:
-** DESCRIPTION: PR_GetProtoByName()
-** Lookup a protocol entry based on protocol's name
-**
-** INPUTS:
-** char *protocolname Character string of the protocol's name.
-** char *buf A scratch buffer for the runtime to return result.
-** This buffer is allocated by the caller.
-** PRIntn bufsize Number of bytes in 'buf'. A recommnded value to
-** use is PR_NETDB_BUF_SIZE.
-** OUTPUTS:
-** PRHostEnt *PRProtoEnt
-** This structure is filled in by the runtime if
-** the function returns PR_SUCCESS. This structure
-** is allocated by the caller.
-** RETURN:
-** PRStatus PR_SUCCESS if the lookup succeeds. If it fails
-** the result will be PR_FAILURE and the reason
-** for the failure can be retrieved by PR_GetError().
-***********************************************************************/
-
-typedef struct PRProtoEnt {
- char *p_name; /* official protocol name */
- char **p_aliases; /* alias list */
-#ifdef WIN32
- PRInt16 p_num; /* protocol # */
-#else
- PRInt32 p_num; /* protocol # */
-#endif
-} PRProtoEnt;
-
-NSPR_API(PRStatus) PR_GetProtoByName(
- const char* protocolname, char* buffer, PRInt32 bufsize, PRProtoEnt* result);
-
-/***********************************************************************
-** FUNCTION:
-** DESCRIPTION: PR_GetProtoByNumber()
-** Lookup a protocol entry based on protocol's number
-**
-** INPUTS:
-** PRInt32 protocolnumber
-** Number assigned to the protocol.
-** char *buf A scratch buffer for the runtime to return result.
-** This buffer is allocated by the caller.
-** PRIntn bufsize Number of bytes in 'buf'. A recommnded value to
-** use is PR_NETDB_BUF_SIZE.
-** OUTPUTS:
-** PRHostEnt *PRProtoEnt
-** This structure is filled in by the runtime if
-** the function returns PR_SUCCESS. This structure
-** is allocated by the caller.
-** RETURN:
-** PRStatus PR_SUCCESS if the lookup succeeds. If it fails
-** the result will be PR_FAILURE and the reason
-** for the failure can be retrieved by PR_GetError().
-***********************************************************************/
-NSPR_API(PRStatus) PR_GetProtoByNumber(
- PRInt32 protocolnumber, char* buffer, PRInt32 bufsize, PRProtoEnt* result);
-
-/***********************************************************************
-** FUNCTION:
-** DESCRIPTION: PR_GetAddrInfoByName()
-** Look up a host by name. Equivalent to getaddrinfo(host, NULL, ...) of
-** RFC 3493.
-**
-** INPUTS:
-** char *hostname Character string defining the host name of interest
-** PRUint16 af May be PR_AF_UNSPEC or PR_AF_INET.
-** PRIntn flags May be either PR_AI_ADDRCONFIG or
-** PR_AI_ADDRCONFIG | PR_AI_NOCANONNAME. Include
-** PR_AI_NOCANONNAME to suppress the determination of
-** the canonical name corresponding to hostname.
-** RETURN:
-** PRAddrInfo* Handle to a data structure containing the results
-** of the host lookup. Use PR_EnumerateAddrInfo to
-** inspect the PRNetAddr values stored in this object.
-** When no longer needed, this handle must be destroyed
-** with a call to PR_FreeAddrInfo. If a lookup error
-** occurs, then NULL will be returned.
-***********************************************************************/
-typedef struct PRAddrInfo PRAddrInfo;
-
-NSPR_API(PRAddrInfo*) PR_GetAddrInfoByName(
- const char *hostname, PRUint16 af, PRIntn flags);
-
-/***********************************************************************
-** FUNCTION:
-** DESCRIPTION: PR_FreeAddrInfo()
-** Destroy the PRAddrInfo handle allocated by PR_GetAddrInfoByName().
-**
-** INPUTS:
-** PRAddrInfo *addrInfo
-** The handle resulting from a successful call to
-** PR_GetAddrInfoByName().
-** RETURN:
-** void
-***********************************************************************/
-NSPR_API(void) PR_FreeAddrInfo(PRAddrInfo *addrInfo);
-
-/***********************************************************************
-** FUNCTION:
-** DESCRIPTION: PR_EnumerateAddrInfo()
-** A stateless enumerator over a PRAddrInfo handle acquired from
-** PR_GetAddrInfoByName() to inspect the possible network addresses.
-**
-** INPUTS:
-** void *enumPtr Index pointer of the enumeration. The enumeration
-** starts and ends with a value of NULL.
-** const PRAddrInfo *addrInfo
-** The PRAddrInfo handle returned by a successful
-** call to PR_GetAddrInfoByName().
-** PRUint16 port The port number to be assigned as part of the
-** PRNetAddr.
-** OUTPUTS:
-** PRNetAddr *result A pointer to an address structure that will be
-** filled in by the call to the enumeration if the
-** result of the call is not NULL.
-** RETURN:
-** void* The value that should be used for the next call
-** of the enumerator ('enumPtr'). The enumeration
-** is ended if this value is NULL.
-***********************************************************************/
-NSPR_API(void *) PR_EnumerateAddrInfo(
- void *enumPtr, const PRAddrInfo *addrInfo, PRUint16 port, PRNetAddr *result);
-
-/***********************************************************************
-** FUNCTION:
-** DESCRIPTION: PR_GetCanonNameFromAddrInfo()
-** Extracts the canonical name of the hostname passed to
-** PR_GetAddrInfoByName().
-**
-** INPUTS:
-** const PRAddrInfo *addrInfo
-** The PRAddrInfo handle returned by a successful
-** call to PR_GetAddrInfoByName().
-** RETURN:
-** const char * A const pointer to the canonical hostname stored
-** in the given PRAddrInfo handle. This pointer is
-** invalidated once the PRAddrInfo handle is destroyed
-** by a call to PR_FreeAddrInfo().
-***********************************************************************/
-NSPR_API(const char *) PR_GetCanonNameFromAddrInfo(
- const PRAddrInfo *addrInfo);
-
-/***********************************************************************
-** FUNCTIONS: PR_ntohs, PR_ntohl, PR_ntohll, PR_htons, PR_htonl, PR_htonll
-**
-** DESCRIPTION: API entries for the common byte ordering routines.
-**
-** PR_ntohs 16 bit conversion from network to host
-** PR_ntohl 32 bit conversion from network to host
-** PR_ntohll 64 bit conversion from network to host
-** PR_htons 16 bit conversion from host to network
-** PR_htonl 32 bit conversion from host to network
-** PR_ntonll 64 bit conversion from host to network
-**
-***********************************************************************/
-NSPR_API(PRUint16) PR_ntohs(PRUint16);
-NSPR_API(PRUint32) PR_ntohl(PRUint32);
-NSPR_API(PRUint64) PR_ntohll(PRUint64);
-NSPR_API(PRUint16) PR_htons(PRUint16);
-NSPR_API(PRUint32) PR_htonl(PRUint32);
-NSPR_API(PRUint64) PR_htonll(PRUint64);
-
-PR_END_EXTERN_C
-
-#endif /* prnetdb_h___ */
diff --git a/nspr/pr/include/prolock.h b/nspr/pr/include/prolock.h
deleted file mode 100644
index 4fe61f8..0000000
--- a/nspr/pr/include/prolock.h
+++ /dev/null
@@ -1,178 +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/. */
-
-#ifndef prolock_h___
-#define prolock_h___
-
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-/*
-** A locking mechanism, built on the existing PRLock definiion,
-** is provided that will permit applications to define a Lock
-** Hierarchy (or Lock Ordering) schema. An application designed
-** using the Ordered Lock functions will terminate with a
-** diagnostic message when a lock inversion condition is
-** detected.
-**
-** The lock ordering detection is complile-time enabled only. in
-** optimized builds of NSPR, the Ordered Lock functions map
-** directly to PRLock functions, providing no lock order
-** detection.
-**
-** The Ordered Lock Facility is compiled in when DEBUG is defined at
-** compile time. Ordered Lock can be forced on in optimized builds by
-** defining FORCE_NSPR_ORDERED_LOCK at compile time. Both the
-** application using Ordered Lock and NSPR must be compiled with the
-** facility enabled to achieve the desired results.
-**
-** Application designers should use the macro interfaces to the Ordered
-** Lock facility to ensure that it is compiled out in optimized builds.
-**
-** Application designers are responsible for defining their own
-** lock hierarchy.
-**
-** Ordered Lock is thread-safe and SMP safe.
-**
-** See Also: prlock.h
-**
-** /lth. 10-Jun-1998.
-**
-*/
-
-/*
-** Opaque type for ordered lock.
-** ... Don't even think of looking in here.
-**
-*/
-
-#if defined(DEBUG) || defined(FORCE_NSPR_ORDERED_LOCKS)
-typedef void * PROrderedLock;
-#else
-/*
-** Map PROrderedLock and methods onto PRLock when ordered locking
-** is not compiled in.
-**
-*/
-#include "prlock.h"
-
-typedef PRLock PROrderedLock;
-#endif
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_CreateOrderedLock() -- Create an Ordered Lock
-**
-** DESCRIPTION: PR_CreateOrderedLock() creates an ordered lock.
-**
-** INPUTS:
-** order: user defined order of this lock.
-** name: name of the lock. For debugging purposes.
-**
-** OUTPUTS: returned
-**
-** RETURNS: PR_OrderedLock pointer
-**
-** RESTRICTIONS:
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_ORDERED_LOCKS)
-#define PR_CREATE_ORDERED_LOCK(order,name)\
- PR_CreateOrderedLock((order),(name))
-#else
-#define PR_CREATE_ORDERED_LOCK(order) PR_NewLock()
-#endif
-
-NSPR_API(PROrderedLock *)
- PR_CreateOrderedLock(
- PRInt32 order,
- const char *name
-);
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_DestroyOrderedLock() -- Destroy an Ordered Lock
-**
-** DESCRIPTION: PR_DestroyOrderedLock() destroys the ordered lock
-** referenced by lock.
-**
-** INPUTS: lock: pointer to a PROrderedLock
-**
-** OUTPUTS: the lock is destroyed
-**
-** RETURNS: void
-**
-** RESTRICTIONS:
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_ORDERED_LOCKS)
-#define PR_DESTROY_ORDERED_LOCK(lock) PR_DestroyOrderedLock((lock))
-#else
-#define PR_DESTROY_ORDERED_LOCK(lock) PR_DestroyLock((lock))
-#endif
-
-NSPR_API(void)
- PR_DestroyOrderedLock(
- PROrderedLock *lock
-);
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_LockOrderedLock() -- Lock an ordered lock
-**
-** DESCRIPTION: PR_LockOrderedLock() locks the ordered lock
-** referenced by lock. If the order of lock is less than or equal
-** to the order of the highest lock held by the locking thread,
-** the function asserts.
-**
-** INPUTS: lock: a pointer to a PROrderedLock
-**
-** OUTPUTS: The lock is held or the function asserts.
-**
-** RETURNS: void
-**
-** RESTRICTIONS:
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_ORDERED_LOCKS)
-#define PR_LOCK_ORDERED_LOCK(lock) PR_LockOrderedLock((lock))
-#else
-#define PR_LOCK_ORDERED_LOCK(lock) PR_Lock((lock))
-#endif
-
-NSPR_API(void)
- PR_LockOrderedLock(
- PROrderedLock *lock
-);
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_UnlockOrderedLock() -- unlock and Ordered Lock
-**
-** DESCRIPTION: PR_UnlockOrderedLock() unlocks the lock referenced
-** by lock.
-**
-** INPUTS: lock: a pointer to a PROrderedLock
-**
-** OUTPUTS: the lock is unlocked
-**
-** RETURNS:
-** PR_SUCCESS
-** PR_FAILURE
-**
-** RESTRICTIONS:
-**
-*/
-#if defined(DEBUG) || defined(FORCE_NSPR_ORDERED_LOCKS)
-#define PR_UNLOCK_ORDERED_LOCK(lock) PR_UnlockOrderedLock((lock))
-#else
-#define PR_UNLOCK_ORDERED_LOCK(lock) PR_Unlock((lock))
-#endif
-
-NSPR_API(PRStatus)
- PR_UnlockOrderedLock(
- PROrderedLock *lock
-);
-
-PR_END_EXTERN_C
-
-#endif /* prolock_h___ */
diff --git a/nspr/pr/include/prpdce.h b/nspr/pr/include/prpdce.h
deleted file mode 100644
index b681795..0000000
--- a/nspr/pr/include/prpdce.h
+++ /dev/null
@@ -1,86 +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/. */
-
-/*
- * File: prpdce.h
- * Description: This file is the API defined to allow for DCE (aka POSIX)
- * thread emulation in an NSPR environment. It is not the
- * intent that this be a fully supported API.
- */
-
-#if !defined(PRPDCE_H)
-#define PRPDCE_H
-
-#include "prlock.h"
-#include "prcvar.h"
-#include "prtypes.h"
-#include "prinrval.h"
-
-PR_BEGIN_EXTERN_C
-
-#define _PR_NAKED_CV_LOCK (PRLock*)0xdce1dce1
-
-/*
-** Test and acquire a lock.
-**
-** If the lock is acquired by the calling thread, the
-** return value will be PR_SUCCESS. If the lock is
-** already held, by another thread or this thread, the
-** result will be PR_FAILURE.
-*/
-NSPR_API(PRStatus) PRP_TryLock(PRLock *lock);
-
-/*
-** Create a naked condition variable
-**
-** A "naked" condition variable is one that is not created bound
-** to a lock. The CV created with this function is the only type
-** that may be used in the subsequent "naked" condition variable
-** operations (see PRP_NakedWait, PRP_NakedNotify, PRP_NakedBroadcast);
-*/
-NSPR_API(PRCondVar*) PRP_NewNakedCondVar(void);
-
-/*
-** Destroy a naked condition variable
-**
-** Destroy the condition variable created by PR_NewNakedCondVar.
-*/
-NSPR_API(void) PRP_DestroyNakedCondVar(PRCondVar *cvar);
-
-/*
-** Wait on a condition
-**
-** Wait on the condition variable 'cvar'. It is asserted that
-** the lock protecting the condition 'lock' is held by the
-** calling thread. If more time expires than that declared in
-** 'timeout' the condition will be notified. Waits can be
-** interrupted by another thread.
-**
-** NB: The CV ('cvar') must be one created using PR_NewNakedCondVar.
-*/
-NSPR_API(PRStatus) PRP_NakedWait(
- PRCondVar *cvar, PRLock *lock, PRIntervalTime timeout);
-
-/*
-** Notify a thread waiting on a condition
-**
-** Notify the condition specified 'cvar'.
-**
-** NB: The CV ('cvar') must be one created using PR_NewNakedCondVar.
-*/
-NSPR_API(PRStatus) PRP_NakedNotify(PRCondVar *cvar);
-
-/*
-** Notify all threads waiting on a condition
-**
-** Notify the condition specified 'cvar'.
-**
-** NB: The CV ('cvar') must be one created using PR_NewNakedCondVar.
-*/
-NSPR_API(PRStatus) PRP_NakedBroadcast(PRCondVar *cvar);
-
-PR_END_EXTERN_C
-
-#endif /* PRPDCE_H */
diff --git a/nspr/pr/include/prprf.h b/nspr/pr/include/prprf.h
deleted file mode 100644
index 440be88..0000000
--- a/nspr/pr/include/prprf.h
+++ /dev/null
@@ -1,122 +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/. */
-
-#ifndef prprf_h___
-#define prprf_h___
-
-/*
-** API for PR printf like routines. Supports the following formats
-** %d - decimal
-** %u - unsigned decimal
-** %x - unsigned hex
-** %X - unsigned uppercase hex
-** %o - unsigned octal
-** %hd, %hu, %hx, %hX, %ho - 16-bit versions of above
-** %ld, %lu, %lx, %lX, %lo - 32-bit versions of above
-** %lld, %llu, %llx, %llX, %llo - 64 bit versions of above
-** %s - string
-** %c - character
-** %p - pointer (deals with machine dependent pointer size)
-** %f - float
-** %g - float
-*/
-#include "prtypes.h"
-#include "prio.h"
-#include <stdio.h>
-#include <stdarg.h>
-
-PR_BEGIN_EXTERN_C
-
-/*
-** sprintf into a fixed size buffer. Guarantees that a NUL is at the end
-** of the buffer. Returns the length of the written output, NOT including
-** the NUL, or (PRUint32)-1 if an error occurs.
-*/
-NSPR_API(PRUint32) PR_snprintf(char *out, PRUint32 outlen, const char *fmt, ...);
-
-/*
-** sprintf into a PR_MALLOC'd buffer. Return a pointer to the malloc'd
-** buffer on success, NULL on failure. Call "PR_smprintf_free" to release
-** the memory returned.
-*/
-NSPR_API(char*) PR_smprintf(const char *fmt, ...);
-
-/*
-** Free the memory allocated, for the caller, by PR_smprintf
-*/
-NSPR_API(void) PR_smprintf_free(char *mem);
-
-/*
-** "append" sprintf into a PR_MALLOC'd buffer. "last" is the last value of
-** the PR_MALLOC'd buffer. sprintf will append data to the end of last,
-** growing it as necessary using realloc. If last is NULL, PR_sprintf_append
-** will allocate the initial string. The return value is the new value of
-** last for subsequent calls, or NULL if there is a malloc failure.
-*/
-NSPR_API(char*) PR_sprintf_append(char *last, const char *fmt, ...);
-
-/*
-** sprintf into a function. The function "f" is called with a string to
-** place into the output. "arg" is an opaque pointer used by the stuff
-** function to hold any state needed to do the storage of the output
-** data. The return value is a count of the number of characters fed to
-** the stuff function, or (PRUint32)-1 if an error occurs.
-*/
-typedef PRIntn (*PRStuffFunc)(void *arg, const char *s, PRUint32 slen);
-
-NSPR_API(PRUint32) PR_sxprintf(PRStuffFunc f, void *arg, const char *fmt, ...);
-
-/*
-** fprintf to a PRFileDesc
-*/
-NSPR_API(PRUint32) PR_fprintf(struct PRFileDesc* fd, const char *fmt, ...);
-
-/*
-** va_list forms of the above.
-*/
-NSPR_API(PRUint32) PR_vsnprintf(char *out, PRUint32 outlen, const char *fmt, va_list ap);
-NSPR_API(char*) PR_vsmprintf(const char *fmt, va_list ap);
-NSPR_API(char*) PR_vsprintf_append(char *last, const char *fmt, va_list ap);
-NSPR_API(PRUint32) PR_vsxprintf(PRStuffFunc f, void *arg, const char *fmt, va_list ap);
-NSPR_API(PRUint32) PR_vfprintf(struct PRFileDesc* fd, const char *fmt, va_list ap);
-
-/*
-***************************************************************************
-** FUNCTION: PR_sscanf
-** DESCRIPTION:
-** PR_sscanf() scans the input character string, performs data
-** conversions, and stores the converted values in the data objects
-** pointed to by its arguments according to the format control
-** string.
-**
-** PR_sscanf() behaves the same way as the sscanf() function in the
-** Standard C Library (stdio.h), with the following exceptions:
-** - PR_sscanf() handles the NSPR integer and floating point types,
-** such as PRInt16, PRInt32, PRInt64, and PRFloat64, whereas
-** sscanf() handles the standard C types like short, int, long,
-** and double.
-** - PR_sscanf() has no multibyte character support, while sscanf()
-** does.
-** INPUTS:
-** const char *buf
-** a character string holding the input to scan
-** const char *fmt
-** the format control string for the conversions
-** ...
-** variable number of arguments, each of them is a pointer to
-** a data object in which the converted value will be stored
-** OUTPUTS: none
-** RETURNS: PRInt32
-** The number of values converted and stored.
-** RESTRICTIONS:
-** Multibyte characters in 'buf' or 'fmt' are not allowed.
-***************************************************************************
-*/
-
-NSPR_API(PRInt32) PR_sscanf(const char *buf, const char *fmt, ...);
-
-PR_END_EXTERN_C
-
-#endif /* prprf_h___ */
diff --git a/nspr/pr/include/prproces.h b/nspr/pr/include/prproces.h
deleted file mode 100644
index 9782542..0000000
--- a/nspr/pr/include/prproces.h
+++ /dev/null
@@ -1,86 +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/. */
-
-#ifndef prproces_h___
-#define prproces_h___
-
-#include "prtypes.h"
-#include "prio.h"
-
-PR_BEGIN_EXTERN_C
-
-/************************************************************************/
-/*****************************PROCESS OPERATIONS*************************/
-/************************************************************************/
-
-typedef struct PRProcess PRProcess;
-typedef struct PRProcessAttr PRProcessAttr;
-
-NSPR_API(PRProcessAttr *) PR_NewProcessAttr(void);
-
-NSPR_API(void) PR_ResetProcessAttr(PRProcessAttr *attr);
-
-NSPR_API(void) PR_DestroyProcessAttr(PRProcessAttr *attr);
-
-NSPR_API(void) PR_ProcessAttrSetStdioRedirect(
- PRProcessAttr *attr,
- PRSpecialFD stdioFd,
- PRFileDesc *redirectFd
-);
-
-/*
- * OBSOLETE -- use PR_ProcessAttrSetStdioRedirect instead.
- */
-NSPR_API(void) PR_SetStdioRedirect(
- PRProcessAttr *attr,
- PRSpecialFD stdioFd,
- PRFileDesc *redirectFd
-);
-
-NSPR_API(PRStatus) PR_ProcessAttrSetCurrentDirectory(
- PRProcessAttr *attr,
- const char *dir
-);
-
-NSPR_API(PRStatus) PR_ProcessAttrSetInheritableFD(
- PRProcessAttr *attr,
- PRFileDesc *fd,
- const char *name
-);
-
-/*
-** Create a new process
-**
-** Create a new process executing the file specified as 'path' and with
-** the supplied arguments and environment.
-**
-** This function may fail because of illegal access (permissions),
-** invalid arguments or insufficient resources.
-**
-** A process may be created such that the creator can later synchronize its
-** termination using PR_WaitProcess().
-*/
-
-NSPR_API(PRProcess*) PR_CreateProcess(
- const char *path,
- char *const *argv,
- char *const *envp,
- const PRProcessAttr *attr);
-
-NSPR_API(PRStatus) PR_CreateProcessDetached(
- const char *path,
- char *const *argv,
- char *const *envp,
- const PRProcessAttr *attr);
-
-NSPR_API(PRStatus) PR_DetachProcess(PRProcess *process);
-
-NSPR_API(PRStatus) PR_WaitProcess(PRProcess *process, PRInt32 *exitCode);
-
-NSPR_API(PRStatus) PR_KillProcess(PRProcess *process);
-
-PR_END_EXTERN_C
-
-#endif /* prproces_h___ */
diff --git a/nspr/pr/include/prrng.h b/nspr/pr/include/prrng.h
deleted file mode 100644
index 3b5a443..0000000
--- a/nspr/pr/include/prrng.h
+++ /dev/null
@@ -1,75 +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/. */
-
-
-/*
-** prrng.h -- NSPR Random Number Generator
-**
-**
-** lth. 29-Oct-1999.
-*/
-
-#ifndef prrng_h___
-#define prrng_h___
-
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-/*
-** PR_GetRandomNoise() -- Get random noise from the host platform
-**
-** Description:
-** PR_GetRandomNoise() provides, depending on platform, a random value.
-** The length of the random value is dependent on platform and the
-** platform's ability to provide a random value at that moment.
-**
-** The intent of PR_GetRandomNoise() is to provide a "seed" value for a
-** another random number generator that may be suitable for
-** cryptographic operations. This implies that the random value
-** provided may not be, by itself, cryptographically secure. The value
-** generated by PR_GetRandomNoise() is at best, extremely difficult to
-** predict and is as non-deterministic as the underlying platfrom can
-** provide.
-**
-** Inputs:
-** buf -- pointer to a caller supplied buffer to contain the
-** generated random number. buf must be at least as large as
-** is specified in the 'size' argument.
-**
-** size -- the requested size of the generated random number
-**
-** Outputs:
-** a random number provided in 'buf'.
-**
-** Returns:
-** PRSize value equal to the size of the random number actually
-** generated, or zero. The generated size may be less than the size
-** requested. A return value of zero means that PR_GetRandomNoise() is
-** not implemented on this platform, or there is no available noise
-** available to be returned at the time of the call.
-**
-** Restrictions:
-** Calls to PR_GetRandomNoise() may use a lot of CPU on some platforms.
-** Some platforms may block for up to a few seconds while they
-** accumulate some noise. Busy machines generate lots of noise, but
-** care is advised when using PR_GetRandomNoise() frequently in your
-** application.
-**
-** History:
-** Parts of the model dependent implementation for PR_GetRandomNoise()
-** were taken in whole or part from code previously in Netscape's NSS
-** component.
-**
-*/
-NSPR_API(PRSize) PR_GetRandomNoise(
- void *buf,
- PRSize size
-);
-
-PR_END_EXTERN_C
-
-#endif /* prrng_h___ */
-/* end prrng.h */
diff --git a/nspr/pr/include/prrwlock.h b/nspr/pr/include/prrwlock.h
deleted file mode 100644
index 65d052d..0000000
--- a/nspr/pr/include/prrwlock.h
+++ /dev/null
@@ -1,88 +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/. */
-
-/*
-** File: prrwlock.h
-** Description: API to basic reader-writer lock functions of NSPR.
-**
-**/
-
-#ifndef prrwlock_h___
-#define prrwlock_h___
-
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-/*
- * PRRWLock --
- *
- * The reader writer lock, PRRWLock, is an opaque object to the clients
- * of NSPR. All routines operate on a pointer to this opaque entity.
- */
-
-
-typedef struct PRRWLock PRRWLock;
-
-#define PR_RWLOCK_RANK_NONE 0
-
-
-/***********************************************************************
-** FUNCTION: PR_NewRWLock
-** DESCRIPTION:
-** Returns a pointer to a newly created reader-writer lock object.
-** INPUTS: Lock rank
-** Lock name
-** OUTPUTS: void
-** RETURN: PRRWLock*
-** If the lock cannot be created because of resource constraints, NULL
-** is returned.
-**
-***********************************************************************/
-NSPR_API(PRRWLock*) PR_NewRWLock(PRUint32 lock_rank, const char *lock_name);
-
-/***********************************************************************
-** FUNCTION: PR_DestroyRWLock
-** DESCRIPTION:
-** Destroys a given RW lock object.
-** INPUTS: PRRWLock *lock - Lock to be freed.
-** OUTPUTS: void
-** RETURN: None
-***********************************************************************/
-NSPR_API(void) PR_DestroyRWLock(PRRWLock *lock);
-
-/***********************************************************************
-** FUNCTION: PR_RWLock_Rlock
-** DESCRIPTION:
-** Apply a read lock (non-exclusive) on a RWLock
-** INPUTS: PRRWLock *lock - Lock to be read-locked.
-** OUTPUTS: void
-** RETURN: None
-***********************************************************************/
-NSPR_API(void) PR_RWLock_Rlock(PRRWLock *lock);
-
-/***********************************************************************
-** FUNCTION: PR_RWLock_Wlock
-** DESCRIPTION:
-** Apply a write lock (exclusive) on a RWLock
-** INPUTS: PRRWLock *lock - Lock to write-locked.
-** OUTPUTS: void
-** RETURN: None
-***********************************************************************/
-NSPR_API(void) PR_RWLock_Wlock(PRRWLock *lock);
-
-/***********************************************************************
-** FUNCTION: PR_RWLock_Unlock
-** DESCRIPTION:
-** Release a RW lock. Unlocking an unlocked lock has undefined results.
-** INPUTS: PRRWLock *lock - Lock to unlocked.
-** OUTPUTS: void
-** RETURN: void
-***********************************************************************/
-NSPR_API(void) PR_RWLock_Unlock(PRRWLock *lock);
-
-PR_END_EXTERN_C
-
-#endif /* prrwlock_h___ */
diff --git a/nspr/pr/include/prshm.h b/nspr/pr/include/prshm.h
deleted file mode 100644
index f821a58..0000000
--- a/nspr/pr/include/prshm.h
+++ /dev/null
@@ -1,257 +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/. */
-
-/*
-** prshm.h -- NSPR Shared Memory
-**
-** NSPR Named Shared Memory API provides a cross-platform named
-** shared-memory interface. NSPR Named Shared Memory is modeled on
-** similar constructs in Unix and Windows operating systems. Shared
-** memory allows multiple processes to access one or more common shared
-** memory regions, using it as an inter-process communication channel.
-**
-** Notes on Platform Independence:
-** NSPR Named Shared Memory is built on the native services offered
-** by most platforms. The NSPR Named Shared Memory API tries to
-** provide a least common denominator interface so that it works
-** across all supported platforms. To ensure that it works everywhere,
-** some platform considerations must be accomodated and the protocol
-** for using NSPR Shared Memory API must be observed.
-**
-** Protocol:
-** Multiple shared memories can be created using NSPR's Shared Memory
-** feature. For each named shared memory, as defined by the name
-** given in the PR_OpenSharedMemory() call, a protocol for using the
-** shared memory API is required to ensure desired behavior. Failing
-** to follow the protocol may yield unpredictable results.
-**
-** PR_OpenSharedMemory() will create the shared memory segment, if it
-** does not already exist, or open a connection that the existing
-** shared memory segment if it already exists.
-**
-** PR_AttachSharedMemory() should be called following
-** PR_OpenSharedMemory() to map the memory segment to an address in
-** the application's address space.
-**
-** PR_AttachSharedMemory() may be called to re-map a shared memory
-** segment after detaching the same PRSharedMemory object. Be
-** sure to detach it when done.
-**
-** PR_DetachSharedMemory() should be called to un-map the shared
-** memory segment from the application's address space.
-**
-** PR_CloseSharedMemory() should be called when no further use of the
-** PRSharedMemory object is required within a process. Following a
-** call to PR_CloseSharedMemory() the PRSharedMemory object is
-** invalid and cannot be reused.
-**
-** PR_DeleteSharedMemory() should be called before process
-** termination. After calling PR_DeleteSharedMemory() any further use
-** of the shared memory associated with the name may cause
-** unpredictable results.
-**
-** Files:
-** The name passed to PR_OpenSharedMemory() should be a valid filename
-** for a unix platform. PR_OpenSharedMemory() creates file using the
-** name passed in. Some platforms may mangle the name before creating
-** the file and the shared memory.
-**
-** The unix implementation may use SysV IPC shared memory, Posix
-** shared memory, or memory mapped files; the filename may used to
-** define the namespace. On Windows, the name is significant, but
-** there is no file associated with name.
-**
-** No assumptions about the persistence of data in the named file
-** should be made. Depending on platform, the shared memory may be
-** mapped onto system paging space and be discarded at process
-** termination.
-**
-** All names provided to PR_OpenSharedMemory() should be valid
-** filename syntax or name syntax for shared memory for the target
-** platform. Referenced directories should have permissions
-** appropriate for writing.
-**
-** Limits:
-** Different platforms have limits on both the number and size of
-** shared memory resources. The default system limits on some
-** platforms may be smaller than your requirements. These limits may
-** be adjusted on some platforms either via boot-time options or by
-** setting the size of the system paging space to accomodate more
-** and/or larger shared memory segment(s).
-**
-** Security:
-** On unix platforms, depending on implementation, contents of the
-** backing store for the shared memory can be exposed via the file
-** system. Set permissions and or access controls at create and attach
-** time to ensure you get the desired security.
-**
-** On windows platforms, no special security measures are provided.
-**
-** Example:
-** The test case pr/tests/nameshm1.c provides an example of use as
-** well as testing the operation of NSPR's Named Shared Memory.
-**
-** lth. 18-Aug-1999.
-*/
-
-#ifndef prshm_h___
-#define prshm_h___
-
-#include "prtypes.h"
-#include "prio.h"
-
-PR_BEGIN_EXTERN_C
-
-/*
-** Declare opaque type PRSharedMemory.
-*/
-typedef struct PRSharedMemory PRSharedMemory;
-
-/*
-** FUNCTION: PR_OpenSharedMemory()
-**
-** DESCRIPTION:
-** PR_OpenSharedMemory() creates a new shared-memory segment or
-** associates a previously created memory segment with name.
-**
-** When parameter create is (PR_SHM_EXCL | PR_SHM_CREATE) and the
-** shared memory already exists, the function returns NULL with the
-** error set to PR_FILE_EXISTS_ERROR.
-**
-** When parameter create is PR_SHM_CREATE and the shared memory
-** already exists, a handle to that memory segment is returned. If
-** the segment does not exist, it is created and a pointer to the
-** related PRSharedMemory structure is returned.
-**
-** When parameter create is 0, and the shared memory exists, a
-** pointer to a PRSharedMemory is returned. If the shared memory does
-** not exist, NULL is returned with the error set to
-** PR_FILE_NOT_FOUND_ERROR.
-**
-** INPUTS:
-** name -- the name the shared-memory segment is known as.
-** size -- the size of the shared memory segment.
-** flags -- Options for creating the shared memory
-** mode -- Same as is passed to PR_Open()
-**
-** OUTPUTS:
-** The shared memory is allocated.
-**
-** RETURNS: Pointer to opaque structure PRSharedMemory or NULL.
-** NULL is returned on error. The reason for the error can be
-** retrieved via PR_GetError() and PR_GetOSError();
-**
-*/
-NSPR_API( PRSharedMemory * )
- PR_OpenSharedMemory(
- const char *name,
- PRSize size,
- PRIntn flags,
- PRIntn mode
-);
-/* Define values for PR_OpenShareMemory(...,create) */
-#define PR_SHM_CREATE 0x1 /* create if not exist */
-#define PR_SHM_EXCL 0x2 /* fail if already exists */
-
-/*
-** FUNCTION: PR_AttachSharedMemory()
-**
-** DESCRIPTION:
-** PR_AttachSharedMemory() maps the shared-memory described by
-** shm to the current process.
-**
-** INPUTS:
-** shm -- The handle returned from PR_OpenSharedMemory().
-** flags -- options for mapping the shared memory.
-** PR_SHM_READONLY causes the memory to be attached
-** read-only.
-**
-** OUTPUTS:
-** On success, the shared memory segment represented by shm is mapped
-** into the process' address space.
-**
-** RETURNS: Address where shared memory is mapped, or NULL.
-** NULL is returned on error. The reason for the error can be
-** retrieved via PR_GetError() and PR_GetOSError();
-**
-**
-*/
-NSPR_API( void * )
- PR_AttachSharedMemory(
- PRSharedMemory *shm,
- PRIntn flags
-);
-/* Define values for PR_AttachSharedMemory(...,flags) */
-#define PR_SHM_READONLY 0x01
-
-/*
-** FUNCTION: PR_DetachSharedMemory()
-**
-** DESCRIPTION:
-** PR_DetachSharedMemory() detaches the shared-memory described
-** by shm.
-**
-** INPUTS:
-** shm -- The handle returned from PR_OpenSharedMemory().
-** addr -- The address at which the memory was attached.
-**
-** OUTPUTS:
-** The shared memory mapped to an address via a previous call to
-** PR_AttachSharedMemory() is unmapped.
-**
-** RETURNS: PRStatus
-**
-*/
-NSPR_API( PRStatus )
- PR_DetachSharedMemory(
- PRSharedMemory *shm,
- void *addr
-);
-
-/*
-** FUNCTION: PR_CloseSharedMemory()
-**
-** DESCRIPTION:
-** PR_CloseSharedMemory() closes the shared-memory described by
-** shm.
-**
-** INPUTS:
-** shm -- The handle returned from PR_OpenSharedMemory().
-**
-** OUTPUTS:
-** the shared memory represented by shm is closed
-**
-** RETURNS: PRStatus
-**
-*/
-NSPR_API( PRStatus )
- PR_CloseSharedMemory(
- PRSharedMemory *shm
-);
-
-/*
-** FUNCTION: PR_DeleteSharedMemory()
-**
-** DESCRIPTION:
-** The shared memory resource represented by name is released.
-**
-** INPUTS:
-** name -- the name the shared-memory segment
-**
-** OUTPUTS:
-** depending on platform, resources may be returned to the underlying
-** operating system.
-**
-** RETURNS: PRStatus
-**
-*/
-NSPR_API( PRStatus )
- PR_DeleteSharedMemory(
- const char *name
-);
-
-PR_END_EXTERN_C
-
-#endif /* prshm_h___ */
diff --git a/nspr/pr/include/prshma.h b/nspr/pr/include/prshma.h
deleted file mode 100644
index 2abc4ae..0000000
--- a/nspr/pr/include/prshma.h
+++ /dev/null
@@ -1,239 +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/. */
-
-/*
-** prshma.h -- NSPR Anonymous Shared Memory
-**
-** NSPR provides an anonymous shared memory based on NSPR's PRFileMap
-** type. The anonymous file-mapped shared memory provides an inheritable
-** shared memory, as in: the child process inherits the shared memory.
-** Compare the file-mapped anonymous shared memory to to a named shared
-** memory described in prshm.h. The intent is to provide a shared
-** memory that is accessable only by parent and child processes. ...
-** It's a security thing.
-**
-** Depending on the underlying platform, the file-mapped shared memory
-** may be backed by a file. ... surprise! ... On some platforms, no
-** real file backs the shared memory. On platforms where the shared
-** memory is backed by a file, the file's name in the filesystem is
-** visible to other processes for only the duration of the creation of
-** the file, hopefully a very short time. This restricts processess
-** that do not inherit the shared memory from opening the file and
-** reading or writing its contents. Further, when all processes
-** using an anonymous shared memory terminate, the backing file is
-** deleted. ... If you are not paranoid, you're not paying attention.
-**
-** The file-mapped shared memory requires a protocol for the parent
-** process and child process to share the memory. NSPR provides two
-** protocols. Use one or the other; don't mix and match.
-**
-** In the first protocol, the job of passing the inheritable shared
-** memory is done via helper-functions with PR_CreateProcess(). In the
-** second protocol, the parent process is responsible for creating the
-** child process; the parent and child are mutually responsible for
-** passing a FileMap string. NSPR provides helper functions for
-** extracting data from the PRFileMap object. ... See the examples
-** below.
-**
-** Both sides should adhere strictly to the protocol for proper
-** operation. The pseudo-code below shows the use of a file-mapped
-** shared memory by a parent and child processes. In the examples, the
-** server creates the file-mapped shared memory, the client attaches to
-** it.
-**
-** First protocol.
-** Server:
-**
-** fm = PR_OpenAnonFileMap(dirName, size, FilemapProt);
-** addr = PR_MemMap(fm);
-** attr = PR_NewProcessAttr();
-** PR_ProcessAttrSetInheritableFileMap( attr, fm, shmname );
-** PR_CreateProcess(Client);
-** PR_DestroyProcessAttr(attr);
-** ... yadda ...
-** PR_MemUnmap( addr );
-** PR_CloseFileMap(fm);
-**
-**
-** Client:
-** ... started by server via PR_CreateProcess()
-** fm = PR_GetInheritedFileMap( shmname );
-** addr = PR_MemMap(fm);
-** ... yadda ...
-** PR_MemUnmap(addr);
-** PR_CloseFileMap(fm);
-**
-**
-** Second Protocol:
-** Server:
-**
-** fm = PR_OpenAnonFileMap(dirName, size, FilemapProt);
-** fmstring = PR_ExportFileMapAsString( fm );
-** addr = PR_MemMap(fm);
-** ... application specific technique to pass fmstring to child
-** ... yadda ... Server uses his own magic to create child
-** PR_MemUnmap( addr );
-** PR_CloseFileMap(fm);
-**
-**
-** Client:
-** ... started by server via his own magic
-** ... application specific technique to find fmstring from parent
-** fm = PR_ImportFileMapFromString( fmstring )
-** addr = PR_MemMap(fm);
-** ... yadda ...
-** PR_MemUnmap(addr);
-** PR_CloseFileMap(fm);
-**
-**
-** lth. 2-Jul-1999.
-**
-** Note: The second protocol was requested by NelsonB (7/1999); this is
-** to accomodate servers which already create their own child processes
-** using platform native methods.
-**
-*/
-
-#ifndef prshma_h___
-#define prshma_h___
-
-#include "prtypes.h"
-#include "prio.h"
-#include "prproces.h"
-
-PR_BEGIN_EXTERN_C
-
-/*
-** PR_OpenAnonFileMap() -- Creates an anonymous file-mapped shared memory
-**
-** Description:
-** PR_OpenAnonFileMap() creates an anonymous shared memory. If the
-** shared memory already exists, a handle is returned to that shared
-** memory object.
-**
-** On Unix platforms, PR_OpenAnonFileMap() uses 'dirName' as a
-** directory name, without the trailing '/', to contain the anonymous
-** file. A filename is generated for the name.
-**
-** On Windows platforms, dirName is ignored.
-**
-** Inputs:
-** dirName -- A directory name to contain the anonymous file.
-** size -- The size of the shared memory
-** prot -- How the shared memory is mapped. See prio.h
-**
-** Outputs:
-** PRFileMap *
-**
-** Returns:
-** Pointer to PRFileMap or NULL on error.
-**
-*/
-NSPR_API( PRFileMap *)
-PR_OpenAnonFileMap(
- const char *dirName,
- PRSize size,
- PRFileMapProtect prot
-);
-
-/*
-** PR_ProcessAttrSetInheritableFileMap() -- Prepare FileMap for export
-** to my children processes via PR_CreateProcess()
-**
-** Description:
-** PR_ProcessAttrSetInheritableFileMap() connects the PRFileMap to
-** PRProcessAttr with shmname. A subsequent call to PR_CreateProcess()
-** makes the PRFileMap importable by the child process.
-**
-** Inputs:
-** attr -- PRProcessAttr, used to pass data to PR_CreateProcess()
-** fm -- PRFileMap structure to be passed to the child process
-** shmname -- The name for the PRFileMap; used by child.
-**
-** Outputs:
-** PRFileMap *
-**
-** Returns:
-** PRStatus
-**
-*/
-NSPR_API(PRStatus)
-PR_ProcessAttrSetInheritableFileMap(
- PRProcessAttr *attr,
- PRFileMap *fm,
- const char *shmname
-);
-
-/*
-** PR_GetInheritedFileMap() -- Import a PRFileMap previously exported
-** by my parent process via PR_CreateProcess()
-**
-** Description:
-** PR_GetInheritedFileMap() retrieves a PRFileMap object exported from
-** its parent process via PR_CreateProcess().
-**
-** Inputs:
-** shmname -- The name provided to PR_ProcessAttrSetInheritableFileMap()
-**
-** Outputs:
-** PRFileMap *
-**
-** Returns:
-** PRFileMap pointer or NULL.
-**
-*/
-NSPR_API( PRFileMap *)
-PR_GetInheritedFileMap(
- const char *shmname
-);
-
-/*
-** PR_ExportFileMapAsString() -- Creates a string identifying a PRFileMap
-**
-** Description:
-** Creates an identifier, as a string, from a PRFileMap object
-** previously created with PR_OpenAnonFileMap().
-**
-** Inputs:
-** fm -- PRFileMap pointer to be represented as a string.
-** bufsize -- sizeof(buf)
-** buf -- a buffer of length PR_FILEMAP_STRING_BUFSIZE
-**
-** Outputs:
-** buf contains the stringized PRFileMap identifier
-**
-** Returns:
-** PRStatus
-**
-*/
-NSPR_API( PRStatus )
-PR_ExportFileMapAsString(
- PRFileMap *fm,
- PRSize bufsize,
- char *buf
-);
-#define PR_FILEMAP_STRING_BUFSIZE 128
-
-/*
-** PR_ImportFileMapFromString() -- Creates a PRFileMap from the identifying string
-**
-** Description:
-** PR_ImportFileMapFromString() creates a PRFileMap object from a
-** string previously created by PR_ExportFileMapAsString().
-**
-** Inputs:
-** fmstring -- string created by PR_ExportFileMapAsString()
-**
-** Returns:
-** PRFileMap pointer or NULL.
-**
-*/
-NSPR_API( PRFileMap * )
-PR_ImportFileMapFromString(
- const char *fmstring
-);
-
-PR_END_EXTERN_C
-#endif /* prshma_h___ */
diff --git a/nspr/pr/include/prsystem.h b/nspr/pr/include/prsystem.h
deleted file mode 100644
index b3e14e7..0000000
--- a/nspr/pr/include/prsystem.h
+++ /dev/null
@@ -1,108 +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/. */
-
-#ifndef prsystem_h___
-#define prsystem_h___
-
-/*
-** API to NSPR functions returning system info.
-*/
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-/*
-** Get the host' directory separator.
-** Pathnames are then assumed to be of the form:
-** [<sep><root_component><sep>]*(<component><sep>)<leaf_name>
-*/
-
-NSPR_API(char) PR_GetDirectorySeparator(void);
-
-/*
-** OBSOLETE -- the function name is misspelled.
-** Use PR_GetDirectorySeparator instead.
-*/
-
-NSPR_API(char) PR_GetDirectorySepartor(void);
-
-/*
-** Get the host' path separator.
-** Paths are assumed to be of the form:
-** <directory>[<sep><directory>]*
-*/
-
-NSPR_API(char) PR_GetPathSeparator(void);
-
-/* Types of information available via PR_GetSystemInfo(...) */
-typedef enum {
- PR_SI_HOSTNAME, /* the hostname with the domain name (if any)
- * removed */
- PR_SI_SYSNAME,
- PR_SI_RELEASE,
- PR_SI_ARCHITECTURE,
- PR_SI_HOSTNAME_UNTRUNCATED /* the hostname exactly as configured
- * on the system */
-} PRSysInfo;
-
-
-/*
-** If successful returns a null termintated string in 'buf' for
-** the information indicated in 'cmd'. If unseccussful the reason for
-** the failure can be retrieved from PR_GetError().
-**
-** The buffer is allocated by the caller and should be at least
-** SYS_INFO_BUFFER_LENGTH bytes in length.
-*/
-
-#define SYS_INFO_BUFFER_LENGTH 256
-
-NSPR_API(PRStatus) PR_GetSystemInfo(PRSysInfo cmd, char *buf, PRUint32 buflen);
-
-/*
-** Return the number of bytes in a page
-*/
-NSPR_API(PRInt32) PR_GetPageSize(void);
-
-/*
-** Return log2 of the size of a page
-*/
-NSPR_API(PRInt32) PR_GetPageShift(void);
-
-/*
-** PR_GetNumberOfProcessors() -- returns the number of CPUs
-**
-** Description:
-** PR_GetNumberOfProcessors() extracts the number of processors
-** (CPUs available in an SMP system) and returns the number.
-**
-** Parameters:
-** none
-**
-** Returns:
-** The number of available processors or -1 on error
-**
-*/
-NSPR_API(PRInt32) PR_GetNumberOfProcessors( void );
-
-/*
-** PR_GetPhysicalMemorySize() -- returns the amount of system RAM
-**
-** Description:
-** PR_GetPhysicalMemorySize() determines the amount of physical RAM
-** in the system and returns the size in bytes.
-**
-** Parameters:
-** none
-**
-** Returns:
-** The amount of system RAM, or 0 on failure.
-**
-*/
-NSPR_API(PRUint64) PR_GetPhysicalMemorySize(void);
-
-PR_END_EXTERN_C
-
-#endif /* prsystem_h___ */
diff --git a/nspr/pr/include/prthread.h b/nspr/pr/include/prthread.h
deleted file mode 100644
index f8b28a6..0000000
--- a/nspr/pr/include/prthread.h
+++ /dev/null
@@ -1,272 +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/. */
-
-#ifndef prthread_h___
-#define prthread_h___
-
-/*
-** API for NSPR threads. On some architectures (Mac OS Classic
-** notably) pre-emptibility is not guaranteed. Hard priority scheduling
-** is not guaranteed, so programming using priority based synchronization
-** is a no-no.
-**
-** NSPR threads are scheduled based loosely on their client set priority.
-** In general, a thread of a higher priority has a statistically better
-** chance of running relative to threads of lower priority. However,
-** NSPR uses multiple strategies to provide execution vehicles for thread
-** abstraction of various host platforms. As it turns out, there is little
-** NSPR can do to affect the scheduling attributes of "GLOBAL" threads.
-** However, a semblance of GLOBAL threads is used to implement "LOCAL"
-** threads. An arbitrary number of such LOCAL threads can be assigned to
-** a single GLOBAL thread.
-**
-** For scheduling, NSPR will attempt to run the highest priority LOCAL
-** thread associated with a given GLOBAL thread. It is further assumed
-** that the host OS will apply some form of "fair" scheduling on the
-** GLOBAL threads.
-**
-** Threads have a "system flag" which when set indicates the thread
-** doesn't count for determining when the process should exit (the
-** process exits when the last user thread exits).
-**
-** Threads also have a "scope flag" which controls whether the threads
-** are scheduled in the local scope or scheduled by the OS globally. This
-** indicates whether a thread is permanently bound to a native OS thread.
-** An unbound thread competes for scheduling resources in the same process.
-**
-** Another flag is "state flag" which control whether the thread is joinable.
-** It allows other threads to wait for the created thread to reach completion.
-**
-** Threads can have "per-thread-data" attached to them. Each thread has a
-** per-thread error number and error string which are updated when NSPR
-** operations fail.
-*/
-#include "prtypes.h"
-#include "prinrval.h"
-
-PR_BEGIN_EXTERN_C
-
-typedef struct PRThread PRThread;
-typedef struct PRThreadStack PRThreadStack;
-
-typedef enum PRThreadType {
- PR_USER_THREAD,
- PR_SYSTEM_THREAD
-} PRThreadType;
-
-typedef enum PRThreadScope {
- PR_LOCAL_THREAD,
- PR_GLOBAL_THREAD,
- PR_GLOBAL_BOUND_THREAD
-} PRThreadScope;
-
-typedef enum PRThreadState {
- PR_JOINABLE_THREAD,
- PR_UNJOINABLE_THREAD
-} PRThreadState;
-
-typedef enum PRThreadPriority
-{
- PR_PRIORITY_FIRST = 0, /* just a placeholder */
- PR_PRIORITY_LOW = 0, /* the lowest possible priority */
- PR_PRIORITY_NORMAL = 1, /* most common expected priority */
- PR_PRIORITY_HIGH = 2, /* slightly more aggressive scheduling */
- PR_PRIORITY_URGENT = 3, /* it does little good to have more than one */
- PR_PRIORITY_LAST = 3 /* this is just a placeholder */
-} PRThreadPriority;
-
-/*
-** Create a new thread:
-** "type" is the type of thread to create
-** "start(arg)" will be invoked as the threads "main"
-** "priority" will be created thread's priority
-** "scope" will specify whether the thread is local or global
-** "state" will specify whether the thread is joinable or not
-** "stackSize" the size of the stack, in bytes. The value can be zero
-** and then a machine specific stack size will be chosen.
-**
-** This can return NULL if some kind of error occurs, such as if memory is
-** tight.
-**
-** If you want the thread to start up waiting for the creator to do
-** something, enter a lock before creating the thread and then have the
-** threads start routine enter and exit the same lock. When you are ready
-** for the thread to run, exit the lock.
-**
-** If you want to detect the completion of the created thread, the thread
-** should be created joinable. Then, use PR_JoinThread to synchrnoize the
-** termination of another thread.
-**
-** When the start function returns the thread exits. If it is the last
-** PR_USER_THREAD to exit then the process exits.
-*/
-NSPR_API(PRThread*) PR_CreateThread(PRThreadType type,
- void (PR_CALLBACK *start)(void *arg),
- void *arg,
- PRThreadPriority priority,
- PRThreadScope scope,
- PRThreadState state,
- PRUint32 stackSize);
-
-/*
-** Wait for thread termination:
-** "thread" is the target thread
-**
-** This can return PR_FAILURE if no joinable thread could be found
-** corresponding to the specified target thread.
-**
-** The calling thread is blocked until the target thread completes.
-** Several threads cannot wait for the same thread to complete; one thread
-** will operate successfully and others will terminate with an error PR_FAILURE.
-** The calling thread will not be blocked if the target thread has already
-** terminated.
-*/
-NSPR_API(PRStatus) PR_JoinThread(PRThread *thread);
-
-/*
-** Return the current thread object for the currently running code.
-** Never returns NULL.
-*/
-NSPR_API(PRThread*) PR_GetCurrentThread(void);
-#ifndef NO_NSPR_10_SUPPORT
-#define PR_CurrentThread() PR_GetCurrentThread() /* for nspr1.0 compat. */
-#endif /* NO_NSPR_10_SUPPORT */
-
-/*
-** Get the priority of "thread".
-*/
-NSPR_API(PRThreadPriority) PR_GetThreadPriority(const PRThread *thread);
-
-/*
-** Change the priority of the "thread" to "priority".
-**
-** PR_SetThreadPriority works in a best-effort manner. On some platforms a
-** special privilege, such as root access, is required to change thread
-** priorities, especially to raise thread priorities. If the caller doesn't
-** have enough privileges to change thread priorites, the function has no
-** effect except causing a future PR_GetThreadPriority call to return
-** |priority|.
-*/
-NSPR_API(void) PR_SetThreadPriority(PRThread *thread, PRThreadPriority priority);
-
-/*
-** Set the name of the current thread, which will be visible in a debugger
-** and accessible via a call to PR_GetThreadName().
-*/
-NSPR_API(PRStatus) PR_SetCurrentThreadName(const char *name);
-
-/*
-** Return the name of "thread", if set. Otherwise return NULL.
-*/
-NSPR_API(const char *) PR_GetThreadName(const PRThread *thread);
-
-/*
-** This routine returns a new index for per-thread-private data table.
-** The index is visible to all threads within a process. This index can
-** be used with the PR_SetThreadPrivate() and PR_GetThreadPrivate() routines
-** to save and retrieve data associated with the index for a thread.
-**
-** Each index is associationed with a destructor function ('dtor'). The function
-** may be specified as NULL when the index is created. If it is not NULL, the
-** function will be called when:
-** - the thread exits and the private data for the associated index
-** is not NULL,
-** - new thread private data is set and the current private data is
-** not NULL.
-**
-** The index independently maintains specific values for each binding thread.
-** A thread can only get access to its own thread-specific-data.
-**
-** Upon a new index return the value associated with the index for all threads
-** is NULL, and upon thread creation the value associated with all indices for
-** that thread is NULL.
-**
-** Returns PR_FAILURE if the total number of indices will exceed the maximun
-** allowed.
-*/
-typedef void (PR_CALLBACK *PRThreadPrivateDTOR)(void *priv);
-
-NSPR_API(PRStatus) PR_NewThreadPrivateIndex(
- PRUintn *newIndex, PRThreadPrivateDTOR destructor);
-
-/*
-** Define some per-thread-private data.
-** "tpdIndex" is an index into the per-thread private data table
-** "priv" is the per-thread-private data
-**
-** If the per-thread private data table has a previously registered
-** destructor function and a non-NULL per-thread-private data value,
-** the destructor function is invoked.
-**
-** This can return PR_FAILURE if the index is invalid.
-*/
-NSPR_API(PRStatus) PR_SetThreadPrivate(PRUintn tpdIndex, void *priv);
-
-/*
-** Recover the per-thread-private data for the current thread. "tpdIndex" is
-** the index into the per-thread private data table.
-**
-** The returned value may be NULL which is indistinguishable from an error
-** condition.
-**
-** A thread can only get access to its own thread-specific-data.
-*/
-NSPR_API(void*) PR_GetThreadPrivate(PRUintn tpdIndex);
-
-/*
-** This routine sets the interrupt request for a target thread. The interrupt
-** request remains in the thread's state until it is delivered exactly once
-** or explicitly canceled.
-**
-** A thread that has been interrupted will fail all NSPR blocking operations
-** that return a PRStatus (I/O, waiting on a condition, etc).
-**
-** PR_Interrupt may itself fail if the target thread is invalid.
-*/
-NSPR_API(PRStatus) PR_Interrupt(PRThread *thread);
-
-/*
-** Clear the interrupt request for the calling thread. If no such request
-** is pending, this operation is a noop.
-*/
-NSPR_API(void) PR_ClearInterrupt(void);
-
-/*
-** Block the interrupt for the calling thread.
-*/
-NSPR_API(void) PR_BlockInterrupt(void);
-
-/*
-** Unblock the interrupt for the calling thread.
-*/
-NSPR_API(void) PR_UnblockInterrupt(void);
-
-/*
-** Make the current thread sleep until "ticks" time amount of time
-** has expired. If "ticks" is PR_INTERVAL_NO_WAIT then the call is
-** equivalent to calling PR_Yield. Calling PR_Sleep with an argument
-** equivalent to PR_INTERVAL_NO_TIMEOUT is an error and will result
-** in a PR_FAILURE error return.
-*/
-NSPR_API(PRStatus) PR_Sleep(PRIntervalTime ticks);
-
-/*
-** Get the scoping of this thread.
-*/
-NSPR_API(PRThreadScope) PR_GetThreadScope(const PRThread *thread);
-
-/*
-** Get the type of this thread.
-*/
-NSPR_API(PRThreadType) PR_GetThreadType(const PRThread *thread);
-
-/*
-** Get the join state of this thread.
-*/
-NSPR_API(PRThreadState) PR_GetThreadState(const PRThread *thread);
-
-PR_END_EXTERN_C
-
-#endif /* prthread_h___ */
diff --git a/nspr/pr/include/prtime.h b/nspr/pr/include/prtime.h
deleted file mode 100644
index caaee14..0000000
--- a/nspr/pr/include/prtime.h
+++ /dev/null
@@ -1,262 +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/. */
-
-/*
- *----------------------------------------------------------------------
- *
- * prtime.h --
- *
- * NSPR date and time functions
- *
- *-----------------------------------------------------------------------
- */
-
-#ifndef prtime_h___
-#define prtime_h___
-
-#include "prlong.h"
-
-PR_BEGIN_EXTERN_C
-
-/**********************************************************************/
-/************************* TYPES AND CONSTANTS ************************/
-/**********************************************************************/
-
-#define PR_MSEC_PER_SEC 1000L
-#define PR_USEC_PER_SEC 1000000L
-#define PR_NSEC_PER_SEC 1000000000L
-#define PR_USEC_PER_MSEC 1000L
-#define PR_NSEC_PER_MSEC 1000000L
-
-/*
- * PRTime --
- *
- * NSPR represents basic time as 64-bit signed integers relative
- * to midnight (00:00:00), January 1, 1970 Greenwich Mean Time (GMT).
- * (GMT is also known as Coordinated Universal Time, UTC.)
- * The units of time are in microseconds. Negative times are allowed
- * to represent times prior to the January 1970 epoch. Such values are
- * intended to be exported to other systems or converted to human
- * readable form.
- *
- * Notes on porting: PRTime corresponds to time_t in ANSI C. NSPR 1.0
- * simply uses PRInt64.
- */
-
-typedef PRInt64 PRTime;
-
-/*
- * Time zone and daylight saving time corrections applied to GMT to
- * obtain the local time of some geographic location
- */
-
-typedef struct PRTimeParameters {
- PRInt32 tp_gmt_offset; /* the offset from GMT in seconds */
- PRInt32 tp_dst_offset; /* contribution of DST in seconds */
-} PRTimeParameters;
-
-/*
- * PRExplodedTime --
- *
- * Time broken down into human-readable components such as year, month,
- * day, hour, minute, second, and microsecond. Time zone and daylight
- * saving time corrections may be applied. If they are applied, the
- * offsets from the GMT must be saved in the 'tm_params' field so that
- * all the information is available to reconstruct GMT.
- *
- * Notes on porting: PRExplodedTime corrresponds to struct tm in
- * ANSI C, with the following differences:
- * - an additional field tm_usec;
- * - replacing tm_isdst by tm_params;
- * - the month field is spelled tm_month, not tm_mon;
- * - we use absolute year, AD, not the year since 1900.
- * The corresponding type in NSPR 1.0 is called PRTime. Below is
- * a table of date/time type correspondence in the three APIs:
- * API time since epoch time in components
- * ANSI C time_t struct tm
- * NSPR 1.0 PRInt64 PRTime
- * NSPR 2.0 PRTime PRExplodedTime
- */
-
-typedef struct PRExplodedTime {
- PRInt32 tm_usec; /* microseconds past tm_sec (0-99999) */
- PRInt32 tm_sec; /* seconds past tm_min (0-61, accomodating
- up to two leap seconds) */
- PRInt32 tm_min; /* minutes past tm_hour (0-59) */
- PRInt32 tm_hour; /* hours past tm_day (0-23) */
- PRInt32 tm_mday; /* days past tm_mon (1-31, note that it
- starts from 1) */
- PRInt32 tm_month; /* months past tm_year (0-11, Jan = 0) */
- PRInt16 tm_year; /* absolute year, AD (note that we do not
- count from 1900) */
-
- PRInt8 tm_wday; /* calculated day of the week
- (0-6, Sun = 0) */
- PRInt16 tm_yday; /* calculated day of the year
- (0-365, Jan 1 = 0) */
-
- PRTimeParameters tm_params; /* time parameters used by conversion */
-} PRExplodedTime;
-
-/*
- * PRTimeParamFn --
- *
- * A function of PRTimeParamFn type returns the time zone and
- * daylight saving time corrections for some geographic location,
- * given the current time in GMT. The input argument gmt should
- * point to a PRExplodedTime that is in GMT, i.e., whose
- * tm_params contains all 0's.
- *
- * For any time zone other than GMT, the computation is intended to
- * consist of two steps:
- * - Figure out the time zone correction, tp_gmt_offset. This number
- * usually depends on the geographic location only. But it may
- * also depend on the current time. For example, all of China
- * is one time zone right now. But this situation may change
- * in the future.
- * - Figure out the daylight saving time correction, tp_dst_offset.
- * This number depends on both the geographic location and the
- * current time. Most of the DST rules are expressed in local
- * current time. If so, one should apply the time zone correction
- * to GMT before applying the DST rules.
- */
-
-typedef PRTimeParameters (PR_CALLBACK *PRTimeParamFn)(const PRExplodedTime *gmt);
-
-/**********************************************************************/
-/****************************** FUNCTIONS *****************************/
-/**********************************************************************/
-
-/*
- * The PR_Now routine returns the current time relative to the
- * epoch, midnight, January 1, 1970 UTC. The units of the returned
- * value are microseconds since the epoch.
- *
- * The values returned are not guaranteed to advance in a linear fashion
- * due to the application of time correction protocols which synchronize
- * computer clocks to some external time source. Consequently it should
- * not be depended on for interval timing.
- *
- * The implementation is machine dependent.
- * Cf. time_t time(time_t *tp) in ANSI C.
- */
-NSPR_API(PRTime)
-PR_Now(void);
-
-/*
- * Expand time binding it to time parameters provided by PRTimeParamFn.
- * The calculation is envisoned to proceed in the following steps:
- * - From given PRTime, calculate PRExplodedTime in GMT
- * - Apply the given PRTimeParamFn to the GMT that we just calculated
- * to obtain PRTimeParameters.
- * - Add the PRTimeParameters offsets to GMT to get the local time
- * as PRExplodedTime.
- */
-
-NSPR_API(void) PR_ExplodeTime(
- PRTime usecs, PRTimeParamFn params, PRExplodedTime *exploded);
-
-/* Reverse operation of PR_ExplodeTime */
-NSPR_API(PRTime)
-PR_ImplodeTime(const PRExplodedTime *exploded);
-
-/*
- * Adjust exploded time to normalize field overflows after manipulation.
- * Note that the following fields of PRExplodedTime should not be
- * manipulated:
- * - tm_month and tm_year: because the number of days in a month and
- * number of days in a year are not constant, it is ambiguous to
- * manipulate the month and year fields, although one may be tempted
- * to. For example, what does "a month from January 31st" mean?
- * - tm_wday and tm_yday: these fields are calculated by NSPR. Users
- * should treat them as "read-only".
- */
-
-NSPR_API(void) PR_NormalizeTime(
- PRExplodedTime *exploded, PRTimeParamFn params);
-
-/**********************************************************************/
-/*********************** TIME PARAMETER FUNCTIONS *********************/
-/**********************************************************************/
-
-/* Time parameters that suit current host machine */
-NSPR_API(PRTimeParameters) PR_LocalTimeParameters(const PRExplodedTime *gmt);
-
-/* Time parameters that represent Greenwich Mean Time */
-NSPR_API(PRTimeParameters) PR_GMTParameters(const PRExplodedTime *gmt);
-
-/*
- * Time parameters that represent the US Pacific Time Zone, with the
- * current daylight saving time rules (for testing only)
- */
-NSPR_API(PRTimeParameters) PR_USPacificTimeParameters(const PRExplodedTime *gmt);
-
-/*
- * This parses a time/date string into a PRExplodedTime
- * struct. It populates all fields but it can't split
- * the offset from UTC into tp_gmt_offset and tp_dst_offset in
- * most cases (exceptions: PST/PDT, MST/MDT, CST/CDT, EST/EDT, GMT/BST).
- * In those cases tp_gmt_offset will be the sum of these two and
- * tp_dst_offset will be 0.
- * It returns PR_SUCCESS on success, and PR_FAILURE
- * if the time/date string can't be parsed.
- *
- * Many formats are handled, including:
- *
- * 14 Apr 89 03:20:12
- * 14 Apr 89 03:20 GMT
- * Fri, 17 Mar 89 4:01:33
- * Fri, 17 Mar 89 4:01 GMT
- * Mon Jan 16 16:12 PDT 1989
- * Mon Jan 16 16:12 +0130 1989
- * 6 May 1992 16:41-JST (Wednesday)
- * 22-AUG-1993 10:59:12.82
- * 22-AUG-1993 10:59pm
- * 22-AUG-1993 12:59am
- * 22-AUG-1993 12:59 PM
- * Friday, August 04, 1995 3:54 PM
- * 06/21/95 04:24:34 PM
- * 20/06/95 21:07
- * 95-06-08 19:32:48 EDT
- *
- * If the input string doesn't contain a description of the timezone,
- * we consult the `default_to_gmt' to decide whether the string should
- * be interpreted relative to the local time zone (PR_FALSE) or GMT (PR_TRUE).
- * The correct value for this argument depends on what standard specified
- * the time string which you are parsing.
- */
-
-NSPR_API(PRStatus) PR_ParseTimeStringToExplodedTime (
- const char *string,
- PRBool default_to_gmt,
- PRExplodedTime *result);
-
-/*
- * This uses PR_ParseTimeStringToExplodedTime to parse
- * a time/date string and PR_ImplodeTime to transform it into
- * a PRTime (microseconds after "1-Jan-1970 00:00:00 GMT").
- * It returns PR_SUCCESS on success, and PR_FAILURE
- * if the time/date string can't be parsed.
- */
-
-NSPR_API(PRStatus) PR_ParseTimeString (
- const char *string,
- PRBool default_to_gmt,
- PRTime *result);
-
-/* Format a time value into a buffer. Same semantics as strftime() */
-NSPR_API(PRUint32) PR_FormatTime(char *buf, int buflen, const char *fmt,
- const PRExplodedTime *time);
-
-/* Format a time value into a buffer. Time is always in US English format,
- * regardless of locale setting.
- */
-NSPR_API(PRUint32)
-PR_FormatTimeUSEnglish(char *buf, PRUint32 bufSize,
- const char *format, const PRExplodedTime *time);
-
-PR_END_EXTERN_C
-
-#endif /* prtime_h___ */
diff --git a/nspr/pr/include/prtpool.h b/nspr/pr/include/prtpool.h
deleted file mode 100644
index 6a434dd..0000000
--- a/nspr/pr/include/prtpool.h
+++ /dev/null
@@ -1,83 +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/. */
-
-#ifndef prtpool_h___
-#define prtpool_h___
-
-#include "prtypes.h"
-#include "prthread.h"
-#include "prio.h"
-#include "prerror.h"
-
-/*
- * NOTE:
- * THIS API IS A PRELIMINARY VERSION IN NSPR 4.0 AND IS SUBJECT TO
- * CHANGE
- */
-
-PR_BEGIN_EXTERN_C
-
-typedef struct PRJobIoDesc {
- PRFileDesc *socket;
- PRErrorCode error;
- PRIntervalTime timeout;
-} PRJobIoDesc;
-
-typedef struct PRThreadPool PRThreadPool;
-typedef struct PRJob PRJob;
-typedef void (PR_CALLBACK *PRJobFn) (void *arg);
-
-/* Create thread pool */
-NSPR_API(PRThreadPool *)
-PR_CreateThreadPool(PRInt32 initial_threads, PRInt32 max_threads,
- PRUint32 stacksize);
-
-/* queue a job */
-NSPR_API(PRJob *)
-PR_QueueJob(PRThreadPool *tpool, PRJobFn fn, void *arg, PRBool joinable);
-
-/* queue a job, when a socket is readable */
-NSPR_API(PRJob *)
-PR_QueueJob_Read(PRThreadPool *tpool, PRJobIoDesc *iod,
- PRJobFn fn, void * arg, PRBool joinable);
-
-/* queue a job, when a socket is writeable */
-NSPR_API(PRJob *)
-PR_QueueJob_Write(PRThreadPool *tpool, PRJobIoDesc *iod,
- PRJobFn fn, void * arg, PRBool joinable);
-
-/* queue a job, when a socket has a pending connection */
-NSPR_API(PRJob *)
-PR_QueueJob_Accept(PRThreadPool *tpool, PRJobIoDesc *iod,
- PRJobFn fn, void * arg, PRBool joinable);
-
-/* queue a job, when the socket connection to addr succeeds or fails */
-NSPR_API(PRJob *)
-PR_QueueJob_Connect(PRThreadPool *tpool, PRJobIoDesc *iod,
- const PRNetAddr *addr, PRJobFn fn, void * arg, PRBool joinable);
-
-/* queue a job, when a timer exipres */
-NSPR_API(PRJob *)
-PR_QueueJob_Timer(PRThreadPool *tpool, PRIntervalTime timeout,
- PRJobFn fn, void * arg, PRBool joinable);
-/* cancel a job */
-NSPR_API(PRStatus)
-PR_CancelJob(PRJob *job);
-
-/* join a job */
-NSPR_API(PRStatus)
-PR_JoinJob(PRJob *job);
-
-/* shutdown pool */
-NSPR_API(PRStatus)
-PR_ShutdownThreadPool(PRThreadPool *tpool);
-
-/* join pool, wait for exit of all threads */
-NSPR_API(PRStatus)
-PR_JoinThreadPool(PRThreadPool *tpool);
-
-PR_END_EXTERN_C
-
-#endif /* prtpool_h___ */
diff --git a/nspr/pr/include/prtrace.h b/nspr/pr/include/prtrace.h
deleted file mode 100644
index 12a5fbf..0000000
--- a/nspr/pr/include/prtrace.h
+++ /dev/null
@@ -1,646 +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/. */
-
-#ifndef prtrace_h___
-#define prtrace_h___
-/*
-** prtrace.h -- NSPR's Trace Facility.
-**
-** The Trace Facility provides a means to trace application
-** program events within a process. When implementing an
-** application program an engineer may insert a "Trace" function
-** call, passing arguments to be traced. The "Trace" function
-** combines the user trace data with identifying data and
-** writes this data in time ordered sequence into a circular
-** in-memory buffer; when the buffer fills, it wraps.
-**
-** Functions are provided to set and/or re-configure the size of
-** the trace buffer, control what events are recorded in the
-** buffer, enable and disable tracing based on specific user
-** supplied data and other control functions. Methods are provided
-** to record the trace entries in the in-memory trace buffer to
-** a file.
-**
-** Tracing may cause a performance degredation to the application
-** depending on the number and placement of calls to the tracing
-** facility. When tracing is compiled in and all tracing is
-** disabled via the runtime controls, the overhead should be
-** minimal. ... Famous last words, eh?
-**
-** When DEBUG is defined at compile time, the Trace Facility is
-** compiled as part of NSPR and any application using NSPR's
-** header files will have tracing compiled in. When DEBUG is not
-** defined, the Trace Facility is not compiled into NSPR nor
-** exported in its header files. If the Trace Facility is
-** desired in a non-debug build, then FORCE_NSPR_TRACE may be
-** defined at compile time for both the optimized build of NSPR
-** and the application. NSPR and any application using NSPR's
-** Trace Facility must be compiled with the same level of trace
-** conditioning or unresolved references may be realized at link
-** time.
-**
-** For any of the Trace Facility methods that requires a trace
-** handle as an input argument, the caller must ensure that the
-** trace handle argument is valid. An invalid trace handle
-** argument may cause unpredictable results.
-**
-** Trace Facility methods are thread-safe and SMP safe.
-**
-** Users of the Trace Facility should use the defined macros to
-** invoke trace methods, not the function calls directly. e.g.
-** PR_TRACE( h1,0,1,2, ...); not PR_Trace(h1,0,1,2, ...);
-**
-** Application designers should be aware of the effects of
-** debug and optimized build differences when using result of the
-** Trace Facility macros in expressions.
-**
-** See Also: prcountr.h
-**
-** /lth. 08-Jun-1998.
-*/
-
-#include "prtypes.h"
-#include "prthread.h"
-#include "prtime.h"
-
-PR_BEGIN_EXTERN_C
-
-/*
-** Opaque type for the trace handle
-** ... Don't even think about looking in here.
-**
-*/
-typedef void * PRTraceHandle;
-
-/*
-** PRTraceEntry -- A trace entry in the in-memory trace buffer
-** looks like this.
-**
-*/
-typedef struct PRTraceEntry
-{
- PRThread *thread; /* The thread creating the trace entry */
- PRTraceHandle handle; /* PRTraceHandle creating the trace entry */
- PRTime time; /* Value of PR_Now() at time of trace entry */
- PRUint32 userData[8]; /* user supplied trace data */
-} PRTraceEntry;
-
-/*
-** PRTraceOption -- command operands to
-** PR_[Set|Get]TraceOption(). See descriptive meanings there.
-**
-*/
-typedef enum PRTraceOption
-{
- PRTraceBufSize,
- PRTraceEnable,
- PRTraceDisable,
- PRTraceSuspend,
- PRTraceResume,
- PRTraceSuspendRecording,
- PRTraceResumeRecording,
- PRTraceLockHandles,
- PRTraceUnLockHandles,
- PRTraceStopRecording
-} PRTraceOption;
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_DEFINE_TRACE() -- Define a PRTraceHandle
-**
-** DESCRIPTION: PR_DEFINE_TRACE() is used to define a trace
-** handle.
-**
-*/
-#define PR_DEFINE_TRACE(name) PRTraceHandle name
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_INIT_TRACE_HANDLE() -- Set the value of a PRTraceHandle
-**
-** DESCRIPTION:
-** PR_INIT_TRACE_HANDLE() sets the value of a PRTraceHandle
-** to value. e.g. PR_INIT_TRACE_HANDLE( myHandle, NULL );
-**
-*/
-#if defined (DEBUG) || defined (FORCE_NSPR_TRACE)
-#define PR_INIT_TRACE_HANDLE(handle,value)\
- (handle) = (PRCounterHandle)(value)
-#else
-#define PR_INIT_TRACE_HANDLE(handle,value)
-#endif
-
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_CreateTrace() -- Create a trace handle
-**
-** DESCRIPTION:
-** PR_CreateTrace() creates a new trace handle. Tracing is
-** enabled for this handle when it is created. The trace handle
-** is intended for use in other Trace Facility calls.
-**
-** PR_CreateTrace() registers the QName, RName and description
-** data so that this data can be retrieved later.
-**
-** INPUTS:
-** qName: pointer to string. QName for this trace handle.
-**
-** rName: pointer to string. RName for this trace handle.
-**
-** description: pointer to string. Descriptive data about this
-** trace handle.
-**
-** OUTPUTS:
-** Creates the trace handle.
-** Registers the QName and RName with the trace facility.
-**
-** RETURNS:
-** PRTraceHandle
-**
-** RESTRICTIONS:
-** qName is limited to 31 characters.
-** rName is limited to 31 characters.
-** description is limited to 255 characters.
-**
-*/
-#define PRTRACE_NAME_MAX 31
-#define PRTRACE_DESC_MAX 255
-
-#if defined (DEBUG) || defined (FORCE_NSPR_TRACE)
-#define PR_CREATE_TRACE(handle,qName,rName,description)\
- (handle) = PR_CreateTrace((qName),(rName),(description))
-#else
-#define PR_CREATE_TRACE(handle,qName,rName,description)
-#endif
-
-NSPR_API(PRTraceHandle)
- PR_CreateTrace(
- const char *qName, /* QName for this trace handle */
- const char *rName, /* RName for this trace handle */
- const char *description /* description for this trace handle */
-);
-
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_DestroyTrace() -- Destroy a trace handle
-**
-** DESCRIPTION:
-** PR_DestroyTrace() removes the referenced trace handle and
-** associated QName, RName and description data from the Trace
-** Facility.
-**
-** INPUTS: handle. A PRTraceHandle
-**
-** OUTPUTS:
-** The trace handle is unregistered.
-** The QName, RName and description are removed.
-**
-** RETURNS: void
-**
-** RESTRICTIONS:
-**
-*/
-#if defined (DEBUG) || defined (FORCE_NSPR_TRACE)
-#define PR_DESTROY_TRACE(handle)\
- PR_DestroyTrace((handle))
-#else
-#define PR_DESTROY_TRACE(handle)
-#endif
-
-NSPR_API(void)
- PR_DestroyTrace(
- PRTraceHandle handle /* Handle to be destroyed */
-);
-
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_Trace() -- Make a trace entry in the in-memory trace
-**
-** DESCRIPTION:
-** PR_Trace() makes an entry in the in-memory trace buffer for
-** the referenced trace handle. The next logically available
-** PRTraceEntry is used; when the next trace entry would overflow
-** the trace table, the table wraps.
-**
-** PR_Trace() for a specific trace handle may be disabled by
-** calling PR_SetTraceOption() specifying PRTraceDisable for the
-** trace handle to be disabled.
-**
-** INPUTS:
-** handle: PRTraceHandle. The trace handle for this trace.
-**
-** userData[0..7]: unsigned 32bit integers. user supplied data
-** that is copied into the PRTraceEntry
-**
-** OUTPUTS:
-** A PRTraceEntry is (conditionally) formatted in the in-memory
-** trace buffer.
-**
-** RETURNS: void.
-**
-** RESTRICTIONS:
-**
-*/
-#if defined (DEBUG) || defined (FORCE_NSPR_TRACE)
-#define PR_TRACE(handle,ud0,ud1,ud2,ud3,ud4,ud5,ud6,ud7)\
- PR_Trace((handle),(ud0),(ud1),(ud2),(ud3),(ud4),(ud5),(ud6),(ud7))
-#else
-#define PR_TRACE(handle,ud0,ud1,ud2,ud3,ud4,ud5,ud6,ud7)
-#endif
-
-NSPR_API(void)
- PR_Trace(
- PRTraceHandle handle, /* use this trace handle */
- PRUint32 userData0, /* User supplied data word 0 */
- PRUint32 userData1, /* User supplied data word 1 */
- PRUint32 userData2, /* User supplied data word 2 */
- PRUint32 userData3, /* User supplied data word 3 */
- PRUint32 userData4, /* User supplied data word 4 */
- PRUint32 userData5, /* User supplied data word 5 */
- PRUint32 userData6, /* User supplied data word 6 */
- PRUint32 userData7 /* User supplied data word 7 */
-);
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_SetTraceOption() -- Control the Trace Facility
-**
-** DESCRIPTION:
-** PR_SetTraceOption() controls the Trace Facility. Depending on
-** command and value, attributes of the Trace Facility may be
-** changed.
-**
-** INPUTS:
-** command: An enumerated value in the set of PRTraceOption.
-** value: pointer to the data to be set. Type of the data is
-** dependent on command; for each value of command, the type
-** and meaning of dereferenced value is shown.
-**
-** PRTraceBufSize: unsigned long: the size of the trace buffer,
-** in bytes.
-**
-** PRTraceEnable: PRTraceHandle. The trace handle to be
-** enabled.
-**
-** PRTraceDisable: PRTraceHandle. The trace handle to be
-** disabled.
-**
-** PRTraceSuspend: void. value must be NULL. All tracing is
-** suspended.
-**
-** PRTraceResume: void. value must be NULL. Tracing for all
-** previously enabled, prior to a PRTraceSuspend, is resumed.
-**
-** PRTraceStopRecording: void. value must be NULL. If recording
-** (see: ** PR_RecordTraceEntries()) is being done,
-** PRTraceStopRecording causes PR_RecordTraceEntries() to return
-** to its caller. If recording is not being done, this function
-** has no effect.
-**
-** PRTraceSuspendRecording: void. Must be NULL. If recording is
-** being done, PRTraceSuspendRecording causes further writes to
-** the trace file to be suspended. Data in the in-memory
-** trace buffer that would ordinarily be written to the
-** trace file will not be written. Trace entries will continue
-** to be entered in the in-memory buffer. If the Trace Facility
-** recording is already in a suspended state, the call has no
-** effect.
-**
-** PRTraceResumeRecording: void. value must be NULL. If
-** recording for the Trace Facility has been previously been
-** suspended, this causes recording to resume. Recording resumes
-** with the next in-memory buffer segment that would be written
-** if trace recording had not been suspended. If recording is
-** not currently suspended, the call has no effect.
-**
-** PRTraceLockHandles: void. value must be NULL. Locks the
-** trace handle lock. While the trace handle lock is held,
-** calls to PR_CreateTrace() will block until the lock is
-** released.
-**
-** PRTraceUnlockHandles: void. value must be NULL. Unlocks the
-** trace handle lock.
-**
-** OUTPUTS:
-** The operation of the Trace Facility may be changed.
-**
-** RETURNS: void
-**
-** RESTRICTIONS:
-**
-*/
-#if defined (DEBUG) || defined (FORCE_NSPR_TRACE)
-#define PR_SET_TRACE_OPTION(command,value)\
- PR_SetTraceOption((command),(value))
-#else
-#define PR_SET_TRACE_OPTION(command,value)
-#endif
-
-NSPR_API(void)
- PR_SetTraceOption(
- PRTraceOption command, /* One of the enumerated values */
- void *value /* command value or NULL */
-);
-
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_GetTraceOption() -- Retrieve settings from the Trace Facility
-**
-** DESCRIPTION:
-** PR_GetTraceOption() retrieves the current setting of the
-** Trace Facility control depending on command.
-**
-**
-** PRTraceBufSize: unsigned long: the size of the trace buffer,
-** in bytes.
-**
-**
-** INPUTS:
-** command: one of the enumerated values in PRTraceOptions
-** valid for PR_GetTraceOption().
-**
-** OUTPUTS:
-** dependent on command.
-**
-** RETURNS: void
-**
-** RESTRICTIONS:
-**
-*/
-#if defined (DEBUG) || defined (FORCE_NSPR_TRACE)
-#define PR_GET_TRACE_OPTION(command,value)\
- PR_GetTraceOption((command),(value))
-#else
-#define PR_GET_TRACE_OPTION(command,value)
-#endif
-
-NSPR_API(void)
- PR_GetTraceOption(
- PRTraceOption command, /* One of the enumerated values */
- void *value /* command value or NULL */
-);
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_GetTraceHandleFromName() -- Retrieve an existing
-** handle by name.
-**
-** DESCRIPTION:
-** PR_GetTraceHandleFromName() retreives an existing tracehandle
-** using the name specified by qName and rName.
-**
-** INPUTS:
-** qName: pointer to string. QName for this trace handle.
-**
-** rName: pointer to string. RName for this trace handle.
-**
-**
-** OUTPUTS: returned.
-**
-** RETURNS:
-** PRTraceHandle associated with qName and rName or NULL when
-** there is no match.
-**
-** RESTRICTIONS:
-**
-*/
-#if defined (DEBUG) || defined (FORCE_NSPR_TRACE)
-#define PR_GET_TRACE_HANDLE_FROM_NAME(handle,qName,rName)\
- (handle) = PR_GetTraceHandleFromName((qName),(rName))
-#else
-#define PR_GET_TRACE_HANDLE_FROM_NAME(handle,qName,rName)
-#endif
-
-NSPR_API(PRTraceHandle)
- PR_GetTraceHandleFromName(
- const char *qName, /* QName search argument */
- const char *rName /* RName search argument */
-);
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_GetTraceNameFromHandle() -- Retreive trace name
-** by bandle.
-**
-** DESCRIPTION:
-** PR_GetTraceNameFromHandle() retreives the existing qName,
-** rName, and description for the referenced trace handle.
-**
-** INPUTS: handle: PRTraceHandle.
-**
-** OUTPUTS: pointers to the Trace Facility's copy of qName,
-** rName and description. ... Don't mess with these values.
-** They're mine.
-**
-** RETURNS: void
-**
-** RESTRICTIONS:
-**
-*/
-#if defined (DEBUG) || defined (FORCE_NSPR_TRACE)
-#define PR_GET_TRACE_NAME_FROM_HANDLE(handle,qName,rName,description)\
- PR_GetTraceNameFromHandle((handle),(qName),(rName),(description))
-#else
-#define PR_GET_TRACE_NAME_FROM_HANDLE(handle,qName,rName,description)
-#endif
-
-NSPR_API(void)
- PR_GetTraceNameFromHandle(
- PRTraceHandle handle, /* handle as search argument */
- const char **qName, /* pointer to associated QName */
- const char **rName, /* pointer to associated RName */
- const char **description /* pointer to associated description */
-);
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_FindNextTraceQname() -- Retrieive a QName handle
-** iterator.
-**
-** DESCRIPTION:
-** PR_FindNextTraceQname() retreives the first or next trace
-** QName handle, depending on the value of handle, from the trace
-** database. The PRTraceHandle returned can be used as an
-** iterator to traverse the QName handles in the Trace database.
-**
-** INPUTS:
-** handle: When NULL, PR_FindNextQname() returns the first QName
-** handle. When a handle is a valid PRTraceHandle previously
-** retreived using PR_FindNextQname() the next QName handle is
-** retreived.
-**
-** OUTPUTS: returned.
-**
-** RETURNS:
-** PRTraceHandle or NULL when there are no trace handles.
-**
-** RESTRICTIONS:
-** Iterating thru the trace handles via FindFirst/FindNext
-** should be done under protection of the trace handle lock.
-** See: PR_SetTraceOption( PRLockTraceHandles ).
-**
-*/
-#if defined (DEBUG) || defined (FORCE_NSPR_TRACE)
-#define PR_FIND_NEXT_TRACE_QNAME(next,handle)\
- (next) = PR_FindNextTraceQname((handle))
-#else
-#define PR_FIND_NEXT_TRACE_QNAME(next,handle)
-#endif
-
-NSPR_API(PRTraceHandle)
- PR_FindNextTraceQname(
- PRTraceHandle handle
-);
-
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_FindNextTraceRname() -- Retrieive an RName handle
-** iterator.
-**
-** DESCRIPTION:
-** PR_FindNextTraceRname() retreives the first or next trace
-** RName handle, depending on the value of handle, from the trace
-** database. The PRTraceHandle returned can be used as an
-** iterator to traverse the RName handles in the Trace database.
-**
-** INPUTS:
-** rhandle: When NULL, PR_FindNextRname() returns the first
-** RName handle. When a handle is a valid PRTraceHandle
-** previously retreived using PR_FindNextRname() the next RName
-** handle is retreived.
-** qhandle: A valid PRTraceHandle retruned from a previous call
-** to PR_FIND_NEXT_TRACE_QNAME().
-**
-** OUTPUTS: returned.
-**
-** RETURNS:
-** PRTraceHandle or NULL when there are no trace handles.
-**
-** RESTRICTIONS:
-** Iterating thru the trace handles via FindNext should be done
-** under protection of the trace handle lock. See: (
-** PR_SetTraceOption( PRLockTraceHandles ).
-**
-*/
-#if defined (DEBUG) || defined (FORCE_NSPR_TRACE)
-#define PR_FIND_NEXT_TRACE_RNAME(next,rhandle,qhandle)\
- (next) = PR_FindNextTraceRname((rhandle),(qhandle))
-#else
-#define PR_FIND_NEXT_TRACE_RNAME(next,rhandle,qhandle)
-#endif
-
-NSPR_API(PRTraceHandle)
- PR_FindNextTraceRname(
- PRTraceHandle rhandle,
- PRTraceHandle qhandle
-);
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_RecordTraceEntries() -- Write trace entries to external media
-**
-** DESCRIPTION:
-** PR_RecordTraceEntries() causes entries in the in-memory trace
-** buffer to be written to external media.
-**
-** When PR_RecordTraceEntries() is called from an application
-** thread, the function appears to block until another thread
-** calls PR_SetTraceOption() with the PRTraceStopRecording
-** option. This suggests that PR_RecordTraceEntries() should be
-** called from a user supplied thread whose only job is to
-** record trace entries.
-**
-** The environment variable NSPR_TRACE_LOG controls the operation
-** of this function. When NSPR_TRACE_LOG is not defined in the
-** environment, no recording of trace entries occurs. When
-** NSPR_TRACE_LOG is defined, the value of its definition must be
-** the filename of the file to receive the trace entry buffer.
-**
-** PR_RecordTraceEntries() attempts to record the in-memory
-** buffer to a file, subject to the setting of the environment
-** variable NSPR_TRACE_LOG. It is possible because of system
-** load, the thread priority of the recording thread, number of
-** active trace records being written over time, and other
-** variables that some trace records can be lost. ... In other
-** words: don't bet the farm on getting everything.
-**
-** INPUTS: none
-**
-** OUTPUTS: none
-**
-** RETURNS: PR_STATUS
-** PR_SUCCESS no errors were found.
-** PR_FAILURE errors were found.
-**
-** RESTRICTIONS:
-** Only one thread can call PR_RecordTraceEntries() within a
-** process.
-**
-** On error, PR_RecordTraceEntries() may return prematurely.
-**
-*/
-#if defined (DEBUG) || defined (FORCE_NSPR_TRACE)
-#define PR_RECORD_TRACE_ENTRIES()\
- PR_RecordTraceEntries()
-#else
-#define PR_RECORD_TRACE_ENTRIES()
-#endif
-
-NSPR_API(void)
- PR_RecordTraceEntries(
- void
-);
-
-/* -----------------------------------------------------------------------
-** FUNCTION: PR_GetTraceEntries() -- Retreive trace entries from
-** the Trace Facility
-**
-** DESCRIPTION:
-** PR_GetTraceEntries() retreives trace entries from the Trace
-** Facility. Up to count trace entries are copied from the Trace
-** Facility into buffer. Only those trace entries that have not
-** been copied via a previous call to PR_GetTraceEntries() are
-** copied. The actual number copied is placed in the PRInt32
-** variable pointed to by found.
-**
-** If more than count trace entries have entered the Trace
-** Facility since the last call to PR_GetTraceEntries()
-** a lost data condition is returned. In this case, the most
-** recent count trace entries are copied into buffer and found is
-** set to count.
-**
-** INPUTS:
-** count. The number of trace entries to be copied into buffer.
-**
-**
-** OUTPUTS:
-** buffer. An array of PRTraceEntries. The buffer is supplied
-** by the caller.
-**
-** found: 32bit signed integer. The number of PRTraceEntries
-** actually copied. found is always less than or equal to count.
-**
-** RETURNS:
-** zero when there is no lost data.
-** non-zero when some PRTraceEntries have been lost.
-**
-** RESTRICTIONS:
-** This is a real performance pig. The copy out operation is bad
-** enough, but depending on then frequency of calls to the
-** function, serious performance impact to the operating
-** application may be realized. ... YMMV.
-**
-*/
-#if defined (DEBUG) || defined (FORCE_NSPR_TRACE)
-#define PR_GET_TRACE_ENTRIES(buffer,count,found)\
- PR_GetTraceEntries((buffer),(count),(found))
-#else
-#define PR_GET_TRACE_ENTRIES(buffer,count,found)
-#endif
-
-NSPR_API(PRIntn)
- PR_GetTraceEntries(
- PRTraceEntry *buffer, /* where to write output */
- PRInt32 count, /* number to get */
- PRInt32 *found /* number you got */
-);
-
-PR_END_EXTERN_C
-
-#endif /* prtrace_h___ */
-
diff --git a/nspr/pr/include/prtypes.h b/nspr/pr/include/prtypes.h
deleted file mode 100644
index d78f580..0000000
--- a/nspr/pr/include/prtypes.h
+++ /dev/null
@@ -1,606 +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/. */
-
-/*
-** File: prtypes.h
-** Description: Definitions of NSPR's basic types
-**
-** Prototypes and macros used to make up for deficiencies that we have found
-** in ANSI environments.
-**
-** Since we do not wrap <stdlib.h> and all the other standard headers, authors
-** of portable code will not know in general that they need these definitions.
-** Instead of requiring these authors to find the dependent uses in their code
-** and take the following steps only in those C files, we take steps once here
-** for all C files.
-**/
-
-#ifndef prtypes_h___
-#define prtypes_h___
-
-#ifdef MDCPUCFG
-#include MDCPUCFG
-#else
-#include "prcpucfg.h"
-#endif
-
-#include <stddef.h>
-
-/***********************************************************************
-** MACROS: PR_EXTERN
-** PR_IMPLEMENT
-** DESCRIPTION:
-** These are only for externally visible routines and globals. For
-** internal routines, just use "extern" for type checking and that
-** will not export internal cross-file or forward-declared symbols.
-** Define a macro for declaring procedures return types. We use this to
-** deal with windoze specific type hackery for DLL definitions. Use
-** PR_EXTERN when the prototype for the method is declared. Use
-** PR_IMPLEMENT for the implementation of the method.
-**
-** Example:
-** in dowhim.h
-** PR_EXTERN( void ) DoWhatIMean( void );
-** in dowhim.c
-** PR_IMPLEMENT( void ) DoWhatIMean( void ) { return; }
-**
-**
-***********************************************************************/
-#if defined(NSPR_STATIC)
-
-#define PR_EXPORT(__type) extern __type
-#define PR_EXPORT_DATA(__type) extern __type
-#define PR_IMPORT(__type) extern __type
-#define PR_IMPORT_DATA(__type) extern __type
-
-#define PR_EXTERN(__type) extern __type
-#define PR_IMPLEMENT(__type) __type
-#define PR_EXTERN_DATA(__type) extern __type
-#define PR_IMPLEMENT_DATA(__type) __type
-
-#define PR_CALLBACK
-#define PR_CALLBACK_DECL
-#define PR_STATIC_CALLBACK(__x) static __x
-
-#elif defined(WIN32)
-
-#define PR_EXPORT(__type) extern __declspec(dllexport) __type
-#define PR_EXPORT_DATA(__type) extern __declspec(dllexport) __type
-#define PR_IMPORT(__type) __declspec(dllimport) __type
-#define PR_IMPORT_DATA(__type) __declspec(dllimport) __type
-
-#define PR_EXTERN(__type) extern __declspec(dllexport) __type
-#define PR_IMPLEMENT(__type) __declspec(dllexport) __type
-#define PR_EXTERN_DATA(__type) extern __declspec(dllexport) __type
-#define PR_IMPLEMENT_DATA(__type) __declspec(dllexport) __type
-
-#define PR_CALLBACK
-#define PR_CALLBACK_DECL
-#define PR_STATIC_CALLBACK(__x) static __x
-
-#elif defined(XP_BEOS)
-
-#define PR_EXPORT(__type) extern __declspec(dllexport) __type
-#define PR_EXPORT_DATA(__type) extern __declspec(dllexport) __type
-#define PR_IMPORT(__type) extern __declspec(dllexport) __type
-#define PR_IMPORT_DATA(__type) extern __declspec(dllexport) __type
-
-#define PR_EXTERN(__type) extern __declspec(dllexport) __type
-#define PR_IMPLEMENT(__type) __declspec(dllexport) __type
-#define PR_EXTERN_DATA(__type) extern __declspec(dllexport) __type
-#define PR_IMPLEMENT_DATA(__type) __declspec(dllexport) __type
-
-#define PR_CALLBACK
-#define PR_CALLBACK_DECL
-#define PR_STATIC_CALLBACK(__x) static __x
-
-#elif defined(XP_OS2) && defined(__declspec)
-
-#define PR_EXPORT(__type) extern __declspec(dllexport) __type
-#define PR_EXPORT_DATA(__type) extern __declspec(dllexport) __type
-#define PR_IMPORT(__type) extern __declspec(dllimport) __type
-#define PR_IMPORT_DATA(__type) extern __declspec(dllimport) __type
-
-#define PR_EXTERN(__type) extern __declspec(dllexport) __type
-#define PR_IMPLEMENT(__type) __declspec(dllexport) __type
-#define PR_EXTERN_DATA(__type) extern __declspec(dllexport) __type
-#define PR_IMPLEMENT_DATA(__type) __declspec(dllexport) __type
-
-#define PR_CALLBACK
-#define PR_CALLBACK_DECL
-#define PR_STATIC_CALLBACK(__x) static __x
-
-#elif defined(SYMBIAN)
-
-#define PR_EXPORT(__type) extern __declspec(dllexport) __type
-#define PR_EXPORT_DATA(__type) extern __declspec(dllexport) __type
-#ifdef __WINS__
-#define PR_IMPORT(__type) extern __declspec(dllexport) __type
-#define PR_IMPORT_DATA(__type) extern __declspec(dllexport) __type
-#else
-#define PR_IMPORT(__type) extern __declspec(dllimport) __type
-#define PR_IMPORT_DATA(__type) extern __declspec(dllimport) __type
-#endif
-
-#define PR_EXTERN(__type) extern __type
-#define PR_IMPLEMENT(__type) __type
-#define PR_EXTERN_DATA(__type) extern __type
-#define PR_IMPLEMENT_DATA(__type) __type
-
-#define PR_CALLBACK
-#define PR_CALLBACK_DECL
-#define PR_STATIC_CALLBACK(__x) static __x
-
-#else /* Unix */
-
-/* GCC 3.3 and later support the visibility attribute. */
-#if (__GNUC__ >= 4) || \
- (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)
-#define PR_VISIBILITY_DEFAULT __attribute__((visibility("default")))
-#else
-#define PR_VISIBILITY_DEFAULT
-#endif
-
-#define PR_EXPORT(__type) extern PR_VISIBILITY_DEFAULT __type
-#define PR_EXPORT_DATA(__type) extern PR_VISIBILITY_DEFAULT __type
-#define PR_IMPORT(__type) extern PR_VISIBILITY_DEFAULT __type
-#define PR_IMPORT_DATA(__type) extern PR_VISIBILITY_DEFAULT __type
-
-#define PR_EXTERN(__type) extern PR_VISIBILITY_DEFAULT __type
-#define PR_IMPLEMENT(__type) PR_VISIBILITY_DEFAULT __type
-#define PR_EXTERN_DATA(__type) extern PR_VISIBILITY_DEFAULT __type
-#define PR_IMPLEMENT_DATA(__type) PR_VISIBILITY_DEFAULT __type
-#define PR_CALLBACK
-#define PR_CALLBACK_DECL
-#define PR_STATIC_CALLBACK(__x) static __x
-
-#endif
-
-#if defined(_NSPR_BUILD_)
-#define NSPR_API(__type) PR_EXPORT(__type)
-#define NSPR_DATA_API(__type) PR_EXPORT_DATA(__type)
-#else
-#define NSPR_API(__type) PR_IMPORT(__type)
-#define NSPR_DATA_API(__type) PR_IMPORT_DATA(__type)
-#endif
-
-/***********************************************************************
-** MACROS: PR_BEGIN_MACRO
-** PR_END_MACRO
-** DESCRIPTION:
-** Macro body brackets so that macros with compound statement definitions
-** behave syntactically more like functions when called.
-***********************************************************************/
-#define PR_BEGIN_MACRO do {
-#define PR_END_MACRO } while (0)
-
-/***********************************************************************
-** MACROS: PR_BEGIN_EXTERN_C
-** PR_END_EXTERN_C
-** DESCRIPTION:
-** Macro shorthands for conditional C++ extern block delimiters.
-***********************************************************************/
-#ifdef __cplusplus
-#define PR_BEGIN_EXTERN_C extern "C" {
-#define PR_END_EXTERN_C }
-#else
-#define PR_BEGIN_EXTERN_C
-#define PR_END_EXTERN_C
-#endif
-
-/***********************************************************************
-** MACROS: PR_BIT
-** PR_BITMASK
-** DESCRIPTION:
-** Bit masking macros. XXX n must be <= 31 to be portable
-***********************************************************************/
-#define PR_BIT(n) ((PRUint32)1 << (n))
-#define PR_BITMASK(n) (PR_BIT(n) - 1)
-
-/***********************************************************************
-** MACROS: PR_ROUNDUP
-** PR_MIN
-** PR_MAX
-** PR_ABS
-** DESCRIPTION:
-** Commonly used macros for operations on compatible types.
-***********************************************************************/
-#define PR_ROUNDUP(x,y) ((((x)+((y)-1))/(y))*(y))
-#define PR_MIN(x,y) ((x)<(y)?(x):(y))
-#define PR_MAX(x,y) ((x)>(y)?(x):(y))
-#define PR_ABS(x) ((x)<0?-(x):(x))
-
-/***********************************************************************
-** MACROS: PR_ARRAY_SIZE
-** DESCRIPTION:
-** The number of elements in an array.
-***********************************************************************/
-#define PR_ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
-
-PR_BEGIN_EXTERN_C
-
-/*
-** Starting in NSPR 4.9.5, NSPR's exact-width integer types should match
-** the exact-width integer types defined in <stdint.h>. This allows sloppy
-** code to use PRInt{N} and int{N}_t interchangeably.
-**
-** The 8-bit and 16-bit integer types can only be defined using char and
-** short. All platforms define the 32-bit integer types using int. So only
-** the 64-bit integer types could be defined differently.
-**
-** NSPR's original strategy was to use the "shortest" 64-bit integer type:
-** if long is 64-bit, then prefer it over long long. This strategy is also
-** used by Linux/glibc, FreeBSD, and NetBSD.
-**
-** Other platforms use a different strategy: simply define the 64-bit
-** integer types using long long. We define the PR_ALTERNATE_INT64_TYPEDEF
-** macro on these platforms. Note that PR_ALTERNATE_INT64_TYPEDEF is for
-** internal use by NSPR headers only. Do not define or test this macro in
-** your code.
-**
-** NOTE: NSPR can't use <stdint.h> because C99 requires C++ code to define
-** __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS to make all the macros
-** defined in <stdint.h> available. This strange requirement is gone in
-** C11. When most platforms ignore this C99 requirement, NSPR will be able
-** to use <stdint.h>. A patch to do that is in NSPR bug 634793.
-*/
-
-#if defined(__APPLE__) || defined(__ANDROID__) || defined(__OpenBSD__)
-#define PR_ALTERNATE_INT64_TYPEDEF
-#endif
-
-/************************************************************************
-** TYPES: PRUint8
-** PRInt8
-** DESCRIPTION:
-** The int8 types are known to be 8 bits each. There is no type that
-** is equivalent to a plain "char".
-************************************************************************/
-#if PR_BYTES_PER_BYTE == 1
-typedef unsigned char PRUint8;
-/*
-** Some cfront-based C++ compilers do not like 'signed char' and
-** issue the warning message:
-** warning: "signed" not implemented (ignored)
-** For these compilers, we have to define PRInt8 as plain 'char'.
-** Make sure that plain 'char' is indeed signed under these compilers.
-*/
-#if (defined(HPUX) && defined(__cplusplus) \
- && !defined(__GNUC__) && __cplusplus < 199707L) \
- || (defined(SCO) && defined(__cplusplus) \
- && !defined(__GNUC__) && __cplusplus == 1L)
-typedef char PRInt8;
-#else
-typedef signed char PRInt8;
-#endif
-#else
-#error No suitable type for PRInt8/PRUint8
-#endif
-
-/************************************************************************
- * MACROS: PR_INT8_MAX
- * PR_INT8_MIN
- * PR_UINT8_MAX
- * DESCRIPTION:
- * The maximum and minimum values of a PRInt8 or PRUint8.
-************************************************************************/
-
-#define PR_INT8_MAX 127
-#define PR_INT8_MIN (-128)
-#define PR_UINT8_MAX 255U
-
-/************************************************************************
-** TYPES: PRUint16
-** PRInt16
-** DESCRIPTION:
-** The int16 types are known to be 16 bits each.
-************************************************************************/
-#if PR_BYTES_PER_SHORT == 2
-typedef unsigned short PRUint16;
-typedef short PRInt16;
-#else
-#error No suitable type for PRInt16/PRUint16
-#endif
-
-/************************************************************************
- * MACROS: PR_INT16_MAX
- * PR_INT16_MIN
- * PR_UINT16_MAX
- * DESCRIPTION:
- * The maximum and minimum values of a PRInt16 or PRUint16.
-************************************************************************/
-
-#define PR_INT16_MAX 32767
-#define PR_INT16_MIN (-32768)
-#define PR_UINT16_MAX 65535U
-
-/************************************************************************
-** TYPES: PRUint32
-** PRInt32
-** DESCRIPTION:
-** The int32 types are known to be 32 bits each.
-************************************************************************/
-#if PR_BYTES_PER_INT == 4
-typedef unsigned int PRUint32;
-typedef int PRInt32;
-#define PR_INT32(x) x
-#define PR_UINT32(x) x ## U
-#elif PR_BYTES_PER_LONG == 4
-typedef unsigned long PRUint32;
-typedef long PRInt32;
-#define PR_INT32(x) x ## L
-#define PR_UINT32(x) x ## UL
-#else
-#error No suitable type for PRInt32/PRUint32
-#endif
-
-/************************************************************************
- * MACROS: PR_INT32_MAX
- * PR_INT32_MIN
- * PR_UINT32_MAX
- * DESCRIPTION:
- * The maximum and minimum values of a PRInt32 or PRUint32.
-************************************************************************/
-
-#define PR_INT32_MAX PR_INT32(2147483647)
-#define PR_INT32_MIN (-PR_INT32_MAX - 1)
-#define PR_UINT32_MAX PR_UINT32(4294967295)
-
-/************************************************************************
-** TYPES: PRUint64
-** PRInt64
-** DESCRIPTION:
-** The int64 types are known to be 64 bits each. Care must be used when
-** declaring variables of type PRUint64 or PRInt64. Different hardware
-** architectures and even different compilers have varying support for
-** 64 bit values. The only guaranteed portability requires the use of
-** the LL_ macros (see prlong.h).
-**
-** MACROS: PR_INT64
-** PR_UINT64
-** DESCRIPTION:
-** The PR_INT64 and PR_UINT64 macros provide a portable way for
-** specifying 64-bit integer constants. They can only be used if
-** PRInt64 and PRUint64 are defined as compiler-supported 64-bit
-** integer types (i.e., if HAVE_LONG_LONG is defined, which is true
-** for all the supported compilers topday). If PRInt64 and PRUint64
-** are defined as structs, the LL_INIT macro defined in prlong.h has
-** to be used.
-**
-** MACROS: PR_INT64_MAX
-** PR_INT64_MIN
-** PR_UINT64_MAX
-** DESCRIPTION:
-** The maximum and minimum values of a PRInt64 or PRUint64.
-************************************************************************/
-#ifdef HAVE_LONG_LONG
-/* Keep this in sync with prlong.h. */
-#if PR_BYTES_PER_LONG == 8 && !defined(PR_ALTERNATE_INT64_TYPEDEF)
-typedef long PRInt64;
-typedef unsigned long PRUint64;
-#define PR_INT64(x) x ## L
-#define PR_UINT64(x) x ## UL
-#elif defined(WIN32) && !defined(__GNUC__)
-typedef __int64 PRInt64;
-typedef unsigned __int64 PRUint64;
-#define PR_INT64(x) x ## i64
-#define PR_UINT64(x) x ## ui64
-#else
-typedef long long PRInt64;
-typedef unsigned long long PRUint64;
-#define PR_INT64(x) x ## LL
-#define PR_UINT64(x) x ## ULL
-#endif /* PR_BYTES_PER_LONG == 8 */
-
-#define PR_INT64_MAX PR_INT64(0x7fffffffffffffff)
-#define PR_INT64_MIN (-PR_INT64_MAX - 1)
-#define PR_UINT64_MAX PR_UINT64(-1)
-#else /* !HAVE_LONG_LONG */
-typedef struct {
-#ifdef IS_LITTLE_ENDIAN
- PRUint32 lo, hi;
-#else
- PRUint32 hi, lo;
-#endif
-} PRInt64;
-typedef PRInt64 PRUint64;
-
-#define PR_INT64_MAX (PRInt64){0x7fffffff, 0xffffffff}
-#define PR_INT64_MIN (PRInt64){0xffffffff, 0xffffffff}
-#define PR_UINT64_MAX (PRUint64){0xffffffff, 0xffffffff}
-
-#endif /* !HAVE_LONG_LONG */
-
-/************************************************************************
-** TYPES: PRUintn
-** PRIntn
-** DESCRIPTION:
-** The PRIntn types are most appropriate for automatic variables. They are
-** guaranteed to be at least 16 bits, though various architectures may
-** define them to be wider (e.g., 32 or even 64 bits). These types are
-** never valid for fields of a structure.
-************************************************************************/
-#if PR_BYTES_PER_INT >= 2
-typedef int PRIntn;
-typedef unsigned int PRUintn;
-#else
-#error 'sizeof(int)' not sufficient for platform use
-#endif
-
-/************************************************************************
-** TYPES: PRFloat64
-** DESCRIPTION:
-** NSPR's floating point type is always 64 bits.
-************************************************************************/
-typedef double PRFloat64;
-
-/************************************************************************
-** TYPES: PRSize
-** DESCRIPTION:
-** A type for representing the size of objects.
-************************************************************************/
-typedef size_t PRSize;
-
-
-/************************************************************************
-** TYPES: PROffset32, PROffset64
-** DESCRIPTION:
-** A type for representing byte offsets from some location.
-************************************************************************/
-typedef PRInt32 PROffset32;
-typedef PRInt64 PROffset64;
-
-/************************************************************************
-** TYPES: PRPtrDiff
-** DESCRIPTION:
-** A type for pointer difference. Variables of this type are suitable
-** for storing a pointer or pointer subtraction.
-************************************************************************/
-typedef ptrdiff_t PRPtrdiff;
-
-/************************************************************************
-** TYPES: PRUptrdiff
-** DESCRIPTION:
-** A type for pointer difference. Variables of this type are suitable
-** for storing a pointer or pointer sutraction.
-************************************************************************/
-#ifdef _WIN64
-typedef PRUint64 PRUptrdiff;
-#else
-typedef unsigned long PRUptrdiff;
-#endif
-
-/************************************************************************
-** TYPES: PRBool
-** DESCRIPTION:
-** Use PRBool for variables and parameter types. Use PR_FALSE and PR_TRUE
-** for clarity of target type in assignments and actual arguments. Use
-** 'if (bool)', 'while (!bool)', '(bool) ? x : y' etc., to test booleans
-** just as you would C int-valued conditions.
-************************************************************************/
-typedef PRIntn PRBool;
-#define PR_TRUE 1
-#define PR_FALSE 0
-
-/************************************************************************
-** TYPES: PRPackedBool
-** DESCRIPTION:
-** Use PRPackedBool within structs where bitfields are not desirable
-** but minimum and consistant overhead matters.
-************************************************************************/
-typedef PRUint8 PRPackedBool;
-
-/*
-** Status code used by some routines that have a single point of failure or
-** special status return.
-*/
-typedef enum { PR_FAILURE = -1, PR_SUCCESS = 0 } PRStatus;
-
-#ifndef __PRUNICHAR__
-#define __PRUNICHAR__
-#ifdef WIN32
-typedef wchar_t PRUnichar;
-#else
-typedef PRUint16 PRUnichar;
-#endif
-#endif
-
-/*
-** WARNING: The undocumented data types PRWord and PRUword are
-** only used in the garbage collection and arena code. Do not
-** use PRWord and PRUword in new code.
-**
-** A PRWord is an integer that is the same size as a void*.
-** It implements the notion of a "word" in the Java Virtual
-** Machine. (See Sec. 3.4 "Words", The Java Virtual Machine
-** Specification, Addison-Wesley, September 1996.
-** http://java.sun.com/docs/books/vmspec/index.html.)
-*/
-#ifdef _WIN64
-typedef PRInt64 PRWord;
-typedef PRUint64 PRUword;
-#else
-typedef long PRWord;
-typedef unsigned long PRUword;
-#endif
-
-/*
- * PR_PRETEND_NORETURN, specified at the end of a function declaration,
- * indicates that for the purposes of static analysis, this function does not
- * return. (The function definition does not need to be annotated.)
- *
- * void PR_Assert(const char *s, const char *file, PRIntn ln)
- * PR_PRETEND_NORETURN;
- *
- * Some static analyzers, like scan-build from clang, can use this information
- * to eliminate false positives. From the upstream documentation of
- * scan-build:
- * This attribute is useful for annotating assertion handlers that actually
- * can return, but for the purpose of using the analyzer we want to pretend
- * that such functions do not return.
- */
-#ifdef __clang_analyzer__
-#if __has_extension(attribute_analyzer_noreturn)
-#define PR_PRETEND_NORETURN __attribute__((analyzer_noreturn))
-#endif
-#endif
-
-#ifndef PR_PRETEND_NORETURN
-#define PR_PRETEND_NORETURN /* no support */
-#endif
-
-#if defined(NO_NSPR_10_SUPPORT)
-#else
-/********* ???????????????? FIX ME ??????????????????????????? *****/
-/********************** Some old definitions until pr=>ds transition is done ***/
-/********************** Also, we are still using NSPR 1.0. GC ******************/
-/*
-** Fundamental NSPR macros, used nearly everywhere.
-*/
-
-#define PR_PUBLIC_API PR_IMPLEMENT
-
-/*
-** Macro body brackets so that macros with compound statement definitions
-** behave syntactically more like functions when called.
-*/
-#define NSPR_BEGIN_MACRO do {
-#define NSPR_END_MACRO } while (0)
-
-/*
-** Macro shorthands for conditional C++ extern block delimiters.
-*/
-#ifdef NSPR_BEGIN_EXTERN_C
-#undef NSPR_BEGIN_EXTERN_C
-#endif
-#ifdef NSPR_END_EXTERN_C
-#undef NSPR_END_EXTERN_C
-#endif
-
-#ifdef __cplusplus
-#define NSPR_BEGIN_EXTERN_C extern "C" {
-#define NSPR_END_EXTERN_C }
-#else
-#define NSPR_BEGIN_EXTERN_C
-#define NSPR_END_EXTERN_C
-#endif
-
-#include "obsolete/protypes.h"
-
-/********* ????????????? End Fix me ?????????????????????????????? *****/
-#endif /* NO_NSPR_10_SUPPORT */
-
-/*
-** Compile-time assert. "condition" must be a constant expression.
-** The macro can be used only in places where an "extern" declaration is
-** allowed.
-*/
-#define PR_STATIC_ASSERT(condition) \
- extern void pr_static_assert(int arg[(condition) ? 1 : -1])
-
-PR_END_EXTERN_C
-
-#endif /* prtypes_h___ */
-
diff --git a/nspr/pr/include/prvrsion.h b/nspr/pr/include/prvrsion.h
deleted file mode 100755
index a8415b2..0000000
--- a/nspr/pr/include/prvrsion.h
+++ /dev/null
@@ -1,105 +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/. */
-
-
-/* author: jstewart */
-
-#if defined(_PRVERSION_H)
-#else
-#define _PRVERSION_H
-
-#include "prtypes.h"
-
-PR_BEGIN_EXTERN_C
-
-/* All components participating in the PR version protocol must expose
- * a structure and a function. The structure is defined below and named
- * according to the naming conventions outlined further below. The function
- * is called libVersionPoint and returns a pointer to this structure.
- */
-
-/* on NT, always pack the structure the same. */
-#ifdef _WIN32
-#pragma pack(push, 8)
-#endif
-
-typedef struct {
- /*
- * The first field defines which version of this structure is in use.
- * At this time, only version 2 is specified. If this value is not
- * 2, you must read no further into the structure.
- */
- PRInt32 version;
-
- /* for Version 2, this is the body format. */
- PRInt64 buildTime; /* 64 bits - usecs since midnight, 1/1/1970 */
- char * buildTimeString;/* a human readable version of the time */
-
- PRUint8 vMajor; /* Major version of this component */
- PRUint8 vMinor; /* Minor version of this component */
- PRUint8 vPatch; /* Patch level of this component */
-
- PRBool beta; /* true if this is a beta component */
- PRBool debug; /* true if this is a debug component */
- PRBool special; /* true if this component is a special build */
-
- char * filename; /* The original filename */
- char * description; /* description of this component */
- char * security; /* level of security in this component */
- char * copyright; /* The copyright for this file */
- char * comment; /* free form field for misc usage */
- char * specialString; /* the special variant for this build */
-} PRVersionDescription;
-
-/* on NT, restore the previous packing */
-#ifdef _WIN32
-#pragma pack(pop)
-#endif
-
-/*
- * All components must define an entrypoint named libVersionPoint which
- * is of type versionEntryPointType.
- *
- * For example, for a library named libfoo, we would have:
- *
- * PRVersionDescription prVersionDescription_libfoo =
- * {
- * ...
- * };
- *
- * PR_IMPLEMENT(const PRVersionDescription*) libVersionPoint(void)
- * {
- * return &prVersionDescription_libfoo;
- * }
- */
-typedef const PRVersionDescription *(*versionEntryPointType)(void);
-
-/*
- * Where you declare your libVersionPoint, do it like this:
- * PR_IMPLEMENT(const PRVersionDescription *) libVersionPoint(void) {
- * fill it in...
- * }
- */
-
-/*
- * NAMING CONVENTION FOR struct
- *
- * all components should also expose a static PRVersionDescription
- * The name of the struct should be calculated as follows:
- * Take the value of filename. (If filename is not specified, calculate
- * a short, unique string.) Convert all non-alphanumeric characters
- * to '_'. To this, prepend "PRVersionDescription_". Thus for libfoo.so,
- * the symbol name is "PRVersionDescription_libfoo_so".
- * so the file should have
- * PRVersionDescription PRVersionDescription_libfoo_so { fill it in };
- * on NT, this file should be declspec export.
- */
-
-PR_END_EXTERN_C
-
-#endif /* defined(_PRVERSION_H) */
-
-/* prvrsion.h */
-
diff --git a/nspr/pr/include/prwin16.h b/nspr/pr/include/prwin16.h
deleted file mode 100644
index 9f8d7a9..0000000
--- a/nspr/pr/include/prwin16.h
+++ /dev/null
@@ -1,164 +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/. */
-
-#ifndef prwin16_h___
-#define prwin16_h___
-
-/*
-** Condition use of this header on platform.
-*/
-#if (defined(XP_PC) && !defined(_WIN32) && !defined(XP_OS2) && defined(MOZILLA_CLIENT)) || defined(WIN16)
-#include <stdio.h>
-
-PR_BEGIN_EXTERN_C
-/*
-** Win16 stdio special case.
-** To get stdio to work for Win16, all calls to printf() and related
-** things must be called from the environment of the .EXE; calls to
-** printf() from the .DLL send output to the bit-bucket.
-**
-** To make sure that PR_fprintf(), and related functions, work correctly,
-** the actual stream I/O to stdout, stderr, stdin must be done in the
-** .EXE. To do this, a hack is placed in _MD_Write() such that the
-** fd for stdio handles results in a call to the .EXE.
-**
-** file w16stdio.c contains the functions that get called from NSPR
-** to do the actual I/O. w16stdio.o must be statically linked with
-** any application needing stdio for Win16.
-**
-** The address of these functions must be made available to the .DLL
-** so he can call back to the .EXE. To do this, function
-** PR_MD_RegisterW16StdioCallbacks() is called from the .EXE.
-** The arguments are the functions defined in w16stdio.c
-** At runtime, MD_Write() calls the registered functions, if any
-** were registered.
-**
-** prinit.h contains a macro PR_STDIO_INIT() that calls the registration
-** function for Win16; For other platforms, the macro is a No-Op.
-**
-** Note that stdio is not operational at all on Win16 GUI applications.
-** This special case exists to provide stdio capability from the NSPR
-** .DLL for command line applications only. NSPR's test cases are
-** almost exclusively command line applications.
-**
-** See also: w16io.c, w16stdio.c
-*/
-typedef PRInt32 (PR_CALLBACK *PRStdinRead)( void *buf, PRInt32 amount);
-typedef PRInt32 (PR_CALLBACK *PRStdoutWrite)( void *buf, PRInt32 amount);
-typedef PRInt32 (PR_CALLBACK *PRStderrWrite)( void *buf, PRInt32 amount);
-
-NSPR_API(PRStatus)
-PR_MD_RegisterW16StdioCallbacks(
- PRStdinRead inReadf, /* i: function pointer for stdin read */
- PRStdoutWrite outWritef, /* i: function pointer for stdout write */
- PRStderrWrite errWritef /* i: function pointer for stderr write */
- );
-
-NSPR_API(PRInt32)
-_PL_W16StdioWrite( void *buf, PRInt32 amount );
-
-NSPR_API(PRInt32)
-_PL_W16StdioRead( void *buf, PRInt32 amount );
-
-#define PR_STDIO_INIT() PR_MD_RegisterW16StdioCallbacks( \
- _PL_W16StdioRead, _PL_W16StdioWrite, _PL_W16StdioWrite ); \
- PR_INIT_CALLBACKS();
-
-/*
-** Win16 hackery.
-**
-*/
-struct PRMethodCallbackStr {
- int (PR_CALLBACK *auxOutput)(const char *outputString);
- size_t (PR_CALLBACK *strftime)(char *s, size_t len, const char *fmt, const struct tm *p);
- void * (PR_CALLBACK *malloc)( size_t size );
- void * (PR_CALLBACK *calloc)(size_t n, size_t size );
- void * (PR_CALLBACK *realloc)( void* old_blk, size_t size );
- void (PR_CALLBACK *free)( void *ptr );
- void * (PR_CALLBACK *getenv)( const char *name);
- int (PR_CALLBACK *putenv)( const char *assoc);
-/* void * (PR_CALLBACK *perror)( const char *prefix ); */
-};
-
-NSPR_API(void) PR_MDRegisterCallbacks(struct PRMethodCallbackStr *);
-
-int PR_CALLBACK _PL_W16CallBackPuts( const char *outputString );
-size_t PR_CALLBACK _PL_W16CallBackStrftime(
- char *s,
- size_t len,
- const char *fmt,
- const struct tm *p );
-void * PR_CALLBACK _PL_W16CallBackMalloc( size_t size );
-void * PR_CALLBACK _PL_W16CallBackCalloc( size_t n, size_t size );
-void * PR_CALLBACK _PL_W16CallBackRealloc(
- void *old_blk,
- size_t size );
-void PR_CALLBACK _PL_W16CallBackFree( void *ptr );
-void * PR_CALLBACK _PL_W16CallBackGetenv( const char *name );
-int PR_CALLBACK _PL_W16CallBackPutenv( const char *assoc );
-
-/*
-** Hackery!
-**
-** These functions are provided as static link points.
-** This is to satisfy the quick port of Gromit to NSPR 2.0
-** ... Don't do this! ... alas, It may never go away.
-**
-*/
-NSPR_API(int) PR_MD_printf(const char *, ...);
-NSPR_API(void) PR_MD_exit(int);
-NSPR_API(size_t) PR_MD_strftime(char *, size_t, const char *, const struct tm *);
-NSPR_API(int) PR_MD_sscanf(const char *, const char *, ...);
-NSPR_API(void*) PR_MD_malloc( size_t size );
-NSPR_API(void*) PR_MD_calloc( size_t n, size_t size );
-NSPR_API(void*) PR_MD_realloc( void* old_blk, size_t size );
-NSPR_API(void) PR_MD_free( void *ptr );
-NSPR_API(char*) PR_MD_getenv( const char *name );
-NSPR_API(int) PR_MD_putenv( const char *assoc );
-NSPR_API(int) PR_MD_fprintf(FILE *fPtr, const char *fmt, ...);
-
-#define PR_INIT_CALLBACKS() \
- { \
- static struct PRMethodCallbackStr cbf = { \
- _PL_W16CallBackPuts, \
- _PL_W16CallBackStrftime, \
- _PL_W16CallBackMalloc, \
- _PL_W16CallBackCalloc, \
- _PL_W16CallBackRealloc, \
- _PL_W16CallBackFree, \
- _PL_W16CallBackGetenv, \
- _PL_W16CallBackPutenv, \
- }; \
- PR_MDRegisterCallbacks( &cbf ); \
- }
-
-
-/*
-** Get the exception context for Win16 MFC applications threads
-*/
-NSPR_API(void *) PR_W16GetExceptionContext(void);
-/*
-** Set the exception context for Win16 MFC applications threads
-*/
-NSPR_API(void) PR_W16SetExceptionContext(void *context);
-
-PR_END_EXTERN_C
-#else
-/*
-** For platforms other than Win16, define
-** PR_STDIO_INIT() as a No-Op.
-*/
-#define PR_STDIO_INIT()
-#endif /* WIN16 || MOZILLA_CLIENT */
-
-#endif /* prwin16_h___ */
-
-
-
-
-
-
-
-
diff --git a/nspr/pr/src/io/prdir.c b/nspr/pr/src/io/prdir.c
deleted file mode 100644
index 3701a6a..0000000
--- a/nspr/pr/src/io/prdir.c
+++ /dev/null
@@ -1,131 +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/. */
-
-#include "primpl.h"
-
-PR_IMPLEMENT(PRDir*) PR_OpenDir(const char *name)
-{
- PRDir *dir;
- PRStatus sts;
-
- dir = PR_NEW(PRDir);
- if (dir) {
- sts = _PR_MD_OPEN_DIR(&dir->md,name);
- if (sts != PR_SUCCESS) {
- PR_DELETE(dir);
- return NULL;
- }
- } else {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- }
- return dir;
-}
-
-PR_IMPLEMENT(PRDirEntry*) PR_ReadDir(PRDir *dir, PRDirFlags flags)
-{
- /* _MD_READ_DIR return a char* to the name; allocation in machine-dependent code */
- char* name = _PR_MD_READ_DIR(&dir->md, flags);
- dir->d.name = name;
- return name ? &dir->d : NULL;
-}
-
-PR_IMPLEMENT(PRStatus) PR_CloseDir(PRDir *dir)
-{
-PRInt32 rv;
-
- if (dir) {
- rv = _PR_MD_CLOSE_DIR(&dir->md);
- PR_DELETE(dir);
- if (rv < 0) {
- return PR_FAILURE;
- } else
- return PR_SUCCESS;
- }
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus) PR_MkDir(const char *name, PRIntn mode)
-{
-PRInt32 rv;
-
- rv = _PR_MD_MKDIR(name, mode);
- if (rv < 0) {
- return PR_FAILURE;
- } else
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus) PR_MakeDir(const char *name, PRIntn mode)
-{
-PRInt32 rv;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- rv = _PR_MD_MAKE_DIR(name, mode);
- if (rv < 0) {
- return PR_FAILURE;
- } else
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus) PR_RmDir(const char *name)
-{
-PRInt32 rv;
-
- rv = _PR_MD_RMDIR(name);
- if (rv < 0) {
- return PR_FAILURE;
- } else
- return PR_SUCCESS;
-}
-
-#ifdef MOZ_UNICODE
-/*
- * UTF16 Interface
- */
-PR_IMPLEMENT(PRDirUTF16*) PR_OpenDirUTF16(const PRUnichar *name)
-{
- PRDirUTF16 *dir;
- PRStatus sts;
-
- dir = PR_NEW(PRDirUTF16);
- if (dir) {
- sts = _PR_MD_OPEN_DIR_UTF16(&dir->md,name);
- if (sts != PR_SUCCESS) {
- PR_DELETE(dir);
- return NULL;
- }
- } else {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- }
- return dir;
-}
-
-PR_IMPLEMENT(PRDirEntryUTF16*) PR_ReadDirUTF16(PRDirUTF16 *dir, PRDirFlags flags)
-{
- /*
- * _MD_READ_DIR_UTF16 return a PRUnichar* to the name; allocation in
- * machine-dependent code
- */
- PRUnichar* name = _PR_MD_READ_DIR_UTF16(&dir->md, flags);
- dir->d.name = name;
- return name ? &dir->d : NULL;
-}
-
-PR_IMPLEMENT(PRStatus) PR_CloseDirUTF16(PRDirUTF16 *dir)
-{
- PRInt32 rv;
-
- if (dir) {
- rv = _PR_MD_CLOSE_DIR_UTF16(&dir->md);
- PR_DELETE(dir);
- if (rv < 0)
- return PR_FAILURE;
- else
- return PR_SUCCESS;
- }
- return PR_SUCCESS;
-}
-
-#endif /* MOZ_UNICODE */
diff --git a/nspr/pr/src/io/prfdcach.c b/nspr/pr/src/io/prfdcach.c
deleted file mode 100644
index 17b71fe..0000000
--- a/nspr/pr/src/io/prfdcach.c
+++ /dev/null
@@ -1,230 +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/. */
-
-#include "primpl.h"
-
-#include <string.h>
-
-/*****************************************************************************/
-/*****************************************************************************/
-/************************** File descriptor caching **************************/
-/*****************************************************************************/
-/*****************************************************************************/
-
-/*
-** This code is built into debuggable versions of NSPR to assist in
-** finding misused file descriptors. Since file descritors (PRFileDesc)
-** are identified by a pointer to their structure, they can be the
-** target of dangling references. Furthermore, NSPR caches and tries
-** to aggressively reuse file descriptors, leading to more ambiguity.
-** The following code will allow a debugging client to set environment
-** variables and control the number of file descriptors that will be
-** preserved before they are recycled. The environment variables are
-** NSPR_FD_CACHE_SIZE_LOW and NSPR_FD_CACHE_SIZE_HIGH. The former sets
-** the number of descriptors NSPR will allocate before beginning to
-** recycle. The latter is the maximum number permitted in the cache
-** (exclusive of those in use) at a time.
-*/
-typedef struct _PR_Fd_Cache
-{
- PRLock *ml;
- PRIntn count;
- PRFileDesc *head, *tail;
- PRIntn limit_low, limit_high;
-} _PR_Fd_Cache;
-
-static _PR_Fd_Cache _pr_fd_cache;
-
-
-/*
-** Get a FileDescriptor from the cache if one exists. If not allocate
-** a new one from the heap.
-*/
-PRFileDesc *_PR_Getfd(void)
-{
- PRFileDesc *fd;
- /*
- ** $$$
- ** This may look a little wasteful. We'll see. Right now I want to
- ** be able to toggle between caching and not at runtime to measure
- ** the differences. If it isn't too annoying, I'll leave it in.
- ** $$$$
- **
- ** The test is against _pr_fd_cache.limit_high. If that's zero,
- ** we're not doing the extended cache but going for performance.
- */
- if (0 == _pr_fd_cache.limit_high)
- {
- goto allocate;
- }
- else
- {
- do
- {
- if (NULL == _pr_fd_cache.head) goto allocate; /* nothing there */
- if (_pr_fd_cache.count < _pr_fd_cache.limit_low) goto allocate;
-
- /* we "should" be able to extract an fd from the cache */
- PR_Lock(_pr_fd_cache.ml); /* need the lock to do this safely */
- fd = _pr_fd_cache.head; /* protected extraction */
- if (NULL == fd) /* unexpected, but not fatal */
- {
- PR_ASSERT(0 == _pr_fd_cache.count);
- PR_ASSERT(NULL == _pr_fd_cache.tail);
- }
- else
- {
- _pr_fd_cache.count -= 1;
- _pr_fd_cache.head = fd->higher;
- if (NULL == _pr_fd_cache.head)
- {
- PR_ASSERT(0 == _pr_fd_cache.count);
- _pr_fd_cache.tail = NULL;
- }
- PR_ASSERT(&_pr_faulty_methods == fd->methods);
- PR_ASSERT(PR_INVALID_IO_LAYER == fd->identity);
- PR_ASSERT(_PR_FILEDESC_FREED == fd->secret->state);
- }
- PR_Unlock(_pr_fd_cache.ml);
-
- } while (NULL == fd); /* then go around and allocate a new one */
- }
-
-finished:
- fd->dtor = NULL;
- fd->lower = fd->higher = NULL;
- fd->identity = PR_NSPR_IO_LAYER;
- memset(fd->secret, 0, sizeof(PRFilePrivate));
- return fd;
-
-allocate:
- fd = PR_NEW(PRFileDesc);
- if (NULL != fd)
- {
- fd->secret = PR_NEW(PRFilePrivate);
- if (NULL == fd->secret) PR_DELETE(fd);
- }
- if (NULL != fd) goto finished;
- else return NULL;
-
-} /* _PR_Getfd */
-
-/*
-** Return a file descriptor to the cache unless there are too many in
-** there already. If put in cache, clear the fields first.
-*/
-void _PR_Putfd(PRFileDesc *fd)
-{
- PR_ASSERT(PR_NSPR_IO_LAYER == fd->identity);
- fd->methods = &_pr_faulty_methods;
- fd->identity = PR_INVALID_IO_LAYER;
- fd->secret->state = _PR_FILEDESC_FREED;
-
- if (0 != _pr_fd_cache.limit_high)
- {
- if (_pr_fd_cache.count < _pr_fd_cache.limit_high)
- {
- PR_Lock(_pr_fd_cache.ml);
- if (NULL == _pr_fd_cache.tail)
- {
- PR_ASSERT(0 == _pr_fd_cache.count);
- PR_ASSERT(NULL == _pr_fd_cache.head);
- _pr_fd_cache.head = _pr_fd_cache.tail = fd;
- }
- else
- {
- PR_ASSERT(NULL == _pr_fd_cache.tail->higher);
- _pr_fd_cache.tail->higher = fd;
- _pr_fd_cache.tail = fd; /* new value */
- }
- fd->higher = NULL; /* always so */
- _pr_fd_cache.count += 1; /* count the new entry */
- PR_Unlock(_pr_fd_cache.ml);
- return;
- }
- }
-
- PR_Free(fd->secret);
- PR_Free(fd);
-} /* _PR_Putfd */
-
-PR_IMPLEMENT(PRStatus) PR_SetFDCacheSize(PRIntn low, PRIntn high)
-{
- /*
- ** This can be called at any time, may adjust the cache sizes,
- ** turn the caches off, or turn them on. It is not dependent
- ** on the compilation setting of DEBUG.
- */
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (low > high) low = high; /* sanity check the params */
-
- PR_Lock(_pr_fd_cache.ml);
- _pr_fd_cache.limit_high = high;
- _pr_fd_cache.limit_low = low;
- PR_Unlock(_pr_fd_cache.ml);
- return PR_SUCCESS;
-} /* PR_SetFDCacheSize */
-
-void _PR_InitFdCache(void)
-{
- /*
- ** The fd caching is enabled by default for DEBUG builds,
- ** disabled by default for OPT builds. That default can
- ** be overridden at runtime using environment variables
- ** or a super-wiz-bang API.
- */
- const char *low = PR_GetEnv("NSPR_FD_CACHE_SIZE_LOW");
- const char *high = PR_GetEnv("NSPR_FD_CACHE_SIZE_HIGH");
-
- /*
- ** _low is allowed to be zero, _high is not.
- ** If _high is zero, we're not doing the caching.
- */
-
- _pr_fd_cache.limit_low = 0;
-#if defined(DEBUG)
- _pr_fd_cache.limit_high = FD_SETSIZE;
-#else
- _pr_fd_cache.limit_high = 0;
-#endif /* defined(DEBUG) */
-
- if (NULL != low) _pr_fd_cache.limit_low = atoi(low);
- if (NULL != high) _pr_fd_cache.limit_high = atoi(high);
-
- if (_pr_fd_cache.limit_low < 0)
- _pr_fd_cache.limit_low = 0;
- if (_pr_fd_cache.limit_low > FD_SETSIZE)
- _pr_fd_cache.limit_low = FD_SETSIZE;
-
- if (_pr_fd_cache.limit_high > FD_SETSIZE)
- _pr_fd_cache.limit_high = FD_SETSIZE;
-
- if (_pr_fd_cache.limit_high < _pr_fd_cache.limit_low)
- _pr_fd_cache.limit_high = _pr_fd_cache.limit_low;
-
- _pr_fd_cache.ml = PR_NewLock();
- PR_ASSERT(NULL != _pr_fd_cache.ml);
-
-} /* _PR_InitFdCache */
-
-void _PR_CleanupFdCache(void)
-{
- PRFileDesc *fd, *next;
-
- for (fd = _pr_fd_cache.head; fd != NULL; fd = next)
- {
- next = fd->higher;
- PR_DELETE(fd->secret);
- PR_DELETE(fd);
- }
- _pr_fd_cache.head = NULL;
- _pr_fd_cache.tail = NULL;
- _pr_fd_cache.count = 0;
- PR_DestroyLock(_pr_fd_cache.ml);
- _pr_fd_cache.ml = NULL;
-} /* _PR_CleanupFdCache */
-
-/* prfdcach.c */
diff --git a/nspr/pr/src/io/prfile.c b/nspr/pr/src/io/prfile.c
deleted file mode 100644
index e32031b..0000000
--- a/nspr/pr/src/io/prfile.c
+++ /dev/null
@@ -1,783 +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/. */
-
-#include "primpl.h"
-
-#include <string.h>
-#include <fcntl.h>
-
-#ifdef XP_UNIX
-#if defined(AIX) || defined(QNX)
-/* To pick up sysconf */
-#include <unistd.h>
-#else
-/* To pick up getrlimit, setrlimit */
-#include <sys/time.h>
-#include <sys/resource.h>
-#endif
-#endif /* XP_UNIX */
-
-extern PRLock *_pr_flock_lock;
-extern PRCondVar *_pr_flock_cv;
-
-static PRInt32 PR_CALLBACK FileRead(PRFileDesc *fd, void *buf, PRInt32 amount)
-{
- PRInt32 rv = 0;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- rv = -1;
- }
- if (_PR_IO_PENDING(me)) {
- PR_SetError(PR_IO_PENDING_ERROR, 0);
- rv = -1;
- }
- if (rv == -1)
- return rv;
-
- rv = _PR_MD_READ(fd, buf, amount);
- if (rv < 0) {
- PR_ASSERT(rv == -1);
- }
- PR_LOG(_pr_io_lm, PR_LOG_MAX, ("read -> %d", rv));
- return rv;
-}
-
-static PRInt32 PR_CALLBACK FileWrite(PRFileDesc *fd, const void *buf, PRInt32 amount)
-{
- PRInt32 rv = 0;
- PRInt32 temp, count;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- rv = -1;
- }
- if (_PR_IO_PENDING(me)) {
- PR_SetError(PR_IO_PENDING_ERROR, 0);
- rv = -1;
- }
- if (rv != 0)
- return rv;
-
- count = 0;
-#if !defined(_PR_HAVE_O_APPEND) /* Bugzilla: 4090, 276330 */
- if (fd->secret->appendMode) {
- if (PR_Seek64(fd, 0, PR_SEEK_END) == -1) {
- return -1;
- }
- } /* if (fd->secret->appendMode...) */
-#endif /* _PR_HAVE_O_APPEND */
- while (amount > 0) {
- temp = _PR_MD_WRITE(fd, buf, amount);
- if (temp < 0) {
- count = -1;
- break;
- }
- count += temp;
- if (fd->secret->nonblocking) {
- break;
- }
- buf = (const void*) ((const char*)buf + temp);
- amount -= temp;
- }
- PR_LOG(_pr_io_lm, PR_LOG_MAX, ("write -> %d", count));
- return count;
-}
-
-static PROffset32 PR_CALLBACK FileSeek(PRFileDesc *fd, PROffset32 offset, PRSeekWhence whence)
-{
- PROffset32 result;
-
- result = _PR_MD_LSEEK(fd, offset, whence);
- return result;
-}
-
-static PROffset64 PR_CALLBACK FileSeek64(PRFileDesc *fd, PROffset64 offset, PRSeekWhence whence)
-{
- PROffset64 result;
-
- result = _PR_MD_LSEEK64(fd, offset, whence);
- return result;
-}
-
-static PRInt32 PR_CALLBACK FileAvailable(PRFileDesc *fd)
-{
- PRInt32 result, cur, end;
-
- cur = _PR_MD_LSEEK(fd, 0, PR_SEEK_CUR);
-
- if (cur >= 0)
- end = _PR_MD_LSEEK(fd, 0, PR_SEEK_END);
-
- if ((cur < 0) || (end < 0)) {
- return -1;
- }
-
- result = end - cur;
- _PR_MD_LSEEK(fd, cur, PR_SEEK_SET);
-
- return result;
-}
-
-static PRInt64 PR_CALLBACK FileAvailable64(PRFileDesc *fd)
-{
- PRInt64 result, cur, end;
- PRInt64 minus_one;
-
- LL_I2L(minus_one, -1);
- cur = _PR_MD_LSEEK64(fd, LL_ZERO, PR_SEEK_CUR);
-
- if (LL_GE_ZERO(cur))
- end = _PR_MD_LSEEK64(fd, LL_ZERO, PR_SEEK_END);
-
- if (!LL_GE_ZERO(cur) || !LL_GE_ZERO(end)) return minus_one;
-
- LL_SUB(result, end, cur);
- (void)_PR_MD_LSEEK64(fd, cur, PR_SEEK_SET);
-
- return result;
-}
-
-static PRInt32 PR_CALLBACK PipeAvailable(PRFileDesc *fd)
-{
- PRInt32 rv;
- rv = _PR_MD_PIPEAVAILABLE(fd);
- return rv;
-}
-
-static PRInt64 PR_CALLBACK PipeAvailable64(PRFileDesc *fd)
-{
- PRInt64 rv;
- LL_I2L(rv, _PR_MD_PIPEAVAILABLE(fd));
- return rv;
-}
-
-static PRStatus PR_CALLBACK PipeSync(PRFileDesc *fd)
-{
- return PR_SUCCESS;
-}
-
-static PRStatus PR_CALLBACK FileGetInfo(PRFileDesc *fd, PRFileInfo *info)
-{
- PRInt32 rv;
-
- rv = _PR_MD_GETOPENFILEINFO(fd, info);
- if (rv < 0) {
- return PR_FAILURE;
- } else
- return PR_SUCCESS;
-}
-
-static PRStatus PR_CALLBACK FileGetInfo64(PRFileDesc *fd, PRFileInfo64 *info)
-{
- /* $$$$ NOT YET IMPLEMENTED */
- PRInt32 rv;
-
- rv = _PR_MD_GETOPENFILEINFO64(fd, info);
- if (rv < 0) return PR_FAILURE;
- else return PR_SUCCESS;
-}
-
-static PRStatus PR_CALLBACK FileSync(PRFileDesc *fd)
-{
- PRInt32 result;
- result = _PR_MD_FSYNC(fd);
- if (result < 0) {
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-static PRStatus PR_CALLBACK FileClose(PRFileDesc *fd)
-{
- if (!fd || !fd->secret
- || (fd->secret->state != _PR_FILEDESC_OPEN
- && fd->secret->state != _PR_FILEDESC_CLOSED)) {
- PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
- return PR_FAILURE;
- }
-
- if (fd->secret->state == _PR_FILEDESC_OPEN) {
- if (_PR_MD_CLOSE_FILE(fd->secret->md.osfd) < 0) {
- return PR_FAILURE;
- }
- fd->secret->state = _PR_FILEDESC_CLOSED;
- }
- PR_FreeFileDesc(fd);
- return PR_SUCCESS;
-}
-
-static PRInt16 PR_CALLBACK FilePoll(
- PRFileDesc *fd, PRInt16 in_flags, PRInt16 *out_flags)
-{
- *out_flags = 0;
- return in_flags;
-} /* FilePoll */
-
-static PRIOMethods _pr_fileMethods = {
- PR_DESC_FILE,
- FileClose,
- FileRead,
- FileWrite,
- FileAvailable,
- FileAvailable64,
- FileSync,
- FileSeek,
- FileSeek64,
- FileGetInfo,
- FileGetInfo64,
- (PRWritevFN)_PR_InvalidInt,
- (PRConnectFN)_PR_InvalidStatus,
- (PRAcceptFN)_PR_InvalidDesc,
- (PRBindFN)_PR_InvalidStatus,
- (PRListenFN)_PR_InvalidStatus,
- (PRShutdownFN)_PR_InvalidStatus,
- (PRRecvFN)_PR_InvalidInt,
- (PRSendFN)_PR_InvalidInt,
- (PRRecvfromFN)_PR_InvalidInt,
- (PRSendtoFN)_PR_InvalidInt,
- FilePoll,
- (PRAcceptreadFN)_PR_InvalidInt,
- (PRTransmitfileFN)_PR_InvalidInt,
- (PRGetsocknameFN)_PR_InvalidStatus,
- (PRGetpeernameFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRGetsocketoptionFN)_PR_InvalidStatus,
- (PRSetsocketoptionFN)_PR_InvalidStatus,
- (PRSendfileFN)_PR_InvalidInt,
- (PRConnectcontinueFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt
-};
-
-PR_IMPLEMENT(const PRIOMethods*) PR_GetFileMethods(void)
-{
- return &_pr_fileMethods;
-}
-
-static PRIOMethods _pr_pipeMethods = {
- PR_DESC_PIPE,
- FileClose,
- FileRead,
- FileWrite,
- PipeAvailable,
- PipeAvailable64,
- PipeSync,
- (PRSeekFN)_PR_InvalidInt,
- (PRSeek64FN)_PR_InvalidInt64,
- (PRFileInfoFN)_PR_InvalidStatus,
- (PRFileInfo64FN)_PR_InvalidStatus,
- (PRWritevFN)_PR_InvalidInt,
- (PRConnectFN)_PR_InvalidStatus,
- (PRAcceptFN)_PR_InvalidDesc,
- (PRBindFN)_PR_InvalidStatus,
- (PRListenFN)_PR_InvalidStatus,
- (PRShutdownFN)_PR_InvalidStatus,
- (PRRecvFN)_PR_InvalidInt,
- (PRSendFN)_PR_InvalidInt,
- (PRRecvfromFN)_PR_InvalidInt,
- (PRSendtoFN)_PR_InvalidInt,
- FilePoll,
- (PRAcceptreadFN)_PR_InvalidInt,
- (PRTransmitfileFN)_PR_InvalidInt,
- (PRGetsocknameFN)_PR_InvalidStatus,
- (PRGetpeernameFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRGetsocketoptionFN)_PR_InvalidStatus,
- (PRSetsocketoptionFN)_PR_InvalidStatus,
- (PRSendfileFN)_PR_InvalidInt,
- (PRConnectcontinueFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt
-};
-
-PR_IMPLEMENT(const PRIOMethods*) PR_GetPipeMethods(void)
-{
- return &_pr_pipeMethods;
-}
-
-PR_IMPLEMENT(PRFileDesc*) PR_Open(const char *name, PRIntn flags, PRIntn mode)
-{
- PROsfd osfd;
- PRFileDesc *fd = 0;
-#if !defined(_PR_HAVE_O_APPEND)
- PRBool appendMode = ( PR_APPEND & flags )? PR_TRUE : PR_FALSE;
-#endif
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- /* Map pr open flags and mode to os specific flags */
-
- osfd = _PR_MD_OPEN(name, flags, mode);
- if (osfd != -1) {
- fd = PR_AllocFileDesc(osfd, &_pr_fileMethods);
- if (!fd) {
- (void) _PR_MD_CLOSE_FILE(osfd);
- } else {
-#if !defined(_PR_HAVE_O_APPEND)
- fd->secret->appendMode = appendMode;
-#endif
- _PR_MD_INIT_FD_INHERITABLE(fd, PR_FALSE);
- }
- }
- return fd;
-}
-
-PR_IMPLEMENT(PRFileDesc*) PR_OpenFile(
- const char *name, PRIntn flags, PRIntn mode)
-{
- PROsfd osfd;
- PRFileDesc *fd = 0;
-#if !defined(_PR_HAVE_O_APPEND)
- PRBool appendMode = ( PR_APPEND & flags )? PR_TRUE : PR_FALSE;
-#endif
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- /* Map pr open flags and mode to os specific flags */
-
- osfd = _PR_MD_OPEN_FILE(name, flags, mode);
- if (osfd != -1) {
- fd = PR_AllocFileDesc(osfd, &_pr_fileMethods);
- if (!fd) {
- (void) _PR_MD_CLOSE_FILE(osfd);
- } else {
-#if !defined(_PR_HAVE_O_APPEND)
- fd->secret->appendMode = appendMode;
-#endif
- _PR_MD_INIT_FD_INHERITABLE(fd, PR_FALSE);
- }
- }
- return fd;
-}
-
-PR_IMPLEMENT(PRInt32) PR_GetSysfdTableMax(void)
-{
-#if defined(XP_UNIX) && !defined(AIX) && !defined(QNX)
- struct rlimit rlim;
-
- if ( getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
- /* XXX need to call PR_SetError() */
- return -1;
- }
-
- return rlim.rlim_max;
-#elif defined(AIX) || defined(QNX)
- return sysconf(_SC_OPEN_MAX);
-#elif defined(WIN32)
- /*
- * There is a systemwide limit of 65536 user handles.
- */
- return 16384;
-#elif defined (WIN16)
- return FOPEN_MAX;
-#elif defined(XP_OS2)
- ULONG ulReqCount = 0;
- ULONG ulCurMaxFH = 0;
- DosSetRelMaxFH(&ulReqCount, &ulCurMaxFH);
- return ulCurMaxFH;
-#elif defined(XP_BEOS)
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return -1;
-#else
- write me;
-#endif
-}
-
-PR_IMPLEMENT(PRInt32) PR_SetSysfdTableSize(int table_size)
-{
-#if defined(XP_UNIX) && !defined(AIX) && !defined(QNX)
- struct rlimit rlim;
- PRInt32 tableMax = PR_GetSysfdTableMax();
-
- if (tableMax < 0)
- return -1;
-
- if (tableMax > FD_SETSIZE)
- tableMax = FD_SETSIZE;
-
- rlim.rlim_max = tableMax;
-
- /* Grow as much as we can; even if too big */
- if ( rlim.rlim_max < table_size )
- rlim.rlim_cur = rlim.rlim_max;
- else
- rlim.rlim_cur = table_size;
-
- if ( setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
- /* XXX need to call PR_SetError() */
- return -1;
- }
-
- return rlim.rlim_cur;
-#elif defined(XP_OS2)
- PRInt32 tableMax = PR_GetSysfdTableMax();
- if (table_size > tableMax) {
- APIRET rc = NO_ERROR;
- rc = DosSetMaxFH(table_size);
- if (rc == NO_ERROR)
- return table_size;
- else
- return -1;
- }
- return tableMax;
-#elif defined(AIX) || defined(QNX) \
- || defined(WIN32) || defined(WIN16) || defined(XP_BEOS)
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return -1;
-#else
- write me;
-#endif
-}
-
-PR_IMPLEMENT(PRStatus) PR_Delete(const char *name)
-{
- PRInt32 rv;
-
- rv = _PR_MD_DELETE(name);
- if (rv < 0) {
- return PR_FAILURE;
- } else
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus) PR_GetFileInfo(const char *fn, PRFileInfo *info)
-{
- PRInt32 rv;
-
- rv = _PR_MD_GETFILEINFO(fn, info);
- if (rv < 0) {
- return PR_FAILURE;
- } else
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus) PR_GetFileInfo64(const char *fn, PRFileInfo64 *info)
-{
- PRInt32 rv;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- rv = _PR_MD_GETFILEINFO64(fn, info);
- if (rv < 0) {
- return PR_FAILURE;
- } else {
- return PR_SUCCESS;
- }
-}
-
-PR_IMPLEMENT(PRStatus) PR_Rename(const char *from, const char *to)
-{
- PRInt32 rv;
-
- rv = _PR_MD_RENAME(from, to);
- if (rv < 0) {
- return PR_FAILURE;
- } else
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus) PR_Access(const char *name, PRAccessHow how)
-{
-PRInt32 rv;
-
- rv = _PR_MD_ACCESS(name, how);
- if (rv < 0) {
- return PR_FAILURE;
- } else
- return PR_SUCCESS;
-}
-
-/*
-** Import an existing OS file to NSPR
-*/
-PR_IMPLEMENT(PRFileDesc*) PR_ImportFile(PROsfd osfd)
-{
- PRFileDesc *fd = NULL;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- fd = PR_AllocFileDesc(osfd, &_pr_fileMethods);
- if( !fd ) {
- (void) _PR_MD_CLOSE_FILE(osfd);
- } else {
- _PR_MD_INIT_FD_INHERITABLE(fd, PR_TRUE);
- }
-
- return fd;
-}
-
-/*
-** Import an existing OS pipe to NSPR
-*/
-PR_IMPLEMENT(PRFileDesc*) PR_ImportPipe(PROsfd osfd)
-{
- PRFileDesc *fd = NULL;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- fd = PR_AllocFileDesc(osfd, &_pr_pipeMethods);
- if( !fd ) {
- (void) _PR_MD_CLOSE_FILE(osfd);
- } else {
- _PR_MD_INIT_FD_INHERITABLE(fd, PR_TRUE);
-#ifdef WINNT
- fd->secret->md.sync_file_io = PR_TRUE;
-#endif
- }
-
- return fd;
-}
-
-#ifndef NO_NSPR_10_SUPPORT
-/*
-** PR_Stat() for Win16 is defined in w16io.c
-** it is a hack to circumvent problems in Gromit and Java
-** See also: BugSplat: 98516.
-*/
-#if !defined(WIN16)
-/*
- * This function is supposed to be for backward compatibility with
- * nspr 1.0. Therefore, it still uses the nspr 1.0 error-reporting
- * mechanism -- returns a PRInt32, which is the error code when the call
- * fails.
- *
- * If we need this function in nspr 2.0, it should be changed to
- * return PRStatus, as follows:
- *
- * PR_IMPLEMENT(PRStatus) PR_Stat(const char *name, struct stat *buf)
- * {
- * PRInt32 rv;
- *
- * rv = _PR_MD_STAT(name, buf);
- * if (rv < 0)
- * return PR_FAILURE;
- * else
- * return PR_SUCCESS;
- * }
- *
- * -- wtc, 2/14/97.
- */
-PR_IMPLEMENT(PRInt32) PR_Stat(const char *name, struct stat *buf)
-{
- PRInt32 rv;
-
- rv = _PR_MD_STAT(name, buf);
- return rv;
-}
-
-#endif /* !defined(WIN16) */
-#endif /* ! NO_NSPR_10_SUPPORT */
-
-PR_IMPLEMENT(PRStatus) PR_LockFile(PRFileDesc *fd)
-{
- PRStatus status = PR_SUCCESS;
-
-#ifdef WINNT
- if (!fd->secret->md.io_model_committed) {
- PRInt32 rv;
- rv = _md_Associate((HANDLE)fd->secret->md.osfd);
- PR_ASSERT(0 != rv);
- fd->secret->md.io_model_committed = PR_TRUE;
- }
-#endif
-
- PR_Lock(_pr_flock_lock);
- while (fd->secret->lockCount == -1)
- PR_WaitCondVar(_pr_flock_cv, PR_INTERVAL_NO_TIMEOUT);
- if (fd->secret->lockCount == 0) {
- fd->secret->lockCount = -1;
- PR_Unlock(_pr_flock_lock);
- status = _PR_MD_LOCKFILE(fd->secret->md.osfd);
- PR_Lock(_pr_flock_lock);
- fd->secret->lockCount = (status == PR_SUCCESS) ? 1 : 0;
- PR_NotifyAllCondVar(_pr_flock_cv);
- } else {
- fd->secret->lockCount++;
- }
- PR_Unlock(_pr_flock_lock);
-
- return status;
-}
-
-PR_IMPLEMENT(PRStatus) PR_TLockFile(PRFileDesc *fd)
-{
- PRStatus status = PR_SUCCESS;
-
-#ifdef WINNT
- if (!fd->secret->md.io_model_committed) {
- PRInt32 rv;
- rv = _md_Associate((HANDLE)fd->secret->md.osfd);
- PR_ASSERT(0 != rv);
- fd->secret->md.io_model_committed = PR_TRUE;
- }
-#endif
-
- PR_Lock(_pr_flock_lock);
- if (fd->secret->lockCount == 0) {
- status = _PR_MD_TLOCKFILE(fd->secret->md.osfd);
- PR_ASSERT(status == PR_SUCCESS || fd->secret->lockCount == 0);
- if (status == PR_SUCCESS)
- fd->secret->lockCount = 1;
- } else {
- fd->secret->lockCount++;
- }
- PR_Unlock(_pr_flock_lock);
-
- return status;
-}
-
-PR_IMPLEMENT(PRStatus) PR_UnlockFile(PRFileDesc *fd)
-{
- PRStatus rv = PR_SUCCESS;
-
- PR_Lock(_pr_flock_lock);
- if (fd->secret->lockCount == 1) {
- rv = _PR_MD_UNLOCKFILE(fd->secret->md.osfd);
- if (rv == PR_SUCCESS)
- fd->secret->lockCount = 0;
- } else {
- fd->secret->lockCount--;
- }
- PR_Unlock(_pr_flock_lock);
-
- return rv;
-}
-
-PR_IMPLEMENT(PRStatus) PR_CreatePipe(
- PRFileDesc **readPipe,
- PRFileDesc **writePipe
-)
-{
-#if defined(WIN32) && !defined(WINCE)
- HANDLE readEnd, writeEnd;
- SECURITY_ATTRIBUTES pipeAttributes;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- ZeroMemory(&pipeAttributes, sizeof(pipeAttributes));
- pipeAttributes.nLength = sizeof(pipeAttributes);
- pipeAttributes.bInheritHandle = TRUE;
- if (CreatePipe(&readEnd, &writeEnd, &pipeAttributes, 0) == 0) {
- PR_SetError(PR_UNKNOWN_ERROR, GetLastError());
- return PR_FAILURE;
- }
- *readPipe = PR_AllocFileDesc((PROsfd)readEnd, &_pr_pipeMethods);
- if (NULL == *readPipe) {
- CloseHandle(readEnd);
- CloseHandle(writeEnd);
- return PR_FAILURE;
- }
- *writePipe = PR_AllocFileDesc((PROsfd)writeEnd, &_pr_pipeMethods);
- if (NULL == *writePipe) {
- PR_Close(*readPipe);
- CloseHandle(writeEnd);
- return PR_FAILURE;
- }
-#ifdef WINNT
- (*readPipe)->secret->md.sync_file_io = PR_TRUE;
- (*writePipe)->secret->md.sync_file_io = PR_TRUE;
-#endif
- (*readPipe)->secret->inheritable = _PR_TRI_TRUE;
- (*writePipe)->secret->inheritable = _PR_TRI_TRUE;
- return PR_SUCCESS;
-#elif defined(XP_UNIX) || defined(XP_OS2) || defined(XP_BEOS)
-#ifdef XP_OS2
- HFILE pipefd[2];
-#else
- int pipefd[2];
-#endif
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
-#ifdef XP_OS2
- if (DosCreatePipe(&pipefd[0], &pipefd[1], 4096) != 0) {
-#else
- if (pipe(pipefd) == -1) {
-#endif
- /* XXX map pipe error */
- PR_SetError(PR_UNKNOWN_ERROR, errno);
- return PR_FAILURE;
- }
- *readPipe = PR_AllocFileDesc(pipefd[0], &_pr_pipeMethods);
- if (NULL == *readPipe) {
- close(pipefd[0]);
- close(pipefd[1]);
- return PR_FAILURE;
- }
- *writePipe = PR_AllocFileDesc(pipefd[1], &_pr_pipeMethods);
- if (NULL == *writePipe) {
- PR_Close(*readPipe);
- close(pipefd[1]);
- return PR_FAILURE;
- }
-#ifndef XP_BEOS /* Pipes are nonblocking on BeOS */
- _PR_MD_MAKE_NONBLOCK(*readPipe);
-#endif
- _PR_MD_INIT_FD_INHERITABLE(*readPipe, PR_FALSE);
-#ifndef XP_BEOS /* Pipes are nonblocking on BeOS */
- _PR_MD_MAKE_NONBLOCK(*writePipe);
-#endif
- _PR_MD_INIT_FD_INHERITABLE(*writePipe, PR_FALSE);
- return PR_SUCCESS;
-#else
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-#endif
-}
-
-#ifdef MOZ_UNICODE
-/* ================ UTF16 Interfaces ================================ */
-PR_IMPLEMENT(PRFileDesc*) PR_OpenFileUTF16(
- const PRUnichar *name, PRIntn flags, PRIntn mode)
-{
- PROsfd osfd;
- PRFileDesc *fd = 0;
-#if !defined(_PR_HAVE_O_APPEND)
- PRBool appendMode = ( PR_APPEND & flags )? PR_TRUE : PR_FALSE;
-#endif
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- /* Map pr open flags and mode to os specific flags */
- osfd = _PR_MD_OPEN_FILE_UTF16(name, flags, mode);
- if (osfd != -1) {
- fd = PR_AllocFileDesc(osfd, &_pr_fileMethods);
- if (!fd) {
- (void) _PR_MD_CLOSE_FILE(osfd);
- } else {
-#if !defined(_PR_HAVE_O_APPEND)
- fd->secret->appendMode = appendMode;
-#endif
- _PR_MD_INIT_FD_INHERITABLE(fd, PR_FALSE);
- }
- }
- return fd;
-}
-
-PR_IMPLEMENT(PRStatus) PR_GetFileInfo64UTF16(const PRUnichar *fn, PRFileInfo64 *info)
-{
- PRInt32 rv;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- rv = _PR_MD_GETFILEINFO64_UTF16(fn, info);
- if (rv < 0) {
- return PR_FAILURE;
- } else {
- return PR_SUCCESS;
- }
-}
-
-/* ================ UTF16 Interfaces ================================ */
-#endif /* MOZ_UNICODE */
diff --git a/nspr/pr/src/io/prio.c b/nspr/pr/src/io/prio.c
deleted file mode 100644
index f69927f..0000000
--- a/nspr/pr/src/io/prio.c
+++ /dev/null
@@ -1,178 +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/. */
-
-#include "primpl.h"
-
-#include <string.h> /* for memset() */
-
-
-/************************************************************************/
-
-PRLock *_pr_flock_lock;
-PRCondVar *_pr_flock_cv;
-
-#ifdef WINCE
-/*
- * There are no stdin, stdout, stderr in Windows CE. INVALID_HANDLE_VALUE
- * should cause all I/O functions on the handle to fail.
- */
-#define STD_INPUT_HANDLE ((DWORD)-10)
-#define STD_OUTPUT_HANDLE ((DWORD)-11)
-#define STD_ERROR_HANDLE ((DWORD)-12)
-
-static HANDLE GetStdHandle(DWORD nStdHandle)
-{
- SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
- return INVALID_HANDLE_VALUE;
-}
-#endif
-
-void _PR_InitIO(void)
-{
- const PRIOMethods *methods = PR_GetFileMethods();
-
- _PR_InitFdCache();
-
- _pr_flock_lock = PR_NewLock();
- _pr_flock_cv = PR_NewCondVar(_pr_flock_lock);
-
-#ifdef WIN32
- _pr_stdin = PR_AllocFileDesc((PROsfd)GetStdHandle(STD_INPUT_HANDLE),
- methods);
- _pr_stdout = PR_AllocFileDesc((PROsfd)GetStdHandle(STD_OUTPUT_HANDLE),
- methods);
- _pr_stderr = PR_AllocFileDesc((PROsfd)GetStdHandle(STD_ERROR_HANDLE),
- methods);
-#ifdef WINNT
- _pr_stdin->secret->md.sync_file_io = PR_TRUE;
- _pr_stdout->secret->md.sync_file_io = PR_TRUE;
- _pr_stderr->secret->md.sync_file_io = PR_TRUE;
-#endif
-#else
- _pr_stdin = PR_AllocFileDesc(0, methods);
- _pr_stdout = PR_AllocFileDesc(1, methods);
- _pr_stderr = PR_AllocFileDesc(2, methods);
-#endif
- _PR_MD_INIT_FD_INHERITABLE(_pr_stdin, PR_TRUE);
- _PR_MD_INIT_FD_INHERITABLE(_pr_stdout, PR_TRUE);
- _PR_MD_INIT_FD_INHERITABLE(_pr_stderr, PR_TRUE);
-}
-
-void _PR_CleanupIO(void)
-{
- PR_FreeFileDesc(_pr_stdin);
- _pr_stdin = NULL;
- PR_FreeFileDesc(_pr_stdout);
- _pr_stdout = NULL;
- PR_FreeFileDesc(_pr_stderr);
- _pr_stderr = NULL;
-
- if (_pr_flock_cv) {
- PR_DestroyCondVar(_pr_flock_cv);
- _pr_flock_cv = NULL;
- }
- if (_pr_flock_lock) {
- PR_DestroyLock(_pr_flock_lock);
- _pr_flock_lock = NULL;
- }
-
- _PR_CleanupFdCache();
-}
-
-PR_IMPLEMENT(PRFileDesc*) PR_GetSpecialFD(PRSpecialFD osfd)
-{
- PRFileDesc *result = NULL;
- PR_ASSERT((int) osfd >= PR_StandardInput && osfd <= PR_StandardError);
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- switch (osfd)
- {
- case PR_StandardInput: result = _pr_stdin; break;
- case PR_StandardOutput: result = _pr_stdout; break;
- case PR_StandardError: result = _pr_stderr; break;
- default:
- (void)PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- }
- return result;
-}
-
-PR_IMPLEMENT(PRFileDesc*) PR_AllocFileDesc(
- PROsfd osfd, const PRIOMethods *methods)
-{
- PRFileDesc *fd;
-
-#ifdef XP_UNIX
- /*
- * Assert that the file descriptor is small enough to fit in the
- * fd_set passed to select
- */
- PR_ASSERT(osfd < FD_SETSIZE);
-#endif
- fd = _PR_Getfd();
- if (fd) {
- /* Initialize the members of PRFileDesc and PRFilePrivate */
- fd->methods = methods;
- fd->secret->state = _PR_FILEDESC_OPEN;
- fd->secret->md.osfd = osfd;
- _PR_MD_INIT_FILEDESC(fd);
- } else {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- }
-
- return fd;
-}
-
-PR_IMPLEMENT(void) PR_FreeFileDesc(PRFileDesc *fd)
-{
- PR_ASSERT(fd);
- _PR_Putfd(fd);
-}
-
-/*
-** Wait for some i/o to finish on one or more more poll descriptors.
-*/
-PR_IMPLEMENT(PRInt32) PR_Poll(PRPollDesc *pds, PRIntn npds, PRIntervalTime timeout)
-{
- return(_PR_MD_PR_POLL(pds, npds, timeout));
-}
-
-/*
-** Set the inheritance attribute of a file descriptor.
-*/
-PR_IMPLEMENT(PRStatus) PR_SetFDInheritable(
- PRFileDesc *fd,
- PRBool inheritable)
-{
-#if defined(XP_UNIX) || defined(WIN32) || defined(XP_OS2) || defined(XP_BEOS)
- /*
- * Only a non-layered, NSPR file descriptor can be inherited
- * by a child process.
- */
- if (fd->identity != PR_NSPR_IO_LAYER) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
- if (fd->secret->inheritable != inheritable) {
- if (_PR_MD_SET_FD_INHERITABLE(fd, inheritable) == PR_FAILURE) {
- return PR_FAILURE;
- }
- fd->secret->inheritable = inheritable;
- }
- return PR_SUCCESS;
-#else
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-#endif
-}
-
-/*
-** This function only has a useful implementation in the debug build of
-** the pthreads version.
-*/
-PR_IMPLEMENT(void) PT_FPrintStats(PRFileDesc *debug_out, const char *msg)
-{
- /* do nothing */
-} /* PT_FPrintStats */
diff --git a/nspr/pr/src/io/priometh.c b/nspr/pr/src/io/priometh.c
deleted file mode 100644
index 4208767..0000000
--- a/nspr/pr/src/io/priometh.c
+++ /dev/null
@@ -1,596 +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/. */
-#include "primpl.h"
-
-#include <string.h>
-
-/*****************************************************************************/
-/************************** Invalid I/O method object ************************/
-/*****************************************************************************/
-PRIOMethods _pr_faulty_methods = {
- (PRDescType)0,
- (PRCloseFN)_PR_InvalidStatus,
- (PRReadFN)_PR_InvalidInt,
- (PRWriteFN)_PR_InvalidInt,
- (PRAvailableFN)_PR_InvalidInt,
- (PRAvailable64FN)_PR_InvalidInt64,
- (PRFsyncFN)_PR_InvalidStatus,
- (PRSeekFN)_PR_InvalidInt,
- (PRSeek64FN)_PR_InvalidInt64,
- (PRFileInfoFN)_PR_InvalidStatus,
- (PRFileInfo64FN)_PR_InvalidStatus,
- (PRWritevFN)_PR_InvalidInt,
- (PRConnectFN)_PR_InvalidStatus,
- (PRAcceptFN)_PR_InvalidDesc,
- (PRBindFN)_PR_InvalidStatus,
- (PRListenFN)_PR_InvalidStatus,
- (PRShutdownFN)_PR_InvalidStatus,
- (PRRecvFN)_PR_InvalidInt,
- (PRSendFN)_PR_InvalidInt,
- (PRRecvfromFN)_PR_InvalidInt,
- (PRSendtoFN)_PR_InvalidInt,
- (PRPollFN)_PR_InvalidInt16,
- (PRAcceptreadFN)_PR_InvalidInt,
- (PRTransmitfileFN)_PR_InvalidInt,
- (PRGetsocknameFN)_PR_InvalidStatus,
- (PRGetpeernameFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRGetsocketoptionFN)_PR_InvalidStatus,
- (PRSetsocketoptionFN)_PR_InvalidStatus,
- (PRSendfileFN)_PR_InvalidInt,
- (PRConnectcontinueFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt
-};
-
-PRIntn _PR_InvalidInt(void)
-{
- PR_NOT_REACHED("I/O method is invalid");
- PR_SetError(PR_INVALID_METHOD_ERROR, 0);
- return -1;
-} /* _PR_InvalidInt */
-
-PRInt16 _PR_InvalidInt16(void)
-{
- PR_NOT_REACHED("I/O method is invalid");
- PR_SetError(PR_INVALID_METHOD_ERROR, 0);
- return -1;
-} /* _PR_InvalidInt */
-
-PRInt64 _PR_InvalidInt64(void)
-{
- PRInt64 rv;
- LL_I2L(rv, -1);
- PR_NOT_REACHED("I/O method is invalid");
- PR_SetError(PR_INVALID_METHOD_ERROR, 0);
- return rv;
-} /* _PR_InvalidInt */
-
-/*
- * An invalid method that returns PRStatus
- */
-
-PRStatus _PR_InvalidStatus(void)
-{
- PR_NOT_REACHED("I/O method is invalid");
- PR_SetError(PR_INVALID_METHOD_ERROR, 0);
- return PR_FAILURE;
-} /* _PR_InvalidDesc */
-
-/*
- * An invalid method that returns a pointer
- */
-
-PRFileDesc *_PR_InvalidDesc(void)
-{
- PR_NOT_REACHED("I/O method is invalid");
- PR_SetError(PR_INVALID_METHOD_ERROR, 0);
- return NULL;
-} /* _PR_InvalidDesc */
-
-PR_IMPLEMENT(PRDescType) PR_GetDescType(PRFileDesc *file)
-{
- return file->methods->file_type;
-}
-
-PR_IMPLEMENT(PRStatus) PR_Close(PRFileDesc *fd)
-{
- return (fd->methods->close)(fd);
-}
-
-PR_IMPLEMENT(PRInt32) PR_Read(PRFileDesc *fd, void *buf, PRInt32 amount)
-{
- return((fd->methods->read)(fd,buf,amount));
-}
-
-PR_IMPLEMENT(PRInt32) PR_Write(PRFileDesc *fd, const void *buf, PRInt32 amount)
-{
- return((fd->methods->write)(fd,buf,amount));
-}
-
-PR_IMPLEMENT(PRInt32) PR_Seek(PRFileDesc *fd, PRInt32 offset, PRSeekWhence whence)
-{
- return((fd->methods->seek)(fd, offset, whence));
-}
-
-PR_IMPLEMENT(PRInt64) PR_Seek64(PRFileDesc *fd, PRInt64 offset, PRSeekWhence whence)
-{
- return((fd->methods->seek64)(fd, offset, whence));
-}
-
-PR_IMPLEMENT(PRInt32) PR_Available(PRFileDesc *fd)
-{
- return((fd->methods->available)(fd));
-}
-
-PR_IMPLEMENT(PRInt64) PR_Available64(PRFileDesc *fd)
-{
- return((fd->methods->available64)(fd));
-}
-
-PR_IMPLEMENT(PRStatus) PR_GetOpenFileInfo(PRFileDesc *fd, PRFileInfo *info)
-{
- return((fd->methods->fileInfo)(fd, info));
-}
-
-PR_IMPLEMENT(PRStatus) PR_GetOpenFileInfo64(PRFileDesc *fd, PRFileInfo64 *info)
-{
- return((fd->methods->fileInfo64)(fd, info));
-}
-
-PR_IMPLEMENT(PRStatus) PR_Sync(PRFileDesc *fd)
-{
- return((fd->methods->fsync)(fd));
-}
-
-PR_IMPLEMENT(PRStatus) PR_Connect(
- PRFileDesc *fd, const PRNetAddr *addr, PRIntervalTime timeout)
-{
- return((fd->methods->connect)(fd,addr,timeout));
-}
-
-PR_IMPLEMENT(PRStatus) PR_ConnectContinue(
- PRFileDesc *fd, PRInt16 out_flags)
-{
- return((fd->methods->connectcontinue)(fd,out_flags));
-}
-
-PR_IMPLEMENT(PRFileDesc*) PR_Accept(PRFileDesc *fd, PRNetAddr *addr,
-PRIntervalTime timeout)
-{
- return((fd->methods->accept)(fd,addr,timeout));
-}
-
-PR_IMPLEMENT(PRStatus) PR_Bind(PRFileDesc *fd, const PRNetAddr *addr)
-{
- return((fd->methods->bind)(fd,addr));
-}
-
-PR_IMPLEMENT(PRStatus) PR_Shutdown(PRFileDesc *fd, PRShutdownHow how)
-{
- return((fd->methods->shutdown)(fd,how));
-}
-
-PR_IMPLEMENT(PRStatus) PR_Listen(PRFileDesc *fd, PRIntn backlog)
-{
- return((fd->methods->listen)(fd,backlog));
-}
-
-PR_IMPLEMENT(PRInt32) PR_Recv(PRFileDesc *fd, void *buf, PRInt32 amount,
-PRIntn flags, PRIntervalTime timeout)
-{
- return((fd->methods->recv)(fd,buf,amount,flags,timeout));
-}
-
-PR_IMPLEMENT(PRInt32) PR_Send(PRFileDesc *fd, const void *buf, PRInt32 amount,
-PRIntn flags, PRIntervalTime timeout)
-{
- return((fd->methods->send)(fd,buf,amount,flags,timeout));
-}
-
-PR_IMPLEMENT(PRInt32) PR_Writev(PRFileDesc *fd, const PRIOVec *iov,
-PRInt32 iov_size, PRIntervalTime timeout)
-{
- if (iov_size > PR_MAX_IOVECTOR_SIZE)
- {
- PR_SetError(PR_BUFFER_OVERFLOW_ERROR, 0);
- return -1;
- }
- return((fd->methods->writev)(fd,iov,iov_size,timeout));
-}
-
-PR_IMPLEMENT(PRInt32) PR_RecvFrom(PRFileDesc *fd, void *buf, PRInt32 amount,
-PRIntn flags, PRNetAddr *addr, PRIntervalTime timeout)
-{
- return((fd->methods->recvfrom)(fd,buf,amount,flags,addr,timeout));
-}
-
-PR_IMPLEMENT(PRInt32) PR_SendTo(
- PRFileDesc *fd, const void *buf, PRInt32 amount,
- PRIntn flags, const PRNetAddr *addr, PRIntervalTime timeout)
-{
- return((fd->methods->sendto)(fd,buf,amount,flags,addr,timeout));
-}
-
-PR_IMPLEMENT(PRInt32) PR_TransmitFile(
- PRFileDesc *sd, PRFileDesc *fd, const void *hdr, PRInt32 hlen,
- PRTransmitFileFlags flags, PRIntervalTime timeout)
-{
- return((sd->methods->transmitfile)(sd,fd,hdr,hlen,flags,timeout));
-}
-
-PR_IMPLEMENT(PRInt32) PR_AcceptRead(
- PRFileDesc *sd, PRFileDesc **nd, PRNetAddr **raddr,
- void *buf, PRInt32 amount, PRIntervalTime timeout)
-{
- return((sd->methods->acceptread)(sd, nd, raddr, buf, amount,timeout));
-}
-
-PR_IMPLEMENT(PRStatus) PR_GetSockName(PRFileDesc *fd, PRNetAddr *addr)
-{
- return((fd->methods->getsockname)(fd,addr));
-}
-
-PR_IMPLEMENT(PRStatus) PR_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
-{
- return((fd->methods->getpeername)(fd,addr));
-}
-
-PR_IMPLEMENT(PRStatus) PR_GetSocketOption(
- PRFileDesc *fd, PRSocketOptionData *data)
-{
- return((fd->methods->getsocketoption)(fd, data));
-}
-
-PR_IMPLEMENT(PRStatus) PR_SetSocketOption(
- PRFileDesc *fd, const PRSocketOptionData *data)
-{
- return((fd->methods->setsocketoption)(fd, data));
-}
-
-PR_IMPLEMENT(PRInt32) PR_SendFile(
- PRFileDesc *sd, PRSendFileData *sfd,
- PRTransmitFileFlags flags, PRIntervalTime timeout)
-{
- return((sd->methods->sendfile)(sd,sfd,flags,timeout));
-}
-
-PR_IMPLEMENT(PRInt32) PR_EmulateAcceptRead(
- PRFileDesc *sd, PRFileDesc **nd, PRNetAddr **raddr,
- void *buf, PRInt32 amount, PRIntervalTime timeout)
-{
- PRInt32 rv = -1;
- PRNetAddr remote;
- PRFileDesc *accepted = NULL;
-
- /*
- ** The timeout does not apply to the accept portion of the
- ** operation - it waits indefinitely.
- */
- accepted = PR_Accept(sd, &remote, PR_INTERVAL_NO_TIMEOUT);
- if (NULL == accepted) return rv;
-
- rv = PR_Recv(accepted, buf, amount, 0, timeout);
- if (rv >= 0)
- {
- /* copy the new info out where caller can see it */
-#define AMASK ((PRPtrdiff)7) /* mask for alignment of PRNetAddr */
- PRPtrdiff aligned = (PRPtrdiff)buf + amount + AMASK;
- *raddr = (PRNetAddr*)(aligned & ~AMASK);
- memcpy(*raddr, &remote, PR_NETADDR_SIZE(&remote));
- *nd = accepted;
- return rv;
- }
-
- PR_Close(accepted);
- return rv;
-}
-
-/*
- * PR_EmulateSendFile
- *
- * Send file sfd->fd across socket sd. If header/trailer are specified
- * they are sent before and after the file, respectively.
- *
- * PR_TRANSMITFILE_CLOSE_SOCKET flag - close socket after sending file
- *
- * return number of bytes sent or -1 on error
- *
- */
-
-#if defined(XP_UNIX) || defined(WIN32)
-
-/*
- * An implementation based on memory-mapped files
- */
-
-#define SENDFILE_MMAP_CHUNK (256 * 1024)
-
-PR_IMPLEMENT(PRInt32) PR_EmulateSendFile(
- PRFileDesc *sd, PRSendFileData *sfd,
- PRTransmitFileFlags flags, PRIntervalTime timeout)
-{
- PRInt32 rv, count = 0;
- PRInt32 len, file_bytes, index = 0;
- PRFileInfo info;
- PRIOVec iov[3];
- PRFileMap *mapHandle = NULL;
- void *addr = (void*)0; /* initialized to some arbitrary value. Keeps compiler warnings down. */
- PRUint32 file_mmap_offset, alignment;
- PRInt64 zero64;
- PROffset64 file_mmap_offset64;
- PRUint32 addr_offset, mmap_len;
-
- /* Get file size */
- if (PR_SUCCESS != PR_GetOpenFileInfo(sfd->fd, &info)) {
- count = -1;
- goto done;
- }
- if (sfd->file_nbytes &&
- (info.size < (sfd->file_offset + sfd->file_nbytes))) {
- /*
- * there are fewer bytes in file to send than specified
- */
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- count = -1;
- goto done;
- }
- if (sfd->file_nbytes)
- file_bytes = sfd->file_nbytes;
- else
- file_bytes = info.size - sfd->file_offset;
-
- alignment = PR_GetMemMapAlignment();
-
- /* number of initial bytes to skip in mmap'd segment */
- addr_offset = sfd->file_offset % alignment;
-
- /* find previous mmap alignment boundary */
- file_mmap_offset = sfd->file_offset - addr_offset;
-
- /*
- * If the file is large, mmap and send the file in chunks so as
- * to not consume too much virtual address space
- */
- mmap_len = PR_MIN(file_bytes + addr_offset, SENDFILE_MMAP_CHUNK);
- len = mmap_len - addr_offset;
-
- /*
- * Map in (part of) file. Take care of zero-length files.
- */
- if (len) {
- LL_I2L(zero64, 0);
- mapHandle = PR_CreateFileMap(sfd->fd, zero64, PR_PROT_READONLY);
- if (!mapHandle) {
- count = -1;
- goto done;
- }
- LL_I2L(file_mmap_offset64, file_mmap_offset);
- addr = PR_MemMap(mapHandle, file_mmap_offset64, mmap_len);
- if (!addr) {
- count = -1;
- goto done;
- }
- }
- /*
- * send headers first, followed by the file
- */
- if (sfd->hlen) {
- iov[index].iov_base = (char *) sfd->header;
- iov[index].iov_len = sfd->hlen;
- index++;
- }
- if (len) {
- iov[index].iov_base = (char*)addr + addr_offset;
- iov[index].iov_len = len;
- index++;
- }
- if ((file_bytes == len) && (sfd->tlen)) {
- /*
- * all file data is mapped in; send the trailer too
- */
- iov[index].iov_base = (char *) sfd->trailer;
- iov[index].iov_len = sfd->tlen;
- index++;
- }
- rv = PR_Writev(sd, iov, index, timeout);
- if (len)
- PR_MemUnmap(addr, mmap_len);
- if (rv < 0) {
- count = -1;
- goto done;
- }
-
- PR_ASSERT(rv == sfd->hlen + len + ((len == file_bytes) ? sfd->tlen : 0));
-
- file_bytes -= len;
- count += rv;
- if (!file_bytes) /* header, file and trailer are sent */
- goto done;
-
- /*
- * send remaining bytes of the file, if any
- */
- len = PR_MIN(file_bytes, SENDFILE_MMAP_CHUNK);
- while (len > 0) {
- /*
- * Map in (part of) file
- */
- file_mmap_offset = sfd->file_offset + count - sfd->hlen;
- PR_ASSERT((file_mmap_offset % alignment) == 0);
-
- LL_I2L(file_mmap_offset64, file_mmap_offset);
- addr = PR_MemMap(mapHandle, file_mmap_offset64, len);
- if (!addr) {
- count = -1;
- goto done;
- }
- rv = PR_Send(sd, addr, len, 0, timeout);
- PR_MemUnmap(addr, len);
- if (rv < 0) {
- count = -1;
- goto done;
- }
-
- PR_ASSERT(rv == len);
- file_bytes -= rv;
- count += rv;
- len = PR_MIN(file_bytes, SENDFILE_MMAP_CHUNK);
- }
- PR_ASSERT(0 == file_bytes);
- if (sfd->tlen) {
- rv = PR_Send(sd, sfd->trailer, sfd->tlen, 0, timeout);
- if (rv >= 0) {
- PR_ASSERT(rv == sfd->tlen);
- count += rv;
- } else
- count = -1;
- }
-done:
- if (mapHandle)
- PR_CloseFileMap(mapHandle);
- if ((count >= 0) && (flags & PR_TRANSMITFILE_CLOSE_SOCKET))
- PR_Close(sd);
- return count;
-}
-
-#else
-
-PR_IMPLEMENT(PRInt32) PR_EmulateSendFile(
- PRFileDesc *sd, PRSendFileData *sfd,
- PRTransmitFileFlags flags, PRIntervalTime timeout)
-{
- PRInt32 rv, count = 0;
- PRInt32 rlen;
- const void * buffer;
- PRInt32 buflen;
- PRInt32 sendbytes, readbytes;
- char *buf;
-
-#define _SENDFILE_BUFSIZE (16 * 1024)
-
- buf = (char*)PR_MALLOC(_SENDFILE_BUFSIZE);
- if (buf == NULL) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return -1;
- }
-
- /*
- * send header first
- */
- buflen = sfd->hlen;
- buffer = sfd->header;
- while (buflen) {
- rv = PR_Send(sd, buffer, buflen, 0, timeout);
- if (rv < 0) {
- /* PR_Send() has invoked PR_SetError(). */
- rv = -1;
- goto done;
- } else {
- count += rv;
- buffer = (const void*) ((const char*)buffer + rv);
- buflen -= rv;
- }
- }
-
- /*
- * send file next
- */
- if (PR_Seek(sfd->fd, sfd->file_offset, PR_SEEK_SET) < 0) {
- rv = -1;
- goto done;
- }
- sendbytes = sfd->file_nbytes;
- if (sendbytes == 0) {
- /* send entire file */
- while ((rlen = PR_Read(sfd->fd, buf, _SENDFILE_BUFSIZE)) > 0) {
- while (rlen) {
- char *bufptr = buf;
-
- rv = PR_Send(sd, bufptr, rlen, 0, timeout);
- if (rv < 0) {
- /* PR_Send() has invoked PR_SetError(). */
- rv = -1;
- goto done;
- } else {
- count += rv;
- bufptr = ((char*)bufptr + rv);
- rlen -= rv;
- }
- }
- }
- if (rlen < 0) {
- /* PR_Read() has invoked PR_SetError(). */
- rv = -1;
- goto done;
- }
- } else {
- readbytes = PR_MIN(sendbytes, _SENDFILE_BUFSIZE);
- while (readbytes && ((rlen = PR_Read(sfd->fd, buf, readbytes)) > 0)) {
- while (rlen) {
- char *bufptr = buf;
-
- rv = PR_Send(sd, bufptr, rlen, 0, timeout);
- if (rv < 0) {
- /* PR_Send() has invoked PR_SetError(). */
- rv = -1;
- goto done;
- } else {
- count += rv;
- sendbytes -= rv;
- bufptr = ((char*)bufptr + rv);
- rlen -= rv;
- }
- }
- readbytes = PR_MIN(sendbytes, _SENDFILE_BUFSIZE);
- }
- if (rlen < 0) {
- /* PR_Read() has invoked PR_SetError(). */
- rv = -1;
- goto done;
- } else if (sendbytes != 0) {
- /*
- * there are fewer bytes in file to send than specified
- */
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- rv = -1;
- goto done;
- }
- }
-
- /*
- * send trailer last
- */
- buflen = sfd->tlen;
- buffer = sfd->trailer;
- while (buflen) {
- rv = PR_Send(sd, buffer, buflen, 0, timeout);
- if (rv < 0) {
- /* PR_Send() has invoked PR_SetError(). */
- rv = -1;
- goto done;
- } else {
- count += rv;
- buffer = (const void*) ((const char*)buffer + rv);
- buflen -= rv;
- }
- }
- rv = count;
-
-done:
- if (buf)
- PR_DELETE(buf);
- if ((rv >= 0) && (flags & PR_TRANSMITFILE_CLOSE_SOCKET))
- PR_Close(sd);
- return rv;
-}
-
-#endif
-
-/* priometh.c */
diff --git a/nspr/pr/src/io/pripv6.c b/nspr/pr/src/io/pripv6.c
deleted file mode 100644
index af7de49..0000000
--- a/nspr/pr/src/io/pripv6.c
+++ /dev/null
@@ -1,364 +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/. */
-
-/*
-** File: pripv6.c
-** Description: Support for various functions unique to IPv6
-*/
-#include "primpl.h"
-#include <string.h>
-
-#if !defined(_PR_INET6) || defined(_PR_INET6_PROBE)
-
-static PRIOMethods ipv6_to_v4_tcpMethods;
-static PRIOMethods ipv6_to_v4_udpMethods;
-static PRDescIdentity _pr_ipv6_to_ipv4_id;
-extern PRBool IsValidNetAddr(const PRNetAddr *addr);
-extern PRIPv6Addr _pr_in6addr_any;
-extern PRIPv6Addr _pr_in6addr_loopback;
-
-/*
- * convert an IPv4-mapped IPv6 addr to an IPv4 addr
- */
-static void _PR_ConvertToIpv4NetAddr(const PRNetAddr *src_v6addr,
- PRNetAddr *dst_v4addr)
-{
-const PRUint8 *srcp;
-
- PR_ASSERT(PR_AF_INET6 == src_v6addr->ipv6.family);
-
- if (PR_IsNetAddrType(src_v6addr, PR_IpAddrV4Mapped)) {
- srcp = src_v6addr->ipv6.ip.pr_s6_addr;
- memcpy((char *) &dst_v4addr->inet.ip, srcp + 12, 4);
- } else if (PR_IsNetAddrType(src_v6addr, PR_IpAddrAny)) {
- dst_v4addr->inet.ip = htonl(INADDR_ANY);
- } else if (PR_IsNetAddrType(src_v6addr, PR_IpAddrLoopback)) {
- dst_v4addr->inet.ip = htonl(INADDR_LOOPBACK);
- }
- dst_v4addr->inet.family = PR_AF_INET;
- dst_v4addr->inet.port = src_v6addr->ipv6.port;
-}
-
-/*
- * convert an IPv4 addr to an IPv4-mapped IPv6 addr
- */
-static void _PR_ConvertToIpv6NetAddr(const PRNetAddr *src_v4addr,
- PRNetAddr *dst_v6addr)
-{
-PRUint8 *dstp;
-
- PR_ASSERT(PR_AF_INET == src_v4addr->inet.family);
- dst_v6addr->ipv6.family = PR_AF_INET6;
- dst_v6addr->ipv6.port = src_v4addr->inet.port;
-
- if (htonl(INADDR_ANY) == src_v4addr->inet.ip) {
- dst_v6addr->ipv6.ip = _pr_in6addr_any;
- } else {
- dstp = dst_v6addr->ipv6.ip.pr_s6_addr;
- memset(dstp, 0, 10);
- memset(dstp + 10, 0xff, 2);
- memcpy(dstp + 12,(char *) &src_v4addr->inet.ip, 4);
- }
-}
-
-static PRStatus PR_CALLBACK Ipv6ToIpv4SocketBind(PRFileDesc *fd,
- const PRNetAddr *addr)
-{
- PRNetAddr tmp_ipv4addr;
- const PRNetAddr *tmp_addrp;
- PRFileDesc *lo = fd->lower;
-
- if (PR_AF_INET6 != addr->raw.family) {
- PR_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR, 0);
- return PR_FAILURE;
- }
- if (PR_IsNetAddrType(addr, PR_IpAddrV4Mapped) ||
- PR_IsNetAddrType(addr, PR_IpAddrAny)) {
- _PR_ConvertToIpv4NetAddr(addr, &tmp_ipv4addr);
- tmp_addrp = &tmp_ipv4addr;
- } else {
- PR_SetError(PR_NETWORK_UNREACHABLE_ERROR, 0);
- return PR_FAILURE;
- }
- return((lo->methods->bind)(lo,tmp_addrp));
-}
-
-static PRStatus PR_CALLBACK Ipv6ToIpv4SocketConnect(
- PRFileDesc *fd, const PRNetAddr *addr, PRIntervalTime timeout)
-{
- PRNetAddr tmp_ipv4addr;
- const PRNetAddr *tmp_addrp;
-
- if (PR_AF_INET6 != addr->raw.family) {
- PR_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR, 0);
- return PR_FAILURE;
- }
- if (PR_IsNetAddrType(addr, PR_IpAddrV4Mapped) ||
- PR_IsNetAddrType(addr, PR_IpAddrLoopback)) {
- _PR_ConvertToIpv4NetAddr(addr, &tmp_ipv4addr);
- tmp_addrp = &tmp_ipv4addr;
- } else {
- PR_SetError(PR_NETWORK_UNREACHABLE_ERROR, 0);
- return PR_FAILURE;
- }
- return (fd->lower->methods->connect)(fd->lower, tmp_addrp, timeout);
-}
-
-static PRInt32 PR_CALLBACK Ipv6ToIpv4SocketSendTo(
- PRFileDesc *fd, const void *buf, PRInt32 amount,
- PRIntn flags, const PRNetAddr *addr, PRIntervalTime timeout)
-{
- PRNetAddr tmp_ipv4addr;
- const PRNetAddr *tmp_addrp;
-
- if (PR_AF_INET6 != addr->raw.family) {
- PR_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR, 0);
- return PR_FAILURE;
- }
- if (PR_IsNetAddrType(addr, PR_IpAddrV4Mapped) ||
- PR_IsNetAddrType(addr, PR_IpAddrLoopback)) {
- _PR_ConvertToIpv4NetAddr(addr, &tmp_ipv4addr);
- tmp_addrp = &tmp_ipv4addr;
- } else {
- PR_SetError(PR_NETWORK_UNREACHABLE_ERROR, 0);
- return PR_FAILURE;
- }
- return (fd->lower->methods->sendto)(
- fd->lower, buf, amount, flags, tmp_addrp, timeout);
-}
-
-static PRFileDesc* PR_CALLBACK Ipv6ToIpv4SocketAccept (
- PRFileDesc *fd, PRNetAddr *addr, PRIntervalTime timeout)
-{
- PRStatus rv;
- PRFileDesc *newfd;
- PRFileDesc *newstack;
- PRNetAddr tmp_ipv4addr;
- PRNetAddr *addrlower = NULL;
-
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- newstack = PR_NEW(PRFileDesc);
- if (NULL == newstack)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
- *newstack = *fd; /* make a copy of the accepting layer */
-
- if (addr)
- addrlower = &tmp_ipv4addr;
- newfd = (fd->lower->methods->accept)(fd->lower, addrlower, timeout);
- if (NULL == newfd)
- {
- PR_DELETE(newstack);
- return NULL;
- }
- if (addr)
- _PR_ConvertToIpv6NetAddr(&tmp_ipv4addr, addr);
-
- rv = PR_PushIOLayer(newfd, PR_TOP_IO_LAYER, newstack);
- PR_ASSERT(PR_SUCCESS == rv);
- return newfd; /* that's it */
-}
-
-static PRInt32 PR_CALLBACK Ipv6ToIpv4SocketAcceptRead(PRFileDesc *sd,
- PRFileDesc **nd, PRNetAddr **ipv6_raddr, void *buf, PRInt32 amount,
- PRIntervalTime timeout)
-{
- PRInt32 nbytes;
- PRStatus rv;
- PRNetAddr tmp_ipv4addr;
- PRFileDesc *newstack;
-
- PR_ASSERT(sd != NULL);
- PR_ASSERT(sd->lower != NULL);
-
- newstack = PR_NEW(PRFileDesc);
- if (NULL == newstack)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return -1;
- }
- *newstack = *sd; /* make a copy of the accepting layer */
-
- nbytes = sd->lower->methods->acceptread(
- sd->lower, nd, ipv6_raddr, buf, amount, timeout);
- if (-1 == nbytes)
- {
- PR_DELETE(newstack);
- return nbytes;
- }
- tmp_ipv4addr = **ipv6_raddr; /* copy */
- _PR_ConvertToIpv6NetAddr(&tmp_ipv4addr, *ipv6_raddr);
-
- /* this PR_PushIOLayer call cannot fail */
- rv = PR_PushIOLayer(*nd, PR_TOP_IO_LAYER, newstack);
- PR_ASSERT(PR_SUCCESS == rv);
- return nbytes;
-}
-
-static PRStatus PR_CALLBACK Ipv6ToIpv4SocketGetName(PRFileDesc *fd,
- PRNetAddr *ipv6addr)
-{
- PRStatus result;
- PRNetAddr tmp_ipv4addr;
-
- result = (fd->lower->methods->getsockname)(fd->lower, &tmp_ipv4addr);
- if (PR_SUCCESS == result) {
- _PR_ConvertToIpv6NetAddr(&tmp_ipv4addr, ipv6addr);
- PR_ASSERT(IsValidNetAddr(ipv6addr) == PR_TRUE);
- }
- return result;
-}
-
-static PRStatus PR_CALLBACK Ipv6ToIpv4SocketGetPeerName(PRFileDesc *fd,
- PRNetAddr *ipv6addr)
-{
- PRStatus result;
- PRNetAddr tmp_ipv4addr;
-
- result = (fd->lower->methods->getpeername)(fd->lower, &tmp_ipv4addr);
- if (PR_SUCCESS == result) {
- _PR_ConvertToIpv6NetAddr(&tmp_ipv4addr, ipv6addr);
- PR_ASSERT(IsValidNetAddr(ipv6addr) == PR_TRUE);
- }
- return result;
-}
-
-static PRInt32 PR_CALLBACK Ipv6ToIpv4SocketRecvFrom(PRFileDesc *fd, void *buf,
- PRInt32 amount, PRIntn flags, PRNetAddr *ipv6addr,
- PRIntervalTime timeout)
-{
- PRNetAddr tmp_ipv4addr;
- PRInt32 result;
-
- result = (fd->lower->methods->recvfrom)(
- fd->lower, buf, amount, flags, &tmp_ipv4addr, timeout);
- if (-1 != result) {
- _PR_ConvertToIpv6NetAddr(&tmp_ipv4addr, ipv6addr);
- PR_ASSERT(IsValidNetAddr(ipv6addr) == PR_TRUE);
- }
- return result;
-}
-
-#if defined(_PR_INET6_PROBE)
-static PRBool ipv6_is_present;
-extern PRBool _pr_test_ipv6_socket(void);
-
-#if !defined(_PR_INET6) && defined(_PR_HAVE_GETIPNODEBYNAME)
-extern PRStatus _pr_find_getipnodebyname(void);
-#endif
-
-#if !defined(_PR_INET6) && defined(_PR_HAVE_GETADDRINFO)
-extern PRStatus _pr_find_getaddrinfo(void);
-#endif
-
-static PRBool
-_pr_probe_ipv6_presence(void)
-{
-#if !defined(_PR_INET6) && defined(_PR_HAVE_GETIPNODEBYNAME)
- if (_pr_find_getipnodebyname() != PR_SUCCESS)
- return PR_FALSE;
-#endif
-
-#if !defined(_PR_INET6) && defined(_PR_HAVE_GETADDRINFO)
- if (_pr_find_getaddrinfo() != PR_SUCCESS)
- return PR_FALSE;
-#endif
-
- return _pr_test_ipv6_socket();
-}
-#endif /* _PR_INET6_PROBE */
-
-static PRCallOnceType _pr_init_ipv6_once;
-
-static PRStatus PR_CALLBACK _pr_init_ipv6(void)
-{
- const PRIOMethods *stubMethods;
-
-#if defined(_PR_INET6_PROBE)
- ipv6_is_present = _pr_probe_ipv6_presence();
- if (ipv6_is_present)
- return PR_SUCCESS;
-#endif
-
- _pr_ipv6_to_ipv4_id = PR_GetUniqueIdentity("Ipv6_to_Ipv4 layer");
- PR_ASSERT(PR_INVALID_IO_LAYER != _pr_ipv6_to_ipv4_id);
-
- stubMethods = PR_GetDefaultIOMethods();
-
- ipv6_to_v4_tcpMethods = *stubMethods; /* first get the entire batch */
- /* then override the ones we care about */
- ipv6_to_v4_tcpMethods.connect = Ipv6ToIpv4SocketConnect;
- ipv6_to_v4_tcpMethods.bind = Ipv6ToIpv4SocketBind;
- ipv6_to_v4_tcpMethods.accept = Ipv6ToIpv4SocketAccept;
- ipv6_to_v4_tcpMethods.acceptread = Ipv6ToIpv4SocketAcceptRead;
- ipv6_to_v4_tcpMethods.getsockname = Ipv6ToIpv4SocketGetName;
- ipv6_to_v4_tcpMethods.getpeername = Ipv6ToIpv4SocketGetPeerName;
-/*
- ipv6_to_v4_tcpMethods.getsocketoption = Ipv6ToIpv4GetSocketOption;
- ipv6_to_v4_tcpMethods.setsocketoption = Ipv6ToIpv4SetSocketOption;
-*/
- ipv6_to_v4_udpMethods = *stubMethods; /* first get the entire batch */
- /* then override the ones we care about */
- ipv6_to_v4_udpMethods.connect = Ipv6ToIpv4SocketConnect;
- ipv6_to_v4_udpMethods.bind = Ipv6ToIpv4SocketBind;
- ipv6_to_v4_udpMethods.sendto = Ipv6ToIpv4SocketSendTo;
- ipv6_to_v4_udpMethods.recvfrom = Ipv6ToIpv4SocketRecvFrom;
- ipv6_to_v4_udpMethods.getsockname = Ipv6ToIpv4SocketGetName;
- ipv6_to_v4_udpMethods.getpeername = Ipv6ToIpv4SocketGetPeerName;
-/*
- ipv6_to_v4_udpMethods.getsocketoption = Ipv6ToIpv4GetSocketOption;
- ipv6_to_v4_udpMethods.setsocketoption = Ipv6ToIpv4SetSocketOption;
-*/
- return PR_SUCCESS;
-}
-
-#if defined(_PR_INET6_PROBE)
-PRBool _pr_ipv6_is_present(void)
-{
- if (PR_CallOnce(&_pr_init_ipv6_once, _pr_init_ipv6) != PR_SUCCESS)
- return PR_FALSE;
- return ipv6_is_present;
-}
-#endif
-
-PR_IMPLEMENT(PRStatus) _pr_push_ipv6toipv4_layer(PRFileDesc *fd)
-{
- PRFileDesc *ipv6_fd = NULL;
-
- if (PR_CallOnce(&_pr_init_ipv6_once, _pr_init_ipv6) != PR_SUCCESS)
- return PR_FAILURE;
-
- /*
- * For platforms with no support for IPv6
- * create layered socket for IPv4-mapped IPv6 addresses
- */
- if (fd->methods->file_type == PR_DESC_SOCKET_TCP)
- ipv6_fd = PR_CreateIOLayerStub(_pr_ipv6_to_ipv4_id,
- &ipv6_to_v4_tcpMethods);
- else
- ipv6_fd = PR_CreateIOLayerStub(_pr_ipv6_to_ipv4_id,
- &ipv6_to_v4_udpMethods);
- if (NULL == ipv6_fd) {
- goto errorExit;
- }
- ipv6_fd->secret = NULL;
-
- if (PR_PushIOLayer(fd, PR_TOP_IO_LAYER, ipv6_fd) == PR_FAILURE) {
- goto errorExit;
- }
-
- return PR_SUCCESS;
-errorExit:
-
- if (ipv6_fd)
- ipv6_fd->dtor(ipv6_fd);
- return PR_FAILURE;
-}
-
-#endif /* !defined(_PR_INET6) || defined(_PR_INET6_PROBE) */
diff --git a/nspr/pr/src/io/prlayer.c b/nspr/pr/src/io/prlayer.c
deleted file mode 100644
index faec909..0000000
--- a/nspr/pr/src/io/prlayer.c
+++ /dev/null
@@ -1,752 +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/. */
-
-/*
-** File: prlayer.c
-** Description: Routines for handling pushable protocol modules on sockets.
-*/
-
-#include "primpl.h"
-#include "prerror.h"
-#include "prmem.h"
-#include "prlock.h"
-#include "prlog.h"
-#include "prio.h"
-
-#include <string.h> /* for memset() */
-static PRStatus _PR_DestroyIOLayer(PRFileDesc *stack);
-
-void PR_CALLBACK pl_FDDestructor(PRFileDesc *fd)
-{
- PR_ASSERT(fd != NULL);
- if (NULL != fd->lower) fd->lower->higher = fd->higher;
- if (NULL != fd->higher) fd->higher->lower = fd->lower;
- PR_DELETE(fd);
-}
-
-/*
-** Default methods that just call down to the next fd.
-*/
-static PRStatus PR_CALLBACK pl_TopClose (PRFileDesc *fd)
-{
- PRFileDesc *top, *lower;
- PRStatus rv;
-
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
- PR_ASSERT(fd->secret == NULL);
- PR_ASSERT(fd->methods->file_type == PR_DESC_LAYERED);
-
- if (PR_IO_LAYER_HEAD == fd->identity) {
- /*
- * new style stack; close all the layers, before deleting the
- * stack head
- */
- rv = fd->lower->methods->close(fd->lower);
- _PR_DestroyIOLayer(fd);
- return rv;
- } else if ((fd->higher) && (PR_IO_LAYER_HEAD == fd->higher->identity)) {
- /*
- * lower layers of new style stack
- */
- lower = fd->lower;
- /*
- * pop and cleanup current layer
- */
- top = PR_PopIOLayer(fd->higher, PR_TOP_IO_LAYER);
- top->dtor(top);
- /*
- * then call lower layer
- */
- return (lower->methods->close(lower));
- } else {
- /* old style stack */
- top = PR_PopIOLayer(fd, PR_TOP_IO_LAYER);
- top->dtor(top);
- return (fd->methods->close)(fd);
- }
-}
-
-static PRInt32 PR_CALLBACK pl_DefRead (PRFileDesc *fd, void *buf, PRInt32 amount)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->read)(fd->lower, buf, amount);
-}
-
-static PRInt32 PR_CALLBACK pl_DefWrite (
- PRFileDesc *fd, const void *buf, PRInt32 amount)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->write)(fd->lower, buf, amount);
-}
-
-static PRInt32 PR_CALLBACK pl_DefAvailable (PRFileDesc *fd)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->available)(fd->lower);
-}
-
-static PRInt64 PR_CALLBACK pl_DefAvailable64 (PRFileDesc *fd)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->available64)(fd->lower);
-}
-
-static PRStatus PR_CALLBACK pl_DefFsync (PRFileDesc *fd)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->fsync)(fd->lower);
-}
-
-static PRInt32 PR_CALLBACK pl_DefSeek (
- PRFileDesc *fd, PRInt32 offset, PRSeekWhence how)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->seek)(fd->lower, offset, how);
-}
-
-static PRInt64 PR_CALLBACK pl_DefSeek64 (
- PRFileDesc *fd, PRInt64 offset, PRSeekWhence how)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->seek64)(fd->lower, offset, how);
-}
-
-static PRStatus PR_CALLBACK pl_DefFileInfo (PRFileDesc *fd, PRFileInfo *info)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->fileInfo)(fd->lower, info);
-}
-
-static PRStatus PR_CALLBACK pl_DefFileInfo64 (PRFileDesc *fd, PRFileInfo64 *info)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->fileInfo64)(fd->lower, info);
-}
-
-static PRInt32 PR_CALLBACK pl_DefWritev (PRFileDesc *fd, const PRIOVec *iov,
- PRInt32 size, PRIntervalTime timeout)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->writev)(fd->lower, iov, size, timeout);
-}
-
-static PRStatus PR_CALLBACK pl_DefConnect (
- PRFileDesc *fd, const PRNetAddr *addr, PRIntervalTime timeout)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->connect)(fd->lower, addr, timeout);
-}
-
-static PRStatus PR_CALLBACK pl_DefConnectcontinue (
- PRFileDesc *fd, PRInt16 out_flags)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->connectcontinue)(fd->lower, out_flags);
-}
-
-static PRFileDesc* PR_CALLBACK pl_TopAccept (
- PRFileDesc *fd, PRNetAddr *addr, PRIntervalTime timeout)
-{
- PRStatus rv;
- PRFileDesc *newfd, *layer = fd;
- PRFileDesc *newstack;
- PRBool newstyle_stack = PR_FALSE;
-
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- /* test for new style stack */
- while (NULL != layer->higher)
- layer = layer->higher;
- newstyle_stack = (PR_IO_LAYER_HEAD == layer->identity) ? PR_TRUE : PR_FALSE;
- newstack = PR_NEW(PRFileDesc);
- if (NULL == newstack)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
- *newstack = *fd; /* make a copy of the accepting layer */
-
- newfd = (fd->lower->methods->accept)(fd->lower, addr, timeout);
- if (NULL == newfd)
- {
- PR_DELETE(newstack);
- return NULL;
- }
-
- if (newstyle_stack) {
- newstack->lower = newfd;
- newfd->higher = newstack;
- return newstack;
- } else {
- /* this PR_PushIOLayer call cannot fail */
- rv = PR_PushIOLayer(newfd, PR_TOP_IO_LAYER, newstack);
- PR_ASSERT(PR_SUCCESS == rv);
- return newfd; /* that's it */
- }
-}
-
-static PRStatus PR_CALLBACK pl_DefBind (PRFileDesc *fd, const PRNetAddr *addr)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->bind)(fd->lower, addr);
-}
-
-static PRStatus PR_CALLBACK pl_DefListen (PRFileDesc *fd, PRIntn backlog)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->listen)(fd->lower, backlog);
-}
-
-static PRStatus PR_CALLBACK pl_DefShutdown (PRFileDesc *fd, PRIntn how)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->shutdown)(fd->lower, how);
-}
-
-static PRInt32 PR_CALLBACK pl_DefRecv (
- PRFileDesc *fd, void *buf, PRInt32 amount,
- PRIntn flags, PRIntervalTime timeout)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->recv)(
- fd->lower, buf, amount, flags, timeout);
-}
-
-static PRInt32 PR_CALLBACK pl_DefSend (
- PRFileDesc *fd, const void *buf,
- PRInt32 amount, PRIntn flags, PRIntervalTime timeout)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->send)(fd->lower, buf, amount, flags, timeout);
-}
-
-static PRInt32 PR_CALLBACK pl_DefRecvfrom (
- PRFileDesc *fd, void *buf, PRInt32 amount,
- PRIntn flags, PRNetAddr *addr, PRIntervalTime timeout)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->recvfrom)(
- fd->lower, buf, amount, flags, addr, timeout);
-}
-
-static PRInt32 PR_CALLBACK pl_DefSendto (
- PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
- const PRNetAddr *addr, PRIntervalTime timeout)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->sendto)(
- fd->lower, buf, amount, flags, addr, timeout);
-}
-
-static PRInt16 PR_CALLBACK pl_DefPoll (
- PRFileDesc *fd, PRInt16 in_flags, PRInt16 *out_flags)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->poll)(fd->lower, in_flags, out_flags);
-}
-
-static PRInt32 PR_CALLBACK pl_DefAcceptread (
- PRFileDesc *sd, PRFileDesc **nd, PRNetAddr **raddr, void *buf,
- PRInt32 amount, PRIntervalTime t)
-{
- PRInt32 nbytes;
- PRStatus rv;
- PRFileDesc *newstack;
- PRFileDesc *layer = sd;
- PRBool newstyle_stack = PR_FALSE;
-
- PR_ASSERT(sd != NULL);
- PR_ASSERT(sd->lower != NULL);
-
- /* test for new style stack */
- while (NULL != layer->higher)
- layer = layer->higher;
- newstyle_stack = (PR_IO_LAYER_HEAD == layer->identity) ? PR_TRUE : PR_FALSE;
- newstack = PR_NEW(PRFileDesc);
- if (NULL == newstack)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return -1;
- }
- *newstack = *sd; /* make a copy of the accepting layer */
-
- nbytes = sd->lower->methods->acceptread(
- sd->lower, nd, raddr, buf, amount, t);
- if (-1 == nbytes)
- {
- PR_DELETE(newstack);
- return nbytes;
- }
- if (newstyle_stack) {
- newstack->lower = *nd;
- (*nd)->higher = newstack;
- *nd = newstack;
- return nbytes;
- } else {
- /* this PR_PushIOLayer call cannot fail */
- rv = PR_PushIOLayer(*nd, PR_TOP_IO_LAYER, newstack);
- PR_ASSERT(PR_SUCCESS == rv);
- return nbytes;
- }
-}
-
-static PRInt32 PR_CALLBACK pl_DefTransmitfile (
- PRFileDesc *sd, PRFileDesc *fd, const void *headers, PRInt32 hlen,
- PRTransmitFileFlags flags, PRIntervalTime t)
-{
- PR_ASSERT(sd != NULL);
- PR_ASSERT(sd->lower != NULL);
-
- return sd->lower->methods->transmitfile(
- sd->lower, fd, headers, hlen, flags, t);
-}
-
-static PRStatus PR_CALLBACK pl_DefGetsockname (PRFileDesc *fd, PRNetAddr *addr)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->getsockname)(fd->lower, addr);
-}
-
-static PRStatus PR_CALLBACK pl_DefGetpeername (PRFileDesc *fd, PRNetAddr *addr)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->getpeername)(fd->lower, addr);
-}
-
-static PRStatus PR_CALLBACK pl_DefGetsocketoption (
- PRFileDesc *fd, PRSocketOptionData *data)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->getsocketoption)(fd->lower, data);
-}
-
-static PRStatus PR_CALLBACK pl_DefSetsocketoption (
- PRFileDesc *fd, const PRSocketOptionData *data)
-{
- PR_ASSERT(fd != NULL);
- PR_ASSERT(fd->lower != NULL);
-
- return (fd->lower->methods->setsocketoption)(fd->lower, data);
-}
-
-static PRInt32 PR_CALLBACK pl_DefSendfile (
- PRFileDesc *sd, PRSendFileData *sfd,
- PRTransmitFileFlags flags, PRIntervalTime timeout)
-{
- PR_ASSERT(sd != NULL);
- PR_ASSERT(sd->lower != NULL);
-
- return sd->lower->methods->sendfile(
- sd->lower, sfd, flags, timeout);
-}
-
-/* Methods for the top of the stack. Just call down to the next fd. */
-static PRIOMethods pl_methods = {
- PR_DESC_LAYERED,
- pl_TopClose,
- pl_DefRead,
- pl_DefWrite,
- pl_DefAvailable,
- pl_DefAvailable64,
- pl_DefFsync,
- pl_DefSeek,
- pl_DefSeek64,
- pl_DefFileInfo,
- pl_DefFileInfo64,
- pl_DefWritev,
- pl_DefConnect,
- pl_TopAccept,
- pl_DefBind,
- pl_DefListen,
- pl_DefShutdown,
- pl_DefRecv,
- pl_DefSend,
- pl_DefRecvfrom,
- pl_DefSendto,
- pl_DefPoll,
- pl_DefAcceptread,
- pl_DefTransmitfile,
- pl_DefGetsockname,
- pl_DefGetpeername,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- pl_DefGetsocketoption,
- pl_DefSetsocketoption,
- pl_DefSendfile,
- pl_DefConnectcontinue,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt
-};
-
-PR_IMPLEMENT(const PRIOMethods*) PR_GetDefaultIOMethods(void)
-{
- return &pl_methods;
-} /* PR_GetDefaultIOMethods */
-
-PR_IMPLEMENT(PRFileDesc*) PR_CreateIOLayerStub(
- PRDescIdentity ident, const PRIOMethods *methods)
-{
- PRFileDesc *fd = NULL;
- PR_ASSERT((PR_NSPR_IO_LAYER != ident) && (PR_TOP_IO_LAYER != ident));
- if ((PR_NSPR_IO_LAYER == ident) || (PR_TOP_IO_LAYER == ident))
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- else
- {
- fd = PR_NEWZAP(PRFileDesc);
- if (NULL == fd)
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- else
- {
- fd->methods = methods;
- fd->dtor = pl_FDDestructor;
- fd->identity = ident;
- }
- }
- return fd;
-} /* PR_CreateIOLayerStub */
-
-/*
- * PR_CreateIOLayer
- * Create a new style stack, where the stack top is a dummy header.
- * Unlike the old style stacks, the contents of the stack head
- * are not modified when a layer is pushed onto or popped from a new
- * style stack.
- */
-
-PR_IMPLEMENT(PRFileDesc*) PR_CreateIOLayer(PRFileDesc *top)
-{
- PRFileDesc *fd = NULL;
-
- fd = PR_NEWZAP(PRFileDesc);
- if (NULL == fd)
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- else
- {
- fd->methods = &pl_methods;
- fd->dtor = pl_FDDestructor;
- fd->identity = PR_IO_LAYER_HEAD;
- fd->higher = NULL;
- fd->lower = top;
- top->higher = fd;
- top->lower = NULL;
- }
- return fd;
-} /* PR_CreateIOLayer */
-
-/*
- * _PR_DestroyIOLayer
- * Delete the stack head of a new style stack.
- */
-
-static PRStatus _PR_DestroyIOLayer(PRFileDesc *stack)
-{
- if (NULL == stack)
- return PR_FAILURE;
- else {
- PR_DELETE(stack);
- return PR_SUCCESS;
- }
-} /* _PR_DestroyIOLayer */
-
-PR_IMPLEMENT(PRStatus) PR_PushIOLayer(
- PRFileDesc *stack, PRDescIdentity id, PRFileDesc *fd)
-{
- PRFileDesc *insert = PR_GetIdentitiesLayer(stack, id);
-
- PR_ASSERT(fd != NULL);
- PR_ASSERT(stack != NULL);
- PR_ASSERT(insert != NULL);
- PR_ASSERT(PR_IO_LAYER_HEAD != id);
- if ((NULL == stack) || (NULL == fd) || (NULL == insert))
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
-
- if (stack == insert)
- {
- /* going on top of the stack */
- /* old-style stack */
- PRFileDesc copy = *stack;
- *stack = *fd;
- *fd = copy;
- fd->higher = stack;
- if (fd->lower)
- {
- PR_ASSERT(fd->lower->higher == stack);
- fd->lower->higher = fd;
- }
- stack->lower = fd;
- stack->higher = NULL;
- } else {
- /*
- * going somewhere in the middle of the stack for both old and new
- * style stacks, or going on top of stack for new style stack
- */
- fd->lower = insert;
- fd->higher = insert->higher;
-
- insert->higher->lower = fd;
- insert->higher = fd;
- }
-
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRFileDesc*) PR_PopIOLayer(PRFileDesc *stack, PRDescIdentity id)
-{
- PRFileDesc *extract = PR_GetIdentitiesLayer(stack, id);
-
- PR_ASSERT(0 != id);
- PR_ASSERT(NULL != stack);
- PR_ASSERT(NULL != extract);
- if ((NULL == stack) || (0 == id) || (NULL == extract))
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return NULL;
- }
-
- if (extract == stack) {
- /* popping top layer of the stack */
- /* old style stack */
- PRFileDesc copy = *stack;
- extract = stack->lower;
- *stack = *extract;
- *extract = copy;
- stack->higher = NULL;
- if (stack->lower) {
- PR_ASSERT(stack->lower->higher == extract);
- stack->lower->higher = stack;
- }
- } else if ((PR_IO_LAYER_HEAD == stack->identity) &&
- (extract == stack->lower) && (extract->lower == NULL)) {
- /*
- * new style stack
- * popping the only layer in the stack; delete the stack too
- */
- stack->lower = NULL;
- _PR_DestroyIOLayer(stack);
- } else {
- /* for both kinds of stacks */
- extract->lower->higher = extract->higher;
- extract->higher->lower = extract->lower;
- }
- extract->higher = extract->lower = NULL;
- return extract;
-} /* PR_PopIOLayer */
-
-#define ID_CACHE_INCREMENT 16
-typedef struct _PRIdentity_cache
-{
- PRLock *ml;
- char **name;
- PRIntn length;
- PRDescIdentity ident;
-} _PRIdentity_cache;
-
-static _PRIdentity_cache identity_cache;
-
-PR_IMPLEMENT(PRDescIdentity) PR_GetUniqueIdentity(const char *layer_name)
-{
- PRDescIdentity identity, length;
- char **names = NULL, *name = NULL, **old = NULL;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- PR_ASSERT((PRDescIdentity)0x7fff > identity_cache.ident);
-
- if (NULL != layer_name)
- {
- name = (char*)PR_Malloc(strlen(layer_name) + 1);
- if (NULL == name)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return PR_INVALID_IO_LAYER;
- }
- strcpy(name, layer_name);
- }
-
- /* this initial code runs unsafe */
-retry:
- PR_ASSERT(NULL == names);
- /*
- * In the initial round, both identity_cache.ident and
- * identity_cache.length are 0, so (identity_cache.ident + 1) is greater
- * than length. In later rounds, identity_cache.ident is always less
- * than length, so (identity_cache.ident + 1) can be equal to but cannot
- * be greater than length.
- */
- length = identity_cache.length;
- if ((identity_cache.ident + 1) >= length)
- {
- length += ID_CACHE_INCREMENT;
- names = (char**)PR_CALLOC(length * sizeof(char*));
- if (NULL == names)
- {
- if (NULL != name) PR_DELETE(name);
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return PR_INVALID_IO_LAYER;
- }
- }
-
- /* now we get serious about thread safety */
- PR_Lock(identity_cache.ml);
- PR_ASSERT(identity_cache.length == 0 ||
- identity_cache.ident < identity_cache.length);
- identity = identity_cache.ident + 1;
- if (identity >= identity_cache.length) /* there's no room */
- {
- /* we have to do something - hopefully it's already done */
- if ((NULL != names) && (identity < length))
- {
- /* what we did is still okay */
- memcpy(
- names, identity_cache.name,
- identity_cache.length * sizeof(char*));
- old = identity_cache.name;
- identity_cache.name = names;
- identity_cache.length = length;
- names = NULL;
- }
- else
- {
- PR_Unlock(identity_cache.ml);
- if (NULL != names) PR_DELETE(names);
- goto retry;
- }
- }
- if (NULL != name) /* there's a name to be stored */
- {
- identity_cache.name[identity] = name;
- }
- identity_cache.ident = identity;
- PR_ASSERT(identity_cache.ident < identity_cache.length);
- PR_Unlock(identity_cache.ml);
-
- if (NULL != old) PR_DELETE(old);
- if (NULL != names) PR_DELETE(names);
-
- return identity;
-} /* PR_GetUniqueIdentity */
-
-PR_IMPLEMENT(const char*) PR_GetNameForIdentity(PRDescIdentity ident)
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (PR_TOP_IO_LAYER == ident) return NULL;
-
- PR_ASSERT(ident <= identity_cache.ident);
- return (ident > identity_cache.ident) ? NULL : identity_cache.name[ident];
-} /* PR_GetNameForIdentity */
-
-PR_IMPLEMENT(PRDescIdentity) PR_GetLayersIdentity(PRFileDesc* fd)
-{
- PR_ASSERT(NULL != fd);
- if (PR_IO_LAYER_HEAD == fd->identity) {
- PR_ASSERT(NULL != fd->lower);
- return fd->lower->identity;
- } else
- return fd->identity;
-} /* PR_GetLayersIdentity */
-
-PR_IMPLEMENT(PRFileDesc*) PR_GetIdentitiesLayer(PRFileDesc* fd, PRDescIdentity id)
-{
- PRFileDesc *layer = fd;
-
- if (PR_TOP_IO_LAYER == id) {
- if (PR_IO_LAYER_HEAD == fd->identity)
- return fd->lower;
- else
- return fd;
- }
-
- for (layer = fd; layer != NULL; layer = layer->lower)
- {
- if (id == layer->identity) return layer;
- }
- for (layer = fd; layer != NULL; layer = layer->higher)
- {
- if (id == layer->identity) return layer;
- }
- return NULL;
-} /* PR_GetIdentitiesLayer */
-
-void _PR_InitLayerCache(void)
-{
- memset(&identity_cache, 0, sizeof(identity_cache));
- identity_cache.ml = PR_NewLock();
- PR_ASSERT(NULL != identity_cache.ml);
-} /* _PR_InitLayerCache */
-
-void _PR_CleanupLayerCache(void)
-{
- if (identity_cache.ml)
- {
- PR_DestroyLock(identity_cache.ml);
- identity_cache.ml = NULL;
- }
-
- if (identity_cache.name)
- {
- PRDescIdentity ident;
-
- for (ident = 0; ident <= identity_cache.ident; ident++)
- PR_DELETE(identity_cache.name[ident]);
-
- PR_DELETE(identity_cache.name);
- }
-} /* _PR_CleanupLayerCache */
-
-/* prlayer.c */
diff --git a/nspr/pr/src/io/prlog.c b/nspr/pr/src/io/prlog.c
deleted file mode 100644
index 6098460..0000000
--- a/nspr/pr/src/io/prlog.c
+++ /dev/null
@@ -1,554 +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/. */
-
-#include "primpl.h"
-#include "prenv.h"
-#include "prprf.h"
-#include <string.h>
-#ifdef ANDROID
-#include <android/log.h>
-#endif
-
-/*
- * Lock used to lock the log.
- *
- * We can't define _PR_LOCK_LOG simply as PR_Lock because PR_Lock may
- * contain assertions. We have to avoid assertions in _PR_LOCK_LOG
- * because PR_ASSERT calls PR_LogPrint, which in turn calls _PR_LOCK_LOG.
- * This can lead to infinite recursion.
- */
-static PRLock *_pr_logLock;
-#if defined(_PR_PTHREADS) || defined(_PR_BTHREADS)
-#define _PR_LOCK_LOG() PR_Lock(_pr_logLock);
-#define _PR_UNLOCK_LOG() PR_Unlock(_pr_logLock);
-#elif defined(_PR_GLOBAL_THREADS_ONLY)
-#define _PR_LOCK_LOG() { _PR_LOCK_LOCK(_pr_logLock)
-#define _PR_UNLOCK_LOG() _PR_LOCK_UNLOCK(_pr_logLock); }
-#else
-
-#define _PR_LOCK_LOG() \
-{ \
- PRIntn _is; \
- PRThread *_me = _PR_MD_CURRENT_THREAD(); \
- if (!_PR_IS_NATIVE_THREAD(_me)) \
- _PR_INTSOFF(_is); \
- _PR_LOCK_LOCK(_pr_logLock)
-
-#define _PR_UNLOCK_LOG() \
- _PR_LOCK_UNLOCK(_pr_logLock); \
- PR_ASSERT(_me == _PR_MD_CURRENT_THREAD()); \
- if (!_PR_IS_NATIVE_THREAD(_me)) \
- _PR_INTSON(_is); \
-}
-
-#endif
-
-#if defined(XP_PC)
-#define strcasecmp stricmp
-#endif
-
-/*
- * On NT, we can't define _PUT_LOG as PR_Write or _PR_MD_WRITE,
- * because every asynchronous file io operation leads to a fiber context
- * switch. So we define _PUT_LOG as fputs (from stdio.h). A side
- * benefit is that fputs handles the LF->CRLF translation. This
- * code can also be used on other platforms with file stream io.
- */
-#if defined(WIN32) || defined(XP_OS2)
-#define _PR_USE_STDIO_FOR_LOGGING
-#endif
-
-/*
-** Coerce Win32 log output to use OutputDebugString() when
-** NSPR_LOG_FILE is set to "WinDebug".
-*/
-#if defined(XP_PC)
-#define WIN32_DEBUG_FILE (FILE*)-2
-#endif
-
-#ifdef WINCE
-static void OutputDebugStringA(const char* msg) {
- int len = MultiByteToWideChar(CP_ACP, 0, msg, -1, 0, 0);
- WCHAR *wMsg = (WCHAR *)PR_Malloc(len * sizeof(WCHAR));
- MultiByteToWideChar(CP_ACP, 0, msg, -1, wMsg, len);
- OutputDebugStringW(wMsg);
- PR_Free(wMsg);
-}
-#endif
-
-/* Macros used to reduce #ifdef pollution */
-
-#if defined(_PR_USE_STDIO_FOR_LOGGING) && defined(XP_PC)
-#define _PUT_LOG(fd, buf, nb) \
- PR_BEGIN_MACRO \
- if (logFile == WIN32_DEBUG_FILE) { \
- char savebyte = buf[nb]; \
- buf[nb] = '\0'; \
- OutputDebugStringA(buf); \
- buf[nb] = savebyte; \
- } else { \
- fwrite(buf, 1, nb, fd); \
- fflush(fd); \
- } \
- PR_END_MACRO
-#elif defined(_PR_USE_STDIO_FOR_LOGGING)
-#define _PUT_LOG(fd, buf, nb) {fwrite(buf, 1, nb, fd); fflush(fd);}
-#elif defined(ANDROID)
-#define _PUT_LOG(fd, buf, nb) \
- PR_BEGIN_MACRO \
- if (fd == _pr_stderr) { \
- char savebyte = buf[nb]; \
- buf[nb] = '\0'; \
- __android_log_write(ANDROID_LOG_INFO, "PRLog", buf); \
- buf[nb] = savebyte; \
- } else { \
- PR_Write(fd, buf, nb); \
- } \
- PR_END_MACRO
-#elif defined(_PR_PTHREADS)
-#define _PUT_LOG(fd, buf, nb) PR_Write(fd, buf, nb)
-#else
-#define _PUT_LOG(fd, buf, nb) _PR_MD_WRITE(fd, buf, nb)
-#endif
-
-/************************************************************************/
-
-static PRLogModuleInfo *logModules;
-
-static char *logBuf = NULL;
-static char *logp;
-static char *logEndp;
-#ifdef _PR_USE_STDIO_FOR_LOGGING
-static FILE *logFile = NULL;
-#else
-static PRFileDesc *logFile = 0;
-#endif
-static PRBool outputTimeStamp = PR_FALSE;
-static PRBool appendToLog = PR_FALSE;
-
-#define LINE_BUF_SIZE 512
-#define DEFAULT_BUF_SIZE 16384
-
-#ifdef _PR_NEED_STRCASECMP
-
-/*
- * strcasecmp is defined in /usr/ucblib/libucb.a on some platforms
- * such as NCR and Unixware. Linking with both libc and libucb
- * may cause some problem, so I just provide our own implementation
- * of strcasecmp here.
- */
-
-static const unsigned char uc[] =
-{
- '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007',
- '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017',
- '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027',
- '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037',
- ' ', '!', '"', '#', '$', '%', '&', '\'',
- '(', ')', '*', '+', ',', '-', '.', '/',
- '0', '1', '2', '3', '4', '5', '6', '7',
- '8', '9', ':', ';', '<', '=', '>', '?',
- '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
- 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
- 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
- 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
- '`', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
- 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
- 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
- 'X', 'Y', 'Z', '{', '|', '}', '~', '\177'
-};
-
-PRIntn strcasecmp(const char *a, const char *b)
-{
- const unsigned char *ua = (const unsigned char *)a;
- const unsigned char *ub = (const unsigned char *)b;
-
- if( ((const char *)0 == a) || (const char *)0 == b )
- return (PRIntn)(a-b);
-
- while( (uc[*ua] == uc[*ub]) && ('\0' != *a) )
- {
- a++;
- ua++;
- ub++;
- }
-
- return (PRIntn)(uc[*ua] - uc[*ub]);
-}
-
-#endif /* _PR_NEED_STRCASECMP */
-
-void _PR_InitLog(void)
-{
- char *ev;
-
- _pr_logLock = PR_NewLock();
-
- ev = PR_GetEnv("NSPR_LOG_MODULES");
- if (ev && ev[0]) {
- char module[64]; /* Security-Critical: If you change this
- * size, you must also change the sscanf
- * format string to be size-1.
- */
- PRBool isSync = PR_FALSE;
- PRIntn evlen = strlen(ev), pos = 0;
- PRInt32 bufSize = DEFAULT_BUF_SIZE;
- while (pos < evlen) {
- PRIntn level = 1, count = 0, delta = 0;
- count = sscanf(&ev[pos], "%63[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-]%n:%d%n",
- module, &delta, &level, &delta);
- pos += delta;
- if (count == 0) break;
-
- /*
- ** If count == 2, then we got module and level. If count
- ** == 1, then level defaults to 1 (module enabled).
- */
- if (strcasecmp(module, "sync") == 0) {
- isSync = PR_TRUE;
- } else if (strcasecmp(module, "bufsize") == 0) {
- if (level >= LINE_BUF_SIZE) {
- bufSize = level;
- }
- } else if (strcasecmp(module, "timestamp") == 0) {
- outputTimeStamp = PR_TRUE;
- } else if (strcasecmp(module, "append") == 0) {
- appendToLog = PR_TRUE;
- } else {
- PRLogModuleInfo *lm = logModules;
- PRBool skip_modcheck =
- (0 == strcasecmp (module, "all")) ? PR_TRUE : PR_FALSE;
-
- while (lm != NULL) {
- if (skip_modcheck) lm -> level = (PRLogModuleLevel)level;
- else if (strcasecmp(module, lm->name) == 0) {
- lm->level = (PRLogModuleLevel)level;
- break;
- }
- lm = lm->next;
- }
- }
- /*found:*/
- count = sscanf(&ev[pos], " , %n", &delta);
- pos += delta;
- if (count == EOF) break;
- }
- PR_SetLogBuffering(isSync ? 0 : bufSize);
-
- ev = PR_GetEnvSecure("NSPR_LOG_FILE");
- if (ev && ev[0]) {
- if (!PR_SetLogFile(ev)) {
-#ifdef XP_PC
- char* str = PR_smprintf("Unable to create nspr log file '%s'\n", ev);
- if (str) {
- OutputDebugStringA(str);
- PR_smprintf_free(str);
- }
-#else
- fprintf(stderr, "Unable to create nspr log file '%s'\n", ev);
-#endif
- }
- } else {
-#ifdef _PR_USE_STDIO_FOR_LOGGING
- logFile = stderr;
-#else
- logFile = _pr_stderr;
-#endif
- }
- }
-}
-
-void _PR_LogCleanup(void)
-{
- PRLogModuleInfo *lm = logModules;
-
- PR_LogFlush();
-
-#ifdef _PR_USE_STDIO_FOR_LOGGING
- if (logFile
- && logFile != stdout
- && logFile != stderr
-#ifdef XP_PC
- && logFile != WIN32_DEBUG_FILE
-#endif
- ) {
- fclose(logFile);
- }
-#else
- if (logFile && logFile != _pr_stdout && logFile != _pr_stderr) {
- PR_Close(logFile);
- }
-#endif
- logFile = NULL;
-
- if (logBuf)
- PR_DELETE(logBuf);
-
- while (lm != NULL) {
- PRLogModuleInfo *next = lm->next;
- free((/*const*/ char *)lm->name);
- PR_Free(lm);
- lm = next;
- }
- logModules = NULL;
-
- if (_pr_logLock) {
- PR_DestroyLock(_pr_logLock);
- _pr_logLock = NULL;
- }
-}
-
-static void _PR_SetLogModuleLevel( PRLogModuleInfo *lm )
-{
- char *ev;
-
- ev = PR_GetEnv("NSPR_LOG_MODULES");
- if (ev && ev[0]) {
- char module[64]; /* Security-Critical: If you change this
- * size, you must also change the sscanf
- * format string to be size-1.
- */
- PRIntn evlen = strlen(ev), pos = 0;
- while (pos < evlen) {
- PRIntn level = 1, count = 0, delta = 0;
-
- count = sscanf(&ev[pos], "%63[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-]%n:%d%n",
- module, &delta, &level, &delta);
- pos += delta;
- if (count == 0) break;
-
- /*
- ** If count == 2, then we got module and level. If count
- ** == 1, then level defaults to 1 (module enabled).
- */
- if (lm != NULL)
- {
- if ((strcasecmp(module, "all") == 0)
- || (strcasecmp(module, lm->name) == 0))
- {
- lm->level = (PRLogModuleLevel)level;
- }
- }
- count = sscanf(&ev[pos], " , %n", &delta);
- pos += delta;
- if (count == EOF) break;
- }
- }
-} /* end _PR_SetLogModuleLevel() */
-
-PR_IMPLEMENT(PRLogModuleInfo*) PR_NewLogModule(const char *name)
-{
- PRLogModuleInfo *lm;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- lm = PR_NEWZAP(PRLogModuleInfo);
- if (lm) {
- lm->name = strdup(name);
- lm->level = PR_LOG_NONE;
- lm->next = logModules;
- logModules = lm;
- _PR_SetLogModuleLevel(lm);
- }
- return lm;
-}
-
-PR_IMPLEMENT(PRBool) PR_SetLogFile(const char *file)
-{
-#ifdef _PR_USE_STDIO_FOR_LOGGING
- FILE *newLogFile;
-
-#ifdef XP_PC
- if ( strcmp( file, "WinDebug") == 0)
- {
- newLogFile = WIN32_DEBUG_FILE;
- }
- else
-#endif
- {
- const char *mode = appendToLog ? "a" : "w";
- newLogFile = fopen(file, mode);
- if (!newLogFile)
- return PR_FALSE;
-
-#ifndef WINCE /* _IONBF does not exist in the Windows Mobile 6 SDK. */
- /* We do buffering ourselves. */
- setvbuf(newLogFile, NULL, _IONBF, 0);
-#endif
- }
- if (logFile
- && logFile != stdout
- && logFile != stderr
-#ifdef XP_PC
- && logFile != WIN32_DEBUG_FILE
-#endif
- ) {
- fclose(logFile);
- }
- logFile = newLogFile;
- return PR_TRUE;
-#else
- PRFileDesc *newLogFile;
- PRIntn flags = PR_WRONLY|PR_CREATE_FILE;
- if (appendToLog) {
- flags |= PR_APPEND;
- } else {
- flags |= PR_TRUNCATE;
- }
-
- newLogFile = PR_Open(file, flags, 0666);
- if (newLogFile) {
- if (logFile && logFile != _pr_stdout && logFile != _pr_stderr) {
- PR_Close(logFile);
- }
- logFile = newLogFile;
- }
- return (PRBool) (newLogFile != 0);
-#endif /* _PR_USE_STDIO_FOR_LOGGING */
-}
-
-PR_IMPLEMENT(void) PR_SetLogBuffering(PRIntn buffer_size)
-{
- PR_LogFlush();
-
- if (logBuf)
- PR_DELETE(logBuf);
-
- if (buffer_size >= LINE_BUF_SIZE) {
- logp = logBuf = (char*) PR_MALLOC(buffer_size);
- logEndp = logp + buffer_size;
- }
-}
-
-PR_IMPLEMENT(void) PR_LogPrint(const char *fmt, ...)
-{
- va_list ap;
- char line[LINE_BUF_SIZE];
- char *line_long = NULL;
- PRUint32 nb_tid = 0, nb;
- PRThread *me;
- PRExplodedTime now;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (!logFile) {
- return;
- }
-
- if (outputTimeStamp) {
- PR_ExplodeTime(PR_Now(), PR_GMTParameters, &now);
- nb_tid = PR_snprintf(line, sizeof(line)-1,
- "%04d-%02d-%02d %02d:%02d:%02d.%06d UTC - ",
- now.tm_year, now.tm_month + 1, now.tm_mday,
- now.tm_hour, now.tm_min, now.tm_sec,
- now.tm_usec);
- }
-
- me = PR_GetCurrentThread();
- nb_tid += PR_snprintf(line+nb_tid, sizeof(line)-nb_tid-1, "%ld[%p]: ",
-#if defined(_PR_BTHREADS)
- me, me);
-#else
- me ? me->id : 0L, me);
-#endif
-
- va_start(ap, fmt);
- nb = nb_tid + PR_vsnprintf(line+nb_tid, sizeof(line)-nb_tid-1, fmt, ap);
- va_end(ap);
-
- /*
- * Check if we might have run out of buffer space (in case we have a
- * long line), and malloc a buffer just this once.
- */
- if (nb == sizeof(line)-2) {
- va_start(ap, fmt);
- line_long = PR_vsmprintf(fmt, ap);
- va_end(ap);
- /* If this failed, we'll fall back to writing the truncated line. */
- }
-
- if (line_long) {
- nb = strlen(line_long);
- _PR_LOCK_LOG();
- if (logBuf != 0) {
- _PUT_LOG(logFile, logBuf, logp - logBuf);
- logp = logBuf;
- }
- /*
- * Write out the thread id (with an optional timestamp) and the
- * malloc'ed buffer.
- */
- _PUT_LOG(logFile, line, nb_tid);
- _PUT_LOG(logFile, line_long, nb);
- /* Ensure there is a trailing newline. */
- if (!nb || (line_long[nb-1] != '\n')) {
- char eol[2];
- eol[0] = '\n';
- eol[1] = '\0';
- _PUT_LOG(logFile, eol, 1);
- }
- _PR_UNLOCK_LOG();
- PR_smprintf_free(line_long);
- } else {
- /* Ensure there is a trailing newline. */
- if (nb && (line[nb-1] != '\n')) {
- line[nb++] = '\n';
- line[nb] = '\0';
- }
- _PR_LOCK_LOG();
- if (logBuf == 0) {
- _PUT_LOG(logFile, line, nb);
- } else {
- /* If nb can't fit into logBuf, write out logBuf first. */
- if (logp + nb > logEndp) {
- _PUT_LOG(logFile, logBuf, logp - logBuf);
- logp = logBuf;
- }
- /* nb is guaranteed to fit into logBuf. */
- memcpy(logp, line, nb);
- logp += nb;
- }
- _PR_UNLOCK_LOG();
- }
- PR_LogFlush();
-}
-
-PR_IMPLEMENT(void) PR_LogFlush(void)
-{
- if (logBuf && logFile) {
- _PR_LOCK_LOG();
- if (logp > logBuf) {
- _PUT_LOG(logFile, logBuf, logp - logBuf);
- logp = logBuf;
- }
- _PR_UNLOCK_LOG();
- }
-}
-
-PR_IMPLEMENT(void) PR_Abort(void)
-{
- PR_LogPrint("Aborting");
-#ifdef ANDROID
- __android_log_write(ANDROID_LOG_ERROR, "PRLog", "Aborting");
-#endif
- abort();
-}
-
-PR_IMPLEMENT(void) PR_Assert(const char *s, const char *file, PRIntn ln)
-{
- PR_LogPrint("Assertion failure: %s, at %s:%d\n", s, file, ln);
- fprintf(stderr, "Assertion failure: %s, at %s:%d\n", s, file, ln);
- fflush(stderr);
-#ifdef WIN32
- DebugBreak();
-#elif defined(XP_OS2)
- asm("int $3");
-#elif defined(ANDROID)
- __android_log_assert(NULL, "PRLog", "Assertion failure: %s, at %s:%d\n",
- s, file, ln);
-#endif
- abort();
-}
diff --git a/nspr/pr/src/io/prmapopt.c b/nspr/pr/src/io/prmapopt.c
deleted file mode 100644
index f92a76b..0000000
--- a/nspr/pr/src/io/prmapopt.c
+++ /dev/null
@@ -1,458 +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/. */
-
-/*
- * This file defines _PR_MapOptionName(). The purpose of putting
- * _PR_MapOptionName() in a separate file is to work around a Winsock
- * header file problem on Windows NT.
- *
- * On Windows NT, if we define _WIN32_WINNT to be 0x0400 (in order
- * to use Service Pack 3 extensions), windows.h includes winsock2.h
- * (instead of winsock.h), which doesn't define many socket options
- * defined in winsock.h.
- *
- * We need the socket options defined in winsock.h. So this file
- * includes winsock.h, with _WIN32_WINNT undefined.
- */
-
-#if defined(WINNT) || defined(__MINGW32__)
-#include <winsock.h>
-#endif
-
-/* MinGW doesn't define these in its winsock.h. */
-#ifdef __MINGW32__
-#ifndef IP_TTL
-#define IP_TTL 7
-#endif
-#ifndef IP_TOS
-#define IP_TOS 8
-#endif
-#endif
-
-#include "primpl.h"
-
-#ifdef HAVE_NETINET_TCP_H
-#include <netinet/tcp.h> /* TCP_NODELAY, TCP_MAXSEG */
-#endif
-
-#ifndef _PR_PTHREADS
-
-PRStatus PR_CALLBACK _PR_SocketGetSocketOption(PRFileDesc *fd, PRSocketOptionData *data)
-{
- PRStatus rv;
- PRInt32 length;
- PRInt32 level, name;
-
- /*
- * PR_SockOpt_Nonblocking is a special case that does not
- * translate to a getsockopt() call
- */
- if (PR_SockOpt_Nonblocking == data->option)
- {
- data->value.non_blocking = fd->secret->nonblocking;
- return PR_SUCCESS;
- }
-
- rv = _PR_MapOptionName(data->option, &level, &name);
- if (PR_SUCCESS == rv)
- {
- switch (data->option)
- {
- case PR_SockOpt_Linger:
- {
-#if !defined(XP_BEOS) || defined(BONE_VERSION)
- struct linger linger;
- length = sizeof(linger);
- rv = _PR_MD_GETSOCKOPT(
- fd, level, name, (char *) &linger, &length);
- if (PR_SUCCESS == rv)
- {
- PR_ASSERT(sizeof(linger) == length);
- data->value.linger.polarity =
- (linger.l_onoff) ? PR_TRUE : PR_FALSE;
- data->value.linger.linger =
- PR_SecondsToInterval(linger.l_linger);
- }
- break;
-#else
- PR_SetError( PR_NOT_IMPLEMENTED_ERROR, 0 );
- return PR_FAILURE;
-#endif
- }
- case PR_SockOpt_Reuseaddr:
- case PR_SockOpt_Keepalive:
- case PR_SockOpt_NoDelay:
- case PR_SockOpt_Broadcast:
- case PR_SockOpt_Reuseport:
- {
-#ifdef WIN32 /* Winsock */
- BOOL value;
-#else
- PRIntn value;
-#endif
- length = sizeof(value);
- rv = _PR_MD_GETSOCKOPT(
- fd, level, name, (char*)&value, &length);
- if (PR_SUCCESS == rv)
- data->value.reuse_addr = (0 == value) ? PR_FALSE : PR_TRUE;
- break;
- }
- case PR_SockOpt_McastLoopback:
- {
-#ifdef WIN32 /* Winsock */
- BOOL bool;
-#else
- PRUint8 bool;
-#endif
- length = sizeof(bool);
- rv = _PR_MD_GETSOCKOPT(
- fd, level, name, (char*)&bool, &length);
- if (PR_SUCCESS == rv)
- data->value.mcast_loopback = (0 == bool) ? PR_FALSE : PR_TRUE;
- break;
- }
- case PR_SockOpt_RecvBufferSize:
- case PR_SockOpt_SendBufferSize:
- case PR_SockOpt_MaxSegment:
- {
- PRIntn value;
- length = sizeof(value);
- rv = _PR_MD_GETSOCKOPT(
- fd, level, name, (char*)&value, &length);
- if (PR_SUCCESS == rv)
- data->value.recv_buffer_size = value;
- break;
- }
- case PR_SockOpt_IpTimeToLive:
- case PR_SockOpt_IpTypeOfService:
- {
- /* These options should really be an int (or PRIntn). */
- length = sizeof(PRUintn);
- rv = _PR_MD_GETSOCKOPT(
- fd, level, name, (char*)&data->value.ip_ttl, &length);
- break;
- }
- case PR_SockOpt_McastTimeToLive:
- {
-#ifdef WIN32 /* Winsock */
- int ttl;
-#else
- PRUint8 ttl;
-#endif
- length = sizeof(ttl);
- rv = _PR_MD_GETSOCKOPT(
- fd, level, name, (char*)&ttl, &length);
- if (PR_SUCCESS == rv)
- data->value.mcast_ttl = ttl;
- break;
- }
-#ifdef IP_ADD_MEMBERSHIP
- case PR_SockOpt_AddMember:
- case PR_SockOpt_DropMember:
- {
- struct ip_mreq mreq;
- length = sizeof(mreq);
- rv = _PR_MD_GETSOCKOPT(
- fd, level, name, (char*)&mreq, &length);
- if (PR_SUCCESS == rv)
- {
- data->value.add_member.mcaddr.inet.ip =
- mreq.imr_multiaddr.s_addr;
- data->value.add_member.ifaddr.inet.ip =
- mreq.imr_interface.s_addr;
- }
- break;
- }
-#endif /* IP_ADD_MEMBERSHIP */
- case PR_SockOpt_McastInterface:
- {
- /* This option is a struct in_addr. */
- length = sizeof(data->value.mcast_if.inet.ip);
- rv = _PR_MD_GETSOCKOPT(
- fd, level, name,
- (char*)&data->value.mcast_if.inet.ip, &length);
- break;
- }
- default:
- PR_NOT_REACHED("Unknown socket option");
- break;
- }
- }
- return rv;
-} /* _PR_SocketGetSocketOption */
-
-PRStatus PR_CALLBACK _PR_SocketSetSocketOption(PRFileDesc *fd, const PRSocketOptionData *data)
-{
- PRStatus rv;
- PRInt32 level, name;
-
- /*
- * PR_SockOpt_Nonblocking is a special case that does not
- * translate to a setsockopt call.
- */
- if (PR_SockOpt_Nonblocking == data->option)
- {
-#ifdef WINNT
- PR_ASSERT((fd->secret->md.io_model_committed == PR_FALSE)
- || (fd->secret->nonblocking == data->value.non_blocking));
- if (fd->secret->md.io_model_committed
- && (fd->secret->nonblocking != data->value.non_blocking))
- {
- /*
- * On NT, once we have associated a socket with the io
- * completion port, we can't disassociate it. So we
- * can't change the nonblocking option of the socket
- * afterwards.
- */
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
-#endif
- fd->secret->nonblocking = data->value.non_blocking;
- return PR_SUCCESS;
- }
-
- rv = _PR_MapOptionName(data->option, &level, &name);
- if (PR_SUCCESS == rv)
- {
- switch (data->option)
- {
- case PR_SockOpt_Linger:
- {
-#if !defined(XP_BEOS) || defined(BONE_VERSION)
- struct linger linger;
- linger.l_onoff = data->value.linger.polarity;
- linger.l_linger = PR_IntervalToSeconds(data->value.linger.linger);
- rv = _PR_MD_SETSOCKOPT(
- fd, level, name, (char*)&linger, sizeof(linger));
- break;
-#else
- PR_SetError( PR_NOT_IMPLEMENTED_ERROR, 0 );
- return PR_FAILURE;
-#endif
- }
- case PR_SockOpt_Reuseaddr:
- case PR_SockOpt_Keepalive:
- case PR_SockOpt_NoDelay:
- case PR_SockOpt_Broadcast:
- case PR_SockOpt_Reuseport:
- {
-#ifdef WIN32 /* Winsock */
- BOOL value;
-#else
- PRIntn value;
-#endif
- value = (data->value.reuse_addr) ? 1 : 0;
- rv = _PR_MD_SETSOCKOPT(
- fd, level, name, (char*)&value, sizeof(value));
- break;
- }
- case PR_SockOpt_McastLoopback:
- {
-#ifdef WIN32 /* Winsock */
- BOOL bool;
-#else
- PRUint8 bool;
-#endif
- bool = data->value.mcast_loopback ? 1 : 0;
- rv = _PR_MD_SETSOCKOPT(
- fd, level, name, (char*)&bool, sizeof(bool));
- break;
- }
- case PR_SockOpt_RecvBufferSize:
- case PR_SockOpt_SendBufferSize:
- case PR_SockOpt_MaxSegment:
- {
- PRIntn value = data->value.recv_buffer_size;
- rv = _PR_MD_SETSOCKOPT(
- fd, level, name, (char*)&value, sizeof(value));
- break;
- }
- case PR_SockOpt_IpTimeToLive:
- case PR_SockOpt_IpTypeOfService:
- {
- /* These options should really be an int (or PRIntn). */
- rv = _PR_MD_SETSOCKOPT(
- fd, level, name, (char*)&data->value.ip_ttl, sizeof(PRUintn));
- break;
- }
- case PR_SockOpt_McastTimeToLive:
- {
-#ifdef WIN32 /* Winsock */
- int ttl;
-#else
- PRUint8 ttl;
-#endif
- ttl = data->value.mcast_ttl;
- rv = _PR_MD_SETSOCKOPT(
- fd, level, name, (char*)&ttl, sizeof(ttl));
- break;
- }
-#ifdef IP_ADD_MEMBERSHIP
- case PR_SockOpt_AddMember:
- case PR_SockOpt_DropMember:
- {
- struct ip_mreq mreq;
- mreq.imr_multiaddr.s_addr =
- data->value.add_member.mcaddr.inet.ip;
- mreq.imr_interface.s_addr =
- data->value.add_member.ifaddr.inet.ip;
- rv = _PR_MD_SETSOCKOPT(
- fd, level, name, (char*)&mreq, sizeof(mreq));
- break;
- }
-#endif /* IP_ADD_MEMBERSHIP */
- case PR_SockOpt_McastInterface:
- {
- /* This option is a struct in_addr. */
- rv = _PR_MD_SETSOCKOPT(
- fd, level, name, (char*)&data->value.mcast_if.inet.ip,
- sizeof(data->value.mcast_if.inet.ip));
- break;
- }
- default:
- PR_NOT_REACHED("Unknown socket option");
- break;
- }
- }
- return rv;
-} /* _PR_SocketSetSocketOption */
-
-#endif /* ! _PR_PTHREADS */
-
-/*
- *********************************************************************
- *********************************************************************
- **
- ** Make sure that the following is at the end of this file,
- ** because we will be playing with macro redefines.
- **
- *********************************************************************
- *********************************************************************
- */
-
-/*
- * Not every platform has all the socket options we want to
- * support. Some older operating systems such as SunOS 4.1.3
- * don't have the IP multicast socket options. Win32 doesn't
- * have TCP_MAXSEG.
- *
- * To deal with this problem, we define the missing socket
- * options as _PR_NO_SUCH_SOCKOPT. _PR_MapOptionName() fails with
- * PR_OPERATION_NOT_SUPPORTED_ERROR if a socket option not
- * available on the platform is requested.
- */
-
-/*
- * Sanity check. SO_LINGER and TCP_NODELAY should be available
- * on all platforms. Just to make sure we have included the
- * appropriate header files. Then any undefined socket options
- * are really missing.
- */
-
-#if !defined(SO_LINGER)
-#error "SO_LINGER is not defined"
-#endif
-
-#if !defined(TCP_NODELAY)
-#error "TCP_NODELAY is not defined"
-#endif
-
-/*
- * Make sure the value of _PR_NO_SUCH_SOCKOPT is not
- * a valid socket option.
- */
-#define _PR_NO_SUCH_SOCKOPT -1
-
-#ifndef SO_KEEPALIVE
-#define SO_KEEPALIVE _PR_NO_SUCH_SOCKOPT
-#endif
-
-#ifndef SO_SNDBUF
-#define SO_SNDBUF _PR_NO_SUCH_SOCKOPT
-#endif
-
-#ifndef SO_RCVBUF
-#define SO_RCVBUF _PR_NO_SUCH_SOCKOPT
-#endif
-
-#ifndef IP_MULTICAST_IF /* set/get IP multicast interface */
-#define IP_MULTICAST_IF _PR_NO_SUCH_SOCKOPT
-#endif
-
-#ifndef IP_MULTICAST_TTL /* set/get IP multicast timetolive */
-#define IP_MULTICAST_TTL _PR_NO_SUCH_SOCKOPT
-#endif
-
-#ifndef IP_MULTICAST_LOOP /* set/get IP multicast loopback */
-#define IP_MULTICAST_LOOP _PR_NO_SUCH_SOCKOPT
-#endif
-
-#ifndef IP_ADD_MEMBERSHIP /* add an IP group membership */
-#define IP_ADD_MEMBERSHIP _PR_NO_SUCH_SOCKOPT
-#endif
-
-#ifndef IP_DROP_MEMBERSHIP /* drop an IP group membership */
-#define IP_DROP_MEMBERSHIP _PR_NO_SUCH_SOCKOPT
-#endif
-
-#ifndef IP_TTL /* set/get IP Time To Live */
-#define IP_TTL _PR_NO_SUCH_SOCKOPT
-#endif
-
-#ifndef IP_TOS /* set/get IP Type Of Service */
-#define IP_TOS _PR_NO_SUCH_SOCKOPT
-#endif
-
-#ifndef TCP_NODELAY /* don't delay to coalesce data */
-#define TCP_NODELAY _PR_NO_SUCH_SOCKOPT
-#endif
-
-#ifndef TCP_MAXSEG /* maxumum segment size for tcp */
-#define TCP_MAXSEG _PR_NO_SUCH_SOCKOPT
-#endif
-
-#ifndef SO_BROADCAST /* enable broadcast on UDP sockets */
-#define SO_BROADCAST _PR_NO_SUCH_SOCKOPT
-#endif
-
-#ifndef SO_REUSEPORT /* allow local address & port reuse */
-#define SO_REUSEPORT _PR_NO_SUCH_SOCKOPT
-#endif
-
-PRStatus _PR_MapOptionName(
- PRSockOption optname, PRInt32 *level, PRInt32 *name)
-{
- static PRInt32 socketOptions[PR_SockOpt_Last] =
- {
- 0, SO_LINGER, SO_REUSEADDR, SO_KEEPALIVE, SO_RCVBUF, SO_SNDBUF,
- IP_TTL, IP_TOS, IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP,
- IP_MULTICAST_IF, IP_MULTICAST_TTL, IP_MULTICAST_LOOP,
- TCP_NODELAY, TCP_MAXSEG, SO_BROADCAST, SO_REUSEPORT
- };
- static PRInt32 socketLevels[PR_SockOpt_Last] =
- {
- 0, SOL_SOCKET, SOL_SOCKET, SOL_SOCKET, SOL_SOCKET, SOL_SOCKET,
- IPPROTO_IP, IPPROTO_IP, IPPROTO_IP, IPPROTO_IP,
- IPPROTO_IP, IPPROTO_IP, IPPROTO_IP,
- IPPROTO_TCP, IPPROTO_TCP, SOL_SOCKET, SOL_SOCKET
- };
-
- if ((optname < PR_SockOpt_Linger)
- || (optname >= PR_SockOpt_Last))
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
-
- if (socketOptions[optname] == _PR_NO_SUCH_SOCKOPT)
- {
- PR_SetError(PR_OPERATION_NOT_SUPPORTED_ERROR, 0);
- return PR_FAILURE;
- }
- *name = socketOptions[optname];
- *level = socketLevels[optname];
- return PR_SUCCESS;
-} /* _PR_MapOptionName */
diff --git a/nspr/pr/src/io/prmmap.c b/nspr/pr/src/io/prmmap.c
deleted file mode 100644
index 6ffc133..0000000
--- a/nspr/pr/src/io/prmmap.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/. */
-
-/*
- *********************************************************************
- *
- * Memory-mapped files
- *
- *********************************************************************
- */
-
-#include "primpl.h"
-
-PR_IMPLEMENT(PRFileMap *) PR_CreateFileMap(
- PRFileDesc *fd,
- PRInt64 size,
- PRFileMapProtect prot)
-{
- PRFileMap *fmap;
-
- PR_ASSERT(prot == PR_PROT_READONLY || prot == PR_PROT_READWRITE
- || prot == PR_PROT_WRITECOPY);
- fmap = PR_NEWZAP(PRFileMap);
- if (NULL == fmap) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
- fmap->fd = fd;
- fmap->prot = prot;
- if (_PR_MD_CREATE_FILE_MAP(fmap, size) == PR_SUCCESS) {
- return fmap;
- } else {
- PR_DELETE(fmap);
- return NULL;
- }
-}
-
-PR_IMPLEMENT(PRInt32) PR_GetMemMapAlignment(void)
-{
- return _PR_MD_GET_MEM_MAP_ALIGNMENT();
-}
-
-PR_IMPLEMENT(void *) PR_MemMap(
- PRFileMap *fmap,
- PROffset64 offset,
- PRUint32 len)
-{
- return _PR_MD_MEM_MAP(fmap, offset, len);
-}
-
-PR_IMPLEMENT(PRStatus) PR_MemUnmap(void *addr, PRUint32 len)
-{
- return _PR_MD_MEM_UNMAP(addr, len);
-}
-
-PR_IMPLEMENT(PRStatus) PR_CloseFileMap(PRFileMap *fmap)
-{
- return _PR_MD_CLOSE_FILE_MAP(fmap);
-}
-
-PR_IMPLEMENT(PRStatus) PR_SyncMemMap(
- PRFileDesc *fd,
- void *addr,
- PRUint32 len)
-{
- return _PR_MD_SYNC_MEM_MAP(fd, addr, len);
-}
diff --git a/nspr/pr/src/io/prmwait.c b/nspr/pr/src/io/prmwait.c
deleted file mode 100644
index ab32fb5..0000000
--- a/nspr/pr/src/io/prmwait.c
+++ /dev/null
@@ -1,1457 +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/. */
-
-#include "primpl.h"
-#include "pprmwait.h"
-
-#define _MW_REHASH_MAX 11
-
-static PRLock *mw_lock = NULL;
-static _PRGlobalState *mw_state = NULL;
-
-static PRIntervalTime max_polling_interval;
-
-#ifdef WINNT
-
-typedef struct TimerEvent {
- PRIntervalTime absolute;
- void (*func)(void *);
- void *arg;
- LONG ref_count;
- PRCList links;
-} TimerEvent;
-
-#define TIMER_EVENT_PTR(_qp) \
- ((TimerEvent *) ((char *) (_qp) - offsetof(TimerEvent, links)))
-
-struct {
- PRLock *ml;
- PRCondVar *new_timer;
- PRCondVar *cancel_timer;
- PRThread *manager_thread;
- PRCList timer_queue;
-} tm_vars;
-
-static PRStatus TimerInit(void);
-static void TimerManager(void *arg);
-static TimerEvent *CreateTimer(PRIntervalTime timeout,
- void (*func)(void *), void *arg);
-static PRBool CancelTimer(TimerEvent *timer);
-
-static void TimerManager(void *arg)
-{
- PRIntervalTime now;
- PRIntervalTime timeout;
- PRCList *head;
- TimerEvent *timer;
-
- PR_Lock(tm_vars.ml);
- while (1)
- {
- if (PR_CLIST_IS_EMPTY(&tm_vars.timer_queue))
- {
- PR_WaitCondVar(tm_vars.new_timer, PR_INTERVAL_NO_TIMEOUT);
- }
- else
- {
- now = PR_IntervalNow();
- head = PR_LIST_HEAD(&tm_vars.timer_queue);
- timer = TIMER_EVENT_PTR(head);
- if ((PRInt32) (now - timer->absolute) >= 0)
- {
- PR_REMOVE_LINK(head);
- /*
- * make its prev and next point to itself so that
- * it's obvious that it's not on the timer_queue.
- */
- PR_INIT_CLIST(head);
- PR_ASSERT(2 == timer->ref_count);
- PR_Unlock(tm_vars.ml);
- timer->func(timer->arg);
- PR_Lock(tm_vars.ml);
- timer->ref_count -= 1;
- if (0 == timer->ref_count)
- {
- PR_NotifyAllCondVar(tm_vars.cancel_timer);
- }
- }
- else
- {
- timeout = (PRIntervalTime)(timer->absolute - now);
- PR_WaitCondVar(tm_vars.new_timer, timeout);
- }
- }
- }
- PR_Unlock(tm_vars.ml);
-}
-
-static TimerEvent *CreateTimer(
- PRIntervalTime timeout,
- void (*func)(void *),
- void *arg)
-{
- TimerEvent *timer;
- PRCList *links, *tail;
- TimerEvent *elem;
-
- timer = PR_NEW(TimerEvent);
- if (NULL == timer)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return timer;
- }
- timer->absolute = PR_IntervalNow() + timeout;
- timer->func = func;
- timer->arg = arg;
- timer->ref_count = 2;
- PR_Lock(tm_vars.ml);
- tail = links = PR_LIST_TAIL(&tm_vars.timer_queue);
- while (links->prev != tail)
- {
- elem = TIMER_EVENT_PTR(links);
- if ((PRInt32)(timer->absolute - elem->absolute) >= 0)
- {
- break;
- }
- links = links->prev;
- }
- PR_INSERT_AFTER(&timer->links, links);
- PR_NotifyCondVar(tm_vars.new_timer);
- PR_Unlock(tm_vars.ml);
- return timer;
-}
-
-static PRBool CancelTimer(TimerEvent *timer)
-{
- PRBool canceled = PR_FALSE;
-
- PR_Lock(tm_vars.ml);
- timer->ref_count -= 1;
- if (timer->links.prev == &timer->links)
- {
- while (timer->ref_count == 1)
- {
- PR_WaitCondVar(tm_vars.cancel_timer, PR_INTERVAL_NO_TIMEOUT);
- }
- }
- else
- {
- PR_REMOVE_LINK(&timer->links);
- canceled = PR_TRUE;
- }
- PR_Unlock(tm_vars.ml);
- PR_DELETE(timer);
- return canceled;
-}
-
-static PRStatus TimerInit(void)
-{
- tm_vars.ml = PR_NewLock();
- if (NULL == tm_vars.ml)
- {
- goto failed;
- }
- tm_vars.new_timer = PR_NewCondVar(tm_vars.ml);
- if (NULL == tm_vars.new_timer)
- {
- goto failed;
- }
- tm_vars.cancel_timer = PR_NewCondVar(tm_vars.ml);
- if (NULL == tm_vars.cancel_timer)
- {
- goto failed;
- }
- PR_INIT_CLIST(&tm_vars.timer_queue);
- tm_vars.manager_thread = PR_CreateThread(
- PR_SYSTEM_THREAD, TimerManager, NULL, PR_PRIORITY_NORMAL,
- PR_LOCAL_THREAD, PR_UNJOINABLE_THREAD, 0);
- if (NULL == tm_vars.manager_thread)
- {
- goto failed;
- }
- return PR_SUCCESS;
-
-failed:
- if (NULL != tm_vars.cancel_timer)
- {
- PR_DestroyCondVar(tm_vars.cancel_timer);
- }
- if (NULL != tm_vars.new_timer)
- {
- PR_DestroyCondVar(tm_vars.new_timer);
- }
- if (NULL != tm_vars.ml)
- {
- PR_DestroyLock(tm_vars.ml);
- }
- return PR_FAILURE;
-}
-
-#endif /* WINNT */
-
-/******************************************************************/
-/******************************************************************/
-/************************ The private portion *********************/
-/******************************************************************/
-/******************************************************************/
-void _PR_InitMW(void)
-{
-#ifdef WINNT
- /*
- * We use NT 4's InterlockedCompareExchange() to operate
- * on PRMWStatus variables.
- */
- PR_ASSERT(sizeof(LONG) == sizeof(PRMWStatus));
- TimerInit();
-#endif
- mw_lock = PR_NewLock();
- PR_ASSERT(NULL != mw_lock);
- mw_state = PR_NEWZAP(_PRGlobalState);
- PR_ASSERT(NULL != mw_state);
- PR_INIT_CLIST(&mw_state->group_list);
- max_polling_interval = PR_MillisecondsToInterval(MAX_POLLING_INTERVAL);
-} /* _PR_InitMW */
-
-void _PR_CleanupMW(void)
-{
- PR_DestroyLock(mw_lock);
- mw_lock = NULL;
- if (mw_state->group) {
- PR_DestroyWaitGroup(mw_state->group);
- /* mw_state->group is set to NULL as a side effect. */
- }
- PR_DELETE(mw_state);
-} /* _PR_CleanupMW */
-
-static PRWaitGroup *MW_Init2(void)
-{
- PRWaitGroup *group = mw_state->group; /* it's the null group */
- if (NULL == group) /* there is this special case */
- {
- group = PR_CreateWaitGroup(_PR_DEFAULT_HASH_LENGTH);
- if (NULL == group) goto failed_alloc;
- PR_Lock(mw_lock);
- if (NULL == mw_state->group)
- {
- mw_state->group = group;
- group = NULL;
- }
- PR_Unlock(mw_lock);
- if (group != NULL) (void)PR_DestroyWaitGroup(group);
- group = mw_state->group; /* somebody beat us to it */
- }
-failed_alloc:
- return group; /* whatever */
-} /* MW_Init2 */
-
-static _PR_HashStory MW_AddHashInternal(PRRecvWait *desc, _PRWaiterHash *hash)
-{
- /*
- ** The entries are put in the table using the fd (PRFileDesc*) of
- ** the receive descriptor as the key. This allows us to locate
- ** the appropriate entry aqain when the poll operation finishes.
- **
- ** The pointer to the file descriptor object is first divided by
- ** the natural alignment of a pointer in the belief that object
- ** will have at least that many zeros in the low order bits.
- ** This may not be a good assuption.
- **
- ** We try to put the entry in by rehashing _MW_REHASH_MAX times. After
- ** that we declare defeat and force the table to be reconstructed.
- ** Since some fds might be added more than once, won't that cause
- ** collisions even in an empty table?
- */
- PRIntn rehash = _MW_REHASH_MAX;
- PRRecvWait **waiter;
- PRUintn hidx = _MW_HASH(desc->fd, hash->length);
- PRUintn hoffset = 0;
-
- while (rehash-- > 0)
- {
- waiter = &hash->recv_wait;
- if (NULL == waiter[hidx])
- {
- waiter[hidx] = desc;
- hash->count += 1;
-#if 0
- printf("Adding 0x%x->0x%x ", desc, desc->fd);
- printf(
- "table[%u:%u:*%u]: 0x%x->0x%x\n",
- hidx, hash->count, hash->length, waiter[hidx], waiter[hidx]->fd);
-#endif
- return _prmw_success;
- }
- if (desc == waiter[hidx])
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0); /* desc already in table */
- return _prmw_error;
- }
-#if 0
- printf("Failing 0x%x->0x%x ", desc, desc->fd);
- printf(
- "table[*%u:%u:%u]: 0x%x->0x%x\n",
- hidx, hash->count, hash->length, waiter[hidx], waiter[hidx]->fd);
-#endif
- if (0 == hoffset)
- {
- hoffset = _MW_HASH2(desc->fd, hash->length);
- PR_ASSERT(0 != hoffset);
- }
- hidx = (hidx + hoffset) % (hash->length);
- }
- return _prmw_rehash;
-} /* MW_AddHashInternal */
-
-static _PR_HashStory MW_ExpandHashInternal(PRWaitGroup *group)
-{
- PRRecvWait **desc;
- PRUint32 pidx, length;
- _PRWaiterHash *newHash, *oldHash = group->waiter;
- PRBool retry;
- _PR_HashStory hrv;
-
- static const PRInt32 prime_number[] = {
- _PR_DEFAULT_HASH_LENGTH, 179, 521, 907, 1427,
- 2711, 3917, 5021, 8219, 11549, 18911, 26711, 33749, 44771};
- PRUintn primes = (sizeof(prime_number) / sizeof(PRInt32));
-
- /* look up the next size we'd like to use for the hash table */
- for (pidx = 0; pidx < primes; ++pidx)
- {
- if (prime_number[pidx] == oldHash->length)
- {
- break;
- }
- }
- /* table size must be one of the prime numbers */
- PR_ASSERT(pidx < primes);
-
- /* if pidx == primes - 1, we can't expand the table any more */
- while (pidx < primes - 1)
- {
- /* next size */
- ++pidx;
- length = prime_number[pidx];
-
- /* allocate the new hash table and fill it in with the old */
- newHash = (_PRWaiterHash*)PR_CALLOC(
- sizeof(_PRWaiterHash) + (length * sizeof(PRRecvWait*)));
- if (NULL == newHash)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return _prmw_error;
- }
-
- newHash->length = length;
- retry = PR_FALSE;
- for (desc = &oldHash->recv_wait;
- newHash->count < oldHash->count; ++desc)
- {
- PR_ASSERT(desc < &oldHash->recv_wait + oldHash->length);
- if (NULL != *desc)
- {
- hrv = MW_AddHashInternal(*desc, newHash);
- PR_ASSERT(_prmw_error != hrv);
- if (_prmw_success != hrv)
- {
- PR_DELETE(newHash);
- retry = PR_TRUE;
- break;
- }
- }
- }
- if (retry) continue;
-
- PR_DELETE(group->waiter);
- group->waiter = newHash;
- group->p_timestamp += 1;
- return _prmw_success;
- }
-
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return _prmw_error; /* we're hosed */
-} /* MW_ExpandHashInternal */
-
-#ifndef WINNT
-static void _MW_DoneInternal(
- PRWaitGroup *group, PRRecvWait **waiter, PRMWStatus outcome)
-{
- /*
- ** Add this receive wait object to the list of finished I/O
- ** operations for this particular group. If there are other
- ** threads waiting on the group, notify one. If not, arrange
- ** for this thread to return.
- */
-
-#if 0
- printf("Removing 0x%x->0x%x\n", *waiter, (*waiter)->fd);
-#endif
- (*waiter)->outcome = outcome;
- PR_APPEND_LINK(&((*waiter)->internal), &group->io_ready);
- PR_NotifyCondVar(group->io_complete);
- PR_ASSERT(0 != group->waiter->count);
- group->waiter->count -= 1;
- *waiter = NULL;
-} /* _MW_DoneInternal */
-#endif /* WINNT */
-
-static PRRecvWait **_MW_LookupInternal(PRWaitGroup *group, PRFileDesc *fd)
-{
- /*
- ** Find the receive wait object corresponding to the file descriptor.
- ** Only search the wait group specified.
- */
- PRRecvWait **desc;
- PRIntn rehash = _MW_REHASH_MAX;
- _PRWaiterHash *hash = group->waiter;
- PRUintn hidx = _MW_HASH(fd, hash->length);
- PRUintn hoffset = 0;
-
- while (rehash-- > 0)
- {
- desc = (&hash->recv_wait) + hidx;
- if ((*desc != NULL) && ((*desc)->fd == fd)) return desc;
- if (0 == hoffset)
- {
- hoffset = _MW_HASH2(fd, hash->length);
- PR_ASSERT(0 != hoffset);
- }
- hidx = (hidx + hoffset) % (hash->length);
- }
- return NULL;
-} /* _MW_LookupInternal */
-
-#ifndef WINNT
-static PRStatus _MW_PollInternal(PRWaitGroup *group)
-{
- PRRecvWait **waiter;
- PRStatus rv = PR_FAILURE;
- PRInt32 count, count_ready;
- PRIntervalTime polling_interval;
-
- group->poller = PR_GetCurrentThread();
-
- while (PR_TRUE)
- {
- PRIntervalTime now, since_last_poll;
- PRPollDesc *poll_list;
-
- while (0 == group->waiter->count)
- {
- PRStatus st;
- st = PR_WaitCondVar(group->new_business, PR_INTERVAL_NO_TIMEOUT);
- if (_prmw_running != group->state)
- {
- PR_SetError(PR_INVALID_STATE_ERROR, 0);
- goto aborted;
- }
- if (_MW_ABORTED(st)) goto aborted;
- }
-
- /*
- ** There's something to do. See if our existing polling list
- ** is large enough for what we have to do?
- */
-
- while (group->polling_count < group->waiter->count)
- {
- PRUint32 old_count = group->waiter->count;
- PRUint32 new_count = PR_ROUNDUP(old_count, _PR_POLL_COUNT_FUDGE);
- PRSize new_size = sizeof(PRPollDesc) * new_count;
- PRPollDesc *old_polling_list = group->polling_list;
-
- PR_Unlock(group->ml);
- poll_list = (PRPollDesc*)PR_CALLOC(new_size);
- if (NULL == poll_list)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- PR_Lock(group->ml);
- goto failed_alloc;
- }
- if (NULL != old_polling_list)
- PR_DELETE(old_polling_list);
- PR_Lock(group->ml);
- if (_prmw_running != group->state)
- {
- PR_DELETE(poll_list);
- PR_SetError(PR_INVALID_STATE_ERROR, 0);
- goto aborted;
- }
- group->polling_list = poll_list;
- group->polling_count = new_count;
- }
-
- now = PR_IntervalNow();
- polling_interval = max_polling_interval;
- since_last_poll = now - group->last_poll;
-
- waiter = &group->waiter->recv_wait;
- poll_list = group->polling_list;
- for (count = 0; count < group->waiter->count; ++waiter)
- {
- PR_ASSERT(waiter < &group->waiter->recv_wait
- + group->waiter->length);
- if (NULL != *waiter) /* a live one! */
- {
- if ((PR_INTERVAL_NO_TIMEOUT != (*waiter)->timeout)
- && (since_last_poll >= (*waiter)->timeout))
- _MW_DoneInternal(group, waiter, PR_MW_TIMEOUT);
- else
- {
- if (PR_INTERVAL_NO_TIMEOUT != (*waiter)->timeout)
- {
- (*waiter)->timeout -= since_last_poll;
- if ((*waiter)->timeout < polling_interval)
- polling_interval = (*waiter)->timeout;
- }
- PR_ASSERT(poll_list < group->polling_list
- + group->polling_count);
- poll_list->fd = (*waiter)->fd;
- poll_list->in_flags = PR_POLL_READ;
- poll_list->out_flags = 0;
-#if 0
- printf(
- "Polling 0x%x[%d]: [fd: 0x%x, tmo: %u]\n",
- poll_list, count, poll_list->fd, (*waiter)->timeout);
-#endif
- poll_list += 1;
- count += 1;
- }
- }
- }
-
- PR_ASSERT(count == group->waiter->count);
-
- /*
- ** If there are no more threads waiting for completion,
- ** we need to return.
- */
- if ((!PR_CLIST_IS_EMPTY(&group->io_ready))
- && (1 == group->waiting_threads)) break;
-
- if (0 == count) continue; /* wait for new business */
-
- group->last_poll = now;
-
- PR_Unlock(group->ml);
-
- count_ready = PR_Poll(group->polling_list, count, polling_interval);
-
- PR_Lock(group->ml);
-
- if (_prmw_running != group->state)
- {
- PR_SetError(PR_INVALID_STATE_ERROR, 0);
- goto aborted;
- }
- if (-1 == count_ready)
- {
- goto failed_poll; /* that's a shame */
- }
- else if (0 < count_ready)
- {
- for (poll_list = group->polling_list; count > 0;
- poll_list++, count--)
- {
- PR_ASSERT(
- poll_list < group->polling_list + group->polling_count);
- if (poll_list->out_flags != 0)
- {
- waiter = _MW_LookupInternal(group, poll_list->fd);
- /*
- ** If 'waiter' is NULL, that means the wait receive
- ** descriptor has been canceled.
- */
- if (NULL != waiter)
- _MW_DoneInternal(group, waiter, PR_MW_SUCCESS);
- }
- }
- }
- /*
- ** If there are no more threads waiting for completion,
- ** we need to return.
- ** This thread was "borrowed" to do the polling, but it really
- ** belongs to the client.
- */
- if ((!PR_CLIST_IS_EMPTY(&group->io_ready))
- && (1 == group->waiting_threads)) break;
- }
-
- rv = PR_SUCCESS;
-
-aborted:
-failed_poll:
-failed_alloc:
- group->poller = NULL; /* we were that, not we ain't */
- if ((_prmw_running == group->state) && (group->waiting_threads > 1))
- {
- /* Wake up one thread to become the new poller. */
- PR_NotifyCondVar(group->io_complete);
- }
- return rv; /* we return with the lock held */
-} /* _MW_PollInternal */
-#endif /* !WINNT */
-
-static PRMWGroupState MW_TestForShutdownInternal(PRWaitGroup *group)
-{
- PRMWGroupState rv = group->state;
- /*
- ** Looking at the group's fields is safe because
- ** once the group's state is no longer running, it
- ** cannot revert and there is a safe check on entry
- ** to make sure no more threads are made to wait.
- */
- if ((_prmw_stopping == rv)
- && (0 == group->waiting_threads))
- {
- rv = group->state = _prmw_stopped;
- PR_NotifyCondVar(group->mw_manage);
- }
- return rv;
-} /* MW_TestForShutdownInternal */
-
-#ifndef WINNT
-static void _MW_InitialRecv(PRCList *io_ready)
-{
- PRRecvWait *desc = (PRRecvWait*)io_ready;
- if ((NULL == desc->buffer.start)
- || (0 == desc->buffer.length))
- desc->bytesRecv = 0;
- else
- {
- desc->bytesRecv = (desc->fd->methods->recv)(
- desc->fd, desc->buffer.start,
- desc->buffer.length, 0, desc->timeout);
- if (desc->bytesRecv < 0) /* SetError should already be there */
- desc->outcome = PR_MW_FAILURE;
- }
-} /* _MW_InitialRecv */
-#endif
-
-#ifdef WINNT
-static void NT_TimeProc(void *arg)
-{
- _MDOverlapped *overlapped = (_MDOverlapped *)arg;
- PRRecvWait *desc = overlapped->data.mw.desc;
- PRFileDesc *bottom;
-
- if (InterlockedCompareExchange((LONG *)&desc->outcome,
- (LONG)PR_MW_TIMEOUT, (LONG)PR_MW_PENDING) != (LONG)PR_MW_PENDING)
- {
- /* This wait recv descriptor has already completed. */
- return;
- }
-
- /* close the osfd to abort the outstanding async io request */
- /* $$$$
- ** Little late to be checking if NSPR's on the bottom of stack,
- ** but if we don't check, we can't assert that the private data
- ** is what we think it is.
- ** $$$$
- */
- bottom = PR_GetIdentitiesLayer(desc->fd, PR_NSPR_IO_LAYER);
- PR_ASSERT(NULL != bottom);
- if (NULL != bottom) /* now what!?!?! */
- {
- bottom->secret->state = _PR_FILEDESC_CLOSED;
- if (closesocket(bottom->secret->md.osfd) == SOCKET_ERROR)
- {
- fprintf(stderr, "closesocket failed: %d\n", WSAGetLastError());
- PR_NOT_REACHED("What shall I do?");
- }
- }
- return;
-} /* NT_TimeProc */
-
-static PRStatus NT_HashRemove(PRWaitGroup *group, PRFileDesc *fd)
-{
- PRRecvWait **waiter;
-
- _PR_MD_LOCK(&group->mdlock);
- waiter = _MW_LookupInternal(group, fd);
- if (NULL != waiter)
- {
- group->waiter->count -= 1;
- *waiter = NULL;
- }
- _PR_MD_UNLOCK(&group->mdlock);
- return (NULL != waiter) ? PR_SUCCESS : PR_FAILURE;
-}
-
-PRStatus NT_HashRemoveInternal(PRWaitGroup *group, PRFileDesc *fd)
-{
- PRRecvWait **waiter;
-
- waiter = _MW_LookupInternal(group, fd);
- if (NULL != waiter)
- {
- group->waiter->count -= 1;
- *waiter = NULL;
- }
- return (NULL != waiter) ? PR_SUCCESS : PR_FAILURE;
-}
-#endif /* WINNT */
-
-/******************************************************************/
-/******************************************************************/
-/********************** The public API portion ********************/
-/******************************************************************/
-/******************************************************************/
-PR_IMPLEMENT(PRStatus) PR_AddWaitFileDesc(
- PRWaitGroup *group, PRRecvWait *desc)
-{
- _PR_HashStory hrv;
- PRStatus rv = PR_FAILURE;
-#ifdef WINNT
- _MDOverlapped *overlapped;
- HANDLE hFile;
- BOOL bResult;
- DWORD dwError;
- PRFileDesc *bottom;
-#endif
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- if ((NULL == group) && (NULL == (group = MW_Init2())))
- {
- return rv;
- }
-
- PR_ASSERT(NULL != desc->fd);
-
- desc->outcome = PR_MW_PENDING; /* nice, well known value */
- desc->bytesRecv = 0; /* likewise, though this value is ambiguious */
-
- PR_Lock(group->ml);
-
- if (_prmw_running != group->state)
- {
- /* Not allowed to add after cancelling the group */
- desc->outcome = PR_MW_INTERRUPT;
- PR_SetError(PR_INVALID_STATE_ERROR, 0);
- PR_Unlock(group->ml);
- return rv;
- }
-
-#ifdef WINNT
- _PR_MD_LOCK(&group->mdlock);
-#endif
-
- /*
- ** If the waiter count is zero at this point, there's no telling
- ** how long we've been idle. Therefore, initialize the beginning
- ** of the timing interval. As long as the list doesn't go empty,
- ** it will maintain itself.
- */
- if (0 == group->waiter->count)
- group->last_poll = PR_IntervalNow();
-
- do
- {
- hrv = MW_AddHashInternal(desc, group->waiter);
- if (_prmw_rehash != hrv) break;
- hrv = MW_ExpandHashInternal(group); /* gruesome */
- if (_prmw_success != hrv) break;
- } while (PR_TRUE);
-
-#ifdef WINNT
- _PR_MD_UNLOCK(&group->mdlock);
-#endif
-
- PR_NotifyCondVar(group->new_business); /* tell the world */
- rv = (_prmw_success == hrv) ? PR_SUCCESS : PR_FAILURE;
- PR_Unlock(group->ml);
-
-#ifdef WINNT
- overlapped = PR_NEWZAP(_MDOverlapped);
- if (NULL == overlapped)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- NT_HashRemove(group, desc->fd);
- return rv;
- }
- overlapped->ioModel = _MD_MultiWaitIO;
- overlapped->data.mw.desc = desc;
- overlapped->data.mw.group = group;
- if (desc->timeout != PR_INTERVAL_NO_TIMEOUT)
- {
- overlapped->data.mw.timer = CreateTimer(
- desc->timeout,
- NT_TimeProc,
- overlapped);
- if (0 == overlapped->data.mw.timer)
- {
- NT_HashRemove(group, desc->fd);
- PR_DELETE(overlapped);
- /*
- * XXX It appears that a maximum of 16 timer events can
- * be outstanding. GetLastError() returns 0 when I try it.
- */
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, GetLastError());
- return PR_FAILURE;
- }
- }
-
- /* Reach to the bottom layer to get the OS fd */
- bottom = PR_GetIdentitiesLayer(desc->fd, PR_NSPR_IO_LAYER);
- PR_ASSERT(NULL != bottom);
- if (NULL == bottom)
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
- hFile = (HANDLE)bottom->secret->md.osfd;
- if (!bottom->secret->md.io_model_committed)
- {
- PRInt32 st;
- st = _md_Associate(hFile);
- PR_ASSERT(0 != st);
- bottom->secret->md.io_model_committed = PR_TRUE;
- }
- bResult = ReadFile(hFile,
- desc->buffer.start,
- (DWORD)desc->buffer.length,
- NULL,
- &overlapped->overlapped);
- if (FALSE == bResult && (dwError = GetLastError()) != ERROR_IO_PENDING)
- {
- if (desc->timeout != PR_INTERVAL_NO_TIMEOUT)
- {
- if (InterlockedCompareExchange((LONG *)&desc->outcome,
- (LONG)PR_MW_FAILURE, (LONG)PR_MW_PENDING)
- == (LONG)PR_MW_PENDING)
- {
- CancelTimer(overlapped->data.mw.timer);
- }
- NT_HashRemove(group, desc->fd);
- PR_DELETE(overlapped);
- }
- _PR_MD_MAP_READ_ERROR(dwError);
- rv = PR_FAILURE;
- }
-#endif
-
- return rv;
-} /* PR_AddWaitFileDesc */
-
-PR_IMPLEMENT(PRRecvWait*) PR_WaitRecvReady(PRWaitGroup *group)
-{
- PRCList *io_ready = NULL;
-#ifdef WINNT
- PRThread *me = _PR_MD_CURRENT_THREAD();
- _MDOverlapped *overlapped;
-#endif
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- if ((NULL == group) && (NULL == (group = MW_Init2()))) goto failed_init;
-
- PR_Lock(group->ml);
-
- if (_prmw_running != group->state)
- {
- PR_SetError(PR_INVALID_STATE_ERROR, 0);
- goto invalid_state;
- }
-
- group->waiting_threads += 1; /* the polling thread is counted */
-
-#ifdef WINNT
- _PR_MD_LOCK(&group->mdlock);
- while (PR_CLIST_IS_EMPTY(&group->io_ready))
- {
- _PR_THREAD_LOCK(me);
- me->state = _PR_IO_WAIT;
- PR_APPEND_LINK(&me->waitQLinks, &group->wait_list);
- if (!_PR_IS_NATIVE_THREAD(me))
- {
- _PR_SLEEPQ_LOCK(me->cpu);
- _PR_ADD_SLEEPQ(me, PR_INTERVAL_NO_TIMEOUT);
- _PR_SLEEPQ_UNLOCK(me->cpu);
- }
- _PR_THREAD_UNLOCK(me);
- _PR_MD_UNLOCK(&group->mdlock);
- PR_Unlock(group->ml);
- _PR_MD_WAIT(me, PR_INTERVAL_NO_TIMEOUT);
- me->state = _PR_RUNNING;
- PR_Lock(group->ml);
- _PR_MD_LOCK(&group->mdlock);
- if (_PR_PENDING_INTERRUPT(me)) {
- PR_REMOVE_LINK(&me->waitQLinks);
- _PR_MD_UNLOCK(&group->mdlock);
- me->flags &= ~_PR_INTERRUPT;
- me->io_suspended = PR_FALSE;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- goto aborted;
- }
- }
- io_ready = PR_LIST_HEAD(&group->io_ready);
- PR_ASSERT(io_ready != NULL);
- PR_REMOVE_LINK(io_ready);
- _PR_MD_UNLOCK(&group->mdlock);
- overlapped = (_MDOverlapped *)
- ((char *)io_ready - offsetof(_MDOverlapped, data));
- io_ready = &overlapped->data.mw.desc->internal;
-#else
- do
- {
- /*
- ** If the I/O ready list isn't empty, have this thread
- ** return with the first receive wait object that's available.
- */
- if (PR_CLIST_IS_EMPTY(&group->io_ready))
- {
- /*
- ** Is there a polling thread yet? If not, grab this thread
- ** and use it.
- */
- if (NULL == group->poller)
- {
- /*
- ** This thread will stay do polling until it becomes the only one
- ** left to service a completion. Then it will return and there will
- ** be none left to actually poll or to run completions.
- **
- ** The polling function should only return w/ failure or
- ** with some I/O ready.
- */
- if (PR_FAILURE == _MW_PollInternal(group)) goto failed_poll;
- }
- else
- {
- /*
- ** There are four reasons a thread can be awakened from
- ** a wait on the io_complete condition variable.
- ** 1. Some I/O has completed, i.e., the io_ready list
- ** is nonempty.
- ** 2. The wait group is canceled.
- ** 3. The thread is interrupted.
- ** 4. The current polling thread has to leave and needs
- ** a replacement.
- ** The logic to find a new polling thread is made more
- ** complicated by all the other possible events.
- ** I tried my best to write the logic clearly, but
- ** it is still full of if's with continue and goto.
- */
- PRStatus st;
- do
- {
- st = PR_WaitCondVar(group->io_complete, PR_INTERVAL_NO_TIMEOUT);
- if (_prmw_running != group->state)
- {
- PR_SetError(PR_INVALID_STATE_ERROR, 0);
- goto aborted;
- }
- if (_MW_ABORTED(st) || (NULL == group->poller)) break;
- } while (PR_CLIST_IS_EMPTY(&group->io_ready));
-
- /*
- ** The thread is interrupted and has to leave. It might
- ** have also been awakened to process ready i/o or be the
- ** new poller. To be safe, if either condition is true,
- ** we awaken another thread to take its place.
- */
- if (_MW_ABORTED(st))
- {
- if ((NULL == group->poller
- || !PR_CLIST_IS_EMPTY(&group->io_ready))
- && group->waiting_threads > 1)
- PR_NotifyCondVar(group->io_complete);
- goto aborted;
- }
-
- /*
- ** A new poller is needed, but can I be the new poller?
- ** If there is no i/o ready, sure. But if there is any
- ** i/o ready, it has a higher priority. I want to
- ** process the ready i/o first and wake up another
- ** thread to be the new poller.
- */
- if (NULL == group->poller)
- {
- if (PR_CLIST_IS_EMPTY(&group->io_ready))
- continue;
- if (group->waiting_threads > 1)
- PR_NotifyCondVar(group->io_complete);
- }
- }
- PR_ASSERT(!PR_CLIST_IS_EMPTY(&group->io_ready));
- }
- io_ready = PR_LIST_HEAD(&group->io_ready);
- PR_NotifyCondVar(group->io_taken);
- PR_ASSERT(io_ready != NULL);
- PR_REMOVE_LINK(io_ready);
- } while (NULL == io_ready);
-
-failed_poll:
-
-#endif
-
-aborted:
-
- group->waiting_threads -= 1;
-invalid_state:
- (void)MW_TestForShutdownInternal(group);
- PR_Unlock(group->ml);
-
-failed_init:
- if (NULL != io_ready)
- {
- /* If the operation failed, record the reason why */
- switch (((PRRecvWait*)io_ready)->outcome)
- {
- case PR_MW_PENDING:
- PR_ASSERT(0);
- break;
- case PR_MW_SUCCESS:
-#ifndef WINNT
- _MW_InitialRecv(io_ready);
-#endif
- break;
-#ifdef WINNT
- case PR_MW_FAILURE:
- _PR_MD_MAP_READ_ERROR(overlapped->data.mw.error);
- break;
-#endif
- case PR_MW_TIMEOUT:
- PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
- break;
- case PR_MW_INTERRUPT:
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- break;
- default: break;
- }
-#ifdef WINNT
- if (NULL != overlapped->data.mw.timer)
- {
- PR_ASSERT(PR_INTERVAL_NO_TIMEOUT
- != overlapped->data.mw.desc->timeout);
- CancelTimer(overlapped->data.mw.timer);
- }
- else
- {
- PR_ASSERT(PR_INTERVAL_NO_TIMEOUT
- == overlapped->data.mw.desc->timeout);
- }
- PR_DELETE(overlapped);
-#endif
- }
- return (PRRecvWait*)io_ready;
-} /* PR_WaitRecvReady */
-
-PR_IMPLEMENT(PRStatus) PR_CancelWaitFileDesc(PRWaitGroup *group, PRRecvWait *desc)
-{
-#if !defined(WINNT)
- PRRecvWait **recv_wait;
-#endif
- PRStatus rv = PR_SUCCESS;
- if (NULL == group) group = mw_state->group;
- PR_ASSERT(NULL != group);
- if (NULL == group)
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
-
- PR_Lock(group->ml);
-
- if (_prmw_running != group->state)
- {
- PR_SetError(PR_INVALID_STATE_ERROR, 0);
- rv = PR_FAILURE;
- goto unlock;
- }
-
-#ifdef WINNT
- if (InterlockedCompareExchange((LONG *)&desc->outcome,
- (LONG)PR_MW_INTERRUPT, (LONG)PR_MW_PENDING) == (LONG)PR_MW_PENDING)
- {
- PRFileDesc *bottom = PR_GetIdentitiesLayer(desc->fd, PR_NSPR_IO_LAYER);
- PR_ASSERT(NULL != bottom);
- if (NULL == bottom)
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- goto unlock;
- }
- bottom->secret->state = _PR_FILEDESC_CLOSED;
-#if 0
- fprintf(stderr, "cancel wait recv: closing socket\n");
-#endif
- if (closesocket(bottom->secret->md.osfd) == SOCKET_ERROR)
- {
- fprintf(stderr, "closesocket failed: %d\n", WSAGetLastError());
- exit(1);
- }
- }
-#else
- if (NULL != (recv_wait = _MW_LookupInternal(group, desc->fd)))
- {
- /* it was in the wait table */
- _MW_DoneInternal(group, recv_wait, PR_MW_INTERRUPT);
- goto unlock;
- }
- if (!PR_CLIST_IS_EMPTY(&group->io_ready))
- {
- /* is it already complete? */
- PRCList *head = PR_LIST_HEAD(&group->io_ready);
- do
- {
- PRRecvWait *done = (PRRecvWait*)head;
- if (done == desc) goto unlock;
- head = PR_NEXT_LINK(head);
- } while (head != &group->io_ready);
- }
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- rv = PR_FAILURE;
-
-#endif
-unlock:
- PR_Unlock(group->ml);
- return rv;
-} /* PR_CancelWaitFileDesc */
-
-PR_IMPLEMENT(PRRecvWait*) PR_CancelWaitGroup(PRWaitGroup *group)
-{
- PRRecvWait **desc;
- PRRecvWait *recv_wait = NULL;
-#ifdef WINNT
- _MDOverlapped *overlapped;
- PRRecvWait **end;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-#endif
-
- if (NULL == group) group = mw_state->group;
- PR_ASSERT(NULL != group);
- if (NULL == group)
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return NULL;
- }
-
- PR_Lock(group->ml);
- if (_prmw_stopped != group->state)
- {
- if (_prmw_running == group->state)
- group->state = _prmw_stopping; /* so nothing new comes in */
- if (0 == group->waiting_threads) /* is there anybody else? */
- group->state = _prmw_stopped; /* we can stop right now */
- else
- {
- PR_NotifyAllCondVar(group->new_business);
- PR_NotifyAllCondVar(group->io_complete);
- }
- while (_prmw_stopped != group->state)
- (void)PR_WaitCondVar(group->mw_manage, PR_INTERVAL_NO_TIMEOUT);
- }
-
-#ifdef WINNT
- _PR_MD_LOCK(&group->mdlock);
-#endif
- /* make all the existing descriptors look done/interrupted */
-#ifdef WINNT
- end = &group->waiter->recv_wait + group->waiter->length;
- for (desc = &group->waiter->recv_wait; desc < end; ++desc)
- {
- if (NULL != *desc)
- {
- if (InterlockedCompareExchange((LONG *)&(*desc)->outcome,
- (LONG)PR_MW_INTERRUPT, (LONG)PR_MW_PENDING)
- == (LONG)PR_MW_PENDING)
- {
- PRFileDesc *bottom = PR_GetIdentitiesLayer(
- (*desc)->fd, PR_NSPR_IO_LAYER);
- PR_ASSERT(NULL != bottom);
- if (NULL == bottom)
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- goto invalid_arg;
- }
- bottom->secret->state = _PR_FILEDESC_CLOSED;
-#if 0
- fprintf(stderr, "cancel wait group: closing socket\n");
-#endif
- if (closesocket(bottom->secret->md.osfd) == SOCKET_ERROR)
- {
- fprintf(stderr, "closesocket failed: %d\n",
- WSAGetLastError());
- exit(1);
- }
- }
- }
- }
- while (group->waiter->count > 0)
- {
- _PR_THREAD_LOCK(me);
- me->state = _PR_IO_WAIT;
- PR_APPEND_LINK(&me->waitQLinks, &group->wait_list);
- if (!_PR_IS_NATIVE_THREAD(me))
- {
- _PR_SLEEPQ_LOCK(me->cpu);
- _PR_ADD_SLEEPQ(me, PR_INTERVAL_NO_TIMEOUT);
- _PR_SLEEPQ_UNLOCK(me->cpu);
- }
- _PR_THREAD_UNLOCK(me);
- _PR_MD_UNLOCK(&group->mdlock);
- PR_Unlock(group->ml);
- _PR_MD_WAIT(me, PR_INTERVAL_NO_TIMEOUT);
- me->state = _PR_RUNNING;
- PR_Lock(group->ml);
- _PR_MD_LOCK(&group->mdlock);
- }
-#else
- for (desc = &group->waiter->recv_wait; group->waiter->count > 0; ++desc)
- {
- PR_ASSERT(desc < &group->waiter->recv_wait + group->waiter->length);
- if (NULL != *desc)
- _MW_DoneInternal(group, desc, PR_MW_INTERRUPT);
- }
-#endif
-
- /* take first element of finished list and return it or NULL */
- if (PR_CLIST_IS_EMPTY(&group->io_ready))
- PR_SetError(PR_GROUP_EMPTY_ERROR, 0);
- else
- {
- PRCList *head = PR_LIST_HEAD(&group->io_ready);
- PR_REMOVE_AND_INIT_LINK(head);
-#ifdef WINNT
- overlapped = (_MDOverlapped *)
- ((char *)head - offsetof(_MDOverlapped, data));
- head = &overlapped->data.mw.desc->internal;
- if (NULL != overlapped->data.mw.timer)
- {
- PR_ASSERT(PR_INTERVAL_NO_TIMEOUT
- != overlapped->data.mw.desc->timeout);
- CancelTimer(overlapped->data.mw.timer);
- }
- else
- {
- PR_ASSERT(PR_INTERVAL_NO_TIMEOUT
- == overlapped->data.mw.desc->timeout);
- }
- PR_DELETE(overlapped);
-#endif
- recv_wait = (PRRecvWait*)head;
- }
-#ifdef WINNT
-invalid_arg:
- _PR_MD_UNLOCK(&group->mdlock);
-#endif
- PR_Unlock(group->ml);
-
- return recv_wait;
-} /* PR_CancelWaitGroup */
-
-PR_IMPLEMENT(PRWaitGroup*) PR_CreateWaitGroup(PRInt32 size /* ignored */)
-{
- PRWaitGroup *wg;
-
- if (NULL == (wg = PR_NEWZAP(PRWaitGroup)))
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- goto failed;
- }
- /* the wait group itself */
- wg->ml = PR_NewLock();
- if (NULL == wg->ml) goto failed_lock;
- wg->io_taken = PR_NewCondVar(wg->ml);
- if (NULL == wg->io_taken) goto failed_cvar0;
- wg->io_complete = PR_NewCondVar(wg->ml);
- if (NULL == wg->io_complete) goto failed_cvar1;
- wg->new_business = PR_NewCondVar(wg->ml);
- if (NULL == wg->new_business) goto failed_cvar2;
- wg->mw_manage = PR_NewCondVar(wg->ml);
- if (NULL == wg->mw_manage) goto failed_cvar3;
-
- PR_INIT_CLIST(&wg->group_link);
- PR_INIT_CLIST(&wg->io_ready);
-
- /* the waiters sequence */
- wg->waiter = (_PRWaiterHash*)PR_CALLOC(
- sizeof(_PRWaiterHash) +
- (_PR_DEFAULT_HASH_LENGTH * sizeof(PRRecvWait*)));
- if (NULL == wg->waiter)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- goto failed_waiter;
- }
- wg->waiter->count = 0;
- wg->waiter->length = _PR_DEFAULT_HASH_LENGTH;
-
-#ifdef WINNT
- _PR_MD_NEW_LOCK(&wg->mdlock);
- PR_INIT_CLIST(&wg->wait_list);
-#endif /* WINNT */
-
- PR_Lock(mw_lock);
- PR_APPEND_LINK(&wg->group_link, &mw_state->group_list);
- PR_Unlock(mw_lock);
- return wg;
-
-failed_waiter:
- PR_DestroyCondVar(wg->mw_manage);
-failed_cvar3:
- PR_DestroyCondVar(wg->new_business);
-failed_cvar2:
- PR_DestroyCondVar(wg->io_complete);
-failed_cvar1:
- PR_DestroyCondVar(wg->io_taken);
-failed_cvar0:
- PR_DestroyLock(wg->ml);
-failed_lock:
- PR_DELETE(wg);
- wg = NULL;
-
-failed:
- return wg;
-} /* MW_CreateWaitGroup */
-
-PR_IMPLEMENT(PRStatus) PR_DestroyWaitGroup(PRWaitGroup *group)
-{
- PRStatus rv = PR_SUCCESS;
- if (NULL == group) group = mw_state->group;
- PR_ASSERT(NULL != group);
- if (NULL != group)
- {
- PR_Lock(group->ml);
- if ((group->waiting_threads == 0)
- && (group->waiter->count == 0)
- && PR_CLIST_IS_EMPTY(&group->io_ready))
- {
- group->state = _prmw_stopped;
- }
- else
- {
- PR_SetError(PR_INVALID_STATE_ERROR, 0);
- rv = PR_FAILURE;
- }
- PR_Unlock(group->ml);
- if (PR_FAILURE == rv) return rv;
-
- PR_Lock(mw_lock);
- PR_REMOVE_LINK(&group->group_link);
- PR_Unlock(mw_lock);
-
-#ifdef WINNT
- /*
- * XXX make sure wait_list is empty and waiter is empty.
- * These must be checked while holding mdlock.
- */
- _PR_MD_FREE_LOCK(&group->mdlock);
-#endif
-
- PR_DELETE(group->waiter);
- PR_DELETE(group->polling_list);
- PR_DestroyCondVar(group->mw_manage);
- PR_DestroyCondVar(group->new_business);
- PR_DestroyCondVar(group->io_complete);
- PR_DestroyCondVar(group->io_taken);
- PR_DestroyLock(group->ml);
- if (group == mw_state->group) mw_state->group = NULL;
- PR_DELETE(group);
- }
- else
- {
- /* The default wait group is not created yet. */
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- rv = PR_FAILURE;
- }
- return rv;
-} /* PR_DestroyWaitGroup */
-
-/**********************************************************************
-***********************************************************************
-******************** Wait group enumerations **************************
-***********************************************************************
-**********************************************************************/
-
-PR_IMPLEMENT(PRMWaitEnumerator*) PR_CreateMWaitEnumerator(PRWaitGroup *group)
-{
- PRMWaitEnumerator *enumerator = PR_NEWZAP(PRMWaitEnumerator);
- if (NULL == enumerator) PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- else
- {
- enumerator->group = group;
- enumerator->seal = _PR_ENUM_SEALED;
- }
- return enumerator;
-} /* PR_CreateMWaitEnumerator */
-
-PR_IMPLEMENT(PRStatus) PR_DestroyMWaitEnumerator(PRMWaitEnumerator* enumerator)
-{
- PR_ASSERT(NULL != enumerator);
- PR_ASSERT(_PR_ENUM_SEALED == enumerator->seal);
- if ((NULL == enumerator) || (_PR_ENUM_SEALED != enumerator->seal))
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
- enumerator->seal = _PR_ENUM_UNSEALED;
- PR_Free(enumerator);
- return PR_SUCCESS;
-} /* PR_DestroyMWaitEnumerator */
-
-PR_IMPLEMENT(PRRecvWait*) PR_EnumerateWaitGroup(
- PRMWaitEnumerator *enumerator, const PRRecvWait *previous)
-{
- PRRecvWait *result = NULL;
-
- /* entry point sanity checking */
- PR_ASSERT(NULL != enumerator);
- PR_ASSERT(_PR_ENUM_SEALED == enumerator->seal);
- if ((NULL == enumerator)
- || (_PR_ENUM_SEALED != enumerator->seal)) goto bad_argument;
-
- /* beginning of enumeration */
- if (NULL == previous)
- {
- if (NULL == enumerator->group)
- {
- enumerator->group = mw_state->group;
- if (NULL == enumerator->group)
- {
- PR_SetError(PR_GROUP_EMPTY_ERROR, 0);
- return NULL;
- }
- }
- enumerator->waiter = &enumerator->group->waiter->recv_wait;
- enumerator->p_timestamp = enumerator->group->p_timestamp;
- enumerator->thread = PR_GetCurrentThread();
- enumerator->index = 0;
- }
- /* continuing an enumeration */
- else
- {
- PRThread *me = PR_GetCurrentThread();
- PR_ASSERT(me == enumerator->thread);
- if (me != enumerator->thread) goto bad_argument;
-
- /* need to restart the enumeration */
- if (enumerator->p_timestamp != enumerator->group->p_timestamp)
- return PR_EnumerateWaitGroup(enumerator, NULL);
- }
-
- /* actually progress the enumeration */
-#if defined(WINNT)
- _PR_MD_LOCK(&enumerator->group->mdlock);
-#else
- PR_Lock(enumerator->group->ml);
-#endif
- while (enumerator->index++ < enumerator->group->waiter->length)
- {
- if (NULL != (result = *(enumerator->waiter)++)) break;
- }
-#if defined(WINNT)
- _PR_MD_UNLOCK(&enumerator->group->mdlock);
-#else
- PR_Unlock(enumerator->group->ml);
-#endif
-
- return result; /* what we live for */
-
-bad_argument:
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return NULL; /* probably ambiguous */
-} /* PR_EnumerateWaitGroup */
-
-/* prmwait.c */
diff --git a/nspr/pr/src/io/prpolevt.c b/nspr/pr/src/io/prpolevt.c
deleted file mode 100644
index ac3eb10..0000000
--- a/nspr/pr/src/io/prpolevt.c
+++ /dev/null
@@ -1,230 +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/. */
-
-/*
- *********************************************************************
- *
- * Pollable events
- *
- * Pollable events are implemented using layered I/O. The only
- * I/O methods that are implemented for pollable events are poll
- * and close. No other methods can be invoked on a pollable
- * event.
- *
- * A pipe or socket pair is created and the pollable event layer
- * is pushed onto the read end. A pointer to the write end is
- * saved in the PRFilePrivate structure of the pollable event.
- *
- *********************************************************************
- */
-
-#include "prinit.h"
-#include "prio.h"
-#include "prmem.h"
-#include "prerror.h"
-#include "prlog.h"
-
-/*
- * These internal functions are declared in primpl.h,
- * but we can't include primpl.h because the definition
- * of struct PRFilePrivate in this file (for the pollable
- * event layer) will conflict with the definition of
- * struct PRFilePrivate in primpl.h (for the NSPR layer).
- */
-extern PRIntn _PR_InvalidInt(void);
-extern PRInt64 _PR_InvalidInt64(void);
-extern PRStatus _PR_InvalidStatus(void);
-extern PRFileDesc *_PR_InvalidDesc(void);
-
-/*
- * PRFilePrivate structure for the NSPR pollable events layer
- */
-struct PRFilePrivate {
- PRFileDesc *writeEnd; /* the write end of the pipe/socketpair */
-};
-
-static PRStatus PR_CALLBACK _pr_PolEvtClose(PRFileDesc *fd);
-
-static PRInt16 PR_CALLBACK _pr_PolEvtPoll(
- PRFileDesc *fd, PRInt16 in_flags, PRInt16 *out_flags);
-
-static PRIOMethods _pr_polevt_methods = {
- PR_DESC_LAYERED,
- _pr_PolEvtClose,
- (PRReadFN)_PR_InvalidInt,
- (PRWriteFN)_PR_InvalidInt,
- (PRAvailableFN)_PR_InvalidInt,
- (PRAvailable64FN)_PR_InvalidInt64,
- (PRFsyncFN)_PR_InvalidStatus,
- (PRSeekFN)_PR_InvalidInt,
- (PRSeek64FN)_PR_InvalidInt64,
- (PRFileInfoFN)_PR_InvalidStatus,
- (PRFileInfo64FN)_PR_InvalidStatus,
- (PRWritevFN)_PR_InvalidInt,
- (PRConnectFN)_PR_InvalidStatus,
- (PRAcceptFN)_PR_InvalidDesc,
- (PRBindFN)_PR_InvalidStatus,
- (PRListenFN)_PR_InvalidStatus,
- (PRShutdownFN)_PR_InvalidStatus,
- (PRRecvFN)_PR_InvalidInt,
- (PRSendFN)_PR_InvalidInt,
- (PRRecvfromFN)_PR_InvalidInt,
- (PRSendtoFN)_PR_InvalidInt,
- _pr_PolEvtPoll,
- (PRAcceptreadFN)_PR_InvalidInt,
- (PRTransmitfileFN)_PR_InvalidInt,
- (PRGetsocknameFN)_PR_InvalidStatus,
- (PRGetpeernameFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRGetsocketoptionFN)_PR_InvalidStatus,
- (PRSetsocketoptionFN)_PR_InvalidStatus,
- (PRSendfileFN)_PR_InvalidInt,
- (PRConnectcontinueFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt
-};
-
-static PRDescIdentity _pr_polevt_id;
-static PRCallOnceType _pr_polevt_once_control;
-static PRStatus PR_CALLBACK _pr_PolEvtInit(void);
-
-static PRInt16 PR_CALLBACK _pr_PolEvtPoll(
- PRFileDesc *fd, PRInt16 in_flags, PRInt16 *out_flags)
-{
- return (fd->lower->methods->poll)(fd->lower, in_flags, out_flags);
-}
-
-static PRStatus PR_CALLBACK _pr_PolEvtInit(void)
-{
- _pr_polevt_id = PR_GetUniqueIdentity("NSPR pollable events");
- if (PR_INVALID_IO_LAYER == _pr_polevt_id) {
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-#if !defined(XP_UNIX)
-#define USE_TCP_SOCKETPAIR
-#endif
-
-PR_IMPLEMENT(PRFileDesc *) PR_NewPollableEvent(void)
-{
- PRFileDesc *event;
- PRFileDesc *fd[2]; /* fd[0] is the read end; fd[1] is the write end */
-#ifdef USE_TCP_SOCKETPAIR
- PRSocketOptionData socket_opt;
- PRStatus rv;
-#endif
-
- fd[0] = fd[1] = NULL;
-
- if (PR_CallOnce(&_pr_polevt_once_control, _pr_PolEvtInit) == PR_FAILURE) {
- return NULL;
- }
-
- event = PR_CreateIOLayerStub(_pr_polevt_id, &_pr_polevt_methods);
- if (NULL == event) {
- goto errorExit;
- }
- event->secret = PR_NEW(PRFilePrivate);
- if (event->secret == NULL) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- goto errorExit;
- }
-
-#ifndef USE_TCP_SOCKETPAIR
- if (PR_CreatePipe(&fd[0], &fd[1]) == PR_FAILURE) {
- fd[0] = fd[1] = NULL;
- goto errorExit;
- }
-#else
- if (PR_NewTCPSocketPair(fd) == PR_FAILURE) {
- fd[0] = fd[1] = NULL;
- goto errorExit;
- }
- /*
- * set the TCP_NODELAY option to reduce notification latency
- */
- socket_opt.option = PR_SockOpt_NoDelay;
- socket_opt.value.no_delay = PR_TRUE;
- rv = PR_SetSocketOption(fd[1], &socket_opt);
- PR_ASSERT(PR_SUCCESS == rv);
-#endif
-
- event->secret->writeEnd = fd[1];
- if (PR_PushIOLayer(fd[0], PR_TOP_IO_LAYER, event) == PR_FAILURE) {
- goto errorExit;
- }
-
- return fd[0];
-
-errorExit:
- if (fd[0]) {
- PR_Close(fd[0]);
- PR_Close(fd[1]);
- }
- if (event) {
- PR_DELETE(event->secret);
- event->dtor(event);
- }
- return NULL;
-}
-
-static PRStatus PR_CALLBACK _pr_PolEvtClose(PRFileDesc *fd)
-{
- PRFileDesc *event;
-
- event = PR_PopIOLayer(fd, PR_TOP_IO_LAYER);
- PR_ASSERT(NULL == event->higher && NULL == event->lower);
- PR_Close(fd);
- PR_Close(event->secret->writeEnd);
- PR_DELETE(event->secret);
- event->dtor(event);
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus) PR_DestroyPollableEvent(PRFileDesc *event)
-{
- return PR_Close(event);
-}
-
-static const char magicChar = '\x38';
-
-PR_IMPLEMENT(PRStatus) PR_SetPollableEvent(PRFileDesc *event)
-{
- if (PR_Write(event->secret->writeEnd, &magicChar, 1) != 1) {
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus) PR_WaitForPollableEvent(PRFileDesc *event)
-{
- char buf[1024];
- PRInt32 nBytes;
-#ifdef DEBUG
- PRIntn i;
-#endif
-
- nBytes = PR_Read(event->lower, buf, sizeof(buf));
- if (nBytes == -1) {
- return PR_FAILURE;
- }
-
-#ifdef DEBUG
- /*
- * Make sure people do not write to the pollable event fd
- * directly.
- */
- for (i = 0; i < nBytes; i++) {
- PR_ASSERT(buf[i] == magicChar);
- }
-#endif
-
- return PR_SUCCESS;
-}
diff --git a/nspr/pr/src/io/prprf.c b/nspr/pr/src/io/prprf.c
deleted file mode 100644
index 798ea2a..0000000
--- a/nspr/pr/src/io/prprf.c
+++ /dev/null
@@ -1,1290 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* 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/. */
-
-/*
-** Portable safe sprintf code.
-**
-** Author: Kipp E.B. Hickman
-*/
-#include <stdarg.h>
-#include <stddef.h>
-#include <stdio.h>
-#include <string.h>
-#include "primpl.h"
-#include "prprf.h"
-#include "prlong.h"
-#include "prlog.h"
-#include "prmem.h"
-
-#if defined(_MSC_VER) && _MSC_VER < 1900
-#define snprintf _snprintf
-#endif
-
-/*
-** WARNING: This code may *NOT* call PR_LOG (because PR_LOG calls it)
-*/
-
-/*
-** XXX This needs to be internationalized!
-*/
-
-typedef struct SprintfStateStr SprintfState;
-
-struct SprintfStateStr {
- int (*stuff)(SprintfState *ss, const char *sp, PRUint32 len);
-
- char *base;
- char *cur;
- PRUint32 maxlen; /* Must not exceed PR_INT32_MAX. */
-
- int (*func)(void *arg, const char *sp, PRUint32 len);
- void *arg;
-};
-
-/*
-** Numbered Argument
-*/
-struct NumArg {
- int type; /* type of the numbered argument */
- union { /* the numbered argument */
- int i;
- unsigned int ui;
- PRInt32 i32;
- PRUint32 ui32;
- PRInt64 ll;
- PRUint64 ull;
- double d;
- const char *s;
- int *ip;
-#ifdef WIN32
- const WCHAR *ws;
-#endif
- } u;
-};
-
-#define NAS_DEFAULT_NUM 20 /* default number of NumberedArgument array */
-
-/*
-** For numeric types, the signed versions must have even values,
-** and their corresponding unsigned versions must have the subsequent
-** odd value.
-*/
-#define TYPE_INT16 0
-#define TYPE_UINT16 1
-#define TYPE_INTN 2
-#define TYPE_UINTN 3
-#define TYPE_INT32 4
-#define TYPE_UINT32 5
-#define TYPE_INT64 6
-#define TYPE_UINT64 7
-#define TYPE_STRING 8
-#define TYPE_DOUBLE 9
-#define TYPE_INTSTR 10
-#ifdef WIN32
-#define TYPE_WSTRING 11
-#endif
-#define TYPE_UNKNOWN 20
-
-#define FLAG_LEFT 0x1
-#define FLAG_SIGNED 0x2
-#define FLAG_SPACED 0x4
-#define FLAG_ZEROS 0x8
-#define FLAG_NEG 0x10
-
-/*
-** Fill into the buffer using the data in src
-*/
-static int fill2(SprintfState *ss, const char *src, int srclen, int width,
- int flags)
-{
- char space = ' ';
- int rv;
-
- width -= srclen;
- if ((width > 0) && ((flags & FLAG_LEFT) == 0)) { /* Right adjusting */
- if (flags & FLAG_ZEROS) {
- space = '0';
- }
- while (--width >= 0) {
- rv = (*ss->stuff)(ss, &space, 1);
- if (rv < 0) {
- return rv;
- }
- }
- }
-
- /* Copy out the source data */
- rv = (*ss->stuff)(ss, src, srclen);
- if (rv < 0) {
- return rv;
- }
-
- if ((width > 0) && ((flags & FLAG_LEFT) != 0)) { /* Left adjusting */
- while (--width >= 0) {
- rv = (*ss->stuff)(ss, &space, 1);
- if (rv < 0) {
- return rv;
- }
- }
- }
- return 0;
-}
-
-/*
-** Fill a number. The order is: optional-sign zero-filling conversion-digits
-*/
-static int fill_n(SprintfState *ss, const char *src, int srclen, int width,
- int prec, int type, int flags)
-{
- int zerowidth = 0;
- int precwidth = 0;
- int signwidth = 0;
- int leftspaces = 0;
- int rightspaces = 0;
- int cvtwidth;
- int rv;
- char sign;
-
- if ((type & 1) == 0) {
- if (flags & FLAG_NEG) {
- sign = '-';
- signwidth = 1;
- } else if (flags & FLAG_SIGNED) {
- sign = '+';
- signwidth = 1;
- } else if (flags & FLAG_SPACED) {
- sign = ' ';
- signwidth = 1;
- }
- }
- cvtwidth = signwidth + srclen;
-
- if (prec > 0) {
- if (prec > srclen) {
- precwidth = prec - srclen; /* Need zero filling */
- cvtwidth += precwidth;
- }
- }
-
- if ((flags & FLAG_ZEROS) && (prec < 0)) {
- if (width > cvtwidth) {
- zerowidth = width - cvtwidth; /* Zero filling */
- cvtwidth += zerowidth;
- }
- }
-
- if (flags & FLAG_LEFT) {
- if (width > cvtwidth) {
- /* Space filling on the right (i.e. left adjusting) */
- rightspaces = width - cvtwidth;
- }
- } else {
- if (width > cvtwidth) {
- /* Space filling on the left (i.e. right adjusting) */
- leftspaces = width - cvtwidth;
- }
- }
- while (--leftspaces >= 0) {
- rv = (*ss->stuff)(ss, " ", 1);
- if (rv < 0) {
- return rv;
- }
- }
- if (signwidth) {
- rv = (*ss->stuff)(ss, &sign, 1);
- if (rv < 0) {
- return rv;
- }
- }
- while (--precwidth >= 0) {
- rv = (*ss->stuff)(ss, "0", 1);
- if (rv < 0) {
- return rv;
- }
- }
- while (--zerowidth >= 0) {
- rv = (*ss->stuff)(ss, "0", 1);
- if (rv < 0) {
- return rv;
- }
- }
- rv = (*ss->stuff)(ss, src, srclen);
- if (rv < 0) {
- return rv;
- }
- while (--rightspaces >= 0) {
- rv = (*ss->stuff)(ss, " ", 1);
- if (rv < 0) {
- return rv;
- }
- }
- return 0;
-}
-
-/*
-** Convert a long into its printable form
-*/
-static int cvt_l(SprintfState *ss, long num, int width, int prec, int radix,
- int type, int flags, const char *hexp)
-{
- char cvtbuf[100];
- char *cvt;
- int digits;
-
- /* according to the man page this needs to happen */
- if ((prec == 0) && (num == 0)) {
- return 0;
- }
-
- /*
- ** Converting decimal is a little tricky. In the unsigned case we
- ** need to stop when we hit 10 digits. In the signed case, we can
- ** stop when the number is zero.
- */
- cvt = cvtbuf + sizeof(cvtbuf);
- digits = 0;
- while (num) {
- int digit = (((unsigned long)num) % radix) & 0xF;
- *--cvt = hexp[digit];
- digits++;
- num = (long)(((unsigned long)num) / radix);
- }
- if (digits == 0) {
- *--cvt = '0';
- digits++;
- }
-
- /*
- ** Now that we have the number converted without its sign, deal with
- ** the sign and zero padding.
- */
- return fill_n(ss, cvt, digits, width, prec, type, flags);
-}
-
-/*
-** Convert a 64-bit integer into its printable form
-*/
-static int cvt_ll(SprintfState *ss, PRInt64 num, int width, int prec, int radix,
- int type, int flags, const char *hexp)
-{
- char cvtbuf[100];
- char *cvt;
- int digits;
- PRInt64 rad;
-
- /* according to the man page this needs to happen */
- if ((prec == 0) && (LL_IS_ZERO(num))) {
- return 0;
- }
-
- /*
- ** Converting decimal is a little tricky. In the unsigned case we
- ** need to stop when we hit 10 digits. In the signed case, we can
- ** stop when the number is zero.
- */
- LL_I2L(rad, radix);
- cvt = cvtbuf + sizeof(cvtbuf);
- digits = 0;
- while (!LL_IS_ZERO(num)) {
- PRInt32 digit;
- PRInt64 quot, rem;
- LL_UDIVMOD(", &rem, num, rad);
- LL_L2I(digit, rem);
- *--cvt = hexp[digit & 0xf];
- digits++;
- num = quot;
- }
- if (digits == 0) {
- *--cvt = '0';
- digits++;
- }
-
- /*
- ** Now that we have the number converted without its sign, deal with
- ** the sign and zero padding.
- */
- return fill_n(ss, cvt, digits, width, prec, type, flags);
-}
-
-/*
-** Convert a double precision floating point number into its printable
-** form.
-**
-** XXX stop using snprintf to convert floating point
-*/
-static int cvt_f(SprintfState *ss, double d, const char *fmt0, const char *fmt1)
-{
- char fin[20];
- char fout[300];
- int amount = fmt1 - fmt0;
-
- if (amount <= 0 || amount >= sizeof(fin)) {
- /* Totally bogus % command to snprintf. Just ignore it */
- return 0;
- }
- memcpy(fin, fmt0, amount);
- fin[amount] = 0;
-
- /* Convert floating point using the native snprintf code */
-#ifdef DEBUG
- {
- const char *p = fin;
- while (*p) {
- PR_ASSERT(*p != 'L');
- p++;
- }
- }
-#endif
- memset(fout, 0, sizeof(fout));
- snprintf(fout, sizeof(fout), fin, d);
- /* Explicitly null-terminate fout because on Windows snprintf doesn't
- * append a null-terminator if the buffer is too small. */
- fout[sizeof(fout) - 1] = '\0';
-
- return (*ss->stuff)(ss, fout, strlen(fout));
-}
-
-/*
-** Convert a string into its printable form. "width" is the output
-** width. "prec" is the maximum number of characters of "s" to output,
-** where -1 means until NUL.
-*/
-static int cvt_s(SprintfState *ss, const char *str, int width, int prec,
- int flags)
-{
- int slen;
-
- if (prec == 0)
- return 0;
-
- /* Limit string length by precision value */
- if (!str) {
- str = "(null)";
- }
- if (prec > 0) {
- /* this is: slen = strnlen(str, prec); */
- register const char *s;
-
- for(s = str; prec && *s; s++, prec-- )
- ;
- slen = s - str;
- } else {
- slen = strlen(str);
- }
-
- /* and away we go */
- return fill2(ss, str, slen, width, flags);
-}
-
-/*
-** BuildArgArray stands for Numbered Argument list Sprintf
-** for example,
-** fmt = "%4$i, %2$d, %3s, %1d";
-** the number must start from 1, and no gap among them
-*/
-
-static struct NumArg* BuildArgArray( const char *fmt, va_list ap, int* rv, struct NumArg* nasArray )
-{
- int number = 0, cn = 0, i;
- const char* p;
- char c;
- struct NumArg* nas;
-
-
- /*
- ** first pass:
- ** determine how many legal % I have got, then allocate space
- */
-
- p = fmt;
- *rv = 0;
- i = 0;
- while( ( c = *p++ ) != 0 ){
- if( c != '%' )
- continue;
- if( ( c = *p++ ) == '%' ) /* skip %% case */
- continue;
-
- while( c != 0 ){
- if( c > '9' || c < '0' ){
- if( c == '$' ){ /* numbered argument case */
- if( i > 0 ){
- *rv = -1;
- return NULL;
- }
- number++;
- } else{ /* non-numbered argument case */
- if( number > 0 ){
- *rv = -1;
- return NULL;
- }
- i = 1;
- }
- break;
- }
-
- c = *p++;
- }
- }
-
- if( number == 0 ){
- return NULL;
- }
-
-
- if( number > NAS_DEFAULT_NUM ){
- nas = (struct NumArg*)PR_MALLOC( number * sizeof( struct NumArg ) );
- if( !nas ){
- *rv = -1;
- return NULL;
- }
- } else {
- nas = nasArray;
- }
-
- for( i = 0; i < number; i++ ){
- nas[i].type = TYPE_UNKNOWN;
- }
-
-
- /*
- ** second pass:
- ** set nas[].type
- */
-
- p = fmt;
- while( ( c = *p++ ) != 0 ){
- if( c != '%' ) continue;
- c = *p++;
- if( c == '%' ) continue;
-
- cn = 0;
- while( c && c != '$' ){ /* should imporve error check later */
- cn = cn*10 + c - '0';
- c = *p++;
- }
-
- if( !c || cn < 1 || cn > number ){
- *rv = -1;
- break;
- }
-
- /* nas[cn] starts from 0, and make sure nas[cn].type is not assigned */
- cn--;
- if( nas[cn].type != TYPE_UNKNOWN )
- continue;
-
- c = *p++;
-
- /* width */
- if (c == '*') {
- /* not supported feature, for the argument is not numbered */
- *rv = -1;
- break;
- }
-
- while ((c >= '0') && (c <= '9')) {
- c = *p++;
- }
-
- /* precision */
- if (c == '.') {
- c = *p++;
- if (c == '*') {
- /* not supported feature, for the argument is not numbered */
- *rv = -1;
- break;
- }
-
- while ((c >= '0') && (c <= '9')) {
- c = *p++;
- }
- }
-
- /* size */
- nas[cn].type = TYPE_INTN;
- if (c == 'h') {
- nas[cn].type = TYPE_INT16;
- c = *p++;
- } else if (c == 'L') {
- /* XXX not quite sure here */
- nas[cn].type = TYPE_INT64;
- c = *p++;
- } else if (c == 'l') {
- nas[cn].type = TYPE_INT32;
- c = *p++;
- if (c == 'l') {
- nas[cn].type = TYPE_INT64;
- c = *p++;
- }
- } else if (c == 'z') {
- if (sizeof(size_t) == sizeof(PRInt32)) {
- nas[ cn ].type = TYPE_INT32;
- } else if (sizeof(size_t) == sizeof(PRInt64)) {
- nas[ cn ].type = TYPE_INT64;
- } else {
- nas[ cn ].type = TYPE_UNKNOWN;
- }
- c = *p++;
- }
-
- /* format */
- switch (c) {
- case 'd':
- case 'c':
- case 'i':
- case 'o':
- case 'u':
- case 'x':
- case 'X':
- break;
-
- case 'e':
- case 'f':
- case 'g':
- nas[ cn ].type = TYPE_DOUBLE;
- break;
-
- case 'p':
- /* XXX should use cpp */
- if (sizeof(void *) == sizeof(PRInt32)) {
- nas[ cn ].type = TYPE_UINT32;
- } else if (sizeof(void *) == sizeof(PRInt64)) {
- nas[ cn ].type = TYPE_UINT64;
- } else if (sizeof(void *) == sizeof(PRIntn)) {
- nas[ cn ].type = TYPE_UINTN;
- } else {
- nas[ cn ].type = TYPE_UNKNOWN;
- }
- break;
-
- case 'S':
-#ifdef WIN32
- nas[ cn ].type = TYPE_WSTRING;
- break;
-#endif
- case 'C':
- case 'E':
- case 'G':
- /* XXX not supported I suppose */
- PR_ASSERT(0);
- nas[ cn ].type = TYPE_UNKNOWN;
- break;
-
- case 's':
- nas[ cn ].type = TYPE_STRING;
- break;
-
- case 'n':
- nas[ cn ].type = TYPE_INTSTR;
- break;
-
- default:
- PR_ASSERT(0);
- nas[ cn ].type = TYPE_UNKNOWN;
- break;
- }
-
- /* get a legal para. */
- if( nas[ cn ].type == TYPE_UNKNOWN ){
- *rv = -1;
- break;
- }
- }
-
-
- /*
- ** third pass
- ** fill the nas[cn].ap
- */
-
- if( *rv < 0 ){
- if( nas != nasArray )
- PR_DELETE( nas );
- return NULL;
- }
-
- cn = 0;
- while( cn < number ){
- if( nas[cn].type == TYPE_UNKNOWN ){
- cn++;
- continue;
- }
-
- switch( nas[cn].type ){
- case TYPE_INT16:
- case TYPE_UINT16:
- case TYPE_INTN:
- nas[cn].u.i = va_arg( ap, int );
- break;
-
- case TYPE_UINTN:
- nas[cn].u.ui = va_arg( ap, unsigned int );
- break;
-
- case TYPE_INT32:
- nas[cn].u.i32 = va_arg( ap, PRInt32 );
- break;
-
- case TYPE_UINT32:
- nas[cn].u.ui32 = va_arg( ap, PRUint32 );
- break;
-
- case TYPE_INT64:
- nas[cn].u.ll = va_arg( ap, PRInt64 );
- break;
-
- case TYPE_UINT64:
- nas[cn].u.ull = va_arg( ap, PRUint64 );
- break;
-
- case TYPE_STRING:
- nas[cn].u.s = va_arg( ap, char* );
- break;
-
-#ifdef WIN32
- case TYPE_WSTRING:
- nas[cn].u.ws = va_arg( ap, WCHAR* );
- break;
-#endif
-
- case TYPE_INTSTR:
- nas[cn].u.ip = va_arg( ap, int* );
- break;
-
- case TYPE_DOUBLE:
- nas[cn].u.d = va_arg( ap, double );
- break;
-
- default:
- if( nas != nasArray )
- PR_DELETE( nas );
- *rv = -1;
- return NULL;
- }
-
- cn++;
- }
-
-
- return nas;
-}
-
-/*
-** The workhorse sprintf code.
-*/
-static int dosprintf(SprintfState *ss, const char *fmt, va_list ap)
-{
- char c;
- int flags, width, prec, radix, type;
- union {
- char ch;
- int i;
- long l;
- PRInt64 ll;
- double d;
- const char *s;
- int *ip;
-#ifdef WIN32
- const WCHAR *ws;
-#endif
- } u;
- const char *fmt0;
- static char *hex = "0123456789abcdef";
- static char *HEX = "0123456789ABCDEF";
- char *hexp;
- int rv, i;
- struct NumArg* nas = NULL;
- struct NumArg* nap = NULL;
- struct NumArg nasArray[ NAS_DEFAULT_NUM ];
- char pattern[20];
- const char* dolPt = NULL; /* in "%4$.2f", dolPt will point to . */
-#ifdef WIN32
- char *pBuf = NULL;
-#endif
-
- /*
- ** build an argument array, IF the fmt is numbered argument
- ** list style, to contain the Numbered Argument list pointers
- */
-
- nas = BuildArgArray( fmt, ap, &rv, nasArray );
- if( rv < 0 ){
- /* the fmt contains error Numbered Argument format, [email protected] */
- PR_ASSERT(0);
- return rv;
- }
-
- while ((c = *fmt++) != 0) {
- if (c != '%') {
- rv = (*ss->stuff)(ss, fmt - 1, 1);
- if (rv < 0) {
- return rv;
- }
- continue;
- }
- fmt0 = fmt - 1;
-
- /*
- ** Gobble up the % format string. Hopefully we have handled all
- ** of the strange cases!
- */
- flags = 0;
- c = *fmt++;
- if (c == '%') {
- /* quoting a % with %% */
- rv = (*ss->stuff)(ss, fmt - 1, 1);
- if (rv < 0) {
- return rv;
- }
- continue;
- }
-
- if( nas != NULL ){
- /* the fmt contains the Numbered Arguments feature */
- i = 0;
- while( c && c != '$' ){ /* should imporve error check later */
- i = ( i * 10 ) + ( c - '0' );
- c = *fmt++;
- }
-
- if( nas[i-1].type == TYPE_UNKNOWN ){
- if( nas && ( nas != nasArray ) )
- PR_DELETE( nas );
- return -1;
- }
-
- nap = &nas[i-1];
- dolPt = fmt;
- c = *fmt++;
- }
-
- /*
- * Examine optional flags. Note that we do not implement the
- * '#' flag of sprintf(). The ANSI C spec. of the '#' flag is
- * somewhat ambiguous and not ideal, which is perhaps why
- * the various sprintf() implementations are inconsistent
- * on this feature.
- */
- while ((c == '-') || (c == '+') || (c == ' ') || (c == '0')) {
- if (c == '-') flags |= FLAG_LEFT;
- if (c == '+') flags |= FLAG_SIGNED;
- if (c == ' ') flags |= FLAG_SPACED;
- if (c == '0') flags |= FLAG_ZEROS;
- c = *fmt++;
- }
- if (flags & FLAG_SIGNED) flags &= ~FLAG_SPACED;
- if (flags & FLAG_LEFT) flags &= ~FLAG_ZEROS;
-
- /* width */
- if (c == '*') {
- c = *fmt++;
- width = va_arg(ap, int);
- } else {
- width = 0;
- while ((c >= '0') && (c <= '9')) {
- width = (width * 10) + (c - '0');
- c = *fmt++;
- }
- }
-
- /* precision */
- prec = -1;
- if (c == '.') {
- c = *fmt++;
- if (c == '*') {
- c = *fmt++;
- prec = va_arg(ap, int);
- } else {
- prec = 0;
- while ((c >= '0') && (c <= '9')) {
- prec = (prec * 10) + (c - '0');
- c = *fmt++;
- }
- }
- }
-
- /* size */
- type = TYPE_INTN;
- if (c == 'h') {
- type = TYPE_INT16;
- c = *fmt++;
- } else if (c == 'L') {
- /* XXX not quite sure here */
- type = TYPE_INT64;
- c = *fmt++;
- } else if (c == 'l') {
- type = TYPE_INT32;
- c = *fmt++;
- if (c == 'l') {
- type = TYPE_INT64;
- c = *fmt++;
- }
- } else if (c == 'z') {
- if (sizeof(size_t) == sizeof(PRInt32)) {
- type = TYPE_INT32;
- } else if (sizeof(size_t) == sizeof(PRInt64)) {
- type = TYPE_INT64;
- }
- c = *fmt++;
- }
-
- /* format */
- hexp = hex;
- switch (c) {
- case 'd': case 'i': /* decimal/integer */
- radix = 10;
- goto fetch_and_convert;
-
- case 'o': /* octal */
- radix = 8;
- type |= 1;
- goto fetch_and_convert;
-
- case 'u': /* unsigned decimal */
- radix = 10;
- type |= 1;
- goto fetch_and_convert;
-
- case 'x': /* unsigned hex */
- radix = 16;
- type |= 1;
- goto fetch_and_convert;
-
- case 'X': /* unsigned HEX */
- radix = 16;
- hexp = HEX;
- type |= 1;
- goto fetch_and_convert;
-
- fetch_and_convert:
- switch (type) {
- case TYPE_INT16:
- u.l = nas ? nap->u.i : va_arg(ap, int);
- if (u.l < 0) {
- u.l = -u.l;
- flags |= FLAG_NEG;
- }
- goto do_long;
- case TYPE_UINT16:
- u.l = (nas ? nap->u.i : va_arg(ap, int)) & 0xffff;
- goto do_long;
- case TYPE_INTN:
- u.l = nas ? nap->u.i : va_arg(ap, int);
- if (u.l < 0) {
- u.l = -u.l;
- flags |= FLAG_NEG;
- }
- goto do_long;
- case TYPE_UINTN:
- u.l = (long)(nas ? nap->u.ui : va_arg(ap, unsigned int));
- goto do_long;
-
- case TYPE_INT32:
- u.l = nas ? nap->u.i32 : va_arg(ap, PRInt32);
- if (u.l < 0) {
- u.l = -u.l;
- flags |= FLAG_NEG;
- }
- goto do_long;
- case TYPE_UINT32:
- u.l = (long)(nas ? nap->u.ui32 : va_arg(ap, PRUint32));
- do_long:
- rv = cvt_l(ss, u.l, width, prec, radix, type, flags, hexp);
- if (rv < 0) {
- return rv;
- }
- break;
-
- case TYPE_INT64:
- u.ll = nas ? nap->u.ll : va_arg(ap, PRInt64);
- if (!LL_GE_ZERO(u.ll)) {
- LL_NEG(u.ll, u.ll);
- flags |= FLAG_NEG;
- }
- goto do_longlong;
- case TYPE_UINT64:
- u.ll = nas ? nap->u.ull : va_arg(ap, PRUint64);
- do_longlong:
- rv = cvt_ll(ss, u.ll, width, prec, radix, type, flags, hexp);
- if (rv < 0) {
- return rv;
- }
- break;
- }
- break;
-
- case 'e':
- case 'E':
- case 'f':
- case 'g':
- u.d = nas ? nap->u.d : va_arg(ap, double);
- if( nas != NULL ){
- i = fmt - dolPt;
- if( i < sizeof( pattern ) ){
- pattern[0] = '%';
- memcpy( &pattern[1], dolPt, i );
- rv = cvt_f(ss, u.d, pattern, &pattern[i+1] );
- }
- } else
- rv = cvt_f(ss, u.d, fmt0, fmt);
-
- if (rv < 0) {
- return rv;
- }
- break;
-
- case 'c':
- u.ch = nas ? nap->u.i : va_arg(ap, int);
- if ((flags & FLAG_LEFT) == 0) {
- while (width-- > 1) {
- rv = (*ss->stuff)(ss, " ", 1);
- if (rv < 0) {
- return rv;
- }
- }
- }
- rv = (*ss->stuff)(ss, &u.ch, 1);
- if (rv < 0) {
- return rv;
- }
- if (flags & FLAG_LEFT) {
- while (width-- > 1) {
- rv = (*ss->stuff)(ss, " ", 1);
- if (rv < 0) {
- return rv;
- }
- }
- }
- break;
-
- case 'p':
- if (sizeof(void *) == sizeof(PRInt32)) {
- type = TYPE_UINT32;
- } else if (sizeof(void *) == sizeof(PRInt64)) {
- type = TYPE_UINT64;
- } else if (sizeof(void *) == sizeof(int)) {
- type = TYPE_UINTN;
- } else {
- PR_ASSERT(0);
- break;
- }
- radix = 16;
- goto fetch_and_convert;
-
-#ifndef WIN32
- case 'S':
- /* XXX not supported I suppose */
- PR_ASSERT(0);
- break;
-#endif
-
-#if 0
- case 'C':
- case 'E':
- case 'G':
- /* XXX not supported I suppose */
- PR_ASSERT(0);
- break;
-#endif
-
-#ifdef WIN32
- case 'S':
- u.ws = nas ? nap->u.ws : va_arg(ap, const WCHAR*);
-
- /* Get the required size in rv */
- rv = WideCharToMultiByte(CP_ACP, 0, u.ws, -1, NULL, 0, NULL, NULL);
- if (rv == 0)
- rv = 1;
- pBuf = PR_MALLOC(rv);
- WideCharToMultiByte(CP_ACP, 0, u.ws, -1, pBuf, (int)rv, NULL, NULL);
- pBuf[rv-1] = '\0';
-
- rv = cvt_s(ss, pBuf, width, prec, flags);
-
- /* We don't need the allocated buffer anymore */
- PR_Free(pBuf);
- if (rv < 0) {
- return rv;
- }
- break;
-
-#endif
-
- case 's':
- u.s = nas ? nap->u.s : va_arg(ap, const char*);
- rv = cvt_s(ss, u.s, width, prec, flags);
- if (rv < 0) {
- return rv;
- }
- break;
-
- case 'n':
- u.ip = nas ? nap->u.ip : va_arg(ap, int*);
- if (u.ip) {
- *u.ip = ss->cur - ss->base;
- }
- break;
-
- default:
- /* Not a % token after all... skip it */
-#if 0
- PR_ASSERT(0);
-#endif
- rv = (*ss->stuff)(ss, "%", 1);
- if (rv < 0) {
- return rv;
- }
- rv = (*ss->stuff)(ss, fmt - 1, 1);
- if (rv < 0) {
- return rv;
- }
- }
- }
-
- /* Stuff trailing NUL */
- rv = (*ss->stuff)(ss, "\0", 1);
-
- if( nas && ( nas != nasArray ) ){
- PR_DELETE( nas );
- }
-
- return rv;
-}
-
-/************************************************************************/
-
-static int FuncStuff(SprintfState *ss, const char *sp, PRUint32 len)
-{
- int rv;
-
- /*
- ** We will add len to ss->maxlen at the end of the function. First check
- ** if ss->maxlen + len would overflow or be greater than PR_INT32_MAX.
- */
- if (PR_UINT32_MAX - ss->maxlen < len || ss->maxlen + len > PR_INT32_MAX) {
- return -1;
- }
- rv = (*ss->func)(ss->arg, sp, len);
- if (rv < 0) {
- return rv;
- }
- ss->maxlen += len;
- return 0;
-}
-
-PR_IMPLEMENT(PRUint32) PR_sxprintf(PRStuffFunc func, void *arg,
- const char *fmt, ...)
-{
- va_list ap;
- PRUint32 rv;
-
- va_start(ap, fmt);
- rv = PR_vsxprintf(func, arg, fmt, ap);
- va_end(ap);
- return rv;
-}
-
-PR_IMPLEMENT(PRUint32) PR_vsxprintf(PRStuffFunc func, void *arg,
- const char *fmt, va_list ap)
-{
- SprintfState ss;
- int rv;
-
- ss.stuff = FuncStuff;
- ss.func = func;
- ss.arg = arg;
- ss.maxlen = 0;
- rv = dosprintf(&ss, fmt, ap);
- return (rv < 0) ? (PRUint32)-1 : ss.maxlen;
-}
-
-/*
-** Stuff routine that automatically grows the malloc'd output buffer
-** before it overflows.
-*/
-static int GrowStuff(SprintfState *ss, const char *sp, PRUint32 len)
-{
- ptrdiff_t off;
- char *newbase;
- PRUint32 newlen;
-
- off = ss->cur - ss->base;
- if (PR_UINT32_MAX - len < off) {
- /* off + len would be too big. */
- return -1;
- }
- if (off + len >= ss->maxlen) {
- /* Grow the buffer */
- PRUint32 increment = (len > 32) ? len : 32;
- if (PR_UINT32_MAX - ss->maxlen < increment) {
- /* ss->maxlen + increment would overflow. */
- return -1;
- }
- newlen = ss->maxlen + increment;
- if (newlen > PR_INT32_MAX) {
- return -1;
- }
- if (ss->base) {
- newbase = (char*) PR_REALLOC(ss->base, newlen);
- } else {
- newbase = (char*) PR_MALLOC(newlen);
- }
- if (!newbase) {
- /* Ran out of memory */
- return -1;
- }
- ss->base = newbase;
- ss->maxlen = newlen;
- ss->cur = ss->base + off;
- }
-
- /* Copy data */
- while (len) {
- --len;
- *ss->cur++ = *sp++;
- }
- PR_ASSERT((PRUint32)(ss->cur - ss->base) <= ss->maxlen);
- return 0;
-}
-
-/*
-** sprintf into a malloc'd buffer
-*/
-PR_IMPLEMENT(char *) PR_smprintf(const char *fmt, ...)
-{
- va_list ap;
- char *rv;
-
- va_start(ap, fmt);
- rv = PR_vsmprintf(fmt, ap);
- va_end(ap);
- return rv;
-}
-
-/*
-** Free memory allocated, for the caller, by PR_smprintf
-*/
-PR_IMPLEMENT(void) PR_smprintf_free(char *mem)
-{
- PR_DELETE(mem);
-}
-
-PR_IMPLEMENT(char *) PR_vsmprintf(const char *fmt, va_list ap)
-{
- SprintfState ss;
- int rv;
-
- ss.stuff = GrowStuff;
- ss.base = 0;
- ss.cur = 0;
- ss.maxlen = 0;
- rv = dosprintf(&ss, fmt, ap);
- if (rv < 0) {
- if (ss.base) {
- PR_DELETE(ss.base);
- }
- return 0;
- }
- return ss.base;
-}
-
-/*
-** Stuff routine that discards overflow data
-*/
-static int LimitStuff(SprintfState *ss, const char *sp, PRUint32 len)
-{
- PRUint32 limit = ss->maxlen - (ss->cur - ss->base);
-
- if (len > limit) {
- len = limit;
- }
- while (len) {
- --len;
- *ss->cur++ = *sp++;
- }
- return 0;
-}
-
-/*
-** sprintf into a fixed size buffer. Make sure there is a NUL at the end
-** when finished.
-*/
-PR_IMPLEMENT(PRUint32) PR_snprintf(char *out, PRUint32 outlen, const char *fmt, ...)
-{
- va_list ap;
- PRUint32 rv;
-
- va_start(ap, fmt);
- rv = PR_vsnprintf(out, outlen, fmt, ap);
- va_end(ap);
- return rv;
-}
-
-PR_IMPLEMENT(PRUint32) PR_vsnprintf(char *out, PRUint32 outlen,const char *fmt,
- va_list ap)
-{
- SprintfState ss;
- PRUint32 n;
-
- PR_ASSERT(outlen != 0 && outlen <= PR_INT32_MAX);
- if (outlen == 0 || outlen > PR_INT32_MAX) {
- return 0;
- }
-
- ss.stuff = LimitStuff;
- ss.base = out;
- ss.cur = out;
- ss.maxlen = outlen;
- (void) dosprintf(&ss, fmt, ap);
-
- /* If we added chars, and we didn't append a null, do it now. */
- if( (ss.cur != ss.base) && (*(ss.cur - 1) != '\0') )
- *(ss.cur - 1) = '\0';
-
- n = ss.cur - ss.base;
- return n ? n - 1 : n;
-}
-
-PR_IMPLEMENT(char *) PR_sprintf_append(char *last, const char *fmt, ...)
-{
- va_list ap;
- char *rv;
-
- va_start(ap, fmt);
- rv = PR_vsprintf_append(last, fmt, ap);
- va_end(ap);
- return rv;
-}
-
-PR_IMPLEMENT(char *) PR_vsprintf_append(char *last, const char *fmt, va_list ap)
-{
- SprintfState ss;
- int rv;
-
- ss.stuff = GrowStuff;
- if (last) {
- size_t lastlen = strlen(last);
- if (lastlen > PR_INT32_MAX) {
- return 0;
- }
- ss.base = last;
- ss.cur = last + lastlen;
- ss.maxlen = lastlen;
- } else {
- ss.base = 0;
- ss.cur = 0;
- ss.maxlen = 0;
- }
- rv = dosprintf(&ss, fmt, ap);
- if (rv < 0) {
- if (ss.base) {
- PR_DELETE(ss.base);
- }
- return 0;
- }
- return ss.base;
-}
-
diff --git a/nspr/pr/src/io/prscanf.c b/nspr/pr/src/io/prscanf.c
deleted file mode 100644
index 9d75d82..0000000
--- a/nspr/pr/src/io/prscanf.c
+++ /dev/null
@@ -1,634 +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/. */
-
-/*
- * Scan functions for NSPR types
- *
- * Author: Wan-Teh Chang
- *
- * Acknowledgment: The implementation is inspired by the source code
- * in P.J. Plauger's "The Standard C Library," Prentice-Hall, 1992.
- */
-
-#include <limits.h>
-#include <ctype.h>
-#include <string.h>
-#include <stdlib.h>
-#include "prprf.h"
-#include "prdtoa.h"
-#include "prlog.h"
-#include "prerror.h"
-
-/*
- * A function that reads a character from 'stream'.
- * Returns the character read, or EOF if end of stream is reached.
- */
-typedef int (*_PRGetCharFN)(void *stream);
-
-/*
- * A function that pushes the character 'ch' back to 'stream'.
- */
-typedef void (*_PRUngetCharFN)(void *stream, int ch);
-
-/*
- * The size specifier for the integer and floating point number
- * conversions in format control strings.
- */
-typedef enum {
- _PR_size_none, /* No size specifier is given */
- _PR_size_h, /* The 'h' specifier, suggesting "short" */
- _PR_size_l, /* The 'l' specifier, suggesting "long" */
- _PR_size_L, /* The 'L' specifier, meaning a 'long double' */
- _PR_size_ll /* The 'll' specifier, suggesting "long long" */
-} _PRSizeSpec;
-
-/*
- * The collection of data that is passed between the scan function
- * and its subordinate functions. The fields of this structure
- * serve as the input or output arguments for these functions.
- */
-typedef struct {
- _PRGetCharFN get; /* get a character from input stream */
- _PRUngetCharFN unget; /* unget (push back) a character */
- void *stream; /* argument for get and unget */
- va_list ap; /* the variable argument list */
- int nChar; /* number of characters read from 'stream' */
-
- PRBool assign; /* assign, or suppress assignment? */
- int width; /* field width */
- _PRSizeSpec sizeSpec; /* 'h', 'l', 'L', or 'll' */
-
- PRBool converted; /* is the value actually converted? */
-} ScanfState;
-
-#define GET(state) ((state)->nChar++, (state)->get((state)->stream))
-#define UNGET(state, ch) \
- ((state)->nChar--, (state)->unget((state)->stream, ch))
-
-/*
- * The following two macros, GET_IF_WITHIN_WIDTH and WITHIN_WIDTH,
- * are always used together.
- *
- * GET_IF_WITHIN_WIDTH calls the GET macro and assigns its return
- * value to 'ch' only if we have not exceeded the field width of
- * 'state'. Therefore, after GET_IF_WITHIN_WIDTH, the value of
- * 'ch' is valid only if the macro WITHIN_WIDTH evaluates to true.
- */
-
-#define GET_IF_WITHIN_WIDTH(state, ch) \
- if (--(state)->width >= 0) { \
- (ch) = GET(state); \
- }
-#define WITHIN_WIDTH(state) ((state)->width >= 0)
-
-/*
- * _pr_strtoull:
- * Convert a string to an unsigned 64-bit integer. The string
- * 'str' is assumed to be a representation of the integer in
- * base 'base'.
- *
- * Warning:
- * - Only handle base 8, 10, and 16.
- * - No overflow checking.
- */
-
-static PRUint64
-_pr_strtoull(const char *str, char **endptr, int base)
-{
- static const int BASE_MAX = 16;
- static const char digits[] = "0123456789abcdef";
- char *digitPtr;
- PRUint64 x; /* return value */
- PRInt64 base64;
- const char *cPtr;
- PRBool negative;
- const char *digitStart;
-
- PR_ASSERT(base == 0 || base == 8 || base == 10 || base == 16);
- if (base < 0 || base == 1 || base > BASE_MAX) {
- if (endptr) {
- *endptr = (char *) str;
- return LL_ZERO;
- }
- }
-
- cPtr = str;
- while (isspace(*cPtr)) {
- ++cPtr;
- }
-
- negative = PR_FALSE;
- if (*cPtr == '-') {
- negative = PR_TRUE;
- cPtr++;
- } else if (*cPtr == '+') {
- cPtr++;
- }
-
- if (base == 16) {
- if (*cPtr == '0' && (cPtr[1] == 'x' || cPtr[1] == 'X')) {
- cPtr += 2;
- }
- } else if (base == 0) {
- if (*cPtr != '0') {
- base = 10;
- } else if (cPtr[1] == 'x' || cPtr[1] == 'X') {
- base = 16;
- cPtr += 2;
- } else {
- base = 8;
- }
- }
- PR_ASSERT(base != 0);
- LL_I2L(base64, base);
- digitStart = cPtr;
-
- /* Skip leading zeros */
- while (*cPtr == '0') {
- cPtr++;
- }
-
- LL_I2L(x, 0);
- while ((digitPtr = (char*)memchr(digits, tolower(*cPtr), base)) != NULL) {
- PRUint64 d;
-
- LL_I2L(d, (digitPtr - digits));
- LL_MUL(x, x, base64);
- LL_ADD(x, x, d);
- cPtr++;
- }
-
- if (cPtr == digitStart) {
- if (endptr) {
- *endptr = (char *) str;
- }
- return LL_ZERO;
- }
-
- if (negative) {
-#ifdef HAVE_LONG_LONG
- /* The cast to a signed type is to avoid a compiler warning */
- x = -(PRInt64)x;
-#else
- LL_NEG(x, x);
-#endif
- }
-
- if (endptr) {
- *endptr = (char *) cPtr;
- }
- return x;
-}
-
-/*
- * The maximum field width (in number of characters) that is enough
- * (may be more than necessary) to represent a 64-bit integer or
- * floating point number.
- */
-#define FMAX 31
-#define DECIMAL_POINT '.'
-
-static PRStatus
-GetInt(ScanfState *state, int code)
-{
- char buf[FMAX + 1], *p;
- int ch = 0;
- static const char digits[] = "0123456789abcdefABCDEF";
- PRBool seenDigit = PR_FALSE;
- int base;
- int dlen;
-
- switch (code) {
- case 'd': case 'u':
- base = 10;
- break;
- case 'i':
- base = 0;
- break;
- case 'x': case 'X': case 'p':
- base = 16;
- break;
- case 'o':
- base = 8;
- break;
- default:
- return PR_FAILURE;
- }
- if (state->width == 0 || state->width > FMAX) {
- state->width = FMAX;
- }
- p = buf;
- GET_IF_WITHIN_WIDTH(state, ch);
- if (WITHIN_WIDTH(state) && (ch == '+' || ch == '-')) {
- *p++ = ch;
- GET_IF_WITHIN_WIDTH(state, ch);
- }
- if (WITHIN_WIDTH(state) && ch == '0') {
- seenDigit = PR_TRUE;
- *p++ = ch;
- GET_IF_WITHIN_WIDTH(state, ch);
- if (WITHIN_WIDTH(state)
- && (ch == 'x' || ch == 'X')
- && (base == 0 || base == 16)) {
- base = 16;
- *p++ = ch;
- GET_IF_WITHIN_WIDTH(state, ch);
- } else if (base == 0) {
- base = 8;
- }
- }
- if (base == 0 || base == 10) {
- dlen = 10;
- } else if (base == 8) {
- dlen = 8;
- } else {
- PR_ASSERT(base == 16);
- dlen = 16 + 6; /* 16 digits, plus 6 in uppercase */
- }
- while (WITHIN_WIDTH(state) && memchr(digits, ch, dlen)) {
- *p++ = ch;
- GET_IF_WITHIN_WIDTH(state, ch);
- seenDigit = PR_TRUE;
- }
- if (WITHIN_WIDTH(state)) {
- UNGET(state, ch);
- }
- if (!seenDigit) {
- return PR_FAILURE;
- }
- *p = '\0';
- if (state->assign) {
- if (code == 'd' || code == 'i') {
- if (state->sizeSpec == _PR_size_ll) {
- PRInt64 llval = _pr_strtoull(buf, NULL, base);
- *va_arg(state->ap, PRInt64 *) = llval;
- } else {
- long lval = strtol(buf, NULL, base);
-
- if (state->sizeSpec == _PR_size_none) {
- *va_arg(state->ap, PRIntn *) = lval;
- } else if (state->sizeSpec == _PR_size_h) {
- *va_arg(state->ap, PRInt16 *) = (PRInt16)lval;
- } else if (state->sizeSpec == _PR_size_l) {
- *va_arg(state->ap, PRInt32 *) = lval;
- } else {
- return PR_FAILURE;
- }
- }
- } else {
- if (state->sizeSpec == _PR_size_ll) {
- PRUint64 llval = _pr_strtoull(buf, NULL, base);
- *va_arg(state->ap, PRUint64 *) = llval;
- } else {
- unsigned long lval = strtoul(buf, NULL, base);
-
- if (state->sizeSpec == _PR_size_none) {
- *va_arg(state->ap, PRUintn *) = lval;
- } else if (state->sizeSpec == _PR_size_h) {
- *va_arg(state->ap, PRUint16 *) = (PRUint16)lval;
- } else if (state->sizeSpec == _PR_size_l) {
- *va_arg(state->ap, PRUint32 *) = lval;
- } else {
- return PR_FAILURE;
- }
- }
- }
- state->converted = PR_TRUE;
- }
- return PR_SUCCESS;
-}
-
-static PRStatus
-GetFloat(ScanfState *state)
-{
- char buf[FMAX + 1], *p;
- int ch = 0;
- PRBool seenDigit = PR_FALSE;
-
- if (state->width == 0 || state->width > FMAX) {
- state->width = FMAX;
- }
- p = buf;
- GET_IF_WITHIN_WIDTH(state, ch);
- if (WITHIN_WIDTH(state) && (ch == '+' || ch == '-')) {
- *p++ = ch;
- GET_IF_WITHIN_WIDTH(state, ch);
- }
- while (WITHIN_WIDTH(state) && isdigit(ch)) {
- *p++ = ch;
- GET_IF_WITHIN_WIDTH(state, ch);
- seenDigit = PR_TRUE;
- }
- if (WITHIN_WIDTH(state) && ch == DECIMAL_POINT) {
- *p++ = ch;
- GET_IF_WITHIN_WIDTH(state, ch);
- while (WITHIN_WIDTH(state) && isdigit(ch)) {
- *p++ = ch;
- GET_IF_WITHIN_WIDTH(state, ch);
- seenDigit = PR_TRUE;
- }
- }
-
- /*
- * This is not robust. For example, "1.2e+" would confuse
- * the code below to read 'e' and '+', only to realize that
- * it should have stopped at "1.2". But we can't push back
- * more than one character, so there is nothing I can do.
- */
-
- /* Parse exponent */
- if (WITHIN_WIDTH(state) && (ch == 'e' || ch == 'E') && seenDigit) {
- *p++ = ch;
- GET_IF_WITHIN_WIDTH(state, ch);
- if (WITHIN_WIDTH(state) && (ch == '+' || ch == '-')) {
- *p++ = ch;
- GET_IF_WITHIN_WIDTH(state, ch);
- }
- while (WITHIN_WIDTH(state) && isdigit(ch)) {
- *p++ = ch;
- GET_IF_WITHIN_WIDTH(state, ch);
- }
- }
- if (WITHIN_WIDTH(state)) {
- UNGET(state, ch);
- }
- if (!seenDigit) {
- return PR_FAILURE;
- }
- *p = '\0';
- if (state->assign) {
- PRFloat64 dval = PR_strtod(buf, NULL);
-
- state->converted = PR_TRUE;
- if (state->sizeSpec == _PR_size_l) {
- *va_arg(state->ap, PRFloat64 *) = dval;
- } else if (state->sizeSpec == _PR_size_L) {
-#if defined(OSF1) || defined(IRIX)
- *va_arg(state->ap, double *) = dval;
-#else
- *va_arg(state->ap, long double *) = dval;
-#endif
- } else {
- *va_arg(state->ap, float *) = (float) dval;
- }
- }
- return PR_SUCCESS;
-}
-
-/*
- * Convert, and return the end of the conversion spec.
- * Return NULL on error.
- */
-
-static const char *
-Convert(ScanfState *state, const char *fmt)
-{
- const char *cPtr;
- int ch;
- char *cArg = NULL;
-
- state->converted = PR_FALSE;
- cPtr = fmt;
- if (*cPtr != 'c' && *cPtr != 'n' && *cPtr != '[') {
- do {
- ch = GET(state);
- } while (isspace(ch));
- UNGET(state, ch);
- }
- switch (*cPtr) {
- case 'c':
- if (state->assign) {
- cArg = va_arg(state->ap, char *);
- }
- if (state->width == 0) {
- state->width = 1;
- }
- for (; state->width > 0; state->width--) {
- ch = GET(state);
- if (ch == EOF) {
- return NULL;
- } else if (state->assign) {
- *cArg++ = ch;
- }
- }
- if (state->assign) {
- state->converted = PR_TRUE;
- }
- break;
- case 'p':
- case 'd': case 'i': case 'o':
- case 'u': case 'x': case 'X':
- if (GetInt(state, *cPtr) == PR_FAILURE) {
- return NULL;
- }
- break;
- case 'e': case 'E': case 'f':
- case 'g': case 'G':
- if (GetFloat(state) == PR_FAILURE) {
- return NULL;
- }
- break;
- case 'n':
- /* do not consume any input */
- if (state->assign) {
- switch (state->sizeSpec) {
- case _PR_size_none:
- *va_arg(state->ap, PRIntn *) = state->nChar;
- break;
- case _PR_size_h:
- *va_arg(state->ap, PRInt16 *) = state->nChar;
- break;
- case _PR_size_l:
- *va_arg(state->ap, PRInt32 *) = state->nChar;
- break;
- case _PR_size_ll:
- LL_I2L(*va_arg(state->ap, PRInt64 *), state->nChar);
- break;
- default:
- PR_ASSERT(0);
- }
- }
- break;
- case 's':
- if (state->width == 0) {
- state->width = INT_MAX;
- }
- if (state->assign) {
- cArg = va_arg(state->ap, char *);
- }
- for (; state->width > 0; state->width--) {
- ch = GET(state);
- if ((ch == EOF) || isspace(ch)) {
- UNGET(state, ch);
- break;
- }
- if (state->assign) {
- *cArg++ = ch;
- }
- }
- if (state->assign) {
- *cArg = '\0';
- state->converted = PR_TRUE;
- }
- break;
- case '%':
- ch = GET(state);
- if (ch != '%') {
- UNGET(state, ch);
- return NULL;
- }
- break;
- case '[':
- {
- PRBool complement = PR_FALSE;
- const char *closeBracket;
- size_t n;
-
- if (*++cPtr == '^') {
- complement = PR_TRUE;
- cPtr++;
- }
- closeBracket = strchr(*cPtr == ']' ? cPtr + 1 : cPtr, ']');
- if (closeBracket == NULL) {
- return NULL;
- }
- n = closeBracket - cPtr;
- if (state->width == 0) {
- state->width = INT_MAX;
- }
- if (state->assign) {
- cArg = va_arg(state->ap, char *);
- }
- for (; state->width > 0; state->width--) {
- ch = GET(state);
- if ((ch == EOF)
- || (!complement && !memchr(cPtr, ch, n))
- || (complement && memchr(cPtr, ch, n))) {
- UNGET(state, ch);
- break;
- }
- if (state->assign) {
- *cArg++ = ch;
- }
- }
- if (state->assign) {
- *cArg = '\0';
- state->converted = PR_TRUE;
- }
- cPtr = closeBracket;
- }
- break;
- default:
- return NULL;
- }
- return cPtr;
-}
-
-static PRInt32
-DoScanf(ScanfState *state, const char *fmt)
-{
- PRInt32 nConverted = 0;
- const char *cPtr;
- int ch;
-
- state->nChar = 0;
- cPtr = fmt;
- while (1) {
- if (isspace(*cPtr)) {
- /* white space: skip */
- do {
- cPtr++;
- } while (isspace(*cPtr));
- do {
- ch = GET(state);
- } while (isspace(ch));
- UNGET(state, ch);
- } else if (*cPtr == '%') {
- /* format spec: convert */
- cPtr++;
- state->assign = PR_TRUE;
- if (*cPtr == '*') {
- cPtr++;
- state->assign = PR_FALSE;
- }
- for (state->width = 0; isdigit(*cPtr); cPtr++) {
- state->width = state->width * 10 + *cPtr - '0';
- }
- state->sizeSpec = _PR_size_none;
- if (*cPtr == 'h') {
- cPtr++;
- state->sizeSpec = _PR_size_h;
- } else if (*cPtr == 'l') {
- cPtr++;
- if (*cPtr == 'l') {
- cPtr++;
- state->sizeSpec = _PR_size_ll;
- } else {
- state->sizeSpec = _PR_size_l;
- }
- } else if (*cPtr == 'L') {
- cPtr++;
- state->sizeSpec = _PR_size_L;
- }
- cPtr = Convert(state, cPtr);
- if (cPtr == NULL) {
- return (nConverted > 0 ? nConverted : EOF);
- }
- if (state->converted) {
- nConverted++;
- }
- cPtr++;
- } else {
- /* others: must match */
- if (*cPtr == '\0') {
- return nConverted;
- }
- ch = GET(state);
- if (ch != *cPtr) {
- UNGET(state, ch);
- return nConverted;
- }
- cPtr++;
- }
- }
-}
-
-static int
-StringGetChar(void *stream)
-{
- char *cPtr = *((char **) stream);
-
- if (*cPtr == '\0') {
- return EOF;
- } else {
- *((char **) stream) = cPtr + 1;
- return (unsigned char) *cPtr;
- }
-}
-
-static void
-StringUngetChar(void *stream, int ch)
-{
- char *cPtr = *((char **) stream);
-
- if (ch != EOF) {
- *((char **) stream) = cPtr - 1;
- }
-}
-
-PR_IMPLEMENT(PRInt32)
-PR_sscanf(const char *buf, const char *fmt, ...)
-{
- PRInt32 rv;
- ScanfState state;
-
- state.get = &StringGetChar;
- state.unget = &StringUngetChar;
- state.stream = (void *) &buf;
- va_start(state.ap, fmt);
- rv = DoScanf(&state, fmt);
- va_end(state.ap);
- return rv;
-}
diff --git a/nspr/pr/src/io/prsocket.c b/nspr/pr/src/io/prsocket.c
deleted file mode 100644
index be97024..0000000
--- a/nspr/pr/src/io/prsocket.c
+++ /dev/null
@@ -1,1794 +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/. */
-
-#include "primpl.h"
-
-#include <string.h>
-
-/************************************************************************/
-
-/* These two functions are only used in assertions. */
-#if defined(DEBUG)
-
-PRBool IsValidNetAddr(const PRNetAddr *addr)
-{
- if ((addr != NULL)
-#if defined(XP_UNIX) || defined(XP_OS2)
- && (addr->raw.family != PR_AF_LOCAL)
-#endif
- && (addr->raw.family != PR_AF_INET6)
- && (addr->raw.family != PR_AF_INET)) {
- return PR_FALSE;
- }
- return PR_TRUE;
-}
-
-static PRBool IsValidNetAddrLen(const PRNetAddr *addr, PRInt32 addr_len)
-{
- /*
- * The definition of the length of a Unix domain socket address
- * is not uniform, so we don't check it.
- */
- if ((addr != NULL)
-#if defined(XP_UNIX) || defined(XP_OS2)
- && (addr->raw.family != AF_UNIX)
-#endif
- && (PR_NETADDR_SIZE(addr) != addr_len)) {
-#if defined(LINUX) && __GLIBC__ == 2 && __GLIBC_MINOR__ == 1
- /*
- * In glibc 2.1, struct sockaddr_in6 is 24 bytes. In glibc 2.2
- * and in the 2.4 kernel, struct sockaddr_in6 has the scope_id
- * field and is 28 bytes. It is possible for socket functions
- * to return an addr_len greater than sizeof(struct sockaddr_in6).
- * We need to allow that. (Bugzilla bug #77264)
- */
- if ((PR_AF_INET6 == addr->raw.family)
- && (sizeof(addr->ipv6) == addr_len)) {
- return PR_TRUE;
- }
-#endif
- /*
- * The accept(), getsockname(), etc. calls on some platforms
- * do not set the actual socket address length on return.
- * In this case, we verifiy addr_len is still the value we
- * passed in (i.e., sizeof(PRNetAddr)).
- */
-#if defined(QNX)
- if (sizeof(PRNetAddr) == addr_len) {
- return PR_TRUE;
- }
-#endif
- return PR_FALSE;
- }
- return PR_TRUE;
-}
-
-#endif /* DEBUG */
-
-static PRInt32 PR_CALLBACK SocketWritev(PRFileDesc *fd, const PRIOVec *iov,
-PRInt32 iov_size, PRIntervalTime timeout)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
- int w = 0;
- const PRIOVec *tmp_iov;
-#define LOCAL_MAXIOV 8
- PRIOVec local_iov[LOCAL_MAXIOV];
- PRIOVec *iov_copy = NULL;
- int tmp_out;
- int index, iov_cnt;
- int count=0, sz = 0; /* 'count' is the return value. */
-
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- return -1;
- }
- if (_PR_IO_PENDING(me)) {
- PR_SetError(PR_IO_PENDING_ERROR, 0);
- return -1;
- }
-
- /*
- * Assume the first writev will succeed. Copy iov's only on
- * failure.
- */
- tmp_iov = iov;
- for (index = 0; index < iov_size; index++)
- sz += iov[index].iov_len;
-
- iov_cnt = iov_size;
-
- while (sz > 0) {
-
- w = _PR_MD_WRITEV(fd, tmp_iov, iov_cnt, timeout);
- if (w < 0) {
- count = -1;
- break;
- }
- count += w;
- if (fd->secret->nonblocking) {
- break;
- }
- sz -= w;
-
- if (sz > 0) {
- /* find the next unwritten vector */
- for ( index = 0, tmp_out = count;
- tmp_out >= iov[index].iov_len;
- tmp_out -= iov[index].iov_len, index++){;} /* nothing to execute */
-
- if (tmp_iov == iov) {
- /*
- * The first writev failed so we
- * must copy iov's around.
- * Avoid calloc/free if there
- * are few enough iov's.
- */
- if (iov_size - index <= LOCAL_MAXIOV)
- iov_copy = local_iov;
- else if ((iov_copy = (PRIOVec *) PR_CALLOC((iov_size - index) *
- sizeof *iov_copy)) == NULL) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return -1;
- }
- tmp_iov = iov_copy;
- }
-
- PR_ASSERT(tmp_iov == iov_copy);
-
- /* fill in the first partial read */
- iov_copy[0].iov_base = &(((char *)iov[index].iov_base)[tmp_out]);
- iov_copy[0].iov_len = iov[index].iov_len - tmp_out;
- index++;
-
- /* copy the remaining vectors */
- for (iov_cnt=1; index<iov_size; iov_cnt++, index++) {
- iov_copy[iov_cnt].iov_base = iov[index].iov_base;
- iov_copy[iov_cnt].iov_len = iov[index].iov_len;
- }
- }
- }
-
- if (iov_copy != local_iov)
- PR_DELETE(iov_copy);
- return count;
-}
-
-/************************************************************************/
-
-PR_IMPLEMENT(PRFileDesc *) PR_ImportTCPSocket(PROsfd osfd)
-{
-PRFileDesc *fd;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- fd = PR_AllocFileDesc(osfd, PR_GetTCPMethods());
- if (fd != NULL) {
- _PR_MD_MAKE_NONBLOCK(fd);
- _PR_MD_INIT_FD_INHERITABLE(fd, PR_TRUE);
-#ifdef _PR_NEED_SECRET_AF
- /* this means we can only import IPv4 sockets here.
- * but this is what the function in ptio.c does.
- * We need a way to import IPv6 sockets, too.
- */
- fd->secret->af = AF_INET;
-#endif
- } else
- _PR_MD_CLOSE_SOCKET(osfd);
- return(fd);
-}
-
-PR_IMPLEMENT(PRFileDesc *) PR_ImportUDPSocket(PROsfd osfd)
-{
-PRFileDesc *fd;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- fd = PR_AllocFileDesc(osfd, PR_GetUDPMethods());
- if (fd != NULL) {
- _PR_MD_MAKE_NONBLOCK(fd);
- _PR_MD_INIT_FD_INHERITABLE(fd, PR_TRUE);
- } else
- _PR_MD_CLOSE_SOCKET(osfd);
- return(fd);
-}
-
-
-static const PRIOMethods* PR_GetSocketPollFdMethods(void);
-
-PR_IMPLEMENT(PRFileDesc*) PR_CreateSocketPollFd(PROsfd osfd)
-{
- PRFileDesc *fd;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- fd = _PR_Getfd();
-
- if (fd == NULL) PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- else
- {
- fd->secret->md.osfd = osfd;
- fd->secret->inheritable = _PR_TRI_FALSE;
- fd->secret->state = _PR_FILEDESC_OPEN;
- fd->methods = PR_GetSocketPollFdMethods();
- }
-
- return fd;
-} /* PR_CreateSocketPollFD */
-
-PR_IMPLEMENT(PRStatus) PR_DestroySocketPollFd(PRFileDesc *fd)
-{
- if (NULL == fd)
- {
- PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
- return PR_FAILURE;
- }
- fd->secret->state = _PR_FILEDESC_CLOSED;
- _PR_Putfd(fd);
- return PR_SUCCESS;
-} /* PR_DestroySocketPollFd */
-
-static PRStatus PR_CALLBACK SocketConnect(
- PRFileDesc *fd, const PRNetAddr *addr, PRIntervalTime timeout)
-{
- PRInt32 rv; /* Return value of _PR_MD_CONNECT */
- const PRNetAddr *addrp = addr;
-#if defined(_PR_INET6)
- PRNetAddr addrCopy;
-#endif
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- return PR_FAILURE;
- }
-#if defined(_PR_INET6)
- if (addr->raw.family == PR_AF_INET6) {
- addrCopy = *addr;
- addrCopy.raw.family = AF_INET6;
- addrp = &addrCopy;
- }
-#endif
-
- rv = _PR_MD_CONNECT(fd, addrp, PR_NETADDR_SIZE(addr), timeout);
- PR_LOG(_pr_io_lm, PR_LOG_MAX, ("connect -> %d", rv));
- if (rv == 0)
- return PR_SUCCESS;
- else
- return PR_FAILURE;
-}
-
-static PRStatus PR_CALLBACK SocketConnectContinue(
- PRFileDesc *fd, PRInt16 out_flags)
-{
- PROsfd osfd;
- int err;
-
- if (out_flags & PR_POLL_NVAL) {
- PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
- return PR_FAILURE;
- }
- if ((out_flags & (PR_POLL_WRITE | PR_POLL_EXCEPT | PR_POLL_ERR)) == 0) {
- PR_ASSERT(out_flags == 0);
- PR_SetError(PR_IN_PROGRESS_ERROR, 0);
- return PR_FAILURE;
- }
-
- osfd = fd->secret->md.osfd;
-
-#if defined(XP_UNIX)
-
- err = _MD_unix_get_nonblocking_connect_error(osfd);
- if (err != 0) {
- _PR_MD_MAP_CONNECT_ERROR(err);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-
-#elif defined(WIN32) || defined(WIN16)
-
- if (out_flags & PR_POLL_EXCEPT) {
- int len = sizeof(err);
- if (getsockopt(osfd, (int)SOL_SOCKET, SO_ERROR, (char *) &err, &len)
- == SOCKET_ERROR) {
- _PR_MD_MAP_GETSOCKOPT_ERROR(WSAGetLastError());
- return PR_FAILURE;
- }
- if (err != 0) {
- _PR_MD_MAP_CONNECT_ERROR(err);
- } else {
- PR_SetError(PR_UNKNOWN_ERROR, 0);
- }
- return PR_FAILURE;
- }
-
- PR_ASSERT(out_flags & PR_POLL_WRITE);
- return PR_SUCCESS;
-
-#elif defined(XP_OS2)
-
- err = _MD_os2_get_nonblocking_connect_error(osfd);
- if (err != 0) {
- _PR_MD_MAP_CONNECT_ERROR(err);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-
-#elif defined(XP_BEOS)
-
-#ifdef BONE_VERSION /* bug 122364 */
- /* temporary workaround until getsockopt(SO_ERROR) works in BONE */
- if (out_flags & PR_POLL_EXCEPT) {
- PR_SetError(PR_CONNECT_REFUSED_ERROR, 0);
- return PR_FAILURE;
- }
- PR_ASSERT(out_flags & PR_POLL_WRITE);
- return PR_SUCCESS;
-#else
- err = _MD_beos_get_nonblocking_connect_error(fd);
- if( err != 0 ) {
- _PR_MD_MAP_CONNECT_ERROR(err);
- return PR_FAILURE;
- }
- else
- return PR_SUCCESS;
-#endif /* BONE_VERSION */
-
-#else
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-#endif
-}
-
-PR_IMPLEMENT(PRStatus) PR_GetConnectStatus(const PRPollDesc *pd)
-{
- /* Find the NSPR layer and invoke its connectcontinue method */
- PRFileDesc *bottom = PR_GetIdentitiesLayer(pd->fd, PR_NSPR_IO_LAYER);
-
- if (NULL == bottom) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
- return SocketConnectContinue(bottom, pd->out_flags);
-}
-
-static PRFileDesc* PR_CALLBACK SocketAccept(PRFileDesc *fd, PRNetAddr *addr,
-PRIntervalTime timeout)
-{
- PROsfd osfd;
- PRFileDesc *fd2;
- PRUint32 al;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-#ifdef WINNT
- PRNetAddr addrCopy;
-#endif
-
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- return 0;
- }
- if (_PR_IO_PENDING(me)) {
- PR_SetError(PR_IO_PENDING_ERROR, 0);
- return 0;
- }
-
-#ifdef WINNT
- if (addr == NULL) {
- addr = &addrCopy;
- }
-#endif
- al = sizeof(PRNetAddr);
- osfd = _PR_MD_ACCEPT(fd, addr, &al, timeout);
- if (osfd == -1)
- return 0;
-
- fd2 = PR_AllocFileDesc(osfd, PR_GetTCPMethods());
- if (!fd2) {
- _PR_MD_CLOSE_SOCKET(osfd);
- return NULL;
- }
-
- fd2->secret->nonblocking = fd->secret->nonblocking;
- fd2->secret->inheritable = fd->secret->inheritable;
-#ifdef WINNT
- if (!fd2->secret->nonblocking && fd2->secret->inheritable != _PR_TRI_TRUE) {
- /*
- * The new socket has been associated with an I/O
- * completion port. There is no going back.
- */
- fd2->secret->md.io_model_committed = PR_TRUE;
- }
- PR_ASSERT(al == PR_NETADDR_SIZE(addr));
- fd2->secret->md.accepted_socket = PR_TRUE;
- memcpy(&fd2->secret->md.peer_addr, addr, al);
-#endif
-
- /*
- * On some platforms, the new socket created by accept()
- * inherits the nonblocking (or overlapped io) attribute
- * of the listening socket. As an optimization, these
- * platforms can skip the following _PR_MD_MAKE_NONBLOCK
- * call.
- */
-#if !defined(SOLARIS) && !defined(IRIX) && !defined(WINNT)
- _PR_MD_MAKE_NONBLOCK(fd2);
-#endif
-
-#ifdef _PR_INET6
- if (addr && (AF_INET6 == addr->raw.family))
- addr->raw.family = PR_AF_INET6;
-#endif
- PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
- PR_ASSERT(IsValidNetAddrLen(addr, al) == PR_TRUE);
-
- return fd2;
-}
-
-#ifdef WINNT
-PR_IMPLEMENT(PRFileDesc*) PR_NTFast_Accept(PRFileDesc *fd, PRNetAddr *addr,
-PRIntervalTime timeout)
-{
- PROsfd osfd;
- PRFileDesc *fd2;
- PRIntn al;
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRNetAddr addrCopy;
-
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- return 0;
- }
- if (_PR_IO_PENDING(me)) {
- PR_SetError(PR_IO_PENDING_ERROR, 0);
- return 0;
- }
-
- if (addr == NULL) {
- addr = &addrCopy;
- }
- al = PR_NETADDR_SIZE(addr);
- osfd = _PR_MD_FAST_ACCEPT(fd, addr, &al, timeout, PR_TRUE, NULL, NULL);
- if (osfd == -1) {
- return 0;
- }
-
- fd2 = PR_AllocFileDesc(osfd, PR_GetTCPMethods());
- if (!fd2) {
- _PR_MD_CLOSE_SOCKET(osfd);
- } else {
- fd2->secret->nonblocking = fd->secret->nonblocking;
- fd2->secret->md.io_model_committed = PR_TRUE;
- PR_ASSERT(al == PR_NETADDR_SIZE(addr));
- fd2->secret->md.accepted_socket = PR_TRUE;
- memcpy(&fd2->secret->md.peer_addr, addr, al);
-#ifdef _PR_INET6
- if (AF_INET6 == addr->raw.family)
- addr->raw.family = PR_AF_INET6;
-#endif
-#ifdef _PR_NEED_SECRET_AF
- fd2->secret->af = fd->secret->af;
-#endif
- }
- return fd2;
-}
-#endif /* WINNT */
-
-
-static PRStatus PR_CALLBACK SocketBind(PRFileDesc *fd, const PRNetAddr *addr)
-{
- PRInt32 result;
- const PRNetAddr *addrp = addr;
-#if defined(_PR_INET6)
- PRNetAddr addrCopy;
-#endif
-
- PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
-
-#ifdef XP_UNIX
- if (addr->raw.family == AF_UNIX) {
- /* Disallow relative pathnames */
- if (addr->local.path[0] != '/') {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
- }
-#endif /* XP_UNIX */
-
-#if defined(_PR_INET6)
- if (addr->raw.family == PR_AF_INET6) {
- addrCopy = *addr;
- addrCopy.raw.family = AF_INET6;
- addrp = &addrCopy;
- }
-#endif
- result = _PR_MD_BIND(fd, addrp, PR_NETADDR_SIZE(addr));
- if (result < 0) {
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-static PRStatus PR_CALLBACK SocketListen(PRFileDesc *fd, PRIntn backlog)
-{
- PRInt32 result;
-
- result = _PR_MD_LISTEN(fd, backlog);
- if (result < 0) {
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-static PRStatus PR_CALLBACK SocketShutdown(PRFileDesc *fd, PRIntn how)
-{
- PRInt32 result;
-
- result = _PR_MD_SHUTDOWN(fd, how);
- if (result < 0) {
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-static PRInt32 PR_CALLBACK SocketRecv(PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags,
-PRIntervalTime timeout)
-{
- PRInt32 rv;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if ((flags != 0) && (flags != PR_MSG_PEEK)) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return -1;
- }
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- return -1;
- }
- if (_PR_IO_PENDING(me)) {
- PR_SetError(PR_IO_PENDING_ERROR, 0);
- return -1;
- }
-
- PR_LOG(_pr_io_lm, PR_LOG_MAX,
- ("recv: fd=%p osfd=%" PR_PRIdOSFD " buf=%p amount=%d flags=%d",
- fd, fd->secret->md.osfd, buf, amount, flags));
-
-#ifdef _PR_HAVE_PEEK_BUFFER
- if (fd->secret->peekBytes != 0) {
- rv = (amount < fd->secret->peekBytes) ?
- amount : fd->secret->peekBytes;
- memcpy(buf, fd->secret->peekBuffer, rv);
- if (flags == 0) {
- /* consume the bytes in the peek buffer */
- fd->secret->peekBytes -= rv;
- if (fd->secret->peekBytes != 0) {
- memmove(fd->secret->peekBuffer,
- fd->secret->peekBuffer + rv,
- fd->secret->peekBytes);
- }
- }
- return rv;
- }
-
- /* allocate peek buffer, if necessary */
- if ((PR_MSG_PEEK == flags) && _PR_FD_NEED_EMULATE_MSG_PEEK(fd)) {
- PR_ASSERT(0 == fd->secret->peekBytes);
- /* impose a max size on the peek buffer */
- if (amount > _PR_PEEK_BUFFER_MAX) {
- amount = _PR_PEEK_BUFFER_MAX;
- }
- if (fd->secret->peekBufSize < amount) {
- if (fd->secret->peekBuffer) {
- PR_Free(fd->secret->peekBuffer);
- }
- fd->secret->peekBufSize = amount;
- fd->secret->peekBuffer = PR_Malloc(amount);
- if (NULL == fd->secret->peekBuffer) {
- fd->secret->peekBufSize = 0;
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return -1;
- }
- }
- }
-#endif
-
- rv = _PR_MD_RECV(fd, buf, amount, flags, timeout);
- PR_LOG(_pr_io_lm, PR_LOG_MAX, ("recv -> %d, error = %d, os error = %d",
- rv, PR_GetError(), PR_GetOSError()));
-
-#ifdef _PR_HAVE_PEEK_BUFFER
- if ((PR_MSG_PEEK == flags) && _PR_FD_NEED_EMULATE_MSG_PEEK(fd)) {
- if (rv > 0) {
- memcpy(fd->secret->peekBuffer, buf, rv);
- fd->secret->peekBytes = rv;
- }
- }
-#endif
-
- return rv;
-}
-
-static PRInt32 PR_CALLBACK SocketRead(PRFileDesc *fd, void *buf, PRInt32 amount)
-{
- return SocketRecv(fd, buf, amount, 0, PR_INTERVAL_NO_TIMEOUT);
-}
-
-static PRInt32 PR_CALLBACK SocketSend(PRFileDesc *fd, const void *buf, PRInt32 amount,
-PRIntn flags, PRIntervalTime timeout)
-{
- PRInt32 temp, count;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- return -1;
- }
- if (_PR_IO_PENDING(me)) {
- PR_SetError(PR_IO_PENDING_ERROR, 0);
- return -1;
- }
-
- count = 0;
- while (amount > 0) {
- PR_LOG(_pr_io_lm, PR_LOG_MAX,
- ("send: fd=%p osfd=%" PR_PRIdOSFD " buf=%p amount=%d",
- fd, fd->secret->md.osfd, buf, amount));
- temp = _PR_MD_SEND(fd, buf, amount, flags, timeout);
- if (temp < 0) {
- count = -1;
- break;
- }
-
- count += temp;
- if (fd->secret->nonblocking) {
- break;
- }
- buf = (const void*) ((const char*)buf + temp);
-
- amount -= temp;
- }
- PR_LOG(_pr_io_lm, PR_LOG_MAX, ("send -> %d", count));
- return count;
-}
-
-static PRInt32 PR_CALLBACK SocketWrite(PRFileDesc *fd, const void *buf, PRInt32 amount)
-{
- return SocketSend(fd, buf, amount, 0, PR_INTERVAL_NO_TIMEOUT);
-}
-
-static PRStatus PR_CALLBACK SocketClose(PRFileDesc *fd)
-{
- if (!fd || !fd->secret
- || (fd->secret->state != _PR_FILEDESC_OPEN
- && fd->secret->state != _PR_FILEDESC_CLOSED)) {
- PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
- return PR_FAILURE;
- }
-
- if (fd->secret->state == _PR_FILEDESC_OPEN) {
- if (_PR_MD_CLOSE_SOCKET(fd->secret->md.osfd) < 0) {
- return PR_FAILURE;
- }
- fd->secret->state = _PR_FILEDESC_CLOSED;
- }
-
-#ifdef _PR_HAVE_PEEK_BUFFER
- if (fd->secret->peekBuffer) {
- PR_ASSERT(fd->secret->peekBufSize > 0);
- PR_DELETE(fd->secret->peekBuffer);
- fd->secret->peekBufSize = 0;
- fd->secret->peekBytes = 0;
- }
-#endif
-
- PR_FreeFileDesc(fd);
- return PR_SUCCESS;
-}
-
-static PRInt32 PR_CALLBACK SocketAvailable(PRFileDesc *fd)
-{
- PRInt32 rv;
-#ifdef _PR_HAVE_PEEK_BUFFER
- if (fd->secret->peekBytes != 0) {
- return fd->secret->peekBytes;
- }
-#endif
- rv = _PR_MD_SOCKETAVAILABLE(fd);
- return rv;
-}
-
-static PRInt64 PR_CALLBACK SocketAvailable64(PRFileDesc *fd)
-{
- PRInt64 rv;
-#ifdef _PR_HAVE_PEEK_BUFFER
- if (fd->secret->peekBytes != 0) {
- LL_I2L(rv, fd->secret->peekBytes);
- return rv;
- }
-#endif
- LL_I2L(rv, _PR_MD_SOCKETAVAILABLE(fd));
- return rv;
-}
-
-static PRStatus PR_CALLBACK SocketSync(PRFileDesc *fd)
-{
- return PR_SUCCESS;
-}
-
-static PRInt32 PR_CALLBACK SocketSendTo(
- PRFileDesc *fd, const void *buf, PRInt32 amount,
- PRIntn flags, const PRNetAddr *addr, PRIntervalTime timeout)
-{
- PRInt32 temp, count;
- const PRNetAddr *addrp = addr;
-#if defined(_PR_INET6)
- PRNetAddr addrCopy;
-#endif
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- return -1;
- }
- if (_PR_IO_PENDING(me)) {
- PR_SetError(PR_IO_PENDING_ERROR, 0);
- return -1;
- }
-
- PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
-#if defined(_PR_INET6)
- if (addr->raw.family == PR_AF_INET6) {
- addrCopy = *addr;
- addrCopy.raw.family = AF_INET6;
- addrp = &addrCopy;
- }
-#endif
-
- count = 0;
- while (amount > 0) {
- temp = _PR_MD_SENDTO(fd, buf, amount, flags,
- addrp, PR_NETADDR_SIZE(addr), timeout);
- if (temp < 0) {
- count = -1;
- break;
- }
- count += temp;
- if (fd->secret->nonblocking) {
- break;
- }
- buf = (const void*) ((const char*)buf + temp);
- amount -= temp;
- }
- return count;
-}
-
-static PRInt32 PR_CALLBACK SocketRecvFrom(PRFileDesc *fd, void *buf, PRInt32 amount,
-PRIntn flags, PRNetAddr *addr, PRIntervalTime timeout)
-{
- PRInt32 rv;
- PRUint32 al;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- return -1;
- }
- if (_PR_IO_PENDING(me)) {
- PR_SetError(PR_IO_PENDING_ERROR, 0);
- return -1;
- }
-
- al = sizeof(PRNetAddr);
- rv = _PR_MD_RECVFROM(fd, buf, amount, flags, addr, &al, timeout);
-#ifdef _PR_INET6
- if (addr && (AF_INET6 == addr->raw.family))
- addr->raw.family = PR_AF_INET6;
-#endif
- return rv;
-}
-
-static PRInt32 PR_CALLBACK SocketAcceptRead(PRFileDesc *sd, PRFileDesc **nd,
-PRNetAddr **raddr, void *buf, PRInt32 amount,
-PRIntervalTime timeout)
-{
- PRInt32 rv;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- return -1;
- }
- if (_PR_IO_PENDING(me)) {
- PR_SetError(PR_IO_PENDING_ERROR, 0);
- return -1;
- }
- /* The socket must be in blocking mode. */
- if (sd->secret->nonblocking) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return -1;
- }
- *nd = NULL;
-
-#if defined(WINNT)
- {
- PROsfd newSock;
- PRNetAddr *raddrCopy;
-
- if (raddr == NULL) {
- raddr = &raddrCopy;
- }
- rv = _PR_MD_ACCEPT_READ(sd, &newSock, raddr, buf, amount, timeout);
- if (rv < 0) {
- rv = -1;
- } else {
- /* Successfully accepted and read; create the new PRFileDesc */
- *nd = PR_AllocFileDesc(newSock, PR_GetTCPMethods());
- if (*nd == 0) {
- _PR_MD_CLOSE_SOCKET(newSock);
- /* PR_AllocFileDesc() has invoked PR_SetError(). */
- rv = -1;
- } else {
- (*nd)->secret->md.io_model_committed = PR_TRUE;
- (*nd)->secret->md.accepted_socket = PR_TRUE;
- memcpy(&(*nd)->secret->md.peer_addr, *raddr,
- PR_NETADDR_SIZE(*raddr));
-#ifdef _PR_INET6
- if (AF_INET6 == *raddr->raw.family)
- *raddr->raw.family = PR_AF_INET6;
-#endif
- }
- }
- }
-#else
- rv = PR_EmulateAcceptRead(sd, nd, raddr, buf, amount, timeout);
-#endif
- return rv;
-}
-
-#ifdef WINNT
-PR_IMPLEMENT(PRInt32) PR_NTFast_AcceptRead(PRFileDesc *sd, PRFileDesc **nd,
-PRNetAddr **raddr, void *buf, PRInt32 amount,
-PRIntervalTime timeout)
-{
- PRInt32 rv;
- PROsfd newSock;
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRNetAddr *raddrCopy;
-
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- return -1;
- }
- if (_PR_IO_PENDING(me)) {
- PR_SetError(PR_IO_PENDING_ERROR, 0);
- return -1;
- }
- *nd = NULL;
-
- if (raddr == NULL) {
- raddr = &raddrCopy;
- }
- rv = _PR_MD_FAST_ACCEPT_READ(sd, &newSock, raddr, buf, amount,
- timeout, PR_TRUE, NULL, NULL);
- if (rv < 0) {
- rv = -1;
- } else {
- /* Successfully accepted and read; create the new PRFileDesc */
- *nd = PR_AllocFileDesc(newSock, PR_GetTCPMethods());
- if (*nd == 0) {
- _PR_MD_CLOSE_SOCKET(newSock);
- /* PR_AllocFileDesc() has invoked PR_SetError(). */
- rv = -1;
- } else {
- (*nd)->secret->md.io_model_committed = PR_TRUE;
- (*nd)->secret->md.accepted_socket = PR_TRUE;
- memcpy(&(*nd)->secret->md.peer_addr, *raddr,
- PR_NETADDR_SIZE(*raddr));
-#ifdef _PR_INET6
- if (AF_INET6 == *raddr->raw.family)
- *raddr->raw.family = PR_AF_INET6;
-#endif
-#ifdef _PR_NEED_SECRET_AF
- (*nd)->secret->af = sd->secret->af;
-#endif
- }
- }
- return rv;
-}
-
-PR_IMPLEMENT(PRInt32) PR_NTFast_AcceptRead_WithTimeoutCallback(
-PRFileDesc *sd, PRFileDesc **nd,
-PRNetAddr **raddr, void *buf, PRInt32 amount,
-PRIntervalTime timeout,
-_PR_AcceptTimeoutCallback callback,
-void *callbackArg)
-{
- PRInt32 rv;
- PROsfd newSock;
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRNetAddr *raddrCopy;
-
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- return -1;
- }
- if (_PR_IO_PENDING(me)) {
- PR_SetError(PR_IO_PENDING_ERROR, 0);
- return -1;
- }
- *nd = NULL;
-
- if (raddr == NULL) {
- raddr = &raddrCopy;
- }
- rv = _PR_MD_FAST_ACCEPT_READ(sd, &newSock, raddr, buf, amount,
- timeout, PR_TRUE, callback, callbackArg);
- if (rv < 0) {
- rv = -1;
- } else {
- /* Successfully accepted and read; create the new PRFileDesc */
- *nd = PR_AllocFileDesc(newSock, PR_GetTCPMethods());
- if (*nd == 0) {
- _PR_MD_CLOSE_SOCKET(newSock);
- /* PR_AllocFileDesc() has invoked PR_SetError(). */
- rv = -1;
- } else {
- (*nd)->secret->md.io_model_committed = PR_TRUE;
- (*nd)->secret->md.accepted_socket = PR_TRUE;
- memcpy(&(*nd)->secret->md.peer_addr, *raddr,
- PR_NETADDR_SIZE(*raddr));
-#ifdef _PR_INET6
- if (AF_INET6 == *raddr->raw.family)
- *raddr->raw.family = PR_AF_INET6;
-#endif
-#ifdef _PR_NEED_SECRET_AF
- (*nd)->secret->af = sd->secret->af;
-#endif
- }
- }
- return rv;
-}
-#endif /* WINNT */
-
-#ifdef WINNT
-PR_IMPLEMENT(void)
-PR_NTFast_UpdateAcceptContext(PRFileDesc *socket, PRFileDesc *acceptSocket)
-{
- _PR_MD_UPDATE_ACCEPT_CONTEXT(
- socket->secret->md.osfd, acceptSocket->secret->md.osfd);
-}
-#endif /* WINNT */
-
-static PRInt32 PR_CALLBACK SocketSendFile(
- PRFileDesc *sd, PRSendFileData *sfd,
- PRTransmitFileFlags flags, PRIntervalTime timeout)
-{
- PRInt32 rv;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- return -1;
- }
- if (_PR_IO_PENDING(me)) {
- PR_SetError(PR_IO_PENDING_ERROR, 0);
- return -1;
- }
- /* The socket must be in blocking mode. */
- if (sd->secret->nonblocking) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return -1;
- }
-#if defined(WINNT)
- rv = _PR_MD_SENDFILE(sd, sfd, flags, timeout);
- if ((rv >= 0) && (flags == PR_TRANSMITFILE_CLOSE_SOCKET)) {
- /*
- * This should be kept the same as SocketClose, except
- * that _PR_MD_CLOSE_SOCKET(sd->secret->md.osfd) should
- * not be called because the socket will be recycled.
- */
- PR_FreeFileDesc(sd);
- }
-#else
- rv = PR_EmulateSendFile(sd, sfd, flags, timeout);
-#endif /* WINNT */
-
- return rv;
-}
-
-static PRInt32 PR_CALLBACK SocketTransmitFile(PRFileDesc *sd, PRFileDesc *fd,
-const void *headers, PRInt32 hlen, PRTransmitFileFlags flags,
-PRIntervalTime timeout)
-{
- PRSendFileData sfd;
-
- sfd.fd = fd;
- sfd.file_offset = 0;
- sfd.file_nbytes = 0;
- sfd.header = headers;
- sfd.hlen = hlen;
- sfd.trailer = NULL;
- sfd.tlen = 0;
-
- return(SocketSendFile(sd, &sfd, flags, timeout));
-}
-
-static PRStatus PR_CALLBACK SocketGetName(PRFileDesc *fd, PRNetAddr *addr)
-{
- PRInt32 result;
- PRUint32 addrlen;
-
- addrlen = sizeof(PRNetAddr);
- result = _PR_MD_GETSOCKNAME(fd, addr, &addrlen);
- if (result < 0) {
- return PR_FAILURE;
- }
-#ifdef _PR_INET6
- if (AF_INET6 == addr->raw.family)
- addr->raw.family = PR_AF_INET6;
-#endif
- PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
- PR_ASSERT(IsValidNetAddrLen(addr, addrlen) == PR_TRUE);
- return PR_SUCCESS;
-}
-
-static PRStatus PR_CALLBACK SocketGetPeerName(PRFileDesc *fd, PRNetAddr *addr)
-{
- PRInt32 result;
- PRUint32 addrlen;
-
- addrlen = sizeof(PRNetAddr);
- result = _PR_MD_GETPEERNAME(fd, addr, &addrlen);
- if (result < 0) {
- return PR_FAILURE;
- }
-#ifdef _PR_INET6
- if (AF_INET6 == addr->raw.family)
- addr->raw.family = PR_AF_INET6;
-#endif
- PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
- PR_ASSERT(IsValidNetAddrLen(addr, addrlen) == PR_TRUE);
- return PR_SUCCESS;
-}
-
-static PRInt16 PR_CALLBACK SocketPoll(
- PRFileDesc *fd, PRInt16 in_flags, PRInt16 *out_flags)
-{
- *out_flags = 0;
- return in_flags;
-} /* SocketPoll */
-
-static PRIOMethods tcpMethods = {
- PR_DESC_SOCKET_TCP,
- SocketClose,
- SocketRead,
- SocketWrite,
- SocketAvailable,
- SocketAvailable64,
- SocketSync,
- (PRSeekFN)_PR_InvalidInt,
- (PRSeek64FN)_PR_InvalidInt64,
- (PRFileInfoFN)_PR_InvalidStatus,
- (PRFileInfo64FN)_PR_InvalidStatus,
- SocketWritev,
- SocketConnect,
- SocketAccept,
- SocketBind,
- SocketListen,
- SocketShutdown,
- SocketRecv,
- SocketSend,
- (PRRecvfromFN)_PR_InvalidInt,
- (PRSendtoFN)_PR_InvalidInt,
- SocketPoll,
- SocketAcceptRead,
- SocketTransmitFile,
- SocketGetName,
- SocketGetPeerName,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- _PR_SocketGetSocketOption,
- _PR_SocketSetSocketOption,
- SocketSendFile,
- SocketConnectContinue,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt
-};
-
-static PRIOMethods udpMethods = {
- PR_DESC_SOCKET_UDP,
- SocketClose,
- SocketRead,
- SocketWrite,
- SocketAvailable,
- SocketAvailable64,
- SocketSync,
- (PRSeekFN)_PR_InvalidInt,
- (PRSeek64FN)_PR_InvalidInt64,
- (PRFileInfoFN)_PR_InvalidStatus,
- (PRFileInfo64FN)_PR_InvalidStatus,
- SocketWritev,
- SocketConnect,
- (PRAcceptFN)_PR_InvalidDesc,
- SocketBind,
- SocketListen,
- SocketShutdown,
- SocketRecv,
- SocketSend,
- SocketRecvFrom,
- SocketSendTo,
- SocketPoll,
- (PRAcceptreadFN)_PR_InvalidInt,
- (PRTransmitfileFN)_PR_InvalidInt,
- SocketGetName,
- SocketGetPeerName,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- _PR_SocketGetSocketOption,
- _PR_SocketSetSocketOption,
- (PRSendfileFN)_PR_InvalidInt,
- (PRConnectcontinueFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt
-};
-
-
-static PRIOMethods socketpollfdMethods = {
- (PRDescType) 0,
- (PRCloseFN)_PR_InvalidStatus,
- (PRReadFN)_PR_InvalidInt,
- (PRWriteFN)_PR_InvalidInt,
- (PRAvailableFN)_PR_InvalidInt,
- (PRAvailable64FN)_PR_InvalidInt64,
- (PRFsyncFN)_PR_InvalidStatus,
- (PRSeekFN)_PR_InvalidInt,
- (PRSeek64FN)_PR_InvalidInt64,
- (PRFileInfoFN)_PR_InvalidStatus,
- (PRFileInfo64FN)_PR_InvalidStatus,
- (PRWritevFN)_PR_InvalidInt,
- (PRConnectFN)_PR_InvalidStatus,
- (PRAcceptFN)_PR_InvalidDesc,
- (PRBindFN)_PR_InvalidStatus,
- (PRListenFN)_PR_InvalidStatus,
- (PRShutdownFN)_PR_InvalidStatus,
- (PRRecvFN)_PR_InvalidInt,
- (PRSendFN)_PR_InvalidInt,
- (PRRecvfromFN)_PR_InvalidInt,
- (PRSendtoFN)_PR_InvalidInt,
- SocketPoll,
- (PRAcceptreadFN)_PR_InvalidInt,
- (PRTransmitfileFN)_PR_InvalidInt,
- (PRGetsocknameFN)_PR_InvalidStatus,
- (PRGetpeernameFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRGetsocketoptionFN)_PR_InvalidStatus,
- (PRSetsocketoptionFN)_PR_InvalidStatus,
- (PRSendfileFN)_PR_InvalidInt,
- (PRConnectcontinueFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt
-};
-
-PR_IMPLEMENT(const PRIOMethods*) PR_GetTCPMethods()
-{
- return &tcpMethods;
-}
-
-PR_IMPLEMENT(const PRIOMethods*) PR_GetUDPMethods()
-{
- return &udpMethods;
-}
-
-static const PRIOMethods* PR_GetSocketPollFdMethods()
-{
- return &socketpollfdMethods;
-} /* PR_GetSocketPollFdMethods */
-
-#if !defined(_PR_INET6) || defined(_PR_INET6_PROBE)
-PR_EXTERN(PRStatus) _pr_push_ipv6toipv4_layer(PRFileDesc *fd);
-
-#if defined(_PR_INET6_PROBE)
-
-extern PRBool _pr_ipv6_is_present(void);
-
-PR_IMPLEMENT(PRBool) _pr_test_ipv6_socket()
-{
- PROsfd osfd;
-
- osfd = _PR_MD_SOCKET(AF_INET6, SOCK_STREAM, 0);
- if (osfd != -1) {
- _PR_MD_CLOSE_SOCKET(osfd);
- return PR_TRUE;
- }
- return PR_FALSE;
-}
-#endif /* _PR_INET6_PROBE */
-
-#endif
-
-PR_IMPLEMENT(PRFileDesc*) PR_Socket(PRInt32 domain, PRInt32 type, PRInt32 proto)
-{
- PROsfd osfd;
- PRFileDesc *fd;
- PRInt32 tmp_domain = domain;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- if (PR_AF_INET != domain
- && PR_AF_INET6 != domain
-#if defined(XP_UNIX) || defined(XP_OS2)
- && PR_AF_LOCAL != domain
-#endif
- ) {
- PR_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR, 0);
- return NULL;
- }
-
-#if defined(_PR_INET6_PROBE)
- if (PR_AF_INET6 == domain)
- domain = _pr_ipv6_is_present() ? AF_INET6 : AF_INET;
-#elif defined(_PR_INET6)
- if (PR_AF_INET6 == domain)
- domain = AF_INET6;
-#else
- if (PR_AF_INET6 == domain)
- domain = AF_INET;
-#endif /* _PR_INET6 */
- osfd = _PR_MD_SOCKET(domain, type, proto);
- if (osfd == -1) {
- return 0;
- }
- if (type == SOCK_STREAM)
- fd = PR_AllocFileDesc(osfd, PR_GetTCPMethods());
- else
- fd = PR_AllocFileDesc(osfd, PR_GetUDPMethods());
- /*
- * Make the sockets non-blocking
- */
- if (fd != NULL) {
- _PR_MD_MAKE_NONBLOCK(fd);
- _PR_MD_INIT_FD_INHERITABLE(fd, PR_FALSE);
-#ifdef _PR_NEED_SECRET_AF
- fd->secret->af = domain;
-#endif
-#if defined(_PR_INET6_PROBE) || !defined(_PR_INET6)
- /*
- * For platforms with no support for IPv6
- * create layered socket for IPv4-mapped IPv6 addresses
- */
- if (PR_AF_INET6 == tmp_domain && PR_AF_INET == domain) {
- if (PR_FAILURE == _pr_push_ipv6toipv4_layer(fd)) {
- PR_Close(fd);
- fd = NULL;
- }
- }
-#endif
- } else
- _PR_MD_CLOSE_SOCKET(osfd);
-
- return fd;
-}
-
-PR_IMPLEMENT(PRFileDesc *) PR_NewTCPSocket(void)
-{
- PRInt32 domain = AF_INET;
-
- return PR_Socket(domain, SOCK_STREAM, 0);
-}
-
-PR_IMPLEMENT(PRFileDesc*) PR_NewUDPSocket(void)
-{
- PRInt32 domain = AF_INET;
-
- return PR_Socket(domain, SOCK_DGRAM, 0);
-}
-
-PR_IMPLEMENT(PRFileDesc *) PR_OpenTCPSocket(PRIntn af)
-{
- return PR_Socket(af, SOCK_STREAM, 0);
-}
-
-PR_IMPLEMENT(PRFileDesc*) PR_OpenUDPSocket(PRIntn af)
-{
- return PR_Socket(af, SOCK_DGRAM, 0);
-}
-
-PR_IMPLEMENT(PRStatus) PR_NewTCPSocketPair(PRFileDesc *f[])
-{
-#ifdef XP_UNIX
- PRInt32 rv, osfd[2];
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- rv = _PR_MD_SOCKETPAIR(AF_UNIX, SOCK_STREAM, 0, osfd);
- if (rv == -1) {
- return PR_FAILURE;
- }
-
- f[0] = PR_AllocFileDesc(osfd[0], PR_GetTCPMethods());
- if (!f[0]) {
- _PR_MD_CLOSE_SOCKET(osfd[0]);
- _PR_MD_CLOSE_SOCKET(osfd[1]);
- /* PR_AllocFileDesc() has invoked PR_SetError(). */
- return PR_FAILURE;
- }
- f[1] = PR_AllocFileDesc(osfd[1], PR_GetTCPMethods());
- if (!f[1]) {
- PR_Close(f[0]);
- _PR_MD_CLOSE_SOCKET(osfd[1]);
- /* PR_AllocFileDesc() has invoked PR_SetError(). */
- return PR_FAILURE;
- }
- _PR_MD_MAKE_NONBLOCK(f[0]);
- _PR_MD_INIT_FD_INHERITABLE(f[0], PR_FALSE);
- _PR_MD_MAKE_NONBLOCK(f[1]);
- _PR_MD_INIT_FD_INHERITABLE(f[1], PR_FALSE);
- return PR_SUCCESS;
-#elif defined(WINNT)
- /*
- * A socket pair is often used for interprocess communication,
- * so we need to make sure neither socket is associated with
- * the I/O completion port; otherwise it can't be used by a
- * child process.
- *
- * The default implementation below cannot be used for NT
- * because PR_Accept would have associated the I/O completion
- * port with the listening and accepted sockets.
- */
- SOCKET listenSock;
- SOCKET osfd[2];
- struct sockaddr_in selfAddr, peerAddr;
- int addrLen;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- osfd[0] = osfd[1] = INVALID_SOCKET;
- listenSock = socket(AF_INET, SOCK_STREAM, 0);
- if (listenSock == INVALID_SOCKET) {
- goto failed;
- }
- selfAddr.sin_family = AF_INET;
- selfAddr.sin_port = 0;
- selfAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); /* BugZilla: 35408 */
- addrLen = sizeof(selfAddr);
- if (bind(listenSock, (struct sockaddr *) &selfAddr,
- addrLen) == SOCKET_ERROR) {
- goto failed;
- }
- if (getsockname(listenSock, (struct sockaddr *) &selfAddr,
- &addrLen) == SOCKET_ERROR) {
- goto failed;
- }
- if (listen(listenSock, 5) == SOCKET_ERROR) {
- goto failed;
- }
- osfd[0] = socket(AF_INET, SOCK_STREAM, 0);
- if (osfd[0] == INVALID_SOCKET) {
- goto failed;
- }
- selfAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
-
- /*
- * Only a thread is used to do the connect and accept.
- * I am relying on the fact that connect returns
- * successfully as soon as the connect request is put
- * into the listen queue (but before accept is called).
- * This is the behavior of the BSD socket code. If
- * connect does not return until accept is called, we
- * will need to create another thread to call connect.
- */
- if (connect(osfd[0], (struct sockaddr *) &selfAddr,
- addrLen) == SOCKET_ERROR) {
- goto failed;
- }
- /*
- * A malicious local process may connect to the listening
- * socket, so we need to verify that the accepted connection
- * is made from our own socket osfd[0].
- */
- if (getsockname(osfd[0], (struct sockaddr *) &selfAddr,
- &addrLen) == SOCKET_ERROR) {
- goto failed;
- }
- osfd[1] = accept(listenSock, (struct sockaddr *) &peerAddr, &addrLen);
- if (osfd[1] == INVALID_SOCKET) {
- goto failed;
- }
- if (peerAddr.sin_port != selfAddr.sin_port) {
- /* the connection we accepted is not from osfd[0] */
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
- goto failed;
- }
- closesocket(listenSock);
-
- f[0] = PR_AllocFileDesc(osfd[0], PR_GetTCPMethods());
- if (!f[0]) {
- closesocket(osfd[0]);
- closesocket(osfd[1]);
- /* PR_AllocFileDesc() has invoked PR_SetError(). */
- return PR_FAILURE;
- }
- f[1] = PR_AllocFileDesc(osfd[1], PR_GetTCPMethods());
- if (!f[1]) {
- PR_Close(f[0]);
- closesocket(osfd[1]);
- /* PR_AllocFileDesc() has invoked PR_SetError(). */
- return PR_FAILURE;
- }
- _PR_MD_INIT_FD_INHERITABLE(f[0], PR_FALSE);
- _PR_MD_INIT_FD_INHERITABLE(f[1], PR_FALSE);
- return PR_SUCCESS;
-
-failed:
- if (listenSock != INVALID_SOCKET) {
- closesocket(listenSock);
- }
- if (osfd[0] != INVALID_SOCKET) {
- closesocket(osfd[0]);
- }
- if (osfd[1] != INVALID_SOCKET) {
- closesocket(osfd[1]);
- }
- return PR_FAILURE;
-#else /* not Unix or NT */
- /*
- * default implementation
- */
- PRFileDesc *listenSock;
- PRNetAddr selfAddr, peerAddr;
- PRUint16 port;
-
- f[0] = f[1] = NULL;
- listenSock = PR_NewTCPSocket();
- if (listenSock == NULL) {
- goto failed;
- }
- PR_InitializeNetAddr(PR_IpAddrLoopback, 0, &selfAddr); /* BugZilla: 35408 */
- if (PR_Bind(listenSock, &selfAddr) == PR_FAILURE) {
- goto failed;
- }
- if (PR_GetSockName(listenSock, &selfAddr) == PR_FAILURE) {
- goto failed;
- }
- port = ntohs(selfAddr.inet.port);
- if (PR_Listen(listenSock, 5) == PR_FAILURE) {
- goto failed;
- }
- f[0] = PR_NewTCPSocket();
- if (f[0] == NULL) {
- goto failed;
- }
-#ifdef _PR_CONNECT_DOES_NOT_BIND
- /*
- * If connect does not implicitly bind the socket (e.g., on
- * BeOS), we have to bind the socket so that we can get its
- * port with getsockname later.
- */
- PR_InitializeNetAddr(PR_IpAddrLoopback, 0, &selfAddr);
- if (PR_Bind(f[0], &selfAddr) == PR_FAILURE) {
- goto failed;
- }
-#endif
- PR_InitializeNetAddr(PR_IpAddrLoopback, port, &selfAddr);
-
- /*
- * Only a thread is used to do the connect and accept.
- * I am relying on the fact that PR_Connect returns
- * successfully as soon as the connect request is put
- * into the listen queue (but before PR_Accept is called).
- * This is the behavior of the BSD socket code. If
- * connect does not return until accept is called, we
- * will need to create another thread to call connect.
- */
- if (PR_Connect(f[0], &selfAddr, PR_INTERVAL_NO_TIMEOUT)
- == PR_FAILURE) {
- goto failed;
- }
- /*
- * A malicious local process may connect to the listening
- * socket, so we need to verify that the accepted connection
- * is made from our own socket f[0].
- */
- if (PR_GetSockName(f[0], &selfAddr) == PR_FAILURE) {
- goto failed;
- }
- f[1] = PR_Accept(listenSock, &peerAddr, PR_INTERVAL_NO_TIMEOUT);
- if (f[1] == NULL) {
- goto failed;
- }
- if (peerAddr.inet.port != selfAddr.inet.port) {
- /* the connection we accepted is not from f[0] */
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
- goto failed;
- }
- PR_Close(listenSock);
- return PR_SUCCESS;
-
-failed:
- if (listenSock) {
- PR_Close(listenSock);
- }
- if (f[0]) {
- PR_Close(f[0]);
- }
- if (f[1]) {
- PR_Close(f[1]);
- }
- return PR_FAILURE;
-#endif
-}
-
-PR_IMPLEMENT(PROsfd)
-PR_FileDesc2NativeHandle(PRFileDesc *fd)
-{
- if (fd) {
- fd = PR_GetIdentitiesLayer(fd, PR_NSPR_IO_LAYER);
- }
- if (!fd) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return -1;
- }
- return fd->secret->md.osfd;
-}
-
-PR_IMPLEMENT(void)
-PR_ChangeFileDescNativeHandle(PRFileDesc *fd, PROsfd handle)
-{
- if (fd)
- fd->secret->md.osfd = handle;
-}
-
-/*
-** Select compatibility
-**
-*/
-
-PR_IMPLEMENT(void) PR_FD_ZERO(PR_fd_set *set)
-{
- memset(set, 0, sizeof(PR_fd_set));
-}
-
-PR_IMPLEMENT(void) PR_FD_SET(PRFileDesc *fh, PR_fd_set *set)
-{
- PR_ASSERT( set->hsize < PR_MAX_SELECT_DESC );
-
- set->harray[set->hsize++] = fh;
-}
-
-PR_IMPLEMENT(void) PR_FD_CLR(PRFileDesc *fh, PR_fd_set *set)
-{
- PRUint32 index, index2;
-
- for (index = 0; index<set->hsize; index++)
- if (set->harray[index] == fh) {
- for (index2=index; index2 < (set->hsize-1); index2++) {
- set->harray[index2] = set->harray[index2+1];
- }
- set->hsize--;
- break;
- }
-}
-
-PR_IMPLEMENT(PRInt32) PR_FD_ISSET(PRFileDesc *fh, PR_fd_set *set)
-{
- PRUint32 index;
- for (index = 0; index<set->hsize; index++)
- if (set->harray[index] == fh) {
- return 1;
- }
- return 0;
-}
-
-PR_IMPLEMENT(void) PR_FD_NSET(PROsfd fd, PR_fd_set *set)
-{
- PR_ASSERT( set->nsize < PR_MAX_SELECT_DESC );
-
- set->narray[set->nsize++] = fd;
-}
-
-PR_IMPLEMENT(void) PR_FD_NCLR(PROsfd fd, PR_fd_set *set)
-{
- PRUint32 index, index2;
-
- for (index = 0; index<set->nsize; index++)
- if (set->narray[index] == fd) {
- for (index2=index; index2 < (set->nsize-1); index2++) {
- set->narray[index2] = set->narray[index2+1];
- }
- set->nsize--;
- break;
- }
-}
-
-PR_IMPLEMENT(PRInt32) PR_FD_NISSET(PROsfd fd, PR_fd_set *set)
-{
- PRUint32 index;
- for (index = 0; index<set->nsize; index++)
- if (set->narray[index] == fd) {
- return 1;
- }
- return 0;
-}
-
-
-#if !defined(NEED_SELECT)
-#include "obsolete/probslet.h"
-
-#define PD_INCR 20
-
-static PRPollDesc *_pr_setfd(
- PR_fd_set *set, PRInt16 flags, PRPollDesc *polldesc)
-{
- PRUintn fsidx, pdidx;
- PRPollDesc *poll = polldesc;
-
- if (NULL == set) return poll;
-
- /* First set the pr file handle osfds */
- for (fsidx = 0; fsidx < set->hsize; fsidx++)
- {
- for (pdidx = 0; 1; pdidx++)
- {
- if ((PRFileDesc*)-1 == poll[pdidx].fd)
- {
- /* our vector is full - extend and condition it */
- poll = (PRPollDesc*)PR_Realloc(
- poll, (pdidx + 1 + PD_INCR) * sizeof(PRPollDesc));
- if (NULL == poll) goto out_of_memory;
- memset(
- poll + pdidx * sizeof(PRPollDesc),
- 0, PD_INCR * sizeof(PRPollDesc));
- poll[pdidx + PD_INCR].fd = (PRFileDesc*)-1;
- }
- if ((NULL == poll[pdidx].fd)
- || (poll[pdidx].fd == set->harray[fsidx]))
- {
- /* PR_ASSERT(0 == (poll[pdidx].in_flags & flags)); */
- /* either empty or prevously defined */
- poll[pdidx].fd = set->harray[fsidx]; /* possibly redundant */
- poll[pdidx].in_flags |= flags; /* possibly redundant */
- break;
- }
- }
- }
-
-#if 0
- /* Second set the native osfds */
- for (fsidx = 0; fsidx < set->nsize; fsidx++)
- {
- for (pdidx = 0; ((PRFileDesc*)-1 != poll[pdidx].fd); pdidx++)
- {
- if ((PRFileDesc*)-1 == poll[pdidx].fd)
- {
- /* our vector is full - extend and condition it */
- poll = PR_Realloc(
- poll, (pdidx + PD_INCR) * sizeof(PRPollDesc));
- if (NULL == poll) goto out_of_memory;
- memset(
- poll + pdidx * sizeof(PRPollDesc),
- 0, PD_INCR * sizeof(PRPollDesc));
- poll[(pdidx + PD_INCR)].fd = (PRFileDesc*)-1;
- }
- if ((NULL == poll[pdidx].fd)
- || (poll[pdidx].fd == set->narray[fsidx]))
- {
- /* either empty or prevously defined */
- poll[pdidx].fd = set->narray[fsidx];
- PR_ASSERT(0 == (poll[pdidx].in_flags & flags));
- poll[pdidx].in_flags |= flags;
- break;
- }
- }
- }
-#endif /* 0 */
-
- return poll;
-
-out_of_memory:
- if (NULL != polldesc) PR_DELETE(polldesc);
- return NULL;
-} /* _pr_setfd */
-
-#endif /* !defined(NEED_SELECT) */
-
-PR_IMPLEMENT(PRInt32) PR_Select(
- PRInt32 unused, PR_fd_set *pr_rd, PR_fd_set *pr_wr,
- PR_fd_set *pr_ex, PRIntervalTime timeout)
-{
-
-#if !defined(NEED_SELECT)
- PRInt32 npds = 0;
- /*
- ** Find out how many fds are represented in the three lists.
- ** Then allocate a polling descriptor for the logical union
- ** (there can't be any overlapping) and call PR_Poll().
- */
-
- PRPollDesc *copy, *poll;
-
- static PRBool warning = PR_TRUE;
- if (warning) warning = _PR_Obsolete( "PR_Select()", "PR_Poll()");
-
- /* try to get an initial guesss at how much space we need */
- npds = 0;
- if ((NULL != pr_rd) && ((pr_rd->hsize + pr_rd->nsize - npds) > 0))
- npds = pr_rd->hsize + pr_rd->nsize;
- if ((NULL != pr_wr) && ((pr_wr->hsize + pr_wr->nsize - npds) > 0))
- npds = pr_wr->hsize + pr_wr->nsize;
- if ((NULL != pr_ex) && ((pr_ex->hsize + pr_ex->nsize - npds) > 0))
- npds = pr_ex->hsize + pr_ex->nsize;
-
- if (0 == npds)
- {
- PR_Sleep(timeout);
- return 0;
- }
-
- copy = poll = (PRPollDesc*)PR_Calloc(npds + PD_INCR, sizeof(PRPollDesc));
- if (NULL == poll) goto out_of_memory;
- poll[npds + PD_INCR - 1].fd = (PRFileDesc*)-1;
-
- poll = _pr_setfd(pr_rd, PR_POLL_READ, poll);
- if (NULL == poll) goto out_of_memory;
- poll = _pr_setfd(pr_wr, PR_POLL_WRITE, poll);
- if (NULL == poll) goto out_of_memory;
- poll = _pr_setfd(pr_ex, PR_POLL_EXCEPT, poll);
- if (NULL == poll) goto out_of_memory;
- unused = 0;
- while (NULL != poll[unused].fd && (PRFileDesc*)-1 != poll[unused].fd)
- {
- ++unused;
- }
-
- PR_ASSERT(unused > 0);
- npds = PR_Poll(poll, unused, timeout);
-
- if (npds > 0)
- {
- /* Copy the results back into the fd sets */
- if (NULL != pr_rd) pr_rd->nsize = pr_rd->hsize = 0;
- if (NULL != pr_wr) pr_wr->nsize = pr_wr->hsize = 0;
- if (NULL != pr_ex) pr_ex->nsize = pr_ex->hsize = 0;
- for (copy = &poll[unused - 1]; copy >= poll; --copy)
- {
- if (copy->out_flags & PR_POLL_NVAL)
- {
- PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
- npds = -1;
- break;
- }
- if (copy->out_flags & PR_POLL_READ)
- if (NULL != pr_rd) pr_rd->harray[pr_rd->hsize++] = copy->fd;
- if (copy->out_flags & PR_POLL_WRITE)
- if (NULL != pr_wr) pr_wr->harray[pr_wr->hsize++] = copy->fd;
- if (copy->out_flags & PR_POLL_EXCEPT)
- if (NULL != pr_ex) pr_ex->harray[pr_ex->hsize++] = copy->fd;
- }
- }
- PR_DELETE(poll);
-
- return npds;
-out_of_memory:
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return -1;
-
-#endif /* !defined(NEED_SELECT) */
-
-}
diff --git a/nspr/pr/src/io/prstdio.c b/nspr/pr/src/io/prstdio.c
deleted file mode 100644
index 74b85d9..0000000
--- a/nspr/pr/src/io/prstdio.c
+++ /dev/null
@@ -1,74 +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/. */
-
-#include "primpl.h"
-
-#include <string.h>
-
-/*
-** fprintf to a PRFileDesc
-*/
-PR_IMPLEMENT(PRUint32) PR_fprintf(PRFileDesc* fd, const char *fmt, ...)
-{
- va_list ap;
- PRUint32 rv;
-
- va_start(ap, fmt);
- rv = PR_vfprintf(fd, fmt, ap);
- va_end(ap);
- return rv;
-}
-
-PR_IMPLEMENT(PRUint32) PR_vfprintf(PRFileDesc* fd, const char *fmt, va_list ap)
-{
- /* XXX this could be better */
- PRUint32 rv, len;
- char* msg = PR_vsmprintf(fmt, ap);
- if (NULL == msg) {
- return -1;
- }
- len = strlen(msg);
-#ifdef XP_OS2
- /*
- * OS/2 really needs a \r for every \n.
- * In the future we should try to use scatter-gather instead of a
- * succession of PR_Write.
- */
- if (isatty(PR_FileDesc2NativeHandle(fd))) {
- PRUint32 last = 0, idx;
- PRInt32 tmp;
- rv = 0;
- for (idx = 0; idx < len+1; idx++) {
- if ((idx - last > 0) && (('\n' == msg[idx]) || (idx == len))) {
- tmp = PR_Write(fd, msg + last, idx - last);
- if (tmp >= 0) {
- rv += tmp;
- }
- last = idx;
- }
- /*
- * if current character is \n, and
- * previous character isn't \r, and
- * next character isn't \r
- */
- if (('\n' == msg[idx]) &&
- ((0 == idx) || ('\r' != msg[idx-1])) &&
- ('\r' != msg[idx+1])) {
- /* add extra \r */
- tmp = PR_Write(fd, "\r", 1);
- if (tmp >= 0) {
- rv += tmp;
- }
- }
- }
- } else {
- rv = PR_Write(fd, msg, len);
- }
-#else
- rv = PR_Write(fd, msg, len);
-#endif
- PR_DELETE(msg);
- return rv;
-}
diff --git a/nspr/pr/src/linking/prlink.c b/nspr/pr/src/linking/prlink.c
deleted file mode 100644
index 4715460..0000000
--- a/nspr/pr/src/linking/prlink.c
+++ /dev/null
@@ -1,1608 +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/. */
-
-#include "primpl.h"
-
-#include <string.h>
-
-#ifdef XP_BEOS
-#include <image.h>
-#endif
-
-#if defined(XP_MACOSX) && defined(USE_MACH_DYLD)
-#include <Carbon/Carbon.h>
-#include <CoreFoundation/CoreFoundation.h>
-#endif
-
-#ifdef XP_UNIX
-#ifdef USE_DLFCN
-#include <dlfcn.h>
-/* Define these on systems that don't have them. */
-#ifndef RTLD_NOW
-#define RTLD_NOW 0
-#endif
-#ifndef RTLD_LAZY
-#define RTLD_LAZY RTLD_NOW
-#endif
-#ifndef RTLD_GLOBAL
-#define RTLD_GLOBAL 0
-#endif
-#ifndef RTLD_LOCAL
-#define RTLD_LOCAL 0
-#endif
-#ifdef AIX
-#include <sys/ldr.h>
-#ifndef L_IGNOREUNLOAD /* AIX 4.3.3 does not have L_IGNOREUNLOAD. */
-#define L_IGNOREUNLOAD 0x10000000
-#endif
-#endif
-#ifdef OSF1
-#include <loader.h>
-#include <rld_interface.h>
-#endif
-#elif defined(USE_HPSHL)
-#include <dl.h>
-#elif defined(USE_MACH_DYLD)
-#include <mach-o/dyld.h>
-#endif
-#endif /* XP_UNIX */
-
-#define _PR_DEFAULT_LD_FLAGS PR_LD_LAZY
-
-/*
- * On these platforms, symbols have a leading '_'.
- */
-#if (defined(DARWIN) && defined(USE_MACH_DYLD)) \
- || defined(XP_OS2) \
- || ((defined(OPENBSD) || defined(NETBSD)) && !defined(__ELF__))
-#define NEED_LEADING_UNDERSCORE
-#endif
-
-#define PR_LD_PATHW 0x8000 /* for PR_LibSpec_PathnameU */
-
-/************************************************************************/
-
-struct PRLibrary {
- char* name; /* Our own copy of the name string */
- PRLibrary* next;
- int refCount;
- const PRStaticLinkTable* staticTable;
-
-#ifdef XP_PC
-#ifdef XP_OS2
- HMODULE dlh;
-#else
- HINSTANCE dlh;
-#endif
-#endif
-
-#if defined(XP_MACOSX) && defined(USE_MACH_DYLD)
- CFragConnectionID connection;
- CFBundleRef bundle;
- Ptr main;
- CFMutableDictionaryRef wrappers;
- const struct mach_header* image;
-#endif
-
-#ifdef XP_UNIX
-#if defined(USE_HPSHL)
- shl_t dlh;
-#elif defined(USE_MACH_DYLD)
- NSModule dlh;
-#else
- void* dlh;
-#endif
-#endif
-
-#ifdef XP_BEOS
- void* dlh;
- void* stub_dlh;
-#endif
-};
-
-static PRLibrary *pr_loadmap;
-static PRLibrary *pr_exe_loadmap;
-static PRMonitor *pr_linker_lock;
-static char* _pr_currentLibPath = NULL;
-
-static PRLibrary *pr_LoadLibraryByPathname(const char *name, PRIntn flags);
-
-/************************************************************************/
-
-#if !defined(USE_DLFCN) && !defined(HAVE_STRERROR)
-#define ERR_STR_BUF_LENGTH 20
-#endif
-
-static void DLLErrorInternal(PRIntn oserr)
-/*
-** This whole function, and most of the code in this file, are run
-** with a big hairy lock wrapped around it. Not the best of situations,
-** but will eventually come up with the right answer.
-*/
-{
- const char *error = NULL;
-#ifdef USE_DLFCN
- error = dlerror(); /* $$$ That'll be wrong some of the time - AOF */
-#elif defined(HAVE_STRERROR)
- error = strerror(oserr); /* this should be okay */
-#else
- char errStrBuf[ERR_STR_BUF_LENGTH];
- PR_snprintf(errStrBuf, sizeof(errStrBuf), "error %d", oserr);
- error = errStrBuf;
-#endif
- if (NULL != error)
- PR_SetErrorText(strlen(error), error);
-} /* DLLErrorInternal */
-
-void _PR_InitLinker(void)
-{
- PRLibrary *lm = NULL;
-#if defined(XP_UNIX)
- void *h;
-#endif
-
- if (!pr_linker_lock) {
- pr_linker_lock = PR_NewNamedMonitor("linker-lock");
- }
- PR_EnterMonitor(pr_linker_lock);
-
-#if defined(XP_PC)
- lm = PR_NEWZAP(PRLibrary);
- lm->name = strdup("Executable");
-#if defined(XP_OS2)
- lm->dlh = NULLHANDLE;
-#else
- /* A module handle for the executable. */
- lm->dlh = GetModuleHandle(NULL);
-#endif /* ! XP_OS2 */
-
- lm->refCount = 1;
- lm->staticTable = NULL;
- pr_exe_loadmap = lm;
- pr_loadmap = lm;
-
-#elif defined(XP_UNIX)
-#ifdef HAVE_DLL
-#if defined(USE_DLFCN) && !defined(NO_DLOPEN_NULL)
- h = dlopen(0, RTLD_LAZY);
- if (!h) {
- char *error;
-
- DLLErrorInternal(_MD_ERRNO());
- error = (char*)PR_MALLOC(PR_GetErrorTextLength());
- (void) PR_GetErrorText(error);
- fprintf(stderr, "failed to initialize shared libraries [%s]\n",
- error);
- PR_DELETE(error);
- abort();/* XXX */
- }
-#elif defined(USE_HPSHL)
- h = NULL;
- /* don't abort with this NULL */
-#elif defined(USE_MACH_DYLD) || defined(NO_DLOPEN_NULL)
- h = NULL; /* XXXX toshok */ /* XXXX vlad */
-#else
-#error no dll strategy
-#endif /* USE_DLFCN */
-
- lm = PR_NEWZAP(PRLibrary);
- if (lm) {
- lm->name = strdup("a.out");
- lm->refCount = 1;
- lm->dlh = h;
- lm->staticTable = NULL;
- }
- pr_exe_loadmap = lm;
- pr_loadmap = lm;
-#endif /* HAVE_DLL */
-#endif /* XP_UNIX */
-
- if (lm) {
- PR_LOG(_pr_linker_lm, PR_LOG_MIN,
- ("Loaded library %s (init)", lm->name));
- }
-
- PR_ExitMonitor(pr_linker_lock);
-}
-
-/*
- * _PR_ShutdownLinker does not unload the dlls loaded by the application
- * via calls to PR_LoadLibrary. Any dlls that still remain on the
- * pr_loadmap list when NSPR shuts down are application programming errors.
- * The only exception is pr_exe_loadmap, which was added to the list by
- * NSPR and hence should be cleaned up by NSPR.
- */
-void _PR_ShutdownLinker(void)
-{
- /* FIXME: pr_exe_loadmap should be destroyed. */
-
- PR_DestroyMonitor(pr_linker_lock);
- pr_linker_lock = NULL;
-
- if (_pr_currentLibPath) {
- free(_pr_currentLibPath);
- _pr_currentLibPath = NULL;
- }
-}
-
-/******************************************************************************/
-
-PR_IMPLEMENT(PRStatus) PR_SetLibraryPath(const char *path)
-{
- PRStatus rv = PR_SUCCESS;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- PR_EnterMonitor(pr_linker_lock);
- if (_pr_currentLibPath) {
- free(_pr_currentLibPath);
- }
- if (path) {
- _pr_currentLibPath = strdup(path);
- if (!_pr_currentLibPath) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- rv = PR_FAILURE;
- }
- } else {
- _pr_currentLibPath = 0;
- }
- PR_ExitMonitor(pr_linker_lock);
- return rv;
-}
-
-/*
-** Return the library path for finding shared libraries.
-*/
-PR_IMPLEMENT(char *)
-PR_GetLibraryPath(void)
-{
- char *ev;
- char *copy = NULL; /* a copy of _pr_currentLibPath */
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- PR_EnterMonitor(pr_linker_lock);
- if (_pr_currentLibPath != NULL) {
- goto exit;
- }
-
- /* initialize pr_currentLibPath */
-
-#ifdef XP_PC
- ev = getenv("LD_LIBRARY_PATH");
- if (!ev) {
- ev = ".;\\lib";
- }
- ev = strdup(ev);
-#endif
-
-#if defined(XP_UNIX) || defined(XP_BEOS)
-#if defined(USE_DLFCN) || defined(USE_MACH_DYLD) || defined(XP_BEOS)
- {
- char *p=NULL;
- int len;
-
-#ifdef XP_BEOS
- ev = getenv("LIBRARY_PATH");
- if (!ev) {
- ev = "%A/lib:/boot/home/config/lib:/boot/beos/system/lib";
- }
-#else
- ev = getenv("LD_LIBRARY_PATH");
- if (!ev) {
- ev = "/usr/lib:/lib";
- }
-#endif
- len = strlen(ev) + 1; /* +1 for the null */
-
- p = (char*) malloc(len);
- if (p) {
- strcpy(p, ev);
- } /* if (p) */
- ev = p;
- PR_LOG(_pr_io_lm, PR_LOG_NOTICE, ("linker path '%s'", ev));
-
- }
-#else
- /* AFAIK there isn't a library path with the HP SHL interface --Rob */
- ev = strdup("");
-#endif
-#endif
-
- /*
- * If ev is NULL, we have run out of memory
- */
- _pr_currentLibPath = ev;
-
- exit:
- if (_pr_currentLibPath) {
- copy = strdup(_pr_currentLibPath);
- }
- PR_ExitMonitor(pr_linker_lock);
- if (!copy) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- }
- return copy;
-}
-
-/*
-** Build library name from path, lib and extensions
-*/
-PR_IMPLEMENT(char*)
-PR_GetLibraryName(const char *path, const char *lib)
-{
- char *fullname;
-
-#ifdef XP_PC
- if (strstr(lib, PR_DLL_SUFFIX) == NULL)
- {
- if (path) {
- fullname = PR_smprintf("%s\\%s%s", path, lib, PR_DLL_SUFFIX);
- } else {
- fullname = PR_smprintf("%s%s", lib, PR_DLL_SUFFIX);
- }
- } else {
- if (path) {
- fullname = PR_smprintf("%s\\%s", path, lib);
- } else {
- fullname = PR_smprintf("%s", lib);
- }
- }
-#endif /* XP_PC */
-#if defined(XP_UNIX) || defined(XP_BEOS)
- if (strstr(lib, PR_DLL_SUFFIX) == NULL)
- {
- if (path) {
- fullname = PR_smprintf("%s/lib%s%s", path, lib, PR_DLL_SUFFIX);
- } else {
- fullname = PR_smprintf("lib%s%s", lib, PR_DLL_SUFFIX);
- }
- } else {
- if (path) {
- fullname = PR_smprintf("%s/%s", path, lib);
- } else {
- fullname = PR_smprintf("%s", lib);
- }
- }
-#endif /* XP_UNIX || XP_BEOS */
- return fullname;
-}
-
-/*
-** Free the memory allocated, for the caller, by PR_GetLibraryName
-*/
-PR_IMPLEMENT(void)
-PR_FreeLibraryName(char *mem)
-{
- PR_smprintf_free(mem);
-}
-
-static PRLibrary*
-pr_UnlockedFindLibrary(const char *name)
-{
- PRLibrary* lm = pr_loadmap;
- const char* np = strrchr(name, PR_DIRECTORY_SEPARATOR);
- np = np ? np + 1 : name;
- while (lm) {
- const char* cp = strrchr(lm->name, PR_DIRECTORY_SEPARATOR);
- cp = cp ? cp + 1 : lm->name;
-#ifdef WIN32
- /* Windows DLL names are case insensitive... */
- if (strcmpi(np, cp) == 0)
-#elif defined(XP_OS2)
- if (stricmp(np, cp) == 0)
-#else
- if (strcmp(np, cp) == 0)
-#endif
- {
- /* found */
- lm->refCount++;
- PR_LOG(_pr_linker_lm, PR_LOG_MIN,
- ("%s incr => %d (find lib)",
- lm->name, lm->refCount));
- return lm;
- }
- lm = lm->next;
- }
- return NULL;
-}
-
-PR_IMPLEMENT(PRLibrary*)
-PR_LoadLibraryWithFlags(PRLibSpec libSpec, PRIntn flags)
-{
- if (flags == 0) {
- flags = _PR_DEFAULT_LD_FLAGS;
- }
- switch (libSpec.type) {
- case PR_LibSpec_Pathname:
- return pr_LoadLibraryByPathname(libSpec.value.pathname, flags);
-#ifdef WIN32
- case PR_LibSpec_PathnameU:
- /*
- * cast to |char *| and set PR_LD_PATHW flag so that
- * it can be cast back to PRUnichar* in the callee.
- */
- return pr_LoadLibraryByPathname((const char*)
- libSpec.value.pathname_u,
- flags | PR_LD_PATHW);
-#endif
- default:
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return NULL;
- }
-}
-
-PR_IMPLEMENT(PRLibrary*)
-PR_LoadLibrary(const char *name)
-{
- PRLibSpec libSpec;
-
- libSpec.type = PR_LibSpec_Pathname;
- libSpec.value.pathname = name;
- return PR_LoadLibraryWithFlags(libSpec, 0);
-}
-
-#if defined(USE_MACH_DYLD)
-static NSModule
-pr_LoadMachDyldModule(const char *name)
-{
- NSObjectFileImage ofi;
- NSModule h = NULL;
- if (NSCreateObjectFileImageFromFile(name, &ofi)
- == NSObjectFileImageSuccess) {
- h = NSLinkModule(ofi, name, NSLINKMODULE_OPTION_PRIVATE
- | NSLINKMODULE_OPTION_RETURN_ON_ERROR);
- if (h == NULL) {
- NSLinkEditErrors linkEditError;
- int errorNum;
- const char *fileName;
- const char *errorString;
- NSLinkEditError(&linkEditError, &errorNum, &fileName, &errorString);
- PR_LOG(_pr_linker_lm, PR_LOG_MIN,
- ("LoadMachDyldModule error %d:%d for file %s:\n%s",
- linkEditError, errorNum, fileName, errorString));
- }
- if (NSDestroyObjectFileImage(ofi) == FALSE) {
- if (h) {
- (void)NSUnLinkModule(h, NSUNLINKMODULE_OPTION_NONE);
- h = NULL;
- }
- }
- }
- return h;
-}
-#endif
-
-#if defined(XP_MACOSX) && defined(USE_MACH_DYLD)
-
-/*
-** macLibraryLoadProc is a function definition for a Mac shared library
-** loading method. The "name" param is the same full or partial pathname
-** that was passed to pr_LoadLibraryByPathName. The function must fill
-** in the fields of "lm" which apply to its library type. Returns
-** PR_SUCCESS if successful.
-*/
-
-typedef PRStatus (*macLibraryLoadProc)(const char *name, PRLibrary *lm);
-
-#ifdef __ppc__
-
-/*
-** CFM and its TVectors only exist on PowerPC. Other OS X architectures
-** only use Mach-O as a native binary format.
-*/
-
-static void* TV2FP(CFMutableDictionaryRef dict, const char* name, void *tvp)
-{
- static uint32 glue[6] = { 0x3D800000, 0x618C0000, 0x800C0000, 0x804C0004, 0x7C0903A6, 0x4E800420 };
- uint32* newGlue = NULL;
-
- if (tvp != NULL) {
- CFStringRef nameRef = CFStringCreateWithCString(NULL, name, kCFStringEncodingASCII);
- if (nameRef) {
- CFMutableDataRef glueData = (CFMutableDataRef) CFDictionaryGetValue(dict, nameRef);
- if (glueData == NULL) {
- glueData = CFDataCreateMutable(NULL, sizeof(glue));
- if (glueData != NULL) {
- newGlue = (uint32*) CFDataGetMutableBytePtr(glueData);
- memcpy(newGlue, glue, sizeof(glue));
- newGlue[0] |= ((UInt32)tvp >> 16);
- newGlue[1] |= ((UInt32)tvp & 0xFFFF);
- MakeDataExecutable(newGlue, sizeof(glue));
- CFDictionaryAddValue(dict, nameRef, glueData);
- CFRelease(glueData);
-
- PR_LOG(_pr_linker_lm, PR_LOG_MIN, ("TV2FP: created wrapper for CFM function %s().", name));
- }
- } else {
- PR_LOG(_pr_linker_lm, PR_LOG_MIN, ("TV2FP: found wrapper for CFM function %s().", name));
-
- newGlue = (uint32*) CFDataGetMutableBytePtr(glueData);
- }
- CFRelease(nameRef);
- }
- }
-
- return newGlue;
-}
-
-static PRStatus
-pr_LoadViaCFM(const char *name, PRLibrary *lm)
-{
- OSErr err;
- Str255 errName;
- FSRef ref;
- FSSpec fileSpec;
- Boolean tempUnusedBool;
-
- /*
- * Make an FSSpec from the path name and call GetDiskFragment.
- */
-
- /* Use direct conversion of POSIX path to FSRef to FSSpec. */
- err = FSPathMakeRef((const UInt8*)name, &ref, NULL);
- if (err != noErr)
- return PR_FAILURE;
- err = FSGetCatalogInfo(&ref, kFSCatInfoNone, NULL, NULL,
- &fileSpec, NULL);
- if (err != noErr)
- return PR_FAILURE;
-
- /* Resolve an alias if this was one */
- err = ResolveAliasFile(&fileSpec, true, &tempUnusedBool,
- &tempUnusedBool);
- if (err != noErr)
- return PR_FAILURE;
-
- /* Finally, try to load the library */
- err = GetDiskFragment(&fileSpec, 0, kCFragGoesToEOF, fileSpec.name,
- kLoadCFrag, &lm->connection, &lm->main, errName);
-
- if (err == noErr && lm->connection) {
- /*
- * if we're a mach-o binary, need to wrap all CFM function
- * pointers. need a hash-table of already seen function
- * pointers, etc.
- */
- lm->wrappers = CFDictionaryCreateMutable(NULL, 16,
- &kCFTypeDictionaryKeyCallBacks,
- &kCFTypeDictionaryValueCallBacks);
- if (lm->wrappers) {
- lm->main = TV2FP(lm->wrappers, "main", lm->main);
- } else
- err = memFullErr;
- }
- return (err == noErr) ? PR_SUCCESS : PR_FAILURE;
-}
-#endif /* __ppc__ */
-
-/*
-** Creates a CFBundleRef if the pathname refers to a Mac OS X bundle
-** directory. The caller is responsible for calling CFRelease() to
-** deallocate.
-*/
-
-static PRStatus
-pr_LoadCFBundle(const char *name, PRLibrary *lm)
-{
- CFURLRef bundleURL;
- CFBundleRef bundle = NULL;
- char pathBuf[PATH_MAX];
- const char *resolvedPath;
- CFStringRef pathRef;
-
- /* Takes care of relative paths and symlinks */
- resolvedPath = realpath(name, pathBuf);
- if (!resolvedPath)
- return PR_FAILURE;
-
- pathRef = CFStringCreateWithCString(NULL, pathBuf, kCFStringEncodingUTF8);
- if (pathRef) {
- bundleURL = CFURLCreateWithFileSystemPath(NULL, pathRef,
- kCFURLPOSIXPathStyle, true);
- if (bundleURL) {
- bundle = CFBundleCreate(NULL, bundleURL);
- CFRelease(bundleURL);
- }
- CFRelease(pathRef);
- }
-
- lm->bundle = bundle;
- return (bundle != NULL) ? PR_SUCCESS : PR_FAILURE;
-}
-
-static PRStatus
-pr_LoadViaDyld(const char *name, PRLibrary *lm)
-{
- lm->dlh = pr_LoadMachDyldModule(name);
- if (lm->dlh == NULL) {
- lm->image = NSAddImage(name, NSADDIMAGE_OPTION_RETURN_ON_ERROR
- | NSADDIMAGE_OPTION_WITH_SEARCHING);
- if (lm->image == NULL) {
- NSLinkEditErrors linkEditError;
- int errorNum;
- const char *fileName;
- const char *errorString;
- NSLinkEditError(&linkEditError, &errorNum, &fileName, &errorString);
- PR_LOG(_pr_linker_lm, PR_LOG_MIN,
- ("LoadMachDyldModule error %d:%d for file %s:\n%s",
- linkEditError, errorNum, fileName, errorString));
- }
- }
- return (lm->dlh != NULL || lm->image != NULL) ? PR_SUCCESS : PR_FAILURE;
-}
-
-#endif /* XP_MACOSX && USE_MACH_DYLD */
-
-/*
-** Dynamically load a library. Only load libraries once, so scan the load
-** map first.
-*/
-static PRLibrary*
-pr_LoadLibraryByPathname(const char *name, PRIntn flags)
-{
- PRLibrary *lm;
- PRLibrary* result = NULL;
- PRInt32 oserr;
-#ifdef WIN32
- char utf8name_stack[MAX_PATH];
- char *utf8name_malloc = NULL;
- char *utf8name = utf8name_stack;
- PRUnichar wname_stack[MAX_PATH];
- PRUnichar *wname_malloc = NULL;
- PRUnichar *wname = wname_stack;
- int len;
-#endif
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- /* See if library is already loaded */
- PR_EnterMonitor(pr_linker_lock);
-
-#ifdef WIN32
- if (flags & PR_LD_PATHW) {
- /* cast back what's cast to |char *| for the argument passing. */
- wname = (LPWSTR) name;
- } else {
- int wlen = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
- if (wlen > MAX_PATH)
- wname = wname_malloc = PR_Malloc(wlen * sizeof(PRUnichar));
- if (wname == NULL ||
- !MultiByteToWideChar(CP_ACP, 0, name, -1, wname, wlen)) {
- oserr = _MD_ERRNO();
- goto unlock;
- }
- }
- len = WideCharToMultiByte(CP_UTF8, 0, wname, -1, NULL, 0, NULL, NULL);
- if (len > MAX_PATH)
- utf8name = utf8name_malloc = PR_Malloc(len);
- if (utf8name == NULL ||
- !WideCharToMultiByte(CP_UTF8, 0, wname, -1,
- utf8name, len, NULL, NULL)) {
- oserr = _MD_ERRNO();
- goto unlock;
- }
- /* the list of loaded library names are always kept in UTF-8
- * on Win32 platforms */
- result = pr_UnlockedFindLibrary(utf8name);
-#else
- result = pr_UnlockedFindLibrary(name);
-#endif
-
- if (result != NULL) goto unlock;
-
- lm = PR_NEWZAP(PRLibrary);
- if (lm == NULL) {
- oserr = _MD_ERRNO();
- goto unlock;
- }
- lm->staticTable = NULL;
-
-#ifdef XP_OS2 /* Why isn't all this stuff in MD code?! */
- {
- HMODULE h;
- UCHAR pszError[_MAX_PATH];
- ULONG ulRc = NO_ERROR;
-
- ulRc = DosLoadModule(pszError, _MAX_PATH, (PSZ) name, &h);
- if (ulRc != NO_ERROR) {
- oserr = ulRc;
- PR_DELETE(lm);
- goto unlock;
- }
- lm->name = strdup(name);
- lm->dlh = h;
- lm->next = pr_loadmap;
- pr_loadmap = lm;
- }
-#endif /* XP_OS2 */
-
-#ifdef WIN32
- {
- HINSTANCE h;
-
- h = LoadLibraryExW(wname, NULL,
- (flags & PR_LD_ALT_SEARCH_PATH) ?
- LOAD_WITH_ALTERED_SEARCH_PATH : 0);
- if (h == NULL) {
- oserr = _MD_ERRNO();
- PR_DELETE(lm);
- goto unlock;
- }
- lm->name = strdup(utf8name);
- lm->dlh = h;
- lm->next = pr_loadmap;
- pr_loadmap = lm;
- }
-#endif /* WIN32 */
-
-#if defined(XP_MACOSX) && defined(USE_MACH_DYLD)
- {
- int i;
- PRStatus status;
-
- static const macLibraryLoadProc loadProcs[] = {
-#ifdef __ppc__
- pr_LoadViaDyld, pr_LoadCFBundle, pr_LoadViaCFM
-#else /* __ppc__ */
- pr_LoadViaDyld, pr_LoadCFBundle
-#endif /* __ppc__ */
- };
-
- for (i = 0; i < sizeof(loadProcs) / sizeof(loadProcs[0]); i++) {
- if ((status = loadProcs[i](name, lm)) == PR_SUCCESS)
- break;
- }
- if (status != PR_SUCCESS) {
- oserr = cfragNoLibraryErr;
- PR_DELETE(lm);
- goto unlock;
- }
- lm->name = strdup(name);
- lm->next = pr_loadmap;
- pr_loadmap = lm;
- }
-#endif
-
-#if defined(XP_UNIX) && !(defined(XP_MACOSX) && defined(USE_MACH_DYLD))
-#ifdef HAVE_DLL
- {
-#if defined(USE_DLFCN)
-#ifdef NTO
- /* Neutrino needs RTLD_GROUP to load Netscape plugins. (bug 71179) */
- int dl_flags = RTLD_GROUP;
-#elif defined(AIX)
- /* AIX needs RTLD_MEMBER to load an archive member. (bug 228899) */
- int dl_flags = RTLD_MEMBER;
-#else
- int dl_flags = 0;
-#endif
- void *h = NULL;
-
- if (flags & PR_LD_LAZY) {
- dl_flags |= RTLD_LAZY;
- }
- if (flags & PR_LD_NOW) {
- dl_flags |= RTLD_NOW;
- }
- if (flags & PR_LD_GLOBAL) {
- dl_flags |= RTLD_GLOBAL;
- }
- if (flags & PR_LD_LOCAL) {
- dl_flags |= RTLD_LOCAL;
- }
-#if defined(DARWIN)
- /* ensure the file exists if it contains a slash character i.e. path */
- /* DARWIN's dlopen ignores the provided path and checks for the */
- /* plain filename in DYLD_LIBRARY_PATH */
- if (strchr(name, PR_DIRECTORY_SEPARATOR) == NULL ||
- PR_Access(name, PR_ACCESS_EXISTS) == PR_SUCCESS) {
- h = dlopen(name, dl_flags);
- }
-#else
- h = dlopen(name, dl_flags);
-#endif
-#elif defined(USE_HPSHL)
- int shl_flags = 0;
- shl_t h;
-
- /*
- * Use the DYNAMIC_PATH flag only if 'name' is a plain file
- * name (containing no directory) to match the behavior of
- * dlopen().
- */
- if (strchr(name, PR_DIRECTORY_SEPARATOR) == NULL) {
- shl_flags |= DYNAMIC_PATH;
- }
- if (flags & PR_LD_LAZY) {
- shl_flags |= BIND_DEFERRED;
- }
- if (flags & PR_LD_NOW) {
- shl_flags |= BIND_IMMEDIATE;
- }
- /* No equivalent of PR_LD_GLOBAL and PR_LD_LOCAL. */
- h = shl_load(name, shl_flags, 0L);
-#elif defined(USE_MACH_DYLD)
- NSModule h = pr_LoadMachDyldModule(name);
-#else
-#error Configuration error
-#endif
- if (!h) {
- oserr = _MD_ERRNO();
- PR_DELETE(lm);
- goto unlock;
- }
- lm->name = strdup(name);
- lm->dlh = h;
- lm->next = pr_loadmap;
- pr_loadmap = lm;
- }
-#endif /* HAVE_DLL */
-#endif /* XP_UNIX && !(XP_MACOSX && USE_MACH_DYLD) */
-
- lm->refCount = 1;
-
-#ifdef XP_BEOS
- {
- image_info info;
- int32 cookie = 0;
- image_id imageid = B_ERROR;
- image_id stubid = B_ERROR;
- PRLibrary *p;
-
- for (p = pr_loadmap; p != NULL; p = p->next) {
- /* hopefully, our caller will always use the same string
- to refer to the same library */
- if (strcmp(name, p->name) == 0) {
- /* we've already loaded this library */
- imageid = info.id;
- lm->refCount++;
- break;
- }
- }
-
- if(imageid == B_ERROR) {
- /* it appears the library isn't yet loaded - load it now */
- char stubName [B_PATH_NAME_LENGTH + 1];
-
- /* the following is a work-around to a "bug" in the beos -
- the beos system loader allows only 32M (system-wide)
- to be used by code loaded as "add-ons" (code loaded
- through the 'load_add_on()' system call, which includes
- mozilla components), but allows 256M to be used by
- shared libraries.
-
- unfortunately, mozilla is too large to fit into the
- "add-on" space, so we must trick the loader into
- loading some of the components as shared libraries. this
- is accomplished by creating a "stub" add-on (an empty
- shared object), and linking it with the component
- (the actual .so file generated by the build process,
- without any modifications). when this stub is loaded
- by load_add_on(), the loader will automatically load the
- component into the shared library space.
- */
-
- strcpy(stubName, name);
- strcat(stubName, ".stub");
-
- /* first, attempt to load the stub (thereby loading the
- component as a shared library */
- if ((stubid = load_add_on(stubName)) > B_ERROR) {
- /* the stub was loaded successfully. */
- imageid = B_FILE_NOT_FOUND;
-
- cookie = 0;
- while (get_next_image_info(0, &cookie, &info) == B_OK) {
- const char *endOfSystemName = strrchr(info.name, '/');
- const char *endOfPassedName = strrchr(name, '/');
- if( 0 == endOfSystemName )
- endOfSystemName = info.name;
- else
- endOfSystemName++;
- if( 0 == endOfPassedName )
- endOfPassedName = name;
- else
- endOfPassedName++;
- if (strcmp(endOfSystemName, endOfPassedName) == 0) {
- /* this is the actual component - remember it */
- imageid = info.id;
- break;
- }
- }
-
- } else {
- /* we failed to load the "stub" - try to load the
- component directly as an add-on */
- stubid = B_ERROR;
- imageid = load_add_on(name);
- }
- }
-
- if (imageid <= B_ERROR) {
- oserr = imageid;
- PR_DELETE( lm );
- goto unlock;
- }
- lm->name = strdup(name);
- lm->dlh = (void*)imageid;
- lm->stub_dlh = (void*)stubid;
- lm->next = pr_loadmap;
- pr_loadmap = lm;
- }
-#endif
-
- result = lm; /* success */
- PR_LOG(_pr_linker_lm, PR_LOG_MIN, ("Loaded library %s (load lib)", lm->name));
-
- unlock:
- if (result == NULL) {
- PR_SetError(PR_LOAD_LIBRARY_ERROR, oserr);
- DLLErrorInternal(oserr); /* sets error text */
- }
-#ifdef WIN32
- if (utf8name_malloc)
- PR_Free(utf8name_malloc);
- if (wname_malloc)
- PR_Free(wname_malloc);
-#endif
- PR_ExitMonitor(pr_linker_lock);
- return result;
-}
-
-/*
-** Unload a shared library which was loaded via PR_LoadLibrary
-*/
-PR_IMPLEMENT(PRStatus)
-PR_UnloadLibrary(PRLibrary *lib)
-{
- int result = 0;
- PRStatus status = PR_SUCCESS;
-
- if (lib == 0) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
-
- PR_EnterMonitor(pr_linker_lock);
-
- if (lib->refCount <= 0) {
- PR_ExitMonitor(pr_linker_lock);
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
-
- if (--lib->refCount > 0) {
- PR_LOG(_pr_linker_lm, PR_LOG_MIN,
- ("%s decr => %d",
- lib->name, lib->refCount));
- goto done;
- }
-
-#ifdef XP_BEOS
- if(((image_id)lib->stub_dlh) == B_ERROR)
- unload_add_on( (image_id) lib->dlh );
- else
- unload_add_on( (image_id) lib->stub_dlh);
-#endif
-
-#ifdef XP_UNIX
-#ifdef HAVE_DLL
-#ifdef USE_DLFCN
- result = dlclose(lib->dlh);
-#elif defined(USE_HPSHL)
- result = shl_unload(lib->dlh);
-#elif defined(USE_MACH_DYLD)
- if (lib->dlh)
- result = NSUnLinkModule(lib->dlh, NSUNLINKMODULE_OPTION_NONE) ? 0 : -1;
-#else
-#error Configuration error
-#endif
-#endif /* HAVE_DLL */
-#endif /* XP_UNIX */
-#ifdef XP_PC
- if (lib->dlh) {
- FreeLibrary((HINSTANCE)(lib->dlh));
- lib->dlh = (HINSTANCE)NULL;
- }
-#endif /* XP_PC */
-
-#if defined(XP_MACOSX) && defined(USE_MACH_DYLD)
- /* Close the connection */
- if (lib->connection)
- CloseConnection(&(lib->connection));
- if (lib->bundle)
- CFRelease(lib->bundle);
- if (lib->wrappers)
- CFRelease(lib->wrappers);
- /* No way to unload an image (lib->image) */
-#endif
-
- /* unlink from library search list */
- if (pr_loadmap == lib)
- pr_loadmap = pr_loadmap->next;
- else if (pr_loadmap != NULL) {
- PRLibrary* prev = pr_loadmap;
- PRLibrary* next = pr_loadmap->next;
- while (next != NULL) {
- if (next == lib) {
- prev->next = next->next;
- goto freeLib;
- }
- prev = next;
- next = next->next;
- }
- /*
- * fail (the library is not on the _pr_loadmap list),
- * but don't wipe out an error from dlclose/shl_unload.
- */
- PR_NOT_REACHED("_pr_loadmap and lib->refCount inconsistent");
- if (result == 0) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- status = PR_FAILURE;
- }
- }
- /*
- * We free the PRLibrary structure whether dlclose/shl_unload
- * succeeds or not.
- */
-
- freeLib:
- PR_LOG(_pr_linker_lm, PR_LOG_MIN, ("Unloaded library %s", lib->name));
- free(lib->name);
- lib->name = NULL;
- PR_DELETE(lib);
- if (result != 0) {
- PR_SetError(PR_UNLOAD_LIBRARY_ERROR, _MD_ERRNO());
- DLLErrorInternal(_MD_ERRNO());
- status = PR_FAILURE;
- }
-
-done:
- PR_ExitMonitor(pr_linker_lock);
- return status;
-}
-
-static void*
-pr_FindSymbolInLib(PRLibrary *lm, const char *name)
-{
- void *f = NULL;
-#ifdef XP_OS2
- int rc;
-#endif
-
- if (lm->staticTable != NULL) {
- const PRStaticLinkTable* tp;
- for (tp = lm->staticTable; tp->name; tp++) {
- if (strcmp(name, tp->name) == 0) {
- return (void*) tp->fp;
- }
- }
- /*
- ** If the symbol was not found in the static table then check if
- ** the symbol was exported in the DLL... Win16 only!!
- */
-#if !defined(WIN16) && !defined(XP_BEOS)
- PR_SetError(PR_FIND_SYMBOL_ERROR, 0);
- return (void*)NULL;
-#endif
- }
-
-#ifdef XP_OS2
- rc = DosQueryProcAddr(lm->dlh, 0, (PSZ) name, (PFN *) &f);
-#if defined(NEED_LEADING_UNDERSCORE)
- /*
- * Older plugins (not built using GCC) will have symbols that are not
- * underscore prefixed. We check for that here.
- */
- if (rc != NO_ERROR) {
- name++;
- DosQueryProcAddr(lm->dlh, 0, (PSZ) name, (PFN *) &f);
- }
-#endif
-#endif /* XP_OS2 */
-
-#ifdef WIN32
- f = GetProcAddress(lm->dlh, name);
-#endif /* WIN32 */
-
-#if defined(XP_MACOSX) && defined(USE_MACH_DYLD)
-/* add this offset to skip the leading underscore in name */
-#define SYM_OFFSET 1
- if (lm->bundle) {
- CFStringRef nameRef = CFStringCreateWithCString(NULL, name + SYM_OFFSET, kCFStringEncodingASCII);
- if (nameRef) {
- f = CFBundleGetFunctionPointerForName(lm->bundle, nameRef);
- CFRelease(nameRef);
- }
- }
- if (lm->connection) {
- Ptr symAddr;
- CFragSymbolClass symClass;
- Str255 pName;
-
- PR_LOG(_pr_linker_lm, PR_LOG_MIN, ("Looking up symbol: %s", name + SYM_OFFSET));
-
- c2pstrcpy(pName, name + SYM_OFFSET);
-
- f = (FindSymbol(lm->connection, pName, &symAddr, &symClass) == noErr) ? symAddr : NULL;
-
-#ifdef __ppc__
- /* callers expect mach-o function pointers, so must wrap tvectors with glue. */
- if (f && symClass == kTVectorCFragSymbol) {
- f = TV2FP(lm->wrappers, name + SYM_OFFSET, f);
- }
-#endif /* __ppc__ */
-
- if (f == NULL && strcmp(name + SYM_OFFSET, "main") == 0) f = lm->main;
- }
- if (lm->image) {
- NSSymbol symbol;
- symbol = NSLookupSymbolInImage(lm->image, name,
- NSLOOKUPSYMBOLINIMAGE_OPTION_BIND
- | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
- if (symbol != NULL)
- f = NSAddressOfSymbol(symbol);
- else
- f = NULL;
- }
-#undef SYM_OFFSET
-#endif /* XP_MACOSX && USE_MACH_DYLD */
-
-#ifdef XP_BEOS
- if( B_NO_ERROR != get_image_symbol( (image_id)lm->dlh, name, B_SYMBOL_TYPE_TEXT, &f ) ) {
- f = NULL;
- }
-#endif
-
-#ifdef XP_UNIX
-#ifdef HAVE_DLL
-#ifdef USE_DLFCN
- f = dlsym(lm->dlh, name);
-#elif defined(USE_HPSHL)
- if (shl_findsym(&lm->dlh, name, TYPE_PROCEDURE, &f) == -1) {
- f = NULL;
- }
-#elif defined(USE_MACH_DYLD)
- if (lm->dlh) {
- NSSymbol symbol;
- symbol = NSLookupSymbolInModule(lm->dlh, name);
- if (symbol != NULL)
- f = NSAddressOfSymbol(symbol);
- else
- f = NULL;
- }
-#endif
-#endif /* HAVE_DLL */
-#endif /* XP_UNIX */
- if (f == NULL) {
- PR_SetError(PR_FIND_SYMBOL_ERROR, _MD_ERRNO());
- DLLErrorInternal(_MD_ERRNO());
- }
- return f;
-}
-
-/*
-** Called by class loader to resolve missing native's
-*/
-PR_IMPLEMENT(void*)
-PR_FindSymbol(PRLibrary *lib, const char *raw_name)
-{
- void *f = NULL;
-#if defined(NEED_LEADING_UNDERSCORE)
- char *name;
-#else
- const char *name;
-#endif
- /*
- ** Mangle the raw symbol name in any way that is platform specific.
- */
-#if defined(NEED_LEADING_UNDERSCORE)
- /* Need a leading _ */
- name = PR_smprintf("_%s", raw_name);
-#elif defined(AIX)
- /*
- ** AIX with the normal linker put's a "." in front of the symbol
- ** name. When use "svcc" and "svld" then the "." disappears. Go
- ** figure.
- */
- name = raw_name;
-#else
- name = raw_name;
-#endif
-
- PR_EnterMonitor(pr_linker_lock);
- PR_ASSERT(lib != NULL);
- f = pr_FindSymbolInLib(lib, name);
-
-#if defined(NEED_LEADING_UNDERSCORE)
- PR_smprintf_free(name);
-#endif
-
- PR_ExitMonitor(pr_linker_lock);
- return f;
-}
-
-/*
-** Return the address of the function 'raw_name' in the library 'lib'
-*/
-PR_IMPLEMENT(PRFuncPtr)
-PR_FindFunctionSymbol(PRLibrary *lib, const char *raw_name)
-{
- return ((PRFuncPtr) PR_FindSymbol(lib, raw_name));
-}
-
-PR_IMPLEMENT(void*)
-PR_FindSymbolAndLibrary(const char *raw_name, PRLibrary* *lib)
-{
- void *f = NULL;
-#if defined(NEED_LEADING_UNDERSCORE)
- char *name;
-#else
- const char *name;
-#endif
- PRLibrary* lm;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- /*
- ** Mangle the raw symbol name in any way that is platform specific.
- */
-#if defined(NEED_LEADING_UNDERSCORE)
- /* Need a leading _ */
- name = PR_smprintf("_%s", raw_name);
-#elif defined(AIX)
- /*
- ** AIX with the normal linker put's a "." in front of the symbol
- ** name. When use "svcc" and "svld" then the "." disappears. Go
- ** figure.
- */
- name = raw_name;
-#else
- name = raw_name;
-#endif
-
- PR_EnterMonitor(pr_linker_lock);
-
- /* search all libraries */
- for (lm = pr_loadmap; lm != NULL; lm = lm->next) {
- f = pr_FindSymbolInLib(lm, name);
- if (f != NULL) {
- *lib = lm;
- lm->refCount++;
- PR_LOG(_pr_linker_lm, PR_LOG_MIN,
- ("%s incr => %d (for %s)",
- lm->name, lm->refCount, name));
- break;
- }
- }
-#if defined(NEED_LEADING_UNDERSCORE)
- PR_smprintf_free(name);
-#endif
-
- PR_ExitMonitor(pr_linker_lock);
- return f;
-}
-
-PR_IMPLEMENT(PRFuncPtr)
-PR_FindFunctionSymbolAndLibrary(const char *raw_name, PRLibrary* *lib)
-{
- return ((PRFuncPtr) PR_FindSymbolAndLibrary(raw_name, lib));
-}
-
-/*
-** Add a static library to the list of loaded libraries. If LoadLibrary
-** is called with the name then we will pretend it was already loaded
-*/
-PR_IMPLEMENT(PRLibrary*)
-PR_LoadStaticLibrary(const char *name, const PRStaticLinkTable *slt)
-{
- PRLibrary *lm=NULL;
- PRLibrary* result = NULL;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- /* See if library is already loaded */
- PR_EnterMonitor(pr_linker_lock);
-
- /* If the lbrary is already loaded, then add the static table information... */
- result = pr_UnlockedFindLibrary(name);
- if (result != NULL) {
- PR_ASSERT( (result->staticTable == NULL) || (result->staticTable == slt) );
- result->staticTable = slt;
- goto unlock;
- }
-
- /* Add library to list...Mark it static */
- lm = PR_NEWZAP(PRLibrary);
- if (lm == NULL) goto unlock;
-
- lm->name = strdup(name);
- lm->refCount = 1;
- lm->dlh = pr_exe_loadmap ? pr_exe_loadmap->dlh : 0;
- lm->staticTable = slt;
- lm->next = pr_loadmap;
- pr_loadmap = lm;
-
- result = lm; /* success */
- PR_ASSERT(lm->refCount == 1);
- PR_LOG(_pr_linker_lm, PR_LOG_MIN, ("Loaded library %s (static lib)", lm->name));
- unlock:
- PR_ExitMonitor(pr_linker_lock);
- return result;
-}
-
-PR_IMPLEMENT(char *)
-PR_GetLibraryFilePathname(const char *name, PRFuncPtr addr)
-{
-#if defined(USE_DLFCN) && defined(HAVE_DLADDR)
- Dl_info dli;
- char *result;
-
- if (dladdr((void *)addr, &dli) == 0) {
- PR_SetError(PR_LIBRARY_NOT_LOADED_ERROR, _MD_ERRNO());
- DLLErrorInternal(_MD_ERRNO());
- return NULL;
- }
- result = PR_Malloc(strlen(dli.dli_fname)+1);
- if (result != NULL) {
- strcpy(result, dli.dli_fname);
- }
- return result;
-#elif defined(USE_MACH_DYLD)
- char *result;
- const char *image_name;
- int i, count = _dyld_image_count();
-
- for (i = 0; i < count; i++) {
- image_name = _dyld_get_image_name(i);
- if (strstr(image_name, name) != NULL) {
- result = PR_Malloc(strlen(image_name)+1);
- if (result != NULL) {
- strcpy(result, image_name);
- }
- return result;
- }
- }
- PR_SetError(PR_LIBRARY_NOT_LOADED_ERROR, 0);
- return NULL;
-#elif defined(AIX)
- char *result;
-#define LD_INFO_INCREMENT 64
- struct ld_info *info;
- unsigned int info_length = LD_INFO_INCREMENT * sizeof(struct ld_info);
- struct ld_info *infop;
- int loadflags = L_GETINFO | L_IGNOREUNLOAD;
-
- for (;;) {
- info = PR_Malloc(info_length);
- if (info == NULL) {
- return NULL;
- }
- /* If buffer is too small, loadquery fails with ENOMEM. */
- if (loadquery(loadflags, info, info_length) != -1) {
- break;
- }
- /*
- * Calling loadquery when compiled for 64-bit with the
- * L_IGNOREUNLOAD flag can cause an invalid argument error
- * on AIX 5.1. Detect this error the first time that
- * loadquery is called, and try calling it again without
- * this flag set.
- */
- if (errno == EINVAL && (loadflags & L_IGNOREUNLOAD)) {
- loadflags &= ~L_IGNOREUNLOAD;
- if (loadquery(loadflags, info, info_length) != -1) {
- break;
- }
- }
- PR_Free(info);
- if (errno != ENOMEM) {
- /* should not happen */
- _PR_MD_MAP_DEFAULT_ERROR(_MD_ERRNO());
- return NULL;
- }
- /* retry with a larger buffer */
- info_length += LD_INFO_INCREMENT * sizeof(struct ld_info);
- }
-
- for (infop = info;
- ;
- infop = (struct ld_info *)((char *)infop + infop->ldinfo_next)) {
- unsigned long start = (unsigned long)infop->ldinfo_dataorg;
- unsigned long end = start + infop->ldinfo_datasize;
- if (start <= (unsigned long)addr && end > (unsigned long)addr) {
- result = PR_Malloc(strlen(infop->ldinfo_filename)+1);
- if (result != NULL) {
- strcpy(result, infop->ldinfo_filename);
- }
- break;
- }
- if (!infop->ldinfo_next) {
- PR_SetError(PR_LIBRARY_NOT_LOADED_ERROR, 0);
- result = NULL;
- break;
- }
- }
- PR_Free(info);
- return result;
-#elif defined(OSF1)
- /* Contributed by Steve Streeter of HP */
- ldr_process_t process, ldr_my_process();
- ldr_module_t mod_id;
- ldr_module_info_t info;
- ldr_region_t regno;
- ldr_region_info_t reginfo;
- size_t retsize;
- int rv;
- char *result;
-
- /* Get process for which dynamic modules will be listed */
-
- process = ldr_my_process();
-
- /* Attach to process */
-
- rv = ldr_xattach(process);
- if (rv) {
- /* should not happen */
- _PR_MD_MAP_DEFAULT_ERROR(_MD_ERRNO());
- return NULL;
- }
-
- /* Print information for list of modules */
-
- mod_id = LDR_NULL_MODULE;
-
- for (;;) {
-
- /* Get information for the next module in the module list. */
-
- ldr_next_module(process, &mod_id);
- if (ldr_inq_module(process, mod_id, &info, sizeof(info),
- &retsize) != 0) {
- /* No more modules */
- break;
- }
- if (retsize < sizeof(info)) {
- continue;
- }
-
- /*
- * Get information for each region in the module and check if any
- * contain the address of this function.
- */
-
- for (regno = 0; ; regno++) {
- if (ldr_inq_region(process, mod_id, regno, ®info,
- sizeof(reginfo), &retsize) != 0) {
- /* No more regions */
- break;
- }
- if (((unsigned long)reginfo.lri_mapaddr <=
- (unsigned long)addr) &&
- (((unsigned long)reginfo.lri_mapaddr + reginfo.lri_size) >
- (unsigned long)addr)) {
- /* Found it. */
- result = PR_Malloc(strlen(info.lmi_name)+1);
- if (result != NULL) {
- strcpy(result, info.lmi_name);
- }
- return result;
- }
- }
- }
- PR_SetError(PR_LIBRARY_NOT_LOADED_ERROR, 0);
- return NULL;
-#elif defined(HPUX) && defined(USE_HPSHL)
- int index;
- struct shl_descriptor desc;
- char *result;
-
- for (index = 0; shl_get_r(index, &desc) == 0; index++) {
- if (strstr(desc.filename, name) != NULL) {
- result = PR_Malloc(strlen(desc.filename)+1);
- if (result != NULL) {
- strcpy(result, desc.filename);
- }
- return result;
- }
- }
- /*
- * Since the index value of a library is decremented if
- * a library preceding it in the shared library search
- * list was unloaded, it is possible that we missed some
- * libraries as we went up the list. So we should go
- * down the list to be sure that we not miss anything.
- */
- for (index--; index >= 0; index--) {
- if ((shl_get_r(index, &desc) == 0)
- && (strstr(desc.filename, name) != NULL)) {
- result = PR_Malloc(strlen(desc.filename)+1);
- if (result != NULL) {
- strcpy(result, desc.filename);
- }
- return result;
- }
- }
- PR_SetError(PR_LIBRARY_NOT_LOADED_ERROR, 0);
- return NULL;
-#elif defined(HPUX) && defined(USE_DLFCN)
- struct load_module_desc desc;
- char *result;
- const char *module_name;
-
- if (dlmodinfo((unsigned long)addr, &desc, sizeof desc, NULL, 0, 0) == 0) {
- PR_SetError(PR_LIBRARY_NOT_LOADED_ERROR, _MD_ERRNO());
- DLLErrorInternal(_MD_ERRNO());
- return NULL;
- }
- module_name = dlgetname(&desc, sizeof desc, NULL, 0, 0);
- if (module_name == NULL) {
- /* should not happen */
- _PR_MD_MAP_DEFAULT_ERROR(_MD_ERRNO());
- DLLErrorInternal(_MD_ERRNO());
- return NULL;
- }
- result = PR_Malloc(strlen(module_name)+1);
- if (result != NULL) {
- strcpy(result, module_name);
- }
- return result;
-#elif defined(WIN32)
- PRUnichar wname[MAX_PATH];
- HMODULE handle = NULL;
- PRUnichar module_name[MAX_PATH];
- int len;
- char *result;
-
- if (MultiByteToWideChar(CP_ACP, 0, name, -1, wname, MAX_PATH)) {
- handle = GetModuleHandleW(wname);
- }
- if (handle == NULL) {
- PR_SetError(PR_LIBRARY_NOT_LOADED_ERROR, _MD_ERRNO());
- DLLErrorInternal(_MD_ERRNO());
- return NULL;
- }
- if (GetModuleFileNameW(handle, module_name, MAX_PATH) == 0) {
- /* should not happen */
- _PR_MD_MAP_DEFAULT_ERROR(_MD_ERRNO());
- return NULL;
- }
- len = WideCharToMultiByte(CP_ACP, 0, module_name, -1,
- NULL, 0, NULL, NULL);
- if (len == 0) {
- _PR_MD_MAP_DEFAULT_ERROR(_MD_ERRNO());
- return NULL;
- }
- result = PR_Malloc(len * sizeof(PRUnichar));
- if (result != NULL) {
- WideCharToMultiByte(CP_ACP, 0, module_name, -1,
- result, len, NULL, NULL);
- }
- return result;
-#elif defined(XP_OS2)
- HMODULE module = NULL;
- char module_name[_MAX_PATH];
- char *result;
- APIRET ulrc = DosQueryModFromEIP(&module, NULL, 0, NULL, NULL, (ULONG) addr);
- if ((NO_ERROR != ulrc) || (NULL == module) ) {
- PR_SetError(PR_LIBRARY_NOT_LOADED_ERROR, _MD_ERRNO());
- DLLErrorInternal(_MD_ERRNO());
- return NULL;
- }
- ulrc = DosQueryModuleName(module, sizeof module_name, module_name);
- if (NO_ERROR != ulrc) {
- /* should not happen */
- _PR_MD_MAP_DEFAULT_ERROR(_MD_ERRNO());
- return NULL;
- }
- result = PR_Malloc(strlen(module_name)+1);
- if (result != NULL) {
- strcpy(result, module_name);
- }
- return result;
-#else
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return NULL;
-#endif
-}
diff --git a/nspr/pr/src/malloc/prmalloc.c b/nspr/pr/src/malloc/prmalloc.c
deleted file mode 100644
index 174d0da..0000000
--- a/nspr/pr/src/malloc/prmalloc.c
+++ /dev/null
@@ -1,1142 +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/. */
-
-#include "primpl.h"
-
-/*
-** We override malloc etc. on any platform which has preemption +
-** nspr20 user level threads. When we're debugging, we can make our
-** version of malloc fail occasionally.
-*/
-#ifdef _PR_OVERRIDE_MALLOC
-
-/*
-** Thread safe version of malloc, calloc, realloc, free
-*/
-#include <stdarg.h>
-
-#ifdef DEBUG
-#define SANITY
-#define EXTRA_SANITY
-#else
-#undef SANITY
-#undef EXTRA_SANITY
-#endif
-
-/* Forward decls */
-void *_PR_UnlockedMalloc(size_t size);
-void _PR_UnlockedFree(void *ptr);
-void *_PR_UnlockedRealloc(void *ptr, size_t size);
-void *_PR_UnlockedCalloc(size_t n, size_t elsize);
-
-/************************************************************************/
-
-/*
- * ----------------------------------------------------------------------------
- * "THE BEER-WARE LICENSE" (Revision 42):
- * <[email protected]> wrote this file. As long as you retain this notice you
- * can do whatever you want with this stuff. If we meet some day, and you think
- * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
- * ----------------------------------------------------------------------------
- *
- */
-
-/*
- * Defining SANITY will enable some checks which will tell you if the users
- * program did botch something
- */
-
-/*
- * Defining EXTRA_SANITY will enable some checks which are mostly related
- * to internal conditions in malloc.c
- */
-
-/*
- * Very verbose progress on stdout...
- */
-#if 0
-# define TRACE(foo) printf foo
-static int malloc_event;
-#else
-# define TRACE(foo)
-#endif
-
-/* XXX Pick a number, any number */
-# define malloc_pagesize 4096UL
-# define malloc_pageshift 12UL
-
-#ifdef XP_UNIX
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <string.h>
-#include <errno.h>
-#include <sys/types.h>
-#include <sys/mman.h>
-#endif
-
-/*
- * This structure describes a page's worth of chunks.
- */
-
-struct pginfo {
- struct pginfo *next; /* next on the free list */
- char *page; /* Pointer to the page */
- u_short size; /* size of this page's chunks */
- u_short shift; /* How far to shift for this size chunks */
- u_short free; /* How many free chunks */
- u_short total; /* How many chunk */
- u_long bits[1]; /* Which chunks are free */
-};
-
-struct pgfree {
- struct pgfree *next; /* next run of free pages */
- struct pgfree *prev; /* prev run of free pages */
- char *page; /* pointer to free pages */
- char *end; /* pointer to end of free pages */
- u_long size; /* number of bytes free */
-};
-
-/*
- * How many bits per u_long in the bitmap.
- * Change only if not 8 bits/byte
- */
-#define MALLOC_BITS (8*sizeof(u_long))
-
-/*
- * Magic values to put in the page_directory
- */
-#define MALLOC_NOT_MINE ((struct pginfo*) 0)
-#define MALLOC_FREE ((struct pginfo*) 1)
-#define MALLOC_FIRST ((struct pginfo*) 2)
-#define MALLOC_FOLLOW ((struct pginfo*) 3)
-#define MALLOC_MAGIC ((struct pginfo*) 4)
-
-/*
- * Set to one when malloc_init has been called
- */
-static unsigned initialized;
-
-/*
- * The size of a page.
- * Must be a integral multiplum of the granularity of mmap(2).
- * Your toes will curl if it isn't a power of two
- */
-#define malloc_pagemask ((malloc_pagesize)-1)
-
-/*
- * The size of the largest chunk.
- * Half a page.
- */
-#define malloc_maxsize ((malloc_pagesize)>>1)
-
-/*
- * malloc_pagesize == 1 << malloc_pageshift
- */
-#ifndef malloc_pageshift
-static unsigned malloc_pageshift;
-#endif /* malloc_pageshift */
-
-/*
- * The smallest allocation we bother about.
- * Must be power of two
- */
-#ifndef malloc_minsize
-static unsigned malloc_minsize;
-#endif /* malloc_minsize */
-
-/*
- * The largest chunk we care about.
- * Must be smaller than pagesize
- * Must be power of two
- */
-#ifndef malloc_maxsize
-static unsigned malloc_maxsize;
-#endif /* malloc_maxsize */
-
-#ifndef malloc_cache
-static unsigned malloc_cache;
-#endif /* malloc_cache */
-
-/*
- * The offset from pagenumber to index into the page directory
- */
-static u_long malloc_origo;
-
-/*
- * The last index in the page directory we care about
- */
-static u_long last_index;
-
-/*
- * Pointer to page directory.
- * Allocated "as if with" malloc
- */
-static struct pginfo **page_dir;
-
-/*
- * How many slots in the page directory
- */
-static unsigned malloc_ninfo;
-
-/*
- * Free pages line up here
- */
-static struct pgfree free_list;
-
-/*
- * Abort() if we fail to get VM ?
- */
-static int malloc_abort;
-
-#ifdef SANITY
-/*
- * Are we trying to die ?
- */
-static int suicide;
-#endif
-
-/*
- * dump statistics
- */
-static int malloc_stats;
-
-/*
- * always realloc ?
- */
-static int malloc_realloc;
-
-/*
- * my last break.
- */
-static void *malloc_brk;
-
-/*
- * one location cache for free-list holders
- */
-static struct pgfree *px;
-
-static int set_pgdir(void *ptr, struct pginfo *info);
-static int extend_page_directory(u_long index);
-
-#ifdef SANITY
-void
-malloc_dump(FILE *fd)
-{
- struct pginfo **pd;
- struct pgfree *pf;
- int j;
-
- pd = page_dir;
-
- /* print out all the pages */
- for(j=0;j<=last_index;j++) {
- fprintf(fd,"%08lx %5d ",(j+malloc_origo) << malloc_pageshift,j);
- if (pd[j] == MALLOC_NOT_MINE) {
- for(j++;j<=last_index && pd[j] == MALLOC_NOT_MINE;j++)
- ;
- j--;
- fprintf(fd,".. %5d not mine\n", j);
- } else if (pd[j] == MALLOC_FREE) {
- for(j++;j<=last_index && pd[j] == MALLOC_FREE;j++)
- ;
- j--;
- fprintf(fd,".. %5d free\n", j);
- } else if (pd[j] == MALLOC_FIRST) {
- for(j++;j<=last_index && pd[j] == MALLOC_FOLLOW;j++)
- ;
- j--;
- fprintf(fd,".. %5d in use\n", j);
- } else if (pd[j] < MALLOC_MAGIC) {
- fprintf(fd,"(%p)\n", pd[j]);
- } else {
- fprintf(fd,"%p %d (of %d) x %d @ %p --> %p\n",
- pd[j],pd[j]->free, pd[j]->total,
- pd[j]->size, pd[j]->page, pd[j]->next);
- }
- }
-
- for(pf=free_list.next; pf; pf=pf->next) {
- fprintf(fd,"Free: @%p [%p...%p[ %ld ->%p <-%p\n",
- pf,pf->page,pf->end,pf->size,pf->prev,pf->next);
- if (pf == pf->next) {
- fprintf(fd,"Free_list loops.\n");
- break;
- }
- }
-
- /* print out various info */
- fprintf(fd,"Minsize\t%d\n",malloc_minsize);
- fprintf(fd,"Maxsize\t%ld\n",malloc_maxsize);
- fprintf(fd,"Pagesize\t%ld\n",malloc_pagesize);
- fprintf(fd,"Pageshift\t%ld\n",malloc_pageshift);
- fprintf(fd,"FirstPage\t%ld\n",malloc_origo);
- fprintf(fd,"LastPage\t%ld %lx\n",last_index+malloc_pageshift,
- (last_index + malloc_pageshift) << malloc_pageshift);
- fprintf(fd,"Break\t%ld\n",(u_long)sbrk(0) >> malloc_pageshift);
-}
-
-static void wrterror(char *fmt, ...)
-{
- char *q = "malloc() error: ";
- char buf[100];
- va_list ap;
-
- suicide = 1;
-
- va_start(ap, fmt);
- PR_vsnprintf(buf, sizeof(buf), fmt, ap);
- va_end(ap);
- fputs(q, stderr);
- fputs(buf, stderr);
-
- malloc_dump(stderr);
- PR_Abort();
-}
-
-static void wrtwarning(char *fmt, ...)
-{
- char *q = "malloc() warning: ";
- char buf[100];
- va_list ap;
-
- va_start(ap, fmt);
- PR_vsnprintf(buf, sizeof(buf), fmt, ap);
- va_end(ap);
- fputs(q, stderr);
- fputs(buf, stderr);
-}
-#endif /* SANITY */
-
-
-/*
- * Allocate a number of pages from the OS
- */
-static caddr_t
-map_pages(int pages, int update)
-{
- caddr_t result,tail;
-
- result = ((caddr_t)sbrk(0)) + malloc_pagemask - 1;
- result = (caddr_t) ((u_long)result & ~malloc_pagemask);
- tail = result + (pages << malloc_pageshift);
- if (!brk(tail)) {
- last_index = ((u_long)tail >> malloc_pageshift) - malloc_origo -1;
- malloc_brk = tail;
- TRACE(("%6d S %p .. %p\n",malloc_event++, result, tail));
- if (!update || last_index < malloc_ninfo ||
- extend_page_directory(last_index))
- return result;
- }
- TRACE(("%6d s %d %p %d\n",malloc_event++,pages,sbrk(0),errno));
-#ifdef EXTRA_SANITY
- wrterror("map_pages fails\n");
-#endif
- return 0;
-}
-
-#define set_bit(_pi,_bit) \
- (_pi)->bits[(_bit)/MALLOC_BITS] |= 1L<<((_bit)%MALLOC_BITS)
-
-#define clr_bit(_pi,_bit) \
- (_pi)->bits[(_bit)/MALLOC_BITS] &= ~(1L<<((_bit)%MALLOC_BITS));
-
-#define tst_bit(_pi,_bit) \
- ((_pi)->bits[(_bit)/MALLOC_BITS] & (1L<<((_bit)%MALLOC_BITS)))
-
-/*
- * Extend page directory
- */
-static int
-extend_page_directory(u_long index)
-{
- struct pginfo **young, **old;
- int i;
-
- TRACE(("%6d E %lu\n",malloc_event++,index));
-
- /* Make it this many pages */
- i = index * sizeof *page_dir;
- i /= malloc_pagesize;
- i += 2;
-
- /* Get new pages, if you used this much mem you don't care :-) */
- young = (struct pginfo**) map_pages(i,0);
- if (!young)
- return 0;
-
- /* Copy the old stuff */
- memset(young, 0, i * malloc_pagesize);
- memcpy(young, page_dir,
- malloc_ninfo * sizeof *page_dir);
-
- /* register the new size */
- malloc_ninfo = i * malloc_pagesize / sizeof *page_dir;
-
- /* swap the pointers */
- old = page_dir;
- page_dir = young;
-
- /* Mark the pages */
- index = ((u_long)young >> malloc_pageshift) - malloc_origo;
- page_dir[index] = MALLOC_FIRST;
- while (--i) {
- page_dir[++index] = MALLOC_FOLLOW;
- }
-
- /* Now free the old stuff */
- _PR_UnlockedFree(old);
- return 1;
-}
-
-/*
- * Set entry in page directory.
- * Extend page directory if need be.
- */
-static int
-set_pgdir(void *ptr, struct pginfo *info)
-{
- u_long index = ((u_long)ptr >> malloc_pageshift) - malloc_origo;
-
- if (index >= malloc_ninfo && !extend_page_directory(index))
- return 0;
- page_dir[index] = info;
- return 1;
-}
-
-/*
- * Initialize the world
- */
-static void
-malloc_init (void)
-{
- int i;
- char *p;
-
- TRACE(("%6d I\n",malloc_event++));
-#ifdef DEBUG
- for (p=getenv("MALLOC_OPTIONS"); p && *p; p++) {
- switch (*p) {
- case 'a': malloc_abort = 0; break;
- case 'A': malloc_abort = 1; break;
- case 'd': malloc_stats = 0; break;
- case 'D': malloc_stats = 1; break;
- case 'r': malloc_realloc = 0; break;
- case 'R': malloc_realloc = 1; break;
- default:
- wrtwarning("Unknown chars in MALLOC_OPTIONS\n");
- break;
- }
- }
-#endif
-
-#ifndef malloc_pagesize
- /* determine our pagesize */
- malloc_pagesize = getpagesize();
-#endif /* malloc_pagesize */
-
-#ifndef malloc_pageshift
- /* determine how much we shift by to get there */
- for (i = malloc_pagesize; i > 1; i >>= 1)
- malloc_pageshift++;
-#endif /* malloc_pageshift */
-
-#ifndef malloc_cache
- malloc_cache = 50 << malloc_pageshift;
-#endif /* malloc_cache */
-
-#ifndef malloc_minsize
- /*
- * find the smallest size allocation we will bother about.
- * this is determined as the smallest allocation that can hold
- * it's own pginfo;
- */
- i = 2;
- for(;;) {
- int j;
-
- /* Figure out the size of the bits */
- j = malloc_pagesize/i;
- j /= 8;
- if (j < sizeof(u_long))
- j = sizeof (u_long);
- if (sizeof(struct pginfo) + j - sizeof (u_long) <= i)
- break;
- i += i;
- }
- malloc_minsize = i;
-#endif /* malloc_minsize */
-
-
- /* Allocate one page for the page directory */
- page_dir = (struct pginfo **) map_pages(1,0);
-#ifdef SANITY
- if (!page_dir)
- wrterror("fatal: my first mmap failed. (check limits ?)\n");
-#endif
-
- /*
- * We need a maximum of malloc_pageshift buckets, steal these from the
- * front of the page_directory;
- */
- malloc_origo = (u_long) page_dir >> malloc_pageshift;
- malloc_origo -= malloc_pageshift;
-
- /* Clear it */
- memset(page_dir,0,malloc_pagesize);
-
- /* Find out how much it tells us */
- malloc_ninfo = malloc_pagesize / sizeof *page_dir;
-
- /* Plug the page directory into itself */
- i = set_pgdir(page_dir,MALLOC_FIRST);
-#ifdef SANITY
- if (!i)
- wrterror("fatal: couldn't set myself in the page directory\n");
-#endif
-
- /* Been here, done that */
- initialized++;
-}
-
-/*
- * Allocate a number of complete pages
- */
-static void *malloc_pages(size_t size)
-{
- void *p,*delay_free = 0;
- int i;
- struct pgfree *pf;
- u_long index;
-
- /* How many pages ? */
- size += (malloc_pagesize-1);
- size &= ~malloc_pagemask;
-
- p = 0;
- /* Look for free pages before asking for more */
- for(pf = free_list.next; pf; pf = pf->next) {
-#ifdef EXTRA_SANITY
- if (pf->page == pf->end)
- wrterror("zero entry on free_list\n");
- if (pf->page > pf->end) {
- TRACE(("%6d !s %p %p %p <%d>\n",malloc_event++,
- pf,pf->page,pf->end,__LINE__));
- wrterror("sick entry on free_list\n");
- }
- if ((void*)pf->page >= (void*)sbrk(0))
- wrterror("entry on free_list past brk\n");
- if (page_dir[((u_long)pf->page >> malloc_pageshift) - malloc_origo]
- != MALLOC_FREE) {
- TRACE(("%6d !f %p %p %p <%d>\n",malloc_event++,
- pf,pf->page,pf->end,__LINE__));
- wrterror("non-free first page on free-list\n");
- }
- if (page_dir[((u_long)pf->end >> malloc_pageshift) - 1 - malloc_origo]
- != MALLOC_FREE)
- wrterror("non-free last page on free-list\n");
-#endif /* EXTRA_SANITY */
- if (pf->size < size)
- continue;
- else if (pf->size == size) {
- p = pf->page;
- if (pf->next)
- pf->next->prev = pf->prev;
- pf->prev->next = pf->next;
- delay_free = pf;
- break;
- } else {
- p = pf->page;
- pf->page += size;
- pf->size -= size;
- break;
- }
- }
-#ifdef EXTRA_SANITY
- if (p && page_dir[((u_long)p >> malloc_pageshift) - malloc_origo]
- != MALLOC_FREE) {
- wrterror("allocated non-free page on free-list\n");
- }
-#endif /* EXTRA_SANITY */
-
- size >>= malloc_pageshift;
-
- /* Map new pages */
- if (!p)
- p = map_pages(size,1);
-
- if (p) {
- /* Mark the pages in the directory */
- index = ((u_long)p >> malloc_pageshift) - malloc_origo;
- page_dir[index] = MALLOC_FIRST;
- for (i=1;i<size;i++)
- page_dir[index+i] = MALLOC_FOLLOW;
- }
- if (delay_free) {
- if (!px)
- px = (struct pgfree*)delay_free;
- else
- _PR_UnlockedFree(delay_free);
- }
- return p;
-}
-
-/*
- * Allocate a page of fragments
- */
-
-static int
-malloc_make_chunks(int bits)
-{
- struct pginfo *bp;
- void *pp;
- int i,k,l;
-
- /* Allocate a new bucket */
- pp = malloc_pages(malloc_pagesize);
- if (!pp)
- return 0;
- l = sizeof *bp - sizeof(u_long);
- l += sizeof(u_long) *
- (((malloc_pagesize >> bits)+MALLOC_BITS-1) / MALLOC_BITS);
- if ((1<<(bits)) <= l+l) {
- bp = (struct pginfo *)pp;
- } else {
- bp = (struct pginfo *)_PR_UnlockedMalloc(l);
- }
- if (!bp)
- return 0;
- bp->size = (1<<bits);
- bp->shift = bits;
- bp->total = bp->free = malloc_pagesize >> bits;
- bp->next = page_dir[bits];
- bp->page = (char*)pp;
- i = set_pgdir(pp,bp);
- if (!i)
- return 0;
-
- /* We can safely assume that there is nobody in this chain */
- page_dir[bits] = bp;
-
- /* set all valid bits in the bits */
- k = bp->total;
- i = 0;
-/*
- for(;k-i >= MALLOC_BITS; i += MALLOC_BITS)
- bp->bits[i / MALLOC_BITS] = ~0;
-*/
- for(; i < k; i++)
- set_bit(bp,i);
-
- if (bp != pp)
- return 1;
-
- /* We may have used the first ones already */
- for(i=0;l > 0;i++) {
- clr_bit(bp,i);
- bp->free--;
- bp->total--;
- l -= (1 << bits);
- }
- return 1;
-}
-
-/*
- * Allocate a fragment
- */
-static void *malloc_bytes(size_t size)
-{
- size_t s;
- int j;
- struct pginfo *bp;
- int k;
- u_long *lp, bf;
-
- /* Don't bother with anything less than this */
- if (size < malloc_minsize) {
- size = malloc_minsize;
- }
-
- /* Find the right bucket */
- j = 1;
- s = size - 1;
- while (s >>= 1) {
- j++;
- }
-
- /* If it's empty, make a page more of that size chunks */
- if (!page_dir[j] && !malloc_make_chunks(j))
- return 0;
-
- /* Find first word of bitmap which isn't empty */
- bp = page_dir[j];
- for (lp = bp->bits; !*lp; lp++)
- ;
-
- /* Find that bit */
- bf = *lp;
- k = 0;
- while ((bf & 1) == 0) {
- bf >>= 1;
- k++;
- }
-
- *lp ^= 1L<<k; /* clear it */
- bp->free--;
- if (!bp->free) {
- page_dir[j] = bp->next;
- bp->next = 0;
- }
- k += (lp - bp->bits)*MALLOC_BITS;
- return bp->page + (k << bp->shift);
-}
-
-void *_PR_UnlockedMalloc(size_t size)
-{
- void *result;
-
- /* Round up to a multiple of 8 bytes */
- if (size & 7) {
- size = size + 8 - (size & 7);
- }
-
- if (!initialized)
- malloc_init();
-
-#ifdef SANITY
- if (suicide)
- PR_Abort();
-#endif
-
- if (size <= malloc_maxsize)
- result = malloc_bytes(size);
- else
- result = malloc_pages(size);
-#ifdef SANITY
- if (malloc_abort && !result)
- wrterror("malloc() returns NULL\n");
-#endif
- TRACE(("%6d M %p %d\n",malloc_event++,result,size));
-
- return result;
-}
-
-void *_PR_UnlockedMemalign(size_t alignment, size_t size)
-{
- void *result;
-
- /*
- * alignment has to be a power of 2
- */
-
- if ((size <= alignment) && (alignment <= malloc_maxsize))
- size = alignment;
- else
- size += alignment - 1;
-
- /* Round up to a multiple of 8 bytes */
- if (size & 7) {
- size = size + 8 - (size & 7);
- }
-
- if (!initialized)
- malloc_init();
-
-#ifdef SANITY
- if (suicide)
- abort();
-#endif
-
- if (size <= malloc_maxsize)
- result = malloc_bytes(size);
- else
- result = malloc_pages(size);
-#ifdef SANITY
- if (malloc_abort && !result)
- wrterror("malloc() returns NULL\n");
-#endif
- TRACE(("%6d A %p %d\n",malloc_event++,result,size));
-
- if ((u_long)result & (alignment - 1))
- return ((void *)(((u_long)result + alignment) & ~(alignment - 1)));
- else
- return result;
-}
-
-void *_PR_UnlockedCalloc(size_t n, size_t nelem)
-{
- void *p;
-
- /* Compute total size and then round up to a double word amount */
- n *= nelem;
- if (n & 7) {
- n = n + 8 - (n & 7);
- }
-
- /* Get the memory */
- p = _PR_UnlockedMalloc(n);
- if (p) {
- /* Zero it */
- memset(p, 0, n);
- }
- return p;
-}
-
-/*
- * Change an allocation's size
- */
-void *_PR_UnlockedRealloc(void *ptr, size_t size)
-{
- void *p;
- u_long osize,page,index,tmp_index;
- struct pginfo **mp;
-
- if (!initialized)
- malloc_init();
-
-#ifdef SANITY
- if (suicide)
- PR_Abort();
-#endif
-
- /* used as free() */
- TRACE(("%6d R %p %d\n",malloc_event++, ptr, size));
- if (ptr && !size) {
- _PR_UnlockedFree(ptr);
- return _PR_UnlockedMalloc (1);
- }
-
- /* used as malloc() */
- if (!ptr) {
- p = _PR_UnlockedMalloc(size);
- return p;
- }
-
- /* Find the page directory entry for the page in question */
- page = (u_long)ptr >> malloc_pageshift;
- index = page - malloc_origo;
-
- /*
- * check if memory was allocated by memalign
- */
- tmp_index = index;
- while (page_dir[tmp_index] == MALLOC_FOLLOW)
- tmp_index--;
- if (tmp_index != index) {
- /*
- * memalign-allocated memory
- */
- index = tmp_index;
- page = index + malloc_origo;
- ptr = (void *) (page << malloc_pageshift);
- }
- TRACE(("%6d R2 %p %d\n",malloc_event++, ptr, size));
-
- /* make sure it makes sense in some fashion */
- if (index < malloc_pageshift || index > last_index) {
-#ifdef SANITY
- wrtwarning("junk pointer passed to realloc()\n");
-#endif
- return 0;
- }
-
- /* find the size of that allocation, and see if we need to relocate */
- mp = &page_dir[index];
- if (*mp == MALLOC_FIRST) {
- osize = malloc_pagesize;
- while (mp[1] == MALLOC_FOLLOW) {
- osize += malloc_pagesize;
- mp++;
- }
- if (!malloc_realloc &&
- size < osize &&
- size > malloc_maxsize &&
- size > (osize - malloc_pagesize)) {
- return ptr;
- }
- } else if (*mp >= MALLOC_MAGIC) {
- osize = (*mp)->size;
- if (!malloc_realloc &&
- size < osize &&
- (size > (*mp)->size/2 || (*mp)->size == malloc_minsize)) {
- return ptr;
- }
- } else {
-#ifdef SANITY
- wrterror("realloc() of wrong page.\n");
-#endif
- }
-
- /* try to reallocate */
- p = _PR_UnlockedMalloc(size);
-
- if (p) {
- /* copy the lesser of the two sizes */
- if (osize < size)
- memcpy(p,ptr,osize);
- else
- memcpy(p,ptr,size);
- _PR_UnlockedFree(ptr);
- }
-#ifdef DEBUG
- else if (malloc_abort)
- wrterror("realloc() returns NULL\n");
-#endif
-
- return p;
-}
-
-/*
- * Free a sequence of pages
- */
-
-static void
-free_pages(char *ptr, u_long page, int index, struct pginfo *info)
-{
- int i;
- struct pgfree *pf,*pt;
- u_long l;
- char *tail;
-
- TRACE(("%6d FP %p %d\n",malloc_event++, ptr, page));
- /* Is it free already ? */
- if (info == MALLOC_FREE) {
-#ifdef SANITY
- wrtwarning("freeing free page at %p.\n", ptr);
-#endif
- return;
- }
-
-#ifdef SANITY
- /* Is it not the right place to begin ? */
- if (info != MALLOC_FIRST)
- wrterror("freeing wrong page.\n");
-
- /* Is this really a pointer to a page ? */
- if ((u_long)ptr & malloc_pagemask)
- wrterror("freeing messed up page pointer.\n");
-#endif
-
- /* Count how many pages it is anyway */
- page_dir[index] = MALLOC_FREE;
- for (i = 1; page_dir[index+i] == MALLOC_FOLLOW; i++)
- page_dir[index + i] = MALLOC_FREE;
-
- l = i << malloc_pageshift;
-
- tail = ptr+l;
-
- /* add to free-list */
- if (!px)
- px = (struct pgfree*)_PR_UnlockedMalloc(sizeof *pt);
- /* XXX check success */
- px->page = ptr;
- px->end = tail;
- px->size = l;
- if (!free_list.next) {
- px->next = free_list.next;
- px->prev = &free_list;
- free_list.next = px;
- pf = px;
- px = 0;
- } else {
- tail = ptr+l;
- for(pf = free_list.next; pf->next && pf->end < ptr; pf = pf->next)
- ;
- for(; pf; pf = pf->next) {
- if (pf->end == ptr ) {
- /* append to entry */
- pf->end += l;
- pf->size += l;
- if (pf->next && pf->end == pf->next->page ) {
- pt = pf->next;
- pf->end = pt->end;
- pf->size += pt->size;
- pf->next = pt->next;
- if (pf->next)
- pf->next->prev = pf;
- _PR_UnlockedFree(pt);
- }
- } else if (pf->page == tail) {
- /* prepend to entry */
- pf->size += l;
- pf->page = ptr;
- } else if (pf->page > ptr) {
- px->next = pf;
- px->prev = pf->prev;
- pf->prev = px;
- px->prev->next = px;
- pf = px;
- px = 0;
- } else if (!pf->next) {
- px->next = 0;
- px->prev = pf;
- pf->next = px;
- pf = px;
- px = 0;
- } else {
- continue;
- }
- break;
- }
- }
- if (!pf->next &&
- pf->size > malloc_cache &&
- pf->end == malloc_brk &&
- malloc_brk == (void*)sbrk(0)) {
- pf->end = pf->page + malloc_cache;
- pf->size = malloc_cache;
- TRACE(("%6d U %p %d\n",malloc_event++,pf->end,pf->end - pf->page));
- brk(pf->end);
- malloc_brk = pf->end;
- /* Find the page directory entry for the page in question */
- page = (u_long)pf->end >> malloc_pageshift;
- index = page - malloc_origo;
- /* Now update the directory */
- for(i=index;i <= last_index;)
- page_dir[i++] = MALLOC_NOT_MINE;
- last_index = index - 1;
- }
-}
-
-/*
- * Free a chunk, and possibly the page it's on, if the page becomes empty.
- */
-
-static void
-free_bytes(void *ptr, u_long page, int index, struct pginfo *info)
-{
- int i;
- struct pginfo **mp;
- void *vp;
-
- /* Make sure that pointer is multiplum of chunk-size */
-#ifdef SANITY
- if ((u_long)ptr & (info->size - 1))
- wrterror("freeing messed up chunk pointer\n");
-#endif
-
- /* Find the chunk number on the page */
- i = ((u_long)ptr & malloc_pagemask) >> info->shift;
-
- /* See if it's free already */
- if (tst_bit(info,i)) {
-#ifdef SANITY
- wrtwarning("freeing free chunk at %p\n", ptr);
-#endif
- return;
- }
-
- /* Mark it free */
- set_bit(info,i);
- info->free++;
-
- /* If the page was full before, we need to put it on the queue now */
- if (info->free == 1) {
- mp = page_dir + info->shift;
- while (*mp && (*mp)->next && (*mp)->next->page < info->page)
- mp = &(*mp)->next;
- info->next = *mp;
- *mp = info;
- return;
- }
-
- /* If this page isn't empty, don't do anything. */
- if (info->free != info->total)
- return;
-
- /* We may want to keep at least one page of each size chunks around. */
- mp = page_dir + info->shift;
- if (0 && (*mp == info) && !info->next)
- return;
-
- /* Find & remove this page in the queue */
- while (*mp != info) {
- mp = &((*mp)->next);
-#ifdef EXTRA_SANITY
- if (!*mp) {
- TRACE(("%6d !q %p\n",malloc_event++,info));
- wrterror("Not on queue\n");
- }
-#endif
- }
- *mp = info->next;
-
- /* Free the page & the info structure if need be */
- set_pgdir(info->page,MALLOC_FIRST);
- if((void*)info->page == (void*)info) {
- _PR_UnlockedFree(info->page);
- } else {
- vp = info->page;
- _PR_UnlockedFree(info);
- _PR_UnlockedFree(vp);
- }
-}
-
-void _PR_UnlockedFree(void *ptr)
-{
- u_long page;
- struct pginfo *info;
- int index, tmp_index;
-
- TRACE(("%6d F %p\n",malloc_event++,ptr));
- /* This is legal */
- if (!ptr)
- return;
-
-#ifdef SANITY
- /* There wouldn't be anything to free */
- if (!initialized) {
- wrtwarning("free() called before malloc() ever got called\n");
- return;
- }
-#endif
-
-#ifdef SANITY
- if (suicide)
- PR_Abort();
-#endif
-
- /* Find the page directory entry for the page in question */
- page = (u_long)ptr >> malloc_pageshift;
- index = page - malloc_origo;
-
- /*
- * check if memory was allocated by memalign
- */
- tmp_index = index;
- while (page_dir[tmp_index] == MALLOC_FOLLOW)
- tmp_index--;
- if (tmp_index != index) {
- /*
- * memalign-allocated memory
- */
- index = tmp_index;
- page = index + malloc_origo;
- ptr = (void *) (page << malloc_pageshift);
- }
- /* make sure it makes sense in some fashion */
- if (index < malloc_pageshift) {
-#ifdef SANITY
- wrtwarning("junk pointer %p (low) passed to free()\n", ptr);
-#endif
- return;
- }
- if (index > last_index) {
-#ifdef SANITY
- wrtwarning("junk pointer %p (high) passed to free()\n", ptr);
-#endif
- return;
- }
-
- /* handle as page-allocation or chunk allocation */
- info = page_dir[index];
- if (info < MALLOC_MAGIC)
- free_pages((char*)ptr, page, index, info);
- else
- free_bytes(ptr,page,index,info);
- return;
-}
-#endif /* _PR_OVERRIDE_MALLOC */
diff --git a/nspr/pr/src/malloc/prmem.c b/nspr/pr/src/malloc/prmem.c
deleted file mode 100644
index e4ae42a..0000000
--- a/nspr/pr/src/malloc/prmem.c
+++ /dev/null
@@ -1,694 +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/. */
-
-/*
-** Thread safe versions of malloc, free, realloc, calloc and cfree.
-*/
-
-#include "primpl.h"
-
-#ifdef _PR_ZONE_ALLOCATOR
-
-/*
-** The zone allocator code must use native mutexes and cannot
-** use PRLocks because PR_NewLock calls PR_Calloc, resulting
-** in cyclic dependency of initialization.
-*/
-
-#include <string.h>
-
-union memBlkHdrUn;
-
-typedef struct MemoryZoneStr {
- union memBlkHdrUn *head; /* free list */
- pthread_mutex_t lock;
- size_t blockSize; /* size of blocks on this free list */
- PRUint32 locked; /* current state of lock */
- PRUint32 contention; /* counter: had to wait for lock */
- PRUint32 hits; /* allocated from free list */
- PRUint32 misses; /* had to call malloc */
- PRUint32 elements; /* on free list */
-} MemoryZone;
-
-typedef union memBlkHdrUn {
- unsigned char filler[48]; /* fix the size of this beast */
- struct memBlkHdrStr {
- union memBlkHdrUn *next;
- MemoryZone *zone;
- size_t blockSize;
- size_t requestedSize;
- PRUint32 magic;
- } s;
-} MemBlockHdr;
-
-#define MEM_ZONES 7
-#define THREAD_POOLS 11 /* prime number for modulus */
-#define ZONE_MAGIC 0x0BADC0DE
-
-static MemoryZone zones[MEM_ZONES][THREAD_POOLS];
-
-static PRBool use_zone_allocator = PR_FALSE;
-
-static void pr_ZoneFree(void *ptr);
-
-void
-_PR_DestroyZones(void)
-{
- int i, j;
-
- if (!use_zone_allocator)
- return;
-
- for (j = 0; j < THREAD_POOLS; j++) {
- for (i = 0; i < MEM_ZONES; i++) {
- MemoryZone *mz = &zones[i][j];
- pthread_mutex_destroy(&mz->lock);
- while (mz->head) {
- MemBlockHdr *hdr = mz->head;
- mz->head = hdr->s.next; /* unlink it */
- free(hdr);
- mz->elements--;
- }
- }
- }
- use_zone_allocator = PR_FALSE;
-}
-
-/*
-** pr_FindSymbolInProg
-**
-** Find the specified data symbol in the program and return
-** its address.
-*/
-
-#ifdef HAVE_DLL
-
-#if defined(USE_DLFCN) && !defined(NO_DLOPEN_NULL)
-
-#include <dlfcn.h>
-
-static void *
-pr_FindSymbolInProg(const char *name)
-{
- void *h;
- void *sym;
-
- h = dlopen(0, RTLD_LAZY);
- if (h == NULL)
- return NULL;
- sym = dlsym(h, name);
- (void)dlclose(h);
- return sym;
-}
-
-#elif defined(USE_HPSHL)
-
-#include <dl.h>
-
-static void *
-pr_FindSymbolInProg(const char *name)
-{
- shl_t h = NULL;
- void *sym;
-
- if (shl_findsym(&h, name, TYPE_DATA, &sym) == -1)
- return NULL;
- return sym;
-}
-
-#elif defined(USE_MACH_DYLD) || defined(NO_DLOPEN_NULL)
-
-static void *
-pr_FindSymbolInProg(const char *name)
-{
- /* FIXME: not implemented */
- return NULL;
-}
-
-#else
-
-#error "The zone allocator is not supported on this platform"
-
-#endif
-
-#else /* !defined(HAVE_DLL) */
-
-static void *
-pr_FindSymbolInProg(const char *name)
-{
- /* can't be implemented */
- return NULL;
-}
-
-#endif /* HAVE_DLL */
-
-void
-_PR_InitZones(void)
-{
- int i, j;
- char *envp;
- PRBool *sym;
-
- if ((sym = (PRBool *)pr_FindSymbolInProg("nspr_use_zone_allocator")) != NULL) {
- use_zone_allocator = *sym;
- } else if ((envp = getenv("NSPR_USE_ZONE_ALLOCATOR")) != NULL) {
- use_zone_allocator = (atoi(envp) == 1);
- }
-
- if (!use_zone_allocator)
- return;
-
- for (j = 0; j < THREAD_POOLS; j++) {
- for (i = 0; i < MEM_ZONES; i++) {
- MemoryZone *mz = &zones[i][j];
- int rv = pthread_mutex_init(&mz->lock, NULL);
- PR_ASSERT(0 == rv);
- if (rv != 0) {
- goto loser;
- }
- mz->blockSize = 16 << ( 2 * i);
- }
- }
- return;
-
-loser:
- _PR_DestroyZones();
- return;
-}
-
-PR_IMPLEMENT(void)
-PR_FPrintZoneStats(PRFileDesc *debug_out)
-{
- int i, j;
-
- for (j = 0; j < THREAD_POOLS; j++) {
- for (i = 0; i < MEM_ZONES; i++) {
- MemoryZone *mz = &zones[i][j];
- MemoryZone zone = *mz;
- if (zone.elements || zone.misses || zone.hits) {
- PR_fprintf(debug_out,
-"pool: %d, zone: %d, size: %d, free: %d, hit: %d, miss: %d, contend: %d\n",
- j, i, zone.blockSize, zone.elements,
- zone.hits, zone.misses, zone.contention);
- }
- }
- }
-}
-
-static void *
-pr_ZoneMalloc(PRUint32 size)
-{
- void *rv;
- unsigned int zone;
- size_t blockSize;
- MemBlockHdr *mb, *mt;
- MemoryZone *mz;
-
- /* Always allocate a non-zero amount of bytes */
- if (size < 1) {
- size = 1;
- }
- for (zone = 0, blockSize = 16; zone < MEM_ZONES; ++zone, blockSize <<= 2) {
- if (size <= blockSize) {
- break;
- }
- }
- if (zone < MEM_ZONES) {
- pthread_t me = pthread_self();
- unsigned int pool = (PRUptrdiff)me % THREAD_POOLS;
- PRUint32 wasLocked;
- mz = &zones[zone][pool];
- wasLocked = mz->locked;
- pthread_mutex_lock(&mz->lock);
- mz->locked = 1;
- if (wasLocked)
- mz->contention++;
- if (mz->head) {
- mb = mz->head;
- PR_ASSERT(mb->s.magic == ZONE_MAGIC);
- PR_ASSERT(mb->s.zone == mz);
- PR_ASSERT(mb->s.blockSize == blockSize);
- PR_ASSERT(mz->blockSize == blockSize);
-
- mt = (MemBlockHdr *)(((char *)(mb + 1)) + blockSize);
- PR_ASSERT(mt->s.magic == ZONE_MAGIC);
- PR_ASSERT(mt->s.zone == mz);
- PR_ASSERT(mt->s.blockSize == blockSize);
-
- mz->hits++;
- mz->elements--;
- mz->head = mb->s.next; /* take off free list */
- mz->locked = 0;
- pthread_mutex_unlock(&mz->lock);
-
- mt->s.next = mb->s.next = NULL;
- mt->s.requestedSize = mb->s.requestedSize = size;
-
- rv = (void *)(mb + 1);
- return rv;
- }
-
- mz->misses++;
- mz->locked = 0;
- pthread_mutex_unlock(&mz->lock);
-
- mb = (MemBlockHdr *)malloc(blockSize + 2 * (sizeof *mb));
- if (!mb) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
- mb->s.next = NULL;
- mb->s.zone = mz;
- mb->s.magic = ZONE_MAGIC;
- mb->s.blockSize = blockSize;
- mb->s.requestedSize = size;
-
- mt = (MemBlockHdr *)(((char *)(mb + 1)) + blockSize);
- memcpy(mt, mb, sizeof *mb);
-
- rv = (void *)(mb + 1);
- return rv;
- }
-
- /* size was too big. Create a block with no zone */
- blockSize = (size & 15) ? size + 16 - (size & 15) : size;
- mb = (MemBlockHdr *)malloc(blockSize + 2 * (sizeof *mb));
- if (!mb) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
- mb->s.next = NULL;
- mb->s.zone = NULL;
- mb->s.magic = ZONE_MAGIC;
- mb->s.blockSize = blockSize;
- mb->s.requestedSize = size;
-
- mt = (MemBlockHdr *)(((char *)(mb + 1)) + blockSize);
- memcpy(mt, mb, sizeof *mb);
-
- rv = (void *)(mb + 1);
- return rv;
-}
-
-
-static void *
-pr_ZoneCalloc(PRUint32 nelem, PRUint32 elsize)
-{
- PRUint32 size = nelem * elsize;
- void *p = pr_ZoneMalloc(size);
- if (p) {
- memset(p, 0, size);
- }
- return p;
-}
-
-static void *
-pr_ZoneRealloc(void *oldptr, PRUint32 bytes)
-{
- void *rv;
- MemBlockHdr *mb;
- int ours;
- MemBlockHdr phony;
-
- if (!oldptr)
- return pr_ZoneMalloc(bytes);
- mb = (MemBlockHdr *)((char *)oldptr - (sizeof *mb));
- if (mb->s.magic != ZONE_MAGIC) {
- /* Maybe this just came from ordinary malloc */
-#ifdef DEBUG
- fprintf(stderr,
- "Warning: reallocing memory block %p from ordinary malloc\n",
- oldptr);
-#endif
- /*
- * We are going to realloc oldptr. If realloc succeeds, the
- * original value of oldptr will point to freed memory. So this
- * function must not fail after a successfull realloc call. We
- * must perform any operation that may fail before the realloc
- * call.
- */
- rv = pr_ZoneMalloc(bytes); /* this may fail */
- if (!rv) {
- return rv;
- }
-
- /* We don't know how big it is. But we can fix that. */
- oldptr = realloc(oldptr, bytes);
- /*
- * If realloc returns NULL, this function loses the original
- * value of oldptr. This isn't a leak because the caller of
- * this function still has the original value of oldptr.
- */
- if (!oldptr) {
- if (bytes) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- pr_ZoneFree(rv);
- return oldptr;
- }
- }
- phony.s.requestedSize = bytes;
- mb = &phony;
- ours = 0;
- } else {
- size_t blockSize = mb->s.blockSize;
- MemBlockHdr *mt = (MemBlockHdr *)(((char *)(mb + 1)) + blockSize);
-
- PR_ASSERT(mt->s.magic == ZONE_MAGIC);
- PR_ASSERT(mt->s.zone == mb->s.zone);
- PR_ASSERT(mt->s.blockSize == blockSize);
-
- if (bytes <= blockSize) {
- /* The block is already big enough. */
- mt->s.requestedSize = mb->s.requestedSize = bytes;
- return oldptr;
- }
- ours = 1;
- rv = pr_ZoneMalloc(bytes);
- if (!rv) {
- return rv;
- }
- }
-
- if (oldptr && mb->s.requestedSize)
- memcpy(rv, oldptr, mb->s.requestedSize);
- if (ours)
- pr_ZoneFree(oldptr);
- else if (oldptr)
- free(oldptr);
- return rv;
-}
-
-static void
-pr_ZoneFree(void *ptr)
-{
- MemBlockHdr *mb, *mt;
- MemoryZone *mz;
- size_t blockSize;
- PRUint32 wasLocked;
-
- if (!ptr)
- return;
-
- mb = (MemBlockHdr *)((char *)ptr - (sizeof *mb));
-
- if (mb->s.magic != ZONE_MAGIC) {
- /* maybe this came from ordinary malloc */
-#ifdef DEBUG
- fprintf(stderr,
- "Warning: freeing memory block %p from ordinary malloc\n", ptr);
-#endif
- free(ptr);
- return;
- }
-
- blockSize = mb->s.blockSize;
- mz = mb->s.zone;
- mt = (MemBlockHdr *)(((char *)(mb + 1)) + blockSize);
- PR_ASSERT(mt->s.magic == ZONE_MAGIC);
- PR_ASSERT(mt->s.zone == mz);
- PR_ASSERT(mt->s.blockSize == blockSize);
- if (!mz) {
- PR_ASSERT(blockSize > 65536);
- /* This block was not in any zone. Just free it. */
- free(mb);
- return;
- }
- PR_ASSERT(mz->blockSize == blockSize);
- wasLocked = mz->locked;
- pthread_mutex_lock(&mz->lock);
- mz->locked = 1;
- if (wasLocked)
- mz->contention++;
- mt->s.next = mb->s.next = mz->head; /* put on head of list */
- mz->head = mb;
- mz->elements++;
- mz->locked = 0;
- pthread_mutex_unlock(&mz->lock);
-}
-
-PR_IMPLEMENT(void *) PR_Malloc(PRUint32 size)
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- return use_zone_allocator ? pr_ZoneMalloc(size) : malloc(size);
-}
-
-PR_IMPLEMENT(void *) PR_Calloc(PRUint32 nelem, PRUint32 elsize)
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- return use_zone_allocator ?
- pr_ZoneCalloc(nelem, elsize) : calloc(nelem, elsize);
-}
-
-PR_IMPLEMENT(void *) PR_Realloc(void *ptr, PRUint32 size)
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- return use_zone_allocator ? pr_ZoneRealloc(ptr, size) : realloc(ptr, size);
-}
-
-PR_IMPLEMENT(void) PR_Free(void *ptr)
-{
- if (use_zone_allocator)
- pr_ZoneFree(ptr);
- else
- free(ptr);
-}
-
-#else /* !defined(_PR_ZONE_ALLOCATOR) */
-
-/*
-** The PR_Malloc, PR_Calloc, PR_Realloc, and PR_Free functions simply
-** call their libc equivalents now. This may seem redundant, but it
-** ensures that we are calling into the same runtime library. On
-** Win32, it is possible to have multiple runtime libraries (e.g.,
-** objects compiled with /MD and /MDd) in the same process, and
-** they maintain separate heaps, which cannot be mixed.
-*/
-PR_IMPLEMENT(void *) PR_Malloc(PRUint32 size)
-{
-#if defined (WIN16)
- return PR_MD_malloc( (size_t) size);
-#else
- return malloc(size);
-#endif
-}
-
-PR_IMPLEMENT(void *) PR_Calloc(PRUint32 nelem, PRUint32 elsize)
-{
-#if defined (WIN16)
- return PR_MD_calloc( (size_t)nelem, (size_t)elsize );
-
-#else
- return calloc(nelem, elsize);
-#endif
-}
-
-PR_IMPLEMENT(void *) PR_Realloc(void *ptr, PRUint32 size)
-{
-#if defined (WIN16)
- return PR_MD_realloc( ptr, (size_t) size);
-#else
- return realloc(ptr, size);
-#endif
-}
-
-PR_IMPLEMENT(void) PR_Free(void *ptr)
-{
-#if defined (WIN16)
- PR_MD_free( ptr );
-#else
- free(ptr);
-#endif
-}
-
-#endif /* _PR_ZONE_ALLOCATOR */
-
-/*
-** Complexity alert!
-**
-** If malloc/calloc/free (etc.) were implemented to use pr lock's then
-** the entry points could block when called if some other thread had the
-** lock.
-**
-** Most of the time this isn't a problem. However, in the case that we
-** are using the thread safe malloc code after PR_Init but before
-** PR_AttachThread has been called (on a native thread that nspr has yet
-** to be told about) we could get royally screwed if the lock was busy
-** and we tried to context switch the thread away. In this scenario
-** PR_CURRENT_THREAD() == NULL
-**
-** To avoid this unfortunate case, we use the low level locking
-** facilities for malloc protection instead of the slightly higher level
-** locking. This makes malloc somewhat faster so maybe it's a good thing
-** anyway.
-*/
-#ifdef _PR_OVERRIDE_MALLOC
-
-/* Imports */
-extern void *_PR_UnlockedMalloc(size_t size);
-extern void *_PR_UnlockedMemalign(size_t alignment, size_t size);
-extern void _PR_UnlockedFree(void *ptr);
-extern void *_PR_UnlockedRealloc(void *ptr, size_t size);
-extern void *_PR_UnlockedCalloc(size_t n, size_t elsize);
-
-static PRBool _PR_malloc_initialised = PR_FALSE;
-
-#ifdef _PR_PTHREADS
-static pthread_mutex_t _PR_MD_malloc_crustylock;
-
-#define _PR_Lock_Malloc() { \
- if(PR_TRUE == _PR_malloc_initialised) { \
- PRStatus rv; \
- rv = pthread_mutex_lock(&_PR_MD_malloc_crustylock); \
- PR_ASSERT(0 == rv); \
- }
-
-#define _PR_Unlock_Malloc() if(PR_TRUE == _PR_malloc_initialised) { \
- PRStatus rv; \
- rv = pthread_mutex_unlock(&_PR_MD_malloc_crustylock); \
- PR_ASSERT(0 == rv); \
- } \
- }
-#else /* _PR_PTHREADS */
-static _MDLock _PR_MD_malloc_crustylock;
-
-#ifdef IRIX
-#define _PR_Lock_Malloc() { \
- PRIntn _is; \
- if(PR_TRUE == _PR_malloc_initialised) { \
- if (_PR_MD_GET_ATTACHED_THREAD() && \
- !_PR_IS_NATIVE_THREAD( \
- _PR_MD_GET_ATTACHED_THREAD())) \
- _PR_INTSOFF(_is); \
- _PR_MD_LOCK(&_PR_MD_malloc_crustylock); \
- }
-
-#define _PR_Unlock_Malloc() if(PR_TRUE == _PR_malloc_initialised) { \
- _PR_MD_UNLOCK(&_PR_MD_malloc_crustylock); \
- if (_PR_MD_GET_ATTACHED_THREAD() && \
- !_PR_IS_NATIVE_THREAD( \
- _PR_MD_GET_ATTACHED_THREAD())) \
- _PR_INTSON(_is); \
- } \
- }
-#else /* IRIX */
-#define _PR_Lock_Malloc() { \
- PRIntn _is; \
- if(PR_TRUE == _PR_malloc_initialised) { \
- if (_PR_MD_CURRENT_THREAD() && \
- !_PR_IS_NATIVE_THREAD( \
- _PR_MD_CURRENT_THREAD())) \
- _PR_INTSOFF(_is); \
- _PR_MD_LOCK(&_PR_MD_malloc_crustylock); \
- }
-
-#define _PR_Unlock_Malloc() if(PR_TRUE == _PR_malloc_initialised) { \
- _PR_MD_UNLOCK(&_PR_MD_malloc_crustylock); \
- if (_PR_MD_CURRENT_THREAD() && \
- !_PR_IS_NATIVE_THREAD( \
- _PR_MD_CURRENT_THREAD())) \
- _PR_INTSON(_is); \
- } \
- }
-#endif /* IRIX */
-#endif /* _PR_PTHREADS */
-
-PR_IMPLEMENT(PRStatus) _PR_MallocInit(void)
-{
- PRStatus rv = PR_SUCCESS;
-
- if( PR_TRUE == _PR_malloc_initialised ) return PR_SUCCESS;
-
-#ifdef _PR_PTHREADS
- {
- int status;
- pthread_mutexattr_t mattr;
-
- status = _PT_PTHREAD_MUTEXATTR_INIT(&mattr);
- PR_ASSERT(0 == status);
- status = _PT_PTHREAD_MUTEX_INIT(_PR_MD_malloc_crustylock, mattr);
- PR_ASSERT(0 == status);
- status = _PT_PTHREAD_MUTEXATTR_DESTROY(&mattr);
- PR_ASSERT(0 == status);
- }
-#else /* _PR_PTHREADS */
- _MD_NEW_LOCK(&_PR_MD_malloc_crustylock);
-#endif /* _PR_PTHREADS */
-
- if( PR_SUCCESS == rv )
- {
- _PR_malloc_initialised = PR_TRUE;
- }
-
- return rv;
-}
-
-void *malloc(size_t size)
-{
- void *p;
- _PR_Lock_Malloc();
- p = _PR_UnlockedMalloc(size);
- _PR_Unlock_Malloc();
- return p;
-}
-
-#if defined(IRIX)
-void *memalign(size_t alignment, size_t size)
-{
- void *p;
- _PR_Lock_Malloc();
- p = _PR_UnlockedMemalign(alignment, size);
- _PR_Unlock_Malloc();
- return p;
-}
-
-void *valloc(size_t size)
-{
- return(memalign(sysconf(_SC_PAGESIZE),size));
-}
-#endif /* IRIX */
-
-void free(void *ptr)
-{
- _PR_Lock_Malloc();
- _PR_UnlockedFree(ptr);
- _PR_Unlock_Malloc();
-}
-
-void *realloc(void *ptr, size_t size)
-{
- void *p;
- _PR_Lock_Malloc();
- p = _PR_UnlockedRealloc(ptr, size);
- _PR_Unlock_Malloc();
- return p;
-}
-
-void *calloc(size_t n, size_t elsize)
-{
- void *p;
- _PR_Lock_Malloc();
- p = _PR_UnlockedCalloc(n, elsize);
- _PR_Unlock_Malloc();
- return p;
-}
-
-void cfree(void *p)
-{
- _PR_Lock_Malloc();
- _PR_UnlockedFree(p);
- _PR_Unlock_Malloc();
-}
-
-void _PR_InitMem(void)
-{
- PRStatus rv;
- rv = _PR_MallocInit();
- PR_ASSERT(PR_SUCCESS == rv);
-}
-
-#endif /* _PR_OVERRIDE_MALLOC */
diff --git a/nspr/pr/src/md/prosdep.c b/nspr/pr/src/md/prosdep.c
deleted file mode 100644
index 137ffae..0000000
--- a/nspr/pr/src/md/prosdep.c
+++ /dev/null
@@ -1,76 +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/. */
-
-#include "prbit.h"
-#include "prsystem.h"
-
-#ifdef XP_UNIX
-#include <unistd.h>
-#endif
-#ifdef _WIN32
-#include <windows.h>
-#endif
-#ifdef XP_BEOS
-#include <OS.h>
-#endif
-
-PRInt32 _pr_pageShift;
-PRInt32 _pr_pageSize;
-
-/*
-** Get system page size
-*/
-static void GetPageSize(void)
-{
- PRInt32 pageSize;
-
- /* Get page size */
-#ifdef XP_UNIX
-#if defined BSDI || defined AIX \
- || defined LINUX || defined __GNU__ || defined __GLIBC__ \
- || defined FREEBSD || defined NETBSD || defined OPENBSD \
- || defined DARWIN || defined SYMBIAN
- _pr_pageSize = getpagesize();
-#elif defined(HPUX)
- /* I have no idea. Don't get me started. --Rob */
- _pr_pageSize = sysconf(_SC_PAGE_SIZE);
-#else
- _pr_pageSize = sysconf(_SC_PAGESIZE);
-#endif
-#endif /* XP_UNIX */
-
-#ifdef XP_BEOS
- _pr_pageSize = B_PAGE_SIZE;
-#endif
-
-#ifdef XP_PC
-#ifdef _WIN32
- SYSTEM_INFO info;
- GetSystemInfo(&info);
- _pr_pageSize = info.dwPageSize;
-#else
- _pr_pageSize = 4096;
-#endif
-#endif /* XP_PC */
-
- pageSize = _pr_pageSize;
- PR_CEILING_LOG2(_pr_pageShift, pageSize);
-}
-
-PR_IMPLEMENT(PRInt32) PR_GetPageShift(void)
-{
- if (!_pr_pageSize) {
- GetPageSize();
- }
- return _pr_pageShift;
-}
-
-PR_IMPLEMENT(PRInt32) PR_GetPageSize(void)
-{
- if (!_pr_pageSize) {
- GetPageSize();
- }
- return _pr_pageSize;
-}
diff --git a/nspr/pr/src/md/unix/darwin.c b/nspr/pr/src/md/unix/darwin.c
deleted file mode 100644
index 719fc30..0000000
--- a/nspr/pr/src/md/unix/darwin.c
+++ /dev/null
@@ -1,113 +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/. */
-
-#include "primpl.h"
-
-#include <mach/mach_time.h>
-
-void _MD_EarlyInit(void)
-{
-}
-
-/*
- * The multiplier (as a fraction) for converting the Mach absolute time
- * unit to nanoseconds.
- */
-static mach_timebase_info_data_t machTimebaseInfo;
-
-void _PR_Mach_IntervalInit(void)
-{
- kern_return_t rv;
-
- rv = mach_timebase_info(&machTimebaseInfo);
- PR_ASSERT(rv == KERN_SUCCESS);
-}
-
-PRIntervalTime _PR_Mach_GetInterval(void)
-{
- uint64_t time;
-
- /*
- * mach_absolute_time returns the time in the Mach absolute time unit.
- * Convert it to milliseconds. See Mac Technical Q&A QA1398.
- */
- time = mach_absolute_time();
- time = time * machTimebaseInfo.numer / machTimebaseInfo.denom /
- PR_NSEC_PER_MSEC;
- return (PRIntervalTime)time;
-} /* _PR_Mach_GetInterval */
-
-PRIntervalTime _PR_Mach_TicksPerSecond(void)
-{
- return 1000;
-}
-
-PRWord *_MD_HomeGCRegisters(PRThread *t, int isCurrent, int *np)
-{
-#if !defined(_PR_PTHREADS)
- if (isCurrent) {
- (void) setjmp(CONTEXT(t));
- }
- *np = sizeof(CONTEXT(t)) / sizeof(PRWord);
- return (PRWord *) CONTEXT(t);
-#else
- *np = 0;
- return NULL;
-#endif
-}
-
-#if !defined(_PR_PTHREADS)
-void
-_MD_SET_PRIORITY(_MDThread *thread, PRUintn newPri)
-{
- return;
-}
-
-PRStatus
-_MD_InitializeThread(PRThread *thread)
-{
- return PR_SUCCESS;
-}
-
-PRStatus
-_MD_WAIT(PRThread *thread, PRIntervalTime ticks)
-{
- PR_ASSERT(!(thread->flags & _PR_GLOBAL_SCOPE));
- _PR_MD_SWITCH_CONTEXT(thread);
- return PR_SUCCESS;
-}
-
-PRStatus
-_MD_WAKEUP_WAITER(PRThread *thread)
-{
- if (thread) {
- PR_ASSERT(!(thread->flags & _PR_GLOBAL_SCOPE));
- }
- return PR_SUCCESS;
-}
-
-/* These functions should not be called for Darwin */
-void
-_MD_YIELD(void)
-{
- PR_NOT_REACHED("_MD_YIELD should not be called for Darwin.");
-}
-
-PRStatus
-_MD_CREATE_THREAD(
- PRThread *thread,
- void (*start) (void *),
- PRThreadPriority priority,
- PRThreadScope scope,
- PRThreadState state,
- PRUint32 stackSize)
-{
- PR_NOT_REACHED("_MD_CREATE_THREAD should not be called for Darwin.");
- return PR_FAILURE;
-}
-#endif /* ! _PR_PTHREADS */
-
-/* darwin.c */
-
diff --git a/nspr/pr/src/md/unix/linux.c b/nspr/pr/src/md/unix/linux.c
deleted file mode 100644
index 1b485a0..0000000
--- a/nspr/pr/src/md/unix/linux.c
+++ /dev/null
@@ -1,91 +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/. */
-
-#include "primpl.h"
-
-void _MD_EarlyInit(void)
-{
-}
-
-PRWord *_MD_HomeGCRegisters(PRThread *t, int isCurrent, int *np)
-{
-#ifndef _PR_PTHREADS
- if (isCurrent) {
- (void) setjmp(CONTEXT(t));
- }
- *np = sizeof(CONTEXT(t)) / sizeof(PRWord);
- return (PRWord *) CONTEXT(t);
-#else
- *np = 0;
- return NULL;
-#endif
-}
-
-#ifdef _PR_PTHREADS
-
-extern void _MD_unix_terminate_waitpid_daemon(void);
-
-void _MD_CleanupBeforeExit(void)
-{
- _MD_unix_terminate_waitpid_daemon();
-}
-
-#else /* ! _PR_PTHREADS */
-
-void
-_MD_SET_PRIORITY(_MDThread *thread, PRUintn newPri)
-{
- return;
-}
-
-PRStatus
-_MD_InitializeThread(PRThread *thread)
-{
- /*
- * set the pointers to the stack-pointer and frame-pointer words in the
- * context structure; this is for debugging use.
- */
- thread->md.sp = _MD_GET_SP_PTR(thread);
- thread->md.fp = _MD_GET_FP_PTR(thread);
- return PR_SUCCESS;
-}
-
-PRStatus
-_MD_WAIT(PRThread *thread, PRIntervalTime ticks)
-{
- PR_ASSERT(!(thread->flags & _PR_GLOBAL_SCOPE));
- _PR_MD_SWITCH_CONTEXT(thread);
- return PR_SUCCESS;
-}
-
-PRStatus
-_MD_WAKEUP_WAITER(PRThread *thread)
-{
- if (thread) {
- PR_ASSERT(!(thread->flags & _PR_GLOBAL_SCOPE));
- }
- return PR_SUCCESS;
-}
-
-/* These functions should not be called for Linux */
-void
-_MD_YIELD(void)
-{
- PR_NOT_REACHED("_MD_YIELD should not be called for Linux.");
-}
-
-PRStatus
-_MD_CREATE_THREAD(
- PRThread *thread,
- void (*start) (void *),
- PRThreadPriority priority,
- PRThreadScope scope,
- PRThreadState state,
- PRUint32 stackSize)
-{
- PR_NOT_REACHED("_MD_CREATE_THREAD should not be called for Linux.");
- return PR_FAILURE;
-}
-#endif /* ! _PR_PTHREADS */
diff --git a/nspr/pr/src/md/unix/os_Darwin.s b/nspr/pr/src/md/unix/os_Darwin.s
deleted file mode 100644
index 26a0b92..0000000
--- a/nspr/pr/src/md/unix/os_Darwin.s
+++ /dev/null
@@ -1,13 +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/.
-
-#ifdef __i386__
-#include "os_Darwin_x86.s"
-#elif defined(__x86_64__)
-#include "os_Darwin_x86_64.s"
-#elif defined(__ppc__)
-#include "os_Darwin_ppc.s"
-#endif
diff --git a/nspr/pr/src/md/unix/os_Darwin_x86.s b/nspr/pr/src/md/unix/os_Darwin_x86.s
deleted file mode 100644
index fc6379f..0000000
--- a/nspr/pr/src/md/unix/os_Darwin_x86.s
+++ /dev/null
@@ -1,80 +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/.
-
-#
-# Based on os_Linux_x86.s
-#
-
-#
-# PRInt32 __PR_Darwin_x86_AtomicIncrement(PRInt32 *val);
-#
-# Atomically increment the integer pointed to by 'val' and return
-# the result of the increment.
-#
- .text
- .globl __PR_Darwin_x86_AtomicIncrement
- .private_extern __PR_Darwin_x86_AtomicIncrement
- .align 4
-__PR_Darwin_x86_AtomicIncrement:
- movl 4(%esp), %ecx
- movl $1, %eax
- lock
- xaddl %eax, (%ecx)
- incl %eax
- ret
-
-#
-# PRInt32 __PR_Darwin_x86_AtomicDecrement(PRInt32 *val);
-#
-# Atomically decrement the integer pointed to by 'val' and return
-# the result of the decrement.
-#
- .text
- .globl __PR_Darwin_x86_AtomicDecrement
- .private_extern __PR_Darwin_x86_AtomicDecrement
- .align 4
-__PR_Darwin_x86_AtomicDecrement:
- movl 4(%esp), %ecx
- movl $-1, %eax
- lock
- xaddl %eax, (%ecx)
- decl %eax
- ret
-
-#
-# PRInt32 __PR_Darwin_x86_AtomicSet(PRInt32 *val, PRInt32 newval);
-#
-# Atomically set the integer pointed to by 'val' to the new
-# value 'newval' and return the old value.
-#
- .text
- .globl __PR_Darwin_x86_AtomicSet
- .private_extern __PR_Darwin_x86_AtomicSet
- .align 4
-__PR_Darwin_x86_AtomicSet:
- movl 4(%esp), %ecx
- movl 8(%esp), %eax
- xchgl %eax, (%ecx)
- ret
-
-#
-# PRInt32 __PR_Darwin_x86_AtomicAdd(PRInt32 *ptr, PRInt32 val);
-#
-# Atomically add 'val' to the integer pointed to by 'ptr'
-# and return the result of the addition.
-#
- .text
- .globl __PR_Darwin_x86_AtomicAdd
- .private_extern __PR_Darwin_x86_AtomicAdd
- .align 4
-__PR_Darwin_x86_AtomicAdd:
- movl 4(%esp), %ecx
- movl 8(%esp), %eax
- movl %eax, %edx
- lock
- xaddl %eax, (%ecx)
- addl %edx, %eax
- ret
diff --git a/nspr/pr/src/md/unix/os_Darwin_x86_64.s b/nspr/pr/src/md/unix/os_Darwin_x86_64.s
deleted file mode 100644
index 449aaa5..0000000
--- a/nspr/pr/src/md/unix/os_Darwin_x86_64.s
+++ /dev/null
@@ -1,67 +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/.
-
-# PRInt32 __PR_Darwin_x86_64_AtomicIncrement(PRInt32 *val)
-#
-# Atomically increment the integer pointed to by 'val' and return
-# the result of the increment.
-#
- .text
- .globl __PR_Darwin_x86_64_AtomicIncrement
- .private_extern __PR_Darwin_x86_64_AtomicIncrement
- .align 4
-__PR_Darwin_x86_64_AtomicIncrement:
- movl $1, %eax
- lock
- xaddl %eax, (%rdi)
- incl %eax
- ret
-
-# PRInt32 __PR_Darwin_x86_64_AtomicDecrement(PRInt32 *val)
-#
-# Atomically decrement the integer pointed to by 'val' and return
-# the result of the decrement.
-#
- .text
- .globl __PR_Darwin_x86_64_AtomicDecrement
- .private_extern __PR_Darwin_x86_64_AtomicDecrement
- .align 4
-__PR_Darwin_x86_64_AtomicDecrement:
- movl $-1, %eax
- lock
- xaddl %eax, (%rdi)
- decl %eax
- ret
-
-# PRInt32 __PR_Darwin_x86_64_AtomicSet(PRInt32 *val, PRInt32 newval)
-#
-# Atomically set the integer pointed to by 'val' to the new
-# value 'newval' and return the old value.
-#
- .text
- .globl __PR_Darwin_x86_64_AtomicSet
- .private_extern __PR_Darwin_x86_64_AtomicSet
- .align 4
-__PR_Darwin_x86_64_AtomicSet:
- movl %esi, %eax
- xchgl %eax, (%rdi)
- ret
-
-# PRInt32 __PR_Darwin_x86_64_AtomicAdd(PRInt32 *ptr, PRInt32 val)
-#
-# Atomically add 'val' to the integer pointed to by 'ptr'
-# and return the result of the addition.
-#
- .text
- .globl __PR_Darwin_x86_64_AtomicAdd
- .private_extern __PR_Darwin_x86_64_AtomicAdd
- .align 4
-__PR_Darwin_x86_64_AtomicAdd:
- movl %esi, %eax
- lock
- xaddl %eax, (%rdi)
- addl %esi, %eax
- ret
diff --git a/nspr/pr/src/md/unix/os_Linux_x86.s b/nspr/pr/src/md/unix/os_Linux_x86.s
deleted file mode 100644
index a72acf5..0000000
--- a/nspr/pr/src/md/unix/os_Linux_x86.s
+++ /dev/null
@@ -1,85 +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/.
-
-// PRInt32 _PR_x86_AtomicIncrement(PRInt32 *val)
-//
-// Atomically increment the integer pointed to by 'val' and return
-// the result of the increment.
-//
- .text
- .globl _PR_x86_AtomicIncrement
- .align 4
-_PR_x86_AtomicIncrement:
- movl 4(%esp), %ecx
- movl $1, %eax
- lock
- xaddl %eax, (%ecx)
- incl %eax
- ret
-
-// PRInt32 _PR_x86_AtomicDecrement(PRInt32 *val)
-//
-// Atomically decrement the integer pointed to by 'val' and return
-// the result of the decrement.
-//
- .text
- .globl _PR_x86_AtomicDecrement
- .align 4
-_PR_x86_AtomicDecrement:
- movl 4(%esp), %ecx
- movl $-1, %eax
- lock
- xaddl %eax, (%ecx)
- decl %eax
- ret
-
-// PRInt32 _PR_x86_AtomicSet(PRInt32 *val, PRInt32 newval)
-//
-// Atomically set the integer pointed to by 'val' to the new
-// value 'newval' and return the old value.
-//
-// An alternative implementation:
-// .text
-// .globl _PR_x86_AtomicSet
-// .align 4
-//_PR_x86_AtomicSet:
-// movl 4(%esp), %ecx
-// movl 8(%esp), %edx
-// movl (%ecx), %eax
-//retry:
-// lock
-// cmpxchgl %edx, (%ecx)
-// jne retry
-// ret
-//
- .text
- .globl _PR_x86_AtomicSet
- .align 4
-_PR_x86_AtomicSet:
- movl 4(%esp), %ecx
- movl 8(%esp), %eax
- xchgl %eax, (%ecx)
- ret
-
-// PRInt32 _PR_x86_AtomicAdd(PRInt32 *ptr, PRInt32 val)
-//
-// Atomically add 'val' to the integer pointed to by 'ptr'
-// and return the result of the addition.
-//
- .text
- .globl _PR_x86_AtomicAdd
- .align 4
-_PR_x86_AtomicAdd:
- movl 4(%esp), %ecx
- movl 8(%esp), %eax
- movl %eax, %edx
- lock
- xaddl %eax, (%ecx)
- addl %edx, %eax
- ret
-
-// Magic indicating no need for an executable stack
-.section .note.GNU-stack, "", @progbits ; .previous
diff --git a/nspr/pr/src/md/unix/os_Linux_x86_64.s b/nspr/pr/src/md/unix/os_Linux_x86_64.s
deleted file mode 100644
index 8e491f0..0000000
--- a/nspr/pr/src/md/unix/os_Linux_x86_64.s
+++ /dev/null
@@ -1,74 +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/.
-
-// PRInt32 _PR_x86_64_AtomicIncrement(PRInt32 *val)
-//
-// Atomically increment the integer pointed to by 'val' and return
-// the result of the increment.
-//
- .text
- .globl _PR_x86_64_AtomicIncrement
- .type _PR_x86_64_AtomicIncrement, @function
- .align 4
-_PR_x86_64_AtomicIncrement:
- movl $1, %eax
- lock
- xaddl %eax, (%rdi)
- incl %eax
- ret
- .size _PR_x86_64_AtomicIncrement, .-_PR_x86_64_AtomicIncrement
-
-// PRInt32 _PR_x86_64_AtomicDecrement(PRInt32 *val)
-//
-// Atomically decrement the integer pointed to by 'val' and return
-// the result of the decrement.
-//
- .text
- .globl _PR_x86_64_AtomicDecrement
- .type _PR_x86_64_AtomicDecrement, @function
- .align 4
-_PR_x86_64_AtomicDecrement:
- movl $-1, %eax
- lock
- xaddl %eax, (%rdi)
- decl %eax
- ret
- .size _PR_x86_64_AtomicDecrement, .-_PR_x86_64_AtomicDecrement
-
-// PRInt32 _PR_x86_64_AtomicSet(PRInt32 *val, PRInt32 newval)
-//
-// Atomically set the integer pointed to by 'val' to the new
-// value 'newval' and return the old value.
-//
- .text
- .globl _PR_x86_64_AtomicSet
- .type _PR_x86_64_AtomicSet, @function
- .align 4
-_PR_x86_64_AtomicSet:
- movl %esi, %eax
- xchgl %eax, (%rdi)
- ret
- .size _PR_x86_64_AtomicSet, .-_PR_x86_64_AtomicSet
-
-// PRInt32 _PR_x86_64_AtomicAdd(PRInt32 *ptr, PRInt32 val)
-//
-// Atomically add 'val' to the integer pointed to by 'ptr'
-// and return the result of the addition.
-//
- .text
- .globl _PR_x86_64_AtomicAdd
- .type _PR_x86_64_AtomicAdd, @function
- .align 4
-_PR_x86_64_AtomicAdd:
- movl %esi, %eax
- lock
- xaddl %eax, (%rdi)
- addl %esi, %eax
- ret
- .size _PR_x86_64_AtomicAdd, .-_PR_x86_64_AtomicAdd
-
-// Magic indicating no need for an executable stack
-.section .note.GNU-stack, "", @progbits ; .previous
diff --git a/nspr/pr/src/md/unix/unix.c b/nspr/pr/src/md/unix/unix.c
deleted file mode 100644
index fdae119..0000000
--- a/nspr/pr/src/md/unix/unix.c
+++ /dev/null
@@ -1,3787 +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/. */
-
-#include "primpl.h"
-
-#include <string.h>
-#include <signal.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/time.h>
-#include <sys/ioctl.h>
-#include <sys/mman.h>
-#include <unistd.h>
-#include <sys/utsname.h>
-
-#ifdef _PR_POLL_AVAILABLE
-#include <poll.h>
-#endif
-
-#if defined(ANDROID)
-#include <android/api-level.h>
-#endif
-
-/* To get FIONREAD */
-#if defined(UNIXWARE)
-#include <sys/filio.h>
-#endif
-
-#if defined(NTO)
-#include <sys/statvfs.h>
-#endif
-
-/*
- * Make sure _PRSockLen_t is 32-bit, because we will cast a PRUint32* or
- * PRInt32* pointer to a _PRSockLen_t* pointer.
- */
-#if defined(HAVE_SOCKLEN_T) \
- || (defined(__GLIBC__) && __GLIBC__ >= 2)
-#define _PRSockLen_t socklen_t
-#elif defined(IRIX) || defined(HPUX) || defined(OSF1) || defined(SOLARIS) \
- || defined(AIX4_1) || defined(LINUX) \
- || defined(BSDI) || defined(SCO) \
- || defined(DARWIN) \
- || defined(QNX)
-#define _PRSockLen_t int
-#elif (defined(AIX) && !defined(AIX4_1)) || defined(FREEBSD) \
- || defined(NETBSD) || defined(OPENBSD) || defined(UNIXWARE) \
- || defined(DGUX) || defined(NTO) || defined(RISCOS)
-#define _PRSockLen_t size_t
-#else
-#error "Cannot determine architecture"
-#endif
-
-/*
-** Global lock variable used to bracket calls into rusty libraries that
-** aren't thread safe (like libc, libX, etc).
-*/
-static PRLock *_pr_rename_lock = NULL;
-static PRMonitor *_pr_Xfe_mon = NULL;
-
-static PRInt64 minus_one;
-
-sigset_t timer_set;
-
-#if !defined(_PR_PTHREADS)
-
-static sigset_t empty_set;
-
-#ifdef SOLARIS
-#include <sys/file.h>
-#include <sys/filio.h>
-#endif
-
-#ifndef PIPE_BUF
-#define PIPE_BUF 512
-#endif
-
-/*
- * _nspr_noclock - if set clock interrupts are disabled
- */
-int _nspr_noclock = 1;
-
-#ifdef IRIX
-extern PRInt32 _nspr_terminate_on_error;
-#endif
-
-/*
- * There is an assertion in this code that NSPR's definition of PRIOVec
- * is bit compatible with UNIX' definition of a struct iovec. This is
- * applicable to the 'writev()' operations where the types are casually
- * cast to avoid warnings.
- */
-
-int _pr_md_pipefd[2] = { -1, -1 };
-static char _pr_md_pipebuf[PIPE_BUF];
-static PRInt32 local_io_wait(PRInt32 osfd, PRInt32 wait_flag,
- PRIntervalTime timeout);
-
-_PRInterruptTable _pr_interruptTable[] = {
- {
- "clock", _PR_MISSED_CLOCK, _PR_ClockInterrupt, },
- {
- 0 }
-};
-
-void _MD_unix_init_running_cpu(_PRCPU *cpu)
-{
- PR_INIT_CLIST(&(cpu->md.md_unix.ioQ));
- cpu->md.md_unix.ioq_max_osfd = -1;
- cpu->md.md_unix.ioq_timeout = PR_INTERVAL_NO_TIMEOUT;
-}
-
-PRStatus _MD_open_dir(_MDDir *d, const char *name)
-{
-int err;
-
- d->d = opendir(name);
- if (!d->d) {
- err = _MD_ERRNO();
- _PR_MD_MAP_OPENDIR_ERROR(err);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-PRInt32 _MD_close_dir(_MDDir *d)
-{
-int rv = 0, err;
-
- if (d->d) {
- rv = closedir(d->d);
- if (rv == -1) {
- err = _MD_ERRNO();
- _PR_MD_MAP_CLOSEDIR_ERROR(err);
- }
- }
- return rv;
-}
-
-char * _MD_read_dir(_MDDir *d, PRIntn flags)
-{
-struct dirent *de;
-int err;
-
- for (;;) {
- /*
- * XXX: readdir() is not MT-safe. There is an MT-safe version
- * readdir_r() on some systems.
- */
- _MD_ERRNO() = 0;
- de = readdir(d->d);
- if (!de) {
- err = _MD_ERRNO();
- _PR_MD_MAP_READDIR_ERROR(err);
- return 0;
- }
- if ((flags & PR_SKIP_DOT) &&
- (de->d_name[0] == '.') && (de->d_name[1] == 0))
- continue;
- if ((flags & PR_SKIP_DOT_DOT) &&
- (de->d_name[0] == '.') && (de->d_name[1] == '.') &&
- (de->d_name[2] == 0))
- continue;
- if ((flags & PR_SKIP_HIDDEN) && (de->d_name[0] == '.'))
- continue;
- break;
- }
- return de->d_name;
-}
-
-PRInt32 _MD_delete(const char *name)
-{
-PRInt32 rv, err;
-#ifdef UNIXWARE
- sigset_t set, oset;
-#endif
-
-#ifdef UNIXWARE
- sigfillset(&set);
- sigprocmask(SIG_SETMASK, &set, &oset);
-#endif
- rv = unlink(name);
-#ifdef UNIXWARE
- sigprocmask(SIG_SETMASK, &oset, NULL);
-#endif
- if (rv == -1) {
- err = _MD_ERRNO();
- _PR_MD_MAP_UNLINK_ERROR(err);
- }
- return(rv);
-}
-
-PRInt32 _MD_rename(const char *from, const char *to)
-{
- PRInt32 rv = -1, err;
-
- /*
- ** This is trying to enforce the semantics of WINDOZE' rename
- ** operation. That means one is not allowed to rename over top
- ** of an existing file. Holding a lock across these two function
- ** and the open function is known to be a bad idea, but ....
- */
- if (NULL != _pr_rename_lock)
- PR_Lock(_pr_rename_lock);
- if (0 == access(to, F_OK))
- PR_SetError(PR_FILE_EXISTS_ERROR, 0);
- else
- {
- rv = rename(from, to);
- if (rv < 0) {
- err = _MD_ERRNO();
- _PR_MD_MAP_RENAME_ERROR(err);
- }
- }
- if (NULL != _pr_rename_lock)
- PR_Unlock(_pr_rename_lock);
- return rv;
-}
-
-PRInt32 _MD_access(const char *name, PRAccessHow how)
-{
-PRInt32 rv, err;
-int amode;
-
- switch (how) {
- case PR_ACCESS_WRITE_OK:
- amode = W_OK;
- break;
- case PR_ACCESS_READ_OK:
- amode = R_OK;
- break;
- case PR_ACCESS_EXISTS:
- amode = F_OK;
- break;
- default:
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- rv = -1;
- goto done;
- }
- rv = access(name, amode);
-
- if (rv < 0) {
- err = _MD_ERRNO();
- _PR_MD_MAP_ACCESS_ERROR(err);
- }
-
-done:
- return(rv);
-}
-
-PRInt32 _MD_mkdir(const char *name, PRIntn mode)
-{
-int rv, err;
-
- /*
- ** This lock is used to enforce rename semantics as described
- ** in PR_Rename. Look there for more fun details.
- */
- if (NULL !=_pr_rename_lock)
- PR_Lock(_pr_rename_lock);
- rv = mkdir(name, mode);
- if (rv < 0) {
- err = _MD_ERRNO();
- _PR_MD_MAP_MKDIR_ERROR(err);
- }
- if (NULL !=_pr_rename_lock)
- PR_Unlock(_pr_rename_lock);
- return rv;
-}
-
-PRInt32 _MD_rmdir(const char *name)
-{
-int rv, err;
-
- rv = rmdir(name);
- if (rv == -1) {
- err = _MD_ERRNO();
- _PR_MD_MAP_RMDIR_ERROR(err);
- }
- return rv;
-}
-
-PRInt32 _MD_read(PRFileDesc *fd, void *buf, PRInt32 amount)
-{
-PRThread *me = _PR_MD_CURRENT_THREAD();
-PRInt32 rv, err;
-#ifndef _PR_USE_POLL
-fd_set rd;
-#else
-struct pollfd pfd;
-#endif /* _PR_USE_POLL */
-PRInt32 osfd = fd->secret->md.osfd;
-
-#ifndef _PR_USE_POLL
- FD_ZERO(&rd);
- FD_SET(osfd, &rd);
-#else
- pfd.fd = osfd;
- pfd.events = POLLIN;
-#endif /* _PR_USE_POLL */
- while ((rv = read(osfd,buf,amount)) == -1) {
- err = _MD_ERRNO();
- if ((err == EAGAIN) || (err == EWOULDBLOCK)) {
- if (fd->secret->nonblocking) {
- break;
- }
- if (!_PR_IS_NATIVE_THREAD(me)) {
- if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_READ,
- PR_INTERVAL_NO_TIMEOUT)) < 0)
- goto done;
- } else {
-#ifndef _PR_USE_POLL
- while ((rv = _MD_SELECT(osfd + 1, &rd, NULL, NULL, NULL))
- == -1 && (err = _MD_ERRNO()) == EINTR) {
- /* retry _MD_SELECT() if it is interrupted */
- }
-#else /* _PR_USE_POLL */
- while ((rv = _MD_POLL(&pfd, 1, -1))
- == -1 && (err = _MD_ERRNO()) == EINTR) {
- /* retry _MD_POLL() if it is interrupted */
- }
-#endif /* _PR_USE_POLL */
- if (rv == -1) {
- break;
- }
- }
- if (_PR_PENDING_INTERRUPT(me))
- break;
- } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))){
- continue;
- } else {
- break;
- }
- }
- if (rv < 0) {
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- } else {
- _PR_MD_MAP_READ_ERROR(err);
- }
- }
-done:
- return(rv);
-}
-
-PRInt32 _MD_write(PRFileDesc *fd, const void *buf, PRInt32 amount)
-{
-PRThread *me = _PR_MD_CURRENT_THREAD();
-PRInt32 rv, err;
-#ifndef _PR_USE_POLL
-fd_set wd;
-#else
-struct pollfd pfd;
-#endif /* _PR_USE_POLL */
-PRInt32 osfd = fd->secret->md.osfd;
-
-#ifndef _PR_USE_POLL
- FD_ZERO(&wd);
- FD_SET(osfd, &wd);
-#else
- pfd.fd = osfd;
- pfd.events = POLLOUT;
-#endif /* _PR_USE_POLL */
- while ((rv = write(osfd,buf,amount)) == -1) {
- err = _MD_ERRNO();
- if ((err == EAGAIN) || (err == EWOULDBLOCK)) {
- if (fd->secret->nonblocking) {
- break;
- }
- if (!_PR_IS_NATIVE_THREAD(me)) {
- if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_WRITE,
- PR_INTERVAL_NO_TIMEOUT)) < 0)
- goto done;
- } else {
-#ifndef _PR_USE_POLL
- while ((rv = _MD_SELECT(osfd + 1, NULL, &wd, NULL, NULL))
- == -1 && (err = _MD_ERRNO()) == EINTR) {
- /* retry _MD_SELECT() if it is interrupted */
- }
-#else /* _PR_USE_POLL */
- while ((rv = _MD_POLL(&pfd, 1, -1))
- == -1 && (err = _MD_ERRNO()) == EINTR) {
- /* retry _MD_POLL() if it is interrupted */
- }
-#endif /* _PR_USE_POLL */
- if (rv == -1) {
- break;
- }
- }
- if (_PR_PENDING_INTERRUPT(me))
- break;
- } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))){
- continue;
- } else {
- break;
- }
- }
- if (rv < 0) {
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- } else {
- _PR_MD_MAP_WRITE_ERROR(err);
- }
- }
-done:
- return(rv);
-}
-
-PRInt32 _MD_fsync(PRFileDesc *fd)
-{
-PRInt32 rv, err;
-
- rv = fsync(fd->secret->md.osfd);
- if (rv == -1) {
- err = _MD_ERRNO();
- _PR_MD_MAP_FSYNC_ERROR(err);
- }
- return(rv);
-}
-
-PRInt32 _MD_close(PRInt32 osfd)
-{
-PRInt32 rv, err;
-
- rv = close(osfd);
- if (rv == -1) {
- err = _MD_ERRNO();
- _PR_MD_MAP_CLOSE_ERROR(err);
- }
- return(rv);
-}
-
-PRInt32 _MD_socket(PRInt32 domain, PRInt32 type, PRInt32 proto)
-{
- PRInt32 osfd, err;
-
- osfd = socket(domain, type, proto);
-
- if (osfd == -1) {
- err = _MD_ERRNO();
- _PR_MD_MAP_SOCKET_ERROR(err);
- return(osfd);
- }
-
- return(osfd);
-}
-
-PRInt32 _MD_socketavailable(PRFileDesc *fd)
-{
- PRInt32 result;
-
- if (ioctl(fd->secret->md.osfd, FIONREAD, &result) < 0) {
- _PR_MD_MAP_SOCKETAVAILABLE_ERROR(_MD_ERRNO());
- return -1;
- }
- return result;
-}
-
-PRInt64 _MD_socketavailable64(PRFileDesc *fd)
-{
- PRInt64 result;
- LL_I2L(result, _MD_socketavailable(fd));
- return result;
-} /* _MD_socketavailable64 */
-
-#define READ_FD 1
-#define WRITE_FD 2
-
-/*
- * socket_io_wait --
- *
- * wait for socket i/o, periodically checking for interrupt
- *
- * The first implementation uses select(), for platforms without
- * poll(). The second (preferred) implementation uses poll().
- */
-
-#ifndef _PR_USE_POLL
-
-static PRInt32 socket_io_wait(PRInt32 osfd, PRInt32 fd_type,
- PRIntervalTime timeout)
-{
- PRInt32 rv = -1;
- struct timeval tv;
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRIntervalTime epoch, now, elapsed, remaining;
- PRBool wait_for_remaining;
- PRInt32 syserror;
- fd_set rd_wr;
-
- switch (timeout) {
- case PR_INTERVAL_NO_WAIT:
- PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
- break;
- case PR_INTERVAL_NO_TIMEOUT:
- /*
- * This is a special case of the 'default' case below.
- * Please see the comments there.
- */
- tv.tv_sec = _PR_INTERRUPT_CHECK_INTERVAL_SECS;
- tv.tv_usec = 0;
- FD_ZERO(&rd_wr);
- do {
- FD_SET(osfd, &rd_wr);
- if (fd_type == READ_FD)
- rv = _MD_SELECT(osfd + 1, &rd_wr, NULL, NULL, &tv);
- else
- rv = _MD_SELECT(osfd + 1, NULL, &rd_wr, NULL, &tv);
- if (rv == -1 && (syserror = _MD_ERRNO()) != EINTR) {
- _PR_MD_MAP_SELECT_ERROR(syserror);
- break;
- }
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- rv = -1;
- break;
- }
- } while (rv == 0 || (rv == -1 && syserror == EINTR));
- break;
- default:
- now = epoch = PR_IntervalNow();
- remaining = timeout;
- FD_ZERO(&rd_wr);
- do {
- /*
- * We block in _MD_SELECT for at most
- * _PR_INTERRUPT_CHECK_INTERVAL_SECS seconds,
- * so that there is an upper limit on the delay
- * before the interrupt bit is checked.
- */
- wait_for_remaining = PR_TRUE;
- tv.tv_sec = PR_IntervalToSeconds(remaining);
- if (tv.tv_sec > _PR_INTERRUPT_CHECK_INTERVAL_SECS) {
- wait_for_remaining = PR_FALSE;
- tv.tv_sec = _PR_INTERRUPT_CHECK_INTERVAL_SECS;
- tv.tv_usec = 0;
- } else {
- tv.tv_usec = PR_IntervalToMicroseconds(
- remaining -
- PR_SecondsToInterval(tv.tv_sec));
- }
- FD_SET(osfd, &rd_wr);
- if (fd_type == READ_FD)
- rv = _MD_SELECT(osfd + 1, &rd_wr, NULL, NULL, &tv);
- else
- rv = _MD_SELECT(osfd + 1, NULL, &rd_wr, NULL, &tv);
- /*
- * we don't consider EINTR a real error
- */
- if (rv == -1 && (syserror = _MD_ERRNO()) != EINTR) {
- _PR_MD_MAP_SELECT_ERROR(syserror);
- break;
- }
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- rv = -1;
- break;
- }
- /*
- * We loop again if _MD_SELECT timed out or got interrupted
- * by a signal, and the timeout deadline has not passed yet.
- */
- if (rv == 0 || (rv == -1 && syserror == EINTR)) {
- /*
- * If _MD_SELECT timed out, we know how much time
- * we spent in blocking, so we can avoid a
- * PR_IntervalNow() call.
- */
- if (rv == 0) {
- if (wait_for_remaining) {
- now += remaining;
- } else {
- now += PR_SecondsToInterval(tv.tv_sec)
- + PR_MicrosecondsToInterval(tv.tv_usec);
- }
- } else {
- now = PR_IntervalNow();
- }
- elapsed = (PRIntervalTime) (now - epoch);
- if (elapsed >= timeout) {
- PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
- rv = -1;
- break;
- } else {
- remaining = timeout - elapsed;
- }
- }
- } while (rv == 0 || (rv == -1 && syserror == EINTR));
- break;
- }
- return(rv);
-}
-
-#else /* _PR_USE_POLL */
-
-static PRInt32 socket_io_wait(PRInt32 osfd, PRInt32 fd_type,
- PRIntervalTime timeout)
-{
- PRInt32 rv = -1;
- int msecs;
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRIntervalTime epoch, now, elapsed, remaining;
- PRBool wait_for_remaining;
- PRInt32 syserror;
- struct pollfd pfd;
-
- switch (timeout) {
- case PR_INTERVAL_NO_WAIT:
- PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
- break;
- case PR_INTERVAL_NO_TIMEOUT:
- /*
- * This is a special case of the 'default' case below.
- * Please see the comments there.
- */
- msecs = _PR_INTERRUPT_CHECK_INTERVAL_SECS * 1000;
- pfd.fd = osfd;
- if (fd_type == READ_FD) {
- pfd.events = POLLIN;
- } else {
- pfd.events = POLLOUT;
- }
- do {
- rv = _MD_POLL(&pfd, 1, msecs);
- if (rv == -1 && (syserror = _MD_ERRNO()) != EINTR) {
- _PR_MD_MAP_POLL_ERROR(syserror);
- break;
- }
- /*
- * If POLLERR is set, don't process it; retry the operation
- */
- if ((rv == 1) && (pfd.revents & (POLLHUP | POLLNVAL))) {
- rv = -1;
- _PR_MD_MAP_POLL_REVENTS_ERROR(pfd.revents);
- break;
- }
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- rv = -1;
- break;
- }
- } while (rv == 0 || (rv == -1 && syserror == EINTR));
- break;
- default:
- now = epoch = PR_IntervalNow();
- remaining = timeout;
- pfd.fd = osfd;
- if (fd_type == READ_FD) {
- pfd.events = POLLIN;
- } else {
- pfd.events = POLLOUT;
- }
- do {
- /*
- * We block in _MD_POLL for at most
- * _PR_INTERRUPT_CHECK_INTERVAL_SECS seconds,
- * so that there is an upper limit on the delay
- * before the interrupt bit is checked.
- */
- wait_for_remaining = PR_TRUE;
- msecs = PR_IntervalToMilliseconds(remaining);
- if (msecs > _PR_INTERRUPT_CHECK_INTERVAL_SECS * 1000) {
- wait_for_remaining = PR_FALSE;
- msecs = _PR_INTERRUPT_CHECK_INTERVAL_SECS * 1000;
- }
- rv = _MD_POLL(&pfd, 1, msecs);
- /*
- * we don't consider EINTR a real error
- */
- if (rv == -1 && (syserror = _MD_ERRNO()) != EINTR) {
- _PR_MD_MAP_POLL_ERROR(syserror);
- break;
- }
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- rv = -1;
- break;
- }
- /*
- * If POLLERR is set, don't process it; retry the operation
- */
- if ((rv == 1) && (pfd.revents & (POLLHUP | POLLNVAL))) {
- rv = -1;
- _PR_MD_MAP_POLL_REVENTS_ERROR(pfd.revents);
- break;
- }
- /*
- * We loop again if _MD_POLL timed out or got interrupted
- * by a signal, and the timeout deadline has not passed yet.
- */
- if (rv == 0 || (rv == -1 && syserror == EINTR)) {
- /*
- * If _MD_POLL timed out, we know how much time
- * we spent in blocking, so we can avoid a
- * PR_IntervalNow() call.
- */
- if (rv == 0) {
- if (wait_for_remaining) {
- now += remaining;
- } else {
- now += PR_MillisecondsToInterval(msecs);
- }
- } else {
- now = PR_IntervalNow();
- }
- elapsed = (PRIntervalTime) (now - epoch);
- if (elapsed >= timeout) {
- PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
- rv = -1;
- break;
- } else {
- remaining = timeout - elapsed;
- }
- }
- } while (rv == 0 || (rv == -1 && syserror == EINTR));
- break;
- }
- return(rv);
-}
-
-#endif /* _PR_USE_POLL */
-
-static PRInt32 local_io_wait(
- PRInt32 osfd,
- PRInt32 wait_flag,
- PRIntervalTime timeout)
-{
- _PRUnixPollDesc pd;
- PRInt32 rv;
-
- PR_LOG(_pr_io_lm, PR_LOG_MIN,
- ("waiting to %s on osfd=%d",
- (wait_flag == _PR_UNIX_POLL_READ) ? "read" : "write",
- osfd));
-
- if (timeout == PR_INTERVAL_NO_WAIT) return 0;
-
- pd.osfd = osfd;
- pd.in_flags = wait_flag;
- pd.out_flags = 0;
-
- rv = _PR_WaitForMultipleFDs(&pd, 1, timeout);
-
- if (rv == 0) {
- PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
- rv = -1;
- }
- return rv;
-}
-
-
-PRInt32 _MD_recv(PRFileDesc *fd, void *buf, PRInt32 amount,
- PRInt32 flags, PRIntervalTime timeout)
-{
- PRInt32 osfd = fd->secret->md.osfd;
- PRInt32 rv, err;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
-/*
- * Many OS's (Solaris, Unixware) have a broken recv which won't read
- * from socketpairs. As long as we don't use flags on socketpairs, this
- * is a decent fix. - mikep
- */
-#if defined(UNIXWARE) || defined(SOLARIS)
- while ((rv = read(osfd,buf,amount)) == -1) {
-#else
- while ((rv = recv(osfd,buf,amount,flags)) == -1) {
-#endif
- err = _MD_ERRNO();
- if ((err == EAGAIN) || (err == EWOULDBLOCK)) {
- if (fd->secret->nonblocking) {
- break;
- }
- if (!_PR_IS_NATIVE_THREAD(me)) {
- if ((rv = local_io_wait(osfd,_PR_UNIX_POLL_READ,timeout)) < 0)
- goto done;
- } else {
- if ((rv = socket_io_wait(osfd, READ_FD, timeout)) < 0)
- goto done;
- }
- } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))){
- continue;
- } else {
- break;
- }
- }
- if (rv < 0) {
- _PR_MD_MAP_RECV_ERROR(err);
- }
-done:
- return(rv);
-}
-
-PRInt32 _MD_recvfrom(PRFileDesc *fd, void *buf, PRInt32 amount,
- PRIntn flags, PRNetAddr *addr, PRUint32 *addrlen,
- PRIntervalTime timeout)
-{
- PRInt32 osfd = fd->secret->md.osfd;
- PRInt32 rv, err;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- while ((*addrlen = PR_NETADDR_SIZE(addr)),
- ((rv = recvfrom(osfd, buf, amount, flags,
- (struct sockaddr *) addr, (_PRSockLen_t *)addrlen)) == -1)) {
- err = _MD_ERRNO();
- if ((err == EAGAIN) || (err == EWOULDBLOCK)) {
- if (fd->secret->nonblocking) {
- break;
- }
- if (!_PR_IS_NATIVE_THREAD(me)) {
- if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_READ, timeout)) < 0)
- goto done;
- } else {
- if ((rv = socket_io_wait(osfd, READ_FD, timeout)) < 0)
- goto done;
- }
- } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))){
- continue;
- } else {
- break;
- }
- }
- if (rv < 0) {
- _PR_MD_MAP_RECVFROM_ERROR(err);
- }
-done:
-#ifdef _PR_HAVE_SOCKADDR_LEN
- if (rv != -1) {
- /* ignore the sa_len field of struct sockaddr */
- if (addr) {
- addr->raw.family = ((struct sockaddr *) addr)->sa_family;
- }
- }
-#endif /* _PR_HAVE_SOCKADDR_LEN */
- return(rv);
-}
-
-PRInt32 _MD_send(PRFileDesc *fd, const void *buf, PRInt32 amount,
- PRInt32 flags, PRIntervalTime timeout)
-{
- PRInt32 osfd = fd->secret->md.osfd;
- PRInt32 rv, err;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-#if defined(SOLARIS)
- PRInt32 tmp_amount = amount;
-#endif
-
- /*
- * On pre-2.6 Solaris, send() is much slower than write().
- * On 2.6 and beyond, with in-kernel sockets, send() and
- * write() are fairly equivalent in performance.
- */
-#if defined(SOLARIS)
- PR_ASSERT(0 == flags);
- while ((rv = write(osfd,buf,tmp_amount)) == -1) {
-#else
- while ((rv = send(osfd,buf,amount,flags)) == -1) {
-#endif
- err = _MD_ERRNO();
- if ((err == EAGAIN) || (err == EWOULDBLOCK)) {
- if (fd->secret->nonblocking) {
- break;
- }
- if (!_PR_IS_NATIVE_THREAD(me)) {
- if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_WRITE, timeout)) < 0)
- goto done;
- } else {
- if ((rv = socket_io_wait(osfd, WRITE_FD, timeout))< 0)
- goto done;
- }
- } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))){
- continue;
- } else {
-#if defined(SOLARIS)
- /*
- * The write system call has been reported to return the ERANGE
- * error on occasion. Try to write in smaller chunks to workaround
- * this bug.
- */
- if (err == ERANGE) {
- if (tmp_amount > 1) {
- tmp_amount = tmp_amount/2; /* half the bytes */
- continue;
- }
- }
-#endif
- break;
- }
- }
- /*
- * optimization; if bytes sent is less than "amount" call
- * select before returning. This is because it is likely that
- * the next send() call will return EWOULDBLOCK.
- */
- if ((!fd->secret->nonblocking) && (rv > 0) && (rv < amount)
- && (timeout != PR_INTERVAL_NO_WAIT)) {
- if (_PR_IS_NATIVE_THREAD(me)) {
- if (socket_io_wait(osfd, WRITE_FD, timeout)< 0) {
- rv = -1;
- goto done;
- }
- } else {
- if (local_io_wait(osfd, _PR_UNIX_POLL_WRITE, timeout) < 0) {
- rv = -1;
- goto done;
- }
- }
- }
- if (rv < 0) {
- _PR_MD_MAP_SEND_ERROR(err);
- }
-done:
- return(rv);
-}
-
-PRInt32 _MD_sendto(
- PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
- const PRNetAddr *addr, PRUint32 addrlen, PRIntervalTime timeout)
-{
- PRInt32 osfd = fd->secret->md.osfd;
- PRInt32 rv, err;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-#ifdef _PR_HAVE_SOCKADDR_LEN
- PRNetAddr addrCopy;
-
- addrCopy = *addr;
- ((struct sockaddr *) &addrCopy)->sa_len = addrlen;
- ((struct sockaddr *) &addrCopy)->sa_family = addr->raw.family;
-
- while ((rv = sendto(osfd, buf, amount, flags,
- (struct sockaddr *) &addrCopy, addrlen)) == -1) {
-#else
- while ((rv = sendto(osfd, buf, amount, flags,
- (struct sockaddr *) addr, addrlen)) == -1) {
-#endif
- err = _MD_ERRNO();
- if ((err == EAGAIN) || (err == EWOULDBLOCK)) {
- if (fd->secret->nonblocking) {
- break;
- }
- if (!_PR_IS_NATIVE_THREAD(me)) {
- if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_WRITE, timeout)) < 0)
- goto done;
- } else {
- if ((rv = socket_io_wait(osfd, WRITE_FD, timeout))< 0)
- goto done;
- }
- } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))){
- continue;
- } else {
- break;
- }
- }
- if (rv < 0) {
- _PR_MD_MAP_SENDTO_ERROR(err);
- }
-done:
- return(rv);
-}
-
-PRInt32 _MD_writev(
- PRFileDesc *fd, const PRIOVec *iov,
- PRInt32 iov_size, PRIntervalTime timeout)
-{
- PRInt32 rv, err;
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRInt32 index, amount = 0;
- PRInt32 osfd = fd->secret->md.osfd;
-
- /*
- * Calculate the total number of bytes to be sent; needed for
- * optimization later.
- * We could avoid this if this number was passed in; but it is
- * probably not a big deal because iov_size is usually small (less than
- * 3)
- */
- if (!fd->secret->nonblocking) {
- for (index=0; index<iov_size; index++) {
- amount += iov[index].iov_len;
- }
- }
-
- while ((rv = writev(osfd, (const struct iovec*)iov, iov_size)) == -1) {
- err = _MD_ERRNO();
- if ((err == EAGAIN) || (err == EWOULDBLOCK)) {
- if (fd->secret->nonblocking) {
- break;
- }
- if (!_PR_IS_NATIVE_THREAD(me)) {
- if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_WRITE, timeout)) < 0)
- goto done;
- } else {
- if ((rv = socket_io_wait(osfd, WRITE_FD, timeout))<0)
- goto done;
- }
- } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))){
- continue;
- } else {
- break;
- }
- }
- /*
- * optimization; if bytes sent is less than "amount" call
- * select before returning. This is because it is likely that
- * the next writev() call will return EWOULDBLOCK.
- */
- if ((!fd->secret->nonblocking) && (rv > 0) && (rv < amount)
- && (timeout != PR_INTERVAL_NO_WAIT)) {
- if (_PR_IS_NATIVE_THREAD(me)) {
- if (socket_io_wait(osfd, WRITE_FD, timeout) < 0) {
- rv = -1;
- goto done;
- }
- } else {
- if (local_io_wait(osfd, _PR_UNIX_POLL_WRITE, timeout) < 0) {
- rv = -1;
- goto done;
- }
- }
- }
- if (rv < 0) {
- _PR_MD_MAP_WRITEV_ERROR(err);
- }
-done:
- return(rv);
-}
-
-PRInt32 _MD_accept(PRFileDesc *fd, PRNetAddr *addr,
- PRUint32 *addrlen, PRIntervalTime timeout)
-{
- PRInt32 osfd = fd->secret->md.osfd;
- PRInt32 rv, err;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- while ((rv = accept(osfd, (struct sockaddr *) addr,
- (_PRSockLen_t *)addrlen)) == -1) {
- err = _MD_ERRNO();
- if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == ECONNABORTED)) {
- if (fd->secret->nonblocking) {
- break;
- }
- if (!_PR_IS_NATIVE_THREAD(me)) {
- if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_READ, timeout)) < 0)
- goto done;
- } else {
- if ((rv = socket_io_wait(osfd, READ_FD, timeout)) < 0)
- goto done;
- }
- } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))){
- continue;
- } else {
- break;
- }
- }
- if (rv < 0) {
- _PR_MD_MAP_ACCEPT_ERROR(err);
- }
-done:
-#ifdef _PR_HAVE_SOCKADDR_LEN
- if (rv != -1) {
- /* ignore the sa_len field of struct sockaddr */
- if (addr) {
- addr->raw.family = ((struct sockaddr *) addr)->sa_family;
- }
- }
-#endif /* _PR_HAVE_SOCKADDR_LEN */
- return(rv);
-}
-
-extern int _connect (int s, const struct sockaddr *name, int namelen);
-PRInt32 _MD_connect(
- PRFileDesc *fd, const PRNetAddr *addr, PRUint32 addrlen, PRIntervalTime timeout)
-{
- PRInt32 rv, err;
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRInt32 osfd = fd->secret->md.osfd;
-#ifdef IRIX
-extern PRInt32 _MD_irix_connect(
- PRInt32 osfd, const PRNetAddr *addr, PRInt32 addrlen, PRIntervalTime timeout);
-#endif
-#ifdef _PR_HAVE_SOCKADDR_LEN
- PRNetAddr addrCopy;
-
- addrCopy = *addr;
- ((struct sockaddr *) &addrCopy)->sa_len = addrlen;
- ((struct sockaddr *) &addrCopy)->sa_family = addr->raw.family;
-#endif
-
- /*
- * We initiate the connection setup by making a nonblocking connect()
- * call. If the connect() call fails, there are two cases we handle
- * specially:
- * 1. The connect() call was interrupted by a signal. In this case
- * we simply retry connect().
- * 2. The NSPR socket is nonblocking and connect() fails with
- * EINPROGRESS. We first wait until the socket becomes writable.
- * Then we try to find out whether the connection setup succeeded
- * or failed.
- */
-
-retry:
-#ifdef IRIX
- if ((rv = _MD_irix_connect(osfd, addr, addrlen, timeout)) == -1) {
-#else
-#ifdef _PR_HAVE_SOCKADDR_LEN
- if ((rv = connect(osfd, (struct sockaddr *)&addrCopy, addrlen)) == -1) {
-#else
- if ((rv = connect(osfd, (struct sockaddr *)addr, addrlen)) == -1) {
-#endif
-#endif
- err = _MD_ERRNO();
-
- if (err == EINTR) {
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError( PR_PENDING_INTERRUPT_ERROR, 0);
- return -1;
- }
- goto retry;
- }
-
- if (!fd->secret->nonblocking && (err == EINPROGRESS)) {
- if (!_PR_IS_NATIVE_THREAD(me)) {
-
- if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_WRITE, timeout)) < 0)
- return -1;
- } else {
- /*
- * socket_io_wait() may return -1 or 1.
- */
-
- rv = socket_io_wait(osfd, WRITE_FD, timeout);
- if (rv == -1) {
- return -1;
- }
- }
-
- PR_ASSERT(rv == 1);
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError( PR_PENDING_INTERRUPT_ERROR, 0);
- return -1;
- }
- err = _MD_unix_get_nonblocking_connect_error(osfd);
- if (err != 0) {
- _PR_MD_MAP_CONNECT_ERROR(err);
- return -1;
- }
- return 0;
- }
-
- _PR_MD_MAP_CONNECT_ERROR(err);
- }
-
- return rv;
-} /* _MD_connect */
-
-PRInt32 _MD_bind(PRFileDesc *fd, const PRNetAddr *addr, PRUint32 addrlen)
-{
- PRInt32 rv, err;
-#ifdef _PR_HAVE_SOCKADDR_LEN
- PRNetAddr addrCopy;
-
- addrCopy = *addr;
- ((struct sockaddr *) &addrCopy)->sa_len = addrlen;
- ((struct sockaddr *) &addrCopy)->sa_family = addr->raw.family;
- rv = bind(fd->secret->md.osfd, (struct sockaddr *) &addrCopy, (int )addrlen);
-#else
- rv = bind(fd->secret->md.osfd, (struct sockaddr *) addr, (int )addrlen);
-#endif
- if (rv < 0) {
- err = _MD_ERRNO();
- _PR_MD_MAP_BIND_ERROR(err);
- }
- return(rv);
-}
-
-PRInt32 _MD_listen(PRFileDesc *fd, PRIntn backlog)
-{
- PRInt32 rv, err;
-
- rv = listen(fd->secret->md.osfd, backlog);
- if (rv < 0) {
- err = _MD_ERRNO();
- _PR_MD_MAP_LISTEN_ERROR(err);
- }
- return(rv);
-}
-
-PRInt32 _MD_shutdown(PRFileDesc *fd, PRIntn how)
-{
- PRInt32 rv, err;
-
- rv = shutdown(fd->secret->md.osfd, how);
- if (rv < 0) {
- err = _MD_ERRNO();
- _PR_MD_MAP_SHUTDOWN_ERROR(err);
- }
- return(rv);
-}
-
-PRInt32 _MD_socketpair(int af, int type, int flags,
- PRInt32 *osfd)
-{
- PRInt32 rv, err;
-
- rv = socketpair(af, type, flags, osfd);
- if (rv < 0) {
- err = _MD_ERRNO();
- _PR_MD_MAP_SOCKETPAIR_ERROR(err);
- }
- return rv;
-}
-
-PRStatus _MD_getsockname(PRFileDesc *fd, PRNetAddr *addr,
- PRUint32 *addrlen)
-{
- PRInt32 rv, err;
-
- rv = getsockname(fd->secret->md.osfd,
- (struct sockaddr *) addr, (_PRSockLen_t *)addrlen);
-#ifdef _PR_HAVE_SOCKADDR_LEN
- if (rv == 0) {
- /* ignore the sa_len field of struct sockaddr */
- if (addr) {
- addr->raw.family = ((struct sockaddr *) addr)->sa_family;
- }
- }
-#endif /* _PR_HAVE_SOCKADDR_LEN */
- if (rv < 0) {
- err = _MD_ERRNO();
- _PR_MD_MAP_GETSOCKNAME_ERROR(err);
- }
- return rv==0?PR_SUCCESS:PR_FAILURE;
-}
-
-PRStatus _MD_getpeername(PRFileDesc *fd, PRNetAddr *addr,
- PRUint32 *addrlen)
-{
- PRInt32 rv, err;
-
- rv = getpeername(fd->secret->md.osfd,
- (struct sockaddr *) addr, (_PRSockLen_t *)addrlen);
-#ifdef _PR_HAVE_SOCKADDR_LEN
- if (rv == 0) {
- /* ignore the sa_len field of struct sockaddr */
- if (addr) {
- addr->raw.family = ((struct sockaddr *) addr)->sa_family;
- }
- }
-#endif /* _PR_HAVE_SOCKADDR_LEN */
- if (rv < 0) {
- err = _MD_ERRNO();
- _PR_MD_MAP_GETPEERNAME_ERROR(err);
- }
- return rv==0?PR_SUCCESS:PR_FAILURE;
-}
-
-PRStatus _MD_getsockopt(PRFileDesc *fd, PRInt32 level,
- PRInt32 optname, char* optval, PRInt32* optlen)
-{
- PRInt32 rv, err;
-
- rv = getsockopt(fd->secret->md.osfd, level, optname, optval, (_PRSockLen_t *)optlen);
- if (rv < 0) {
- err = _MD_ERRNO();
- _PR_MD_MAP_GETSOCKOPT_ERROR(err);
- }
- return rv==0?PR_SUCCESS:PR_FAILURE;
-}
-
-PRStatus _MD_setsockopt(PRFileDesc *fd, PRInt32 level,
- PRInt32 optname, const char* optval, PRInt32 optlen)
-{
- PRInt32 rv, err;
-
- rv = setsockopt(fd->secret->md.osfd, level, optname, optval, optlen);
- if (rv < 0) {
- err = _MD_ERRNO();
- _PR_MD_MAP_SETSOCKOPT_ERROR(err);
- }
- return rv==0?PR_SUCCESS:PR_FAILURE;
-}
-
-PRStatus _MD_set_fd_inheritable(PRFileDesc *fd, PRBool inheritable)
-{
- int rv;
-
- rv = fcntl(fd->secret->md.osfd, F_SETFD, inheritable ? 0 : FD_CLOEXEC);
- if (-1 == rv) {
- PR_SetError(PR_UNKNOWN_ERROR, _MD_ERRNO());
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-void _MD_init_fd_inheritable(PRFileDesc *fd, PRBool imported)
-{
- if (imported) {
- fd->secret->inheritable = _PR_TRI_UNKNOWN;
- } else {
- /* By default, a Unix fd is not closed on exec. */
-#ifdef DEBUG
- {
- int flags = fcntl(fd->secret->md.osfd, F_GETFD, 0);
- PR_ASSERT(0 == flags);
- }
-#endif
- fd->secret->inheritable = _PR_TRI_TRUE;
- }
-}
-
-/************************************************************************/
-#if !defined(_PR_USE_POLL)
-
-/*
-** Scan through io queue and find any bad fd's that triggered the error
-** from _MD_SELECT
-*/
-static void FindBadFDs(void)
-{
- PRCList *q;
- PRThread *me = _MD_CURRENT_THREAD();
-
- PR_ASSERT(!_PR_IS_NATIVE_THREAD(me));
- q = (_PR_IOQ(me->cpu)).next;
- _PR_IOQ_MAX_OSFD(me->cpu) = -1;
- _PR_IOQ_TIMEOUT(me->cpu) = PR_INTERVAL_NO_TIMEOUT;
- while (q != &_PR_IOQ(me->cpu)) {
- PRPollQueue *pq = _PR_POLLQUEUE_PTR(q);
- PRBool notify = PR_FALSE;
- _PRUnixPollDesc *pds = pq->pds;
- _PRUnixPollDesc *epds = pds + pq->npds;
- PRInt32 pq_max_osfd = -1;
-
- q = q->next;
- for (; pds < epds; pds++) {
- PRInt32 osfd = pds->osfd;
- pds->out_flags = 0;
- PR_ASSERT(osfd >= 0 || pds->in_flags == 0);
- if (pds->in_flags == 0) {
- continue; /* skip this fd */
- }
- if (fcntl(osfd, F_GETFL, 0) == -1) {
- /* Found a bad descriptor, remove it from the fd_sets. */
- PR_LOG(_pr_io_lm, PR_LOG_MAX,
- ("file descriptor %d is bad", osfd));
- pds->out_flags = _PR_UNIX_POLL_NVAL;
- notify = PR_TRUE;
- }
- if (osfd > pq_max_osfd) {
- pq_max_osfd = osfd;
- }
- }
-
- if (notify) {
- PRIntn pri;
- PR_REMOVE_LINK(&pq->links);
- pq->on_ioq = PR_FALSE;
-
- /*
- * Decrement the count of descriptors for each desciptor/event
- * because this I/O request is being removed from the
- * ioq
- */
- pds = pq->pds;
- for (; pds < epds; pds++) {
- PRInt32 osfd = pds->osfd;
- PRInt16 in_flags = pds->in_flags;
- PR_ASSERT(osfd >= 0 || in_flags == 0);
- if (in_flags & _PR_UNIX_POLL_READ) {
- if (--(_PR_FD_READ_CNT(me->cpu))[osfd] == 0)
- FD_CLR(osfd, &_PR_FD_READ_SET(me->cpu));
- }
- if (in_flags & _PR_UNIX_POLL_WRITE) {
- if (--(_PR_FD_WRITE_CNT(me->cpu))[osfd] == 0)
- FD_CLR(osfd, &_PR_FD_WRITE_SET(me->cpu));
- }
- if (in_flags & _PR_UNIX_POLL_EXCEPT) {
- if (--(_PR_FD_EXCEPTION_CNT(me->cpu))[osfd] == 0)
- FD_CLR(osfd, &_PR_FD_EXCEPTION_SET(me->cpu));
- }
- }
-
- _PR_THREAD_LOCK(pq->thr);
- if (pq->thr->flags & (_PR_ON_PAUSEQ|_PR_ON_SLEEPQ)) {
- _PRCPU *cpu = pq->thr->cpu;
- _PR_SLEEPQ_LOCK(pq->thr->cpu);
- _PR_DEL_SLEEPQ(pq->thr, PR_TRUE);
- _PR_SLEEPQ_UNLOCK(pq->thr->cpu);
-
- if (pq->thr->flags & _PR_SUSPENDING) {
- /*
- * set thread state to SUSPENDED;
- * a Resume operation on the thread
- * will move it to the runQ
- */
- pq->thr->state = _PR_SUSPENDED;
- _PR_MISCQ_LOCK(pq->thr->cpu);
- _PR_ADD_SUSPENDQ(pq->thr, pq->thr->cpu);
- _PR_MISCQ_UNLOCK(pq->thr->cpu);
- } else {
- pri = pq->thr->priority;
- pq->thr->state = _PR_RUNNABLE;
-
- _PR_RUNQ_LOCK(cpu);
- _PR_ADD_RUNQ(pq->thr, cpu, pri);
- _PR_RUNQ_UNLOCK(cpu);
- }
- }
- _PR_THREAD_UNLOCK(pq->thr);
- } else {
- if (pq->timeout < _PR_IOQ_TIMEOUT(me->cpu))
- _PR_IOQ_TIMEOUT(me->cpu) = pq->timeout;
- if (_PR_IOQ_MAX_OSFD(me->cpu) < pq_max_osfd)
- _PR_IOQ_MAX_OSFD(me->cpu) = pq_max_osfd;
- }
- }
- if (_PR_IS_NATIVE_THREAD_SUPPORTED()) {
- if (_PR_IOQ_MAX_OSFD(me->cpu) < _pr_md_pipefd[0])
- _PR_IOQ_MAX_OSFD(me->cpu) = _pr_md_pipefd[0];
- }
-}
-#endif /* !defined(_PR_USE_POLL) */
-
-/************************************************************************/
-
-/*
-** Called by the scheduler when there is nothing to do. This means that
-** all threads are blocked on some monitor somewhere.
-**
-** Note: this code doesn't release the scheduler lock.
-*/
-/*
-** Pause the current CPU. longjmp to the cpu's pause stack
-**
-** This must be called with the scheduler locked
-*/
-void _MD_PauseCPU(PRIntervalTime ticks)
-{
- PRThread *me = _MD_CURRENT_THREAD();
-#ifdef _PR_USE_POLL
- int timeout;
- struct pollfd *pollfds; /* an array of pollfd structures */
- struct pollfd *pollfdPtr; /* a pointer that steps through the array */
- unsigned long npollfds; /* number of pollfd structures in array */
- unsigned long pollfds_size;
- int nfd; /* to hold the return value of poll() */
-#else
- struct timeval timeout, *tvp;
- fd_set r, w, e;
- fd_set *rp, *wp, *ep;
- PRInt32 max_osfd, nfd;
-#endif /* _PR_USE_POLL */
- PRInt32 rv;
- PRCList *q;
- PRUint32 min_timeout;
- sigset_t oldset;
-#ifdef IRIX
-extern sigset_t ints_off;
-#endif
-
- PR_ASSERT(_PR_MD_GET_INTSOFF() != 0);
-
- _PR_MD_IOQ_LOCK();
-
-#ifdef _PR_USE_POLL
- /* Build up the pollfd structure array to wait on */
-
- /* Find out how many pollfd structures are needed */
- npollfds = _PR_IOQ_OSFD_CNT(me->cpu);
- PR_ASSERT(npollfds >= 0);
-
- /*
- * We use a pipe to wake up a native thread. An fd is needed
- * for the pipe and we poll it for reading.
- */
- if (_PR_IS_NATIVE_THREAD_SUPPORTED()) {
- npollfds++;
-#ifdef IRIX
- /*
- * On Irix, a second pipe is used to cause the primordial cpu to
- * wakeup and exit, when the process is exiting because of a call
- * to exit/PR_ProcessExit.
- */
- if (me->cpu->id == 0) {
- npollfds++;
- }
-#endif
- }
-
- /*
- * if the cpu's pollfd array is not big enough, release it and allocate a new one
- */
- if (npollfds > _PR_IOQ_POLLFDS_SIZE(me->cpu)) {
- if (_PR_IOQ_POLLFDS(me->cpu) != NULL)
- PR_DELETE(_PR_IOQ_POLLFDS(me->cpu));
- pollfds_size = PR_MAX(_PR_IOQ_MIN_POLLFDS_SIZE(me->cpu), npollfds);
- pollfds = (struct pollfd *) PR_MALLOC(pollfds_size * sizeof(struct pollfd));
- _PR_IOQ_POLLFDS(me->cpu) = pollfds;
- _PR_IOQ_POLLFDS_SIZE(me->cpu) = pollfds_size;
- } else {
- pollfds = _PR_IOQ_POLLFDS(me->cpu);
- }
- pollfdPtr = pollfds;
-
- /*
- * If we need to poll the pipe for waking up a native thread,
- * the pipe's fd is the first element in the pollfds array.
- */
- if (_PR_IS_NATIVE_THREAD_SUPPORTED()) {
- pollfdPtr->fd = _pr_md_pipefd[0];
- pollfdPtr->events = POLLIN;
- pollfdPtr++;
-#ifdef IRIX
- /*
- * On Irix, the second element is the exit pipe
- */
- if (me->cpu->id == 0) {
- pollfdPtr->fd = _pr_irix_primoridal_cpu_fd[0];
- pollfdPtr->events = POLLIN;
- pollfdPtr++;
- }
-#endif
- }
-
- min_timeout = PR_INTERVAL_NO_TIMEOUT;
- for (q = _PR_IOQ(me->cpu).next; q != &_PR_IOQ(me->cpu); q = q->next) {
- PRPollQueue *pq = _PR_POLLQUEUE_PTR(q);
- _PRUnixPollDesc *pds = pq->pds;
- _PRUnixPollDesc *epds = pds + pq->npds;
-
- if (pq->timeout < min_timeout) {
- min_timeout = pq->timeout;
- }
- for (; pds < epds; pds++, pollfdPtr++) {
- /*
- * Assert that the pollfdPtr pointer does not go
- * beyond the end of the pollfds array
- */
- PR_ASSERT(pollfdPtr < pollfds + npollfds);
- pollfdPtr->fd = pds->osfd;
- /* direct copy of poll flags */
- pollfdPtr->events = pds->in_flags;
- }
- }
- _PR_IOQ_TIMEOUT(me->cpu) = min_timeout;
-#else
- /*
- * assigment of fd_sets
- */
- r = _PR_FD_READ_SET(me->cpu);
- w = _PR_FD_WRITE_SET(me->cpu);
- e = _PR_FD_EXCEPTION_SET(me->cpu);
-
- rp = &r;
- wp = &w;
- ep = &e;
-
- max_osfd = _PR_IOQ_MAX_OSFD(me->cpu) + 1;
- min_timeout = _PR_IOQ_TIMEOUT(me->cpu);
-#endif /* _PR_USE_POLL */
- /*
- ** Compute the minimum timeout value: make it the smaller of the
- ** timeouts specified by the i/o pollers or the timeout of the first
- ** sleeping thread.
- */
- q = _PR_SLEEPQ(me->cpu).next;
-
- if (q != &_PR_SLEEPQ(me->cpu)) {
- PRThread *t = _PR_THREAD_PTR(q);
-
- if (t->sleep < min_timeout) {
- min_timeout = t->sleep;
- }
- }
- if (min_timeout > ticks) {
- min_timeout = ticks;
- }
-
-#ifdef _PR_USE_POLL
- if (min_timeout == PR_INTERVAL_NO_TIMEOUT)
- timeout = -1;
- else
- timeout = PR_IntervalToMilliseconds(min_timeout);
-#else
- if (min_timeout == PR_INTERVAL_NO_TIMEOUT) {
- tvp = NULL;
- } else {
- timeout.tv_sec = PR_IntervalToSeconds(min_timeout);
- timeout.tv_usec = PR_IntervalToMicroseconds(min_timeout)
- % PR_USEC_PER_SEC;
- tvp = &timeout;
- }
-#endif /* _PR_USE_POLL */
-
- _PR_MD_IOQ_UNLOCK();
- _MD_CHECK_FOR_EXIT();
- /*
- * check for i/o operations
- */
-#ifndef _PR_NO_CLOCK_TIMER
- /*
- * Disable the clock interrupts while we are in select, if clock interrupts
- * are enabled. Otherwise, when the select/poll calls are interrupted, the
- * timer value starts ticking from zero again when the system call is restarted.
- */
-#ifdef IRIX
- /*
- * SIGCHLD signal is used on Irix to detect he termination of an
- * sproc by SIGSEGV, SIGBUS or SIGABRT signals when
- * _nspr_terminate_on_error is set.
- */
- if ((!_nspr_noclock) || (_nspr_terminate_on_error))
-#else
- if (!_nspr_noclock)
-#endif /* IRIX */
-#ifdef IRIX
- sigprocmask(SIG_BLOCK, &ints_off, &oldset);
-#else
- PR_ASSERT(sigismember(&timer_set, SIGALRM));
- sigprocmask(SIG_BLOCK, &timer_set, &oldset);
-#endif /* IRIX */
-#endif /* !_PR_NO_CLOCK_TIMER */
-
-#ifndef _PR_USE_POLL
- PR_ASSERT(FD_ISSET(_pr_md_pipefd[0],rp));
- nfd = _MD_SELECT(max_osfd, rp, wp, ep, tvp);
-#else
- nfd = _MD_POLL(pollfds, npollfds, timeout);
-#endif /* !_PR_USE_POLL */
-
-#ifndef _PR_NO_CLOCK_TIMER
-#ifdef IRIX
- if ((!_nspr_noclock) || (_nspr_terminate_on_error))
-#else
- if (!_nspr_noclock)
-#endif /* IRIX */
- sigprocmask(SIG_SETMASK, &oldset, 0);
-#endif /* !_PR_NO_CLOCK_TIMER */
-
- _MD_CHECK_FOR_EXIT();
-
-#ifdef IRIX
- _PR_MD_primordial_cpu();
-#endif
-
- _PR_MD_IOQ_LOCK();
- /*
- ** Notify monitors that are associated with the selected descriptors.
- */
-#ifdef _PR_USE_POLL
- if (nfd > 0) {
- pollfdPtr = pollfds;
- if (_PR_IS_NATIVE_THREAD_SUPPORTED()) {
- /*
- * Assert that the pipe is the first element in the
- * pollfds array.
- */
- PR_ASSERT(pollfds[0].fd == _pr_md_pipefd[0]);
- if ((pollfds[0].revents & POLLIN) && (nfd == 1)) {
- /*
- * woken up by another thread; read all the data
- * in the pipe to empty the pipe
- */
- while ((rv = read(_pr_md_pipefd[0], _pr_md_pipebuf,
- PIPE_BUF)) == PIPE_BUF){
- }
- PR_ASSERT((rv > 0) || ((rv == -1) && (errno == EAGAIN)));
- }
- pollfdPtr++;
-#ifdef IRIX
- /*
- * On Irix, check to see if the primordial cpu needs to exit
- * to cause the process to terminate
- */
- if (me->cpu->id == 0) {
- PR_ASSERT(pollfds[1].fd == _pr_irix_primoridal_cpu_fd[0]);
- if (pollfdPtr->revents & POLLIN) {
- if (_pr_irix_process_exit) {
- /*
- * process exit due to a call to PR_ProcessExit
- */
- prctl(PR_SETEXITSIG, SIGKILL);
- _exit(_pr_irix_process_exit_code);
- } else {
- while ((rv = read(_pr_irix_primoridal_cpu_fd[0],
- _pr_md_pipebuf, PIPE_BUF)) == PIPE_BUF) {
- }
- PR_ASSERT(rv > 0);
- }
- }
- pollfdPtr++;
- }
-#endif
- }
- for (q = _PR_IOQ(me->cpu).next; q != &_PR_IOQ(me->cpu); q = q->next) {
- PRPollQueue *pq = _PR_POLLQUEUE_PTR(q);
- PRBool notify = PR_FALSE;
- _PRUnixPollDesc *pds = pq->pds;
- _PRUnixPollDesc *epds = pds + pq->npds;
-
- for (; pds < epds; pds++, pollfdPtr++) {
- /*
- * Assert that the pollfdPtr pointer does not go beyond
- * the end of the pollfds array.
- */
- PR_ASSERT(pollfdPtr < pollfds + npollfds);
- /*
- * Assert that the fd's in the pollfds array (stepped
- * through by pollfdPtr) are in the same order as
- * the fd's in _PR_IOQ() (stepped through by q and pds).
- * This is how the pollfds array was created earlier.
- */
- PR_ASSERT(pollfdPtr->fd == pds->osfd);
- pds->out_flags = pollfdPtr->revents;
- /* Negative fd's are ignored by poll() */
- if (pds->osfd >= 0 && pds->out_flags) {
- notify = PR_TRUE;
- }
- }
- if (notify) {
- PRIntn pri;
- PRThread *thred;
-
- PR_REMOVE_LINK(&pq->links);
- pq->on_ioq = PR_FALSE;
-
- thred = pq->thr;
- _PR_THREAD_LOCK(thred);
- if (pq->thr->flags & (_PR_ON_PAUSEQ|_PR_ON_SLEEPQ)) {
- _PRCPU *cpu = pq->thr->cpu;
- _PR_SLEEPQ_LOCK(pq->thr->cpu);
- _PR_DEL_SLEEPQ(pq->thr, PR_TRUE);
- _PR_SLEEPQ_UNLOCK(pq->thr->cpu);
-
- if (pq->thr->flags & _PR_SUSPENDING) {
- /*
- * set thread state to SUSPENDED;
- * a Resume operation on the thread
- * will move it to the runQ
- */
- pq->thr->state = _PR_SUSPENDED;
- _PR_MISCQ_LOCK(pq->thr->cpu);
- _PR_ADD_SUSPENDQ(pq->thr, pq->thr->cpu);
- _PR_MISCQ_UNLOCK(pq->thr->cpu);
- } else {
- pri = pq->thr->priority;
- pq->thr->state = _PR_RUNNABLE;
-
- _PR_RUNQ_LOCK(cpu);
- _PR_ADD_RUNQ(pq->thr, cpu, pri);
- _PR_RUNQ_UNLOCK(cpu);
- if (_pr_md_idle_cpus > 1)
- _PR_MD_WAKEUP_WAITER(thred);
- }
- }
- _PR_THREAD_UNLOCK(thred);
- _PR_IOQ_OSFD_CNT(me->cpu) -= pq->npds;
- PR_ASSERT(_PR_IOQ_OSFD_CNT(me->cpu) >= 0);
- }
- }
- } else if (nfd == -1) {
- PR_LOG(_pr_io_lm, PR_LOG_MAX, ("poll() failed with errno %d", errno));
- }
-
-#else
- if (nfd > 0) {
- q = _PR_IOQ(me->cpu).next;
- _PR_IOQ_MAX_OSFD(me->cpu) = -1;
- _PR_IOQ_TIMEOUT(me->cpu) = PR_INTERVAL_NO_TIMEOUT;
- while (q != &_PR_IOQ(me->cpu)) {
- PRPollQueue *pq = _PR_POLLQUEUE_PTR(q);
- PRBool notify = PR_FALSE;
- _PRUnixPollDesc *pds = pq->pds;
- _PRUnixPollDesc *epds = pds + pq->npds;
- PRInt32 pq_max_osfd = -1;
-
- q = q->next;
- for (; pds < epds; pds++) {
- PRInt32 osfd = pds->osfd;
- PRInt16 in_flags = pds->in_flags;
- PRInt16 out_flags = 0;
- PR_ASSERT(osfd >= 0 || in_flags == 0);
- if ((in_flags & _PR_UNIX_POLL_READ) && FD_ISSET(osfd, rp)) {
- out_flags |= _PR_UNIX_POLL_READ;
- }
- if ((in_flags & _PR_UNIX_POLL_WRITE) && FD_ISSET(osfd, wp)) {
- out_flags |= _PR_UNIX_POLL_WRITE;
- }
- if ((in_flags & _PR_UNIX_POLL_EXCEPT) && FD_ISSET(osfd, ep)) {
- out_flags |= _PR_UNIX_POLL_EXCEPT;
- }
- pds->out_flags = out_flags;
- if (out_flags) {
- notify = PR_TRUE;
- }
- if (osfd > pq_max_osfd) {
- pq_max_osfd = osfd;
- }
- }
- if (notify == PR_TRUE) {
- PRIntn pri;
- PRThread *thred;
-
- PR_REMOVE_LINK(&pq->links);
- pq->on_ioq = PR_FALSE;
-
- /*
- * Decrement the count of descriptors for each desciptor/event
- * because this I/O request is being removed from the
- * ioq
- */
- pds = pq->pds;
- for (; pds < epds; pds++) {
- PRInt32 osfd = pds->osfd;
- PRInt16 in_flags = pds->in_flags;
- PR_ASSERT(osfd >= 0 || in_flags == 0);
- if (in_flags & _PR_UNIX_POLL_READ) {
- if (--(_PR_FD_READ_CNT(me->cpu))[osfd] == 0)
- FD_CLR(osfd, &_PR_FD_READ_SET(me->cpu));
- }
- if (in_flags & _PR_UNIX_POLL_WRITE) {
- if (--(_PR_FD_WRITE_CNT(me->cpu))[osfd] == 0)
- FD_CLR(osfd, &_PR_FD_WRITE_SET(me->cpu));
- }
- if (in_flags & _PR_UNIX_POLL_EXCEPT) {
- if (--(_PR_FD_EXCEPTION_CNT(me->cpu))[osfd] == 0)
- FD_CLR(osfd, &_PR_FD_EXCEPTION_SET(me->cpu));
- }
- }
-
- /*
- * Because this thread can run on a different cpu right
- * after being added to the run queue, do not dereference
- * pq
- */
- thred = pq->thr;
- _PR_THREAD_LOCK(thred);
- if (pq->thr->flags & (_PR_ON_PAUSEQ|_PR_ON_SLEEPQ)) {
- _PRCPU *cpu = thred->cpu;
- _PR_SLEEPQ_LOCK(pq->thr->cpu);
- _PR_DEL_SLEEPQ(pq->thr, PR_TRUE);
- _PR_SLEEPQ_UNLOCK(pq->thr->cpu);
-
- if (pq->thr->flags & _PR_SUSPENDING) {
- /*
- * set thread state to SUSPENDED;
- * a Resume operation on the thread
- * will move it to the runQ
- */
- pq->thr->state = _PR_SUSPENDED;
- _PR_MISCQ_LOCK(pq->thr->cpu);
- _PR_ADD_SUSPENDQ(pq->thr, pq->thr->cpu);
- _PR_MISCQ_UNLOCK(pq->thr->cpu);
- } else {
- pri = pq->thr->priority;
- pq->thr->state = _PR_RUNNABLE;
-
- pq->thr->cpu = cpu;
- _PR_RUNQ_LOCK(cpu);
- _PR_ADD_RUNQ(pq->thr, cpu, pri);
- _PR_RUNQ_UNLOCK(cpu);
- if (_pr_md_idle_cpus > 1)
- _PR_MD_WAKEUP_WAITER(thred);
- }
- }
- _PR_THREAD_UNLOCK(thred);
- } else {
- if (pq->timeout < _PR_IOQ_TIMEOUT(me->cpu))
- _PR_IOQ_TIMEOUT(me->cpu) = pq->timeout;
- if (_PR_IOQ_MAX_OSFD(me->cpu) < pq_max_osfd)
- _PR_IOQ_MAX_OSFD(me->cpu) = pq_max_osfd;
- }
- }
- if (_PR_IS_NATIVE_THREAD_SUPPORTED()) {
- if ((FD_ISSET(_pr_md_pipefd[0], rp)) && (nfd == 1)) {
- /*
- * woken up by another thread; read all the data
- * in the pipe to empty the pipe
- */
- while ((rv =
- read(_pr_md_pipefd[0], _pr_md_pipebuf, PIPE_BUF))
- == PIPE_BUF){
- }
- PR_ASSERT((rv > 0) ||
- ((rv == -1) && (errno == EAGAIN)));
- }
- if (_PR_IOQ_MAX_OSFD(me->cpu) < _pr_md_pipefd[0])
- _PR_IOQ_MAX_OSFD(me->cpu) = _pr_md_pipefd[0];
-#ifdef IRIX
- if ((me->cpu->id == 0) &&
- (FD_ISSET(_pr_irix_primoridal_cpu_fd[0], rp))) {
- if (_pr_irix_process_exit) {
- /*
- * process exit due to a call to PR_ProcessExit
- */
- prctl(PR_SETEXITSIG, SIGKILL);
- _exit(_pr_irix_process_exit_code);
- } else {
- while ((rv = read(_pr_irix_primoridal_cpu_fd[0],
- _pr_md_pipebuf, PIPE_BUF)) == PIPE_BUF) {
- }
- PR_ASSERT(rv > 0);
- }
- }
- if (me->cpu->id == 0) {
- if (_PR_IOQ_MAX_OSFD(me->cpu) < _pr_irix_primoridal_cpu_fd[0])
- _PR_IOQ_MAX_OSFD(me->cpu) = _pr_irix_primoridal_cpu_fd[0];
- }
-#endif
- }
- } else if (nfd < 0) {
- if (errno == EBADF) {
- FindBadFDs();
- } else {
- PR_LOG(_pr_io_lm, PR_LOG_MAX, ("select() failed with errno %d",
- errno));
- }
- } else {
- PR_ASSERT(nfd == 0);
- /*
- * compute the new value of _PR_IOQ_TIMEOUT
- */
- q = _PR_IOQ(me->cpu).next;
- _PR_IOQ_MAX_OSFD(me->cpu) = -1;
- _PR_IOQ_TIMEOUT(me->cpu) = PR_INTERVAL_NO_TIMEOUT;
- while (q != &_PR_IOQ(me->cpu)) {
- PRPollQueue *pq = _PR_POLLQUEUE_PTR(q);
- _PRUnixPollDesc *pds = pq->pds;
- _PRUnixPollDesc *epds = pds + pq->npds;
- PRInt32 pq_max_osfd = -1;
-
- q = q->next;
- for (; pds < epds; pds++) {
- if (pds->osfd > pq_max_osfd) {
- pq_max_osfd = pds->osfd;
- }
- }
- if (pq->timeout < _PR_IOQ_TIMEOUT(me->cpu))
- _PR_IOQ_TIMEOUT(me->cpu) = pq->timeout;
- if (_PR_IOQ_MAX_OSFD(me->cpu) < pq_max_osfd)
- _PR_IOQ_MAX_OSFD(me->cpu) = pq_max_osfd;
- }
- if (_PR_IS_NATIVE_THREAD_SUPPORTED()) {
- if (_PR_IOQ_MAX_OSFD(me->cpu) < _pr_md_pipefd[0])
- _PR_IOQ_MAX_OSFD(me->cpu) = _pr_md_pipefd[0];
- }
- }
-#endif /* _PR_USE_POLL */
- _PR_MD_IOQ_UNLOCK();
-}
-
-void _MD_Wakeup_CPUs()
-{
- PRInt32 rv, data;
-
- data = 0;
- rv = write(_pr_md_pipefd[1], &data, 1);
-
- while ((rv < 0) && (errno == EAGAIN)) {
- /*
- * pipe full, read all data in pipe to empty it
- */
- while ((rv =
- read(_pr_md_pipefd[0], _pr_md_pipebuf, PIPE_BUF))
- == PIPE_BUF) {
- }
- PR_ASSERT((rv > 0) ||
- ((rv == -1) && (errno == EAGAIN)));
- rv = write(_pr_md_pipefd[1], &data, 1);
- }
-}
-
-
-void _MD_InitCPUS()
-{
- PRInt32 rv, flags;
- PRThread *me = _MD_CURRENT_THREAD();
-
- rv = pipe(_pr_md_pipefd);
- PR_ASSERT(rv == 0);
- _PR_IOQ_MAX_OSFD(me->cpu) = _pr_md_pipefd[0];
-#ifndef _PR_USE_POLL
- FD_SET(_pr_md_pipefd[0], &_PR_FD_READ_SET(me->cpu));
-#endif
-
- flags = fcntl(_pr_md_pipefd[0], F_GETFL, 0);
- fcntl(_pr_md_pipefd[0], F_SETFL, flags | O_NONBLOCK);
- flags = fcntl(_pr_md_pipefd[1], F_GETFL, 0);
- fcntl(_pr_md_pipefd[1], F_SETFL, flags | O_NONBLOCK);
-}
-
-/*
-** Unix SIGALRM (clock) signal handler
-*/
-static void ClockInterruptHandler()
-{
- int olderrno;
- PRUintn pri;
- _PRCPU *cpu = _PR_MD_CURRENT_CPU();
- PRThread *me = _MD_CURRENT_THREAD();
-
-#ifdef SOLARIS
- if (!me || _PR_IS_NATIVE_THREAD(me)) {
- _pr_primordialCPU->u.missed[_pr_primordialCPU->where] |= _PR_MISSED_CLOCK;
- return;
- }
-#endif
-
- if (_PR_MD_GET_INTSOFF() != 0) {
- cpu->u.missed[cpu->where] |= _PR_MISSED_CLOCK;
- return;
- }
- _PR_MD_SET_INTSOFF(1);
-
- olderrno = errno;
- _PR_ClockInterrupt();
- errno = olderrno;
-
- /*
- ** If the interrupt wants a resched or if some other thread at
- ** the same priority needs the cpu, reschedule.
- */
- pri = me->priority;
- if ((cpu->u.missed[3] || (_PR_RUNQREADYMASK(me->cpu) >> pri))) {
-#ifdef _PR_NO_PREEMPT
- cpu->resched = PR_TRUE;
- if (pr_interruptSwitchHook) {
- (*pr_interruptSwitchHook)(pr_interruptSwitchHookArg);
- }
-#else /* _PR_NO_PREEMPT */
- /*
- ** Re-enable unix interrupts (so that we can use
- ** setjmp/longjmp for context switching without having to
- ** worry about the signal state)
- */
- sigprocmask(SIG_SETMASK, &empty_set, 0);
- PR_LOG(_pr_sched_lm, PR_LOG_MIN, ("clock caused context switch"));
-
- if(!(me->flags & _PR_IDLE_THREAD)) {
- _PR_THREAD_LOCK(me);
- me->state = _PR_RUNNABLE;
- me->cpu = cpu;
- _PR_RUNQ_LOCK(cpu);
- _PR_ADD_RUNQ(me, cpu, pri);
- _PR_RUNQ_UNLOCK(cpu);
- _PR_THREAD_UNLOCK(me);
- } else
- me->state = _PR_RUNNABLE;
- _MD_SWITCH_CONTEXT(me);
- PR_LOG(_pr_sched_lm, PR_LOG_MIN, ("clock back from context switch"));
-#endif /* _PR_NO_PREEMPT */
- }
- /*
- * Because this thread could be running on a different cpu after
- * a context switch the current cpu should be accessed and the
- * value of the 'cpu' variable should not be used.
- */
- _PR_MD_SET_INTSOFF(0);
-}
-
-/*
- * On HP-UX 9, we have to use the sigvector() interface to restart
- * interrupted system calls, because sigaction() does not have the
- * SA_RESTART flag.
- */
-
-#ifdef HPUX9
-static void HPUX9_ClockInterruptHandler(
- int sig,
- int code,
- struct sigcontext *scp)
-{
- ClockInterruptHandler();
- scp->sc_syscall_action = SIG_RESTART;
-}
-#endif /* HPUX9 */
-
-/* # of milliseconds per clock tick that we will use */
-#define MSEC_PER_TICK 50
-
-
-void _MD_StartInterrupts()
-{
- char *eval;
-
- if ((eval = getenv("NSPR_NOCLOCK")) != NULL) {
- if (atoi(eval) == 0)
- _nspr_noclock = 0;
- else
- _nspr_noclock = 1;
- }
-
-#ifndef _PR_NO_CLOCK_TIMER
- if (!_nspr_noclock) {
- _MD_EnableClockInterrupts();
- }
-#endif
-}
-
-void _MD_StopInterrupts()
-{
- sigprocmask(SIG_BLOCK, &timer_set, 0);
-}
-
-void _MD_EnableClockInterrupts()
-{
- struct itimerval itval;
- extern PRUintn _pr_numCPU;
-#ifdef HPUX9
- struct sigvec vec;
-
- vec.sv_handler = (void (*)()) HPUX9_ClockInterruptHandler;
- vec.sv_mask = 0;
- vec.sv_flags = 0;
- sigvector(SIGALRM, &vec, 0);
-#else
- struct sigaction vtact;
-
- vtact.sa_handler = (void (*)()) ClockInterruptHandler;
- sigemptyset(&vtact.sa_mask);
- vtact.sa_flags = SA_RESTART;
- sigaction(SIGALRM, &vtact, 0);
-#endif /* HPUX9 */
-
- PR_ASSERT(_pr_numCPU == 1);
- itval.it_interval.tv_sec = 0;
- itval.it_interval.tv_usec = MSEC_PER_TICK * PR_USEC_PER_MSEC;
- itval.it_value = itval.it_interval;
- setitimer(ITIMER_REAL, &itval, 0);
-}
-
-void _MD_DisableClockInterrupts()
-{
- struct itimerval itval;
- extern PRUintn _pr_numCPU;
-
- PR_ASSERT(_pr_numCPU == 1);
- itval.it_interval.tv_sec = 0;
- itval.it_interval.tv_usec = 0;
- itval.it_value = itval.it_interval;
- setitimer(ITIMER_REAL, &itval, 0);
-}
-
-void _MD_BlockClockInterrupts()
-{
- sigprocmask(SIG_BLOCK, &timer_set, 0);
-}
-
-void _MD_UnblockClockInterrupts()
-{
- sigprocmask(SIG_UNBLOCK, &timer_set, 0);
-}
-
-void _MD_MakeNonblock(PRFileDesc *fd)
-{
- PRInt32 osfd = fd->secret->md.osfd;
- int flags;
-
- if (osfd <= 2) {
- /* Don't mess around with stdin, stdout or stderr */
- return;
- }
- flags = fcntl(osfd, F_GETFL, 0);
-
- /*
- * Use O_NONBLOCK (POSIX-style non-blocking I/O) whenever possible.
- * On SunOS 4, we must use FNDELAY (BSD-style non-blocking I/O),
- * otherwise connect() still blocks and can be interrupted by SIGALRM.
- */
-
- fcntl(osfd, F_SETFL, flags | O_NONBLOCK);
- }
-
-PRInt32 _MD_open(const char *name, PRIntn flags, PRIntn mode)
-{
- PRInt32 osflags;
- PRInt32 rv, err;
-
- if (flags & PR_RDWR) {
- osflags = O_RDWR;
- } else if (flags & PR_WRONLY) {
- osflags = O_WRONLY;
- } else {
- osflags = O_RDONLY;
- }
-
- if (flags & PR_EXCL)
- osflags |= O_EXCL;
- if (flags & PR_APPEND)
- osflags |= O_APPEND;
- if (flags & PR_TRUNCATE)
- osflags |= O_TRUNC;
- if (flags & PR_SYNC) {
-#if defined(O_SYNC)
- osflags |= O_SYNC;
-#elif defined(O_FSYNC)
- osflags |= O_FSYNC;
-#else
-#error "Neither O_SYNC nor O_FSYNC is defined on this platform"
-#endif
- }
-
- /*
- ** On creations we hold the 'create' lock in order to enforce
- ** the semantics of PR_Rename. (see the latter for more details)
- */
- if (flags & PR_CREATE_FILE)
- {
- osflags |= O_CREAT;
- if (NULL !=_pr_rename_lock)
- PR_Lock(_pr_rename_lock);
- }
-
-#if defined(ANDROID)
- osflags |= O_LARGEFILE;
-#endif
-
- rv = _md_iovector._open64(name, osflags, mode);
-
- if (rv < 0) {
- err = _MD_ERRNO();
- _PR_MD_MAP_OPEN_ERROR(err);
- }
-
- if ((flags & PR_CREATE_FILE) && (NULL !=_pr_rename_lock))
- PR_Unlock(_pr_rename_lock);
- return rv;
-}
-
-PRIntervalTime intr_timeout_ticks;
-
-#if defined(SOLARIS) || defined(IRIX)
-static void sigsegvhandler() {
- fprintf(stderr,"Received SIGSEGV\n");
- fflush(stderr);
- pause();
-}
-
-static void sigaborthandler() {
- fprintf(stderr,"Received SIGABRT\n");
- fflush(stderr);
- pause();
-}
-
-static void sigbushandler() {
- fprintf(stderr,"Received SIGBUS\n");
- fflush(stderr);
- pause();
-}
-#endif /* SOLARIS, IRIX */
-
-#endif /* !defined(_PR_PTHREADS) */
-
-void _MD_query_fd_inheritable(PRFileDesc *fd)
-{
- int flags;
-
- PR_ASSERT(_PR_TRI_UNKNOWN == fd->secret->inheritable);
- flags = fcntl(fd->secret->md.osfd, F_GETFD, 0);
- PR_ASSERT(-1 != flags);
- fd->secret->inheritable = (flags & FD_CLOEXEC) ?
- _PR_TRI_FALSE : _PR_TRI_TRUE;
-}
-
-PROffset32 _MD_lseek(PRFileDesc *fd, PROffset32 offset, PRSeekWhence whence)
-{
- PROffset32 rv, where;
-
- switch (whence) {
- case PR_SEEK_SET:
- where = SEEK_SET;
- break;
- case PR_SEEK_CUR:
- where = SEEK_CUR;
- break;
- case PR_SEEK_END:
- where = SEEK_END;
- break;
- default:
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- rv = -1;
- goto done;
- }
- rv = lseek(fd->secret->md.osfd,offset,where);
- if (rv == -1)
- {
- PRInt32 syserr = _MD_ERRNO();
- _PR_MD_MAP_LSEEK_ERROR(syserr);
- }
-done:
- return(rv);
-}
-
-PROffset64 _MD_lseek64(PRFileDesc *fd, PROffset64 offset, PRSeekWhence whence)
-{
- PRInt32 where;
- PROffset64 rv;
-
- switch (whence)
- {
- case PR_SEEK_SET:
- where = SEEK_SET;
- break;
- case PR_SEEK_CUR:
- where = SEEK_CUR;
- break;
- case PR_SEEK_END:
- where = SEEK_END;
- break;
- default:
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- rv = minus_one;
- goto done;
- }
- rv = _md_iovector._lseek64(fd->secret->md.osfd, offset, where);
- if (LL_EQ(rv, minus_one))
- {
- PRInt32 syserr = _MD_ERRNO();
- _PR_MD_MAP_LSEEK_ERROR(syserr);
- }
-done:
- return rv;
-} /* _MD_lseek64 */
-
-/*
-** _MD_set_fileinfo_times --
-** Set the modifyTime and creationTime of the PRFileInfo
-** structure using the values in struct stat.
-**
-** _MD_set_fileinfo64_times --
-** Set the modifyTime and creationTime of the PRFileInfo64
-** structure using the values in _MDStat64.
-*/
-
-#if defined(_PR_STAT_HAS_ST_ATIM)
-/*
-** struct stat has st_atim, st_mtim, and st_ctim fields of
-** type timestruc_t.
-*/
-static void _MD_set_fileinfo_times(
- const struct stat *sb,
- PRFileInfo *info)
-{
- PRInt64 us, s2us;
-
- LL_I2L(s2us, PR_USEC_PER_SEC);
- LL_I2L(info->modifyTime, sb->st_mtim.tv_sec);
- LL_MUL(info->modifyTime, info->modifyTime, s2us);
- LL_I2L(us, sb->st_mtim.tv_nsec / 1000);
- LL_ADD(info->modifyTime, info->modifyTime, us);
- LL_I2L(info->creationTime, sb->st_ctim.tv_sec);
- LL_MUL(info->creationTime, info->creationTime, s2us);
- LL_I2L(us, sb->st_ctim.tv_nsec / 1000);
- LL_ADD(info->creationTime, info->creationTime, us);
-}
-
-static void _MD_set_fileinfo64_times(
- const _MDStat64 *sb,
- PRFileInfo64 *info)
-{
- PRInt64 us, s2us;
-
- LL_I2L(s2us, PR_USEC_PER_SEC);
- LL_I2L(info->modifyTime, sb->st_mtim.tv_sec);
- LL_MUL(info->modifyTime, info->modifyTime, s2us);
- LL_I2L(us, sb->st_mtim.tv_nsec / 1000);
- LL_ADD(info->modifyTime, info->modifyTime, us);
- LL_I2L(info->creationTime, sb->st_ctim.tv_sec);
- LL_MUL(info->creationTime, info->creationTime, s2us);
- LL_I2L(us, sb->st_ctim.tv_nsec / 1000);
- LL_ADD(info->creationTime, info->creationTime, us);
-}
-#elif defined(_PR_STAT_HAS_ST_ATIM_UNION)
-/*
-** The st_atim, st_mtim, and st_ctim fields in struct stat are
-** unions with a st__tim union member of type timestruc_t.
-*/
-static void _MD_set_fileinfo_times(
- const struct stat *sb,
- PRFileInfo *info)
-{
- PRInt64 us, s2us;
-
- LL_I2L(s2us, PR_USEC_PER_SEC);
- LL_I2L(info->modifyTime, sb->st_mtim.st__tim.tv_sec);
- LL_MUL(info->modifyTime, info->modifyTime, s2us);
- LL_I2L(us, sb->st_mtim.st__tim.tv_nsec / 1000);
- LL_ADD(info->modifyTime, info->modifyTime, us);
- LL_I2L(info->creationTime, sb->st_ctim.st__tim.tv_sec);
- LL_MUL(info->creationTime, info->creationTime, s2us);
- LL_I2L(us, sb->st_ctim.st__tim.tv_nsec / 1000);
- LL_ADD(info->creationTime, info->creationTime, us);
-}
-
-static void _MD_set_fileinfo64_times(
- const _MDStat64 *sb,
- PRFileInfo64 *info)
-{
- PRInt64 us, s2us;
-
- LL_I2L(s2us, PR_USEC_PER_SEC);
- LL_I2L(info->modifyTime, sb->st_mtim.st__tim.tv_sec);
- LL_MUL(info->modifyTime, info->modifyTime, s2us);
- LL_I2L(us, sb->st_mtim.st__tim.tv_nsec / 1000);
- LL_ADD(info->modifyTime, info->modifyTime, us);
- LL_I2L(info->creationTime, sb->st_ctim.st__tim.tv_sec);
- LL_MUL(info->creationTime, info->creationTime, s2us);
- LL_I2L(us, sb->st_ctim.st__tim.tv_nsec / 1000);
- LL_ADD(info->creationTime, info->creationTime, us);
-}
-#elif defined(_PR_STAT_HAS_ST_ATIMESPEC)
-/*
-** struct stat has st_atimespec, st_mtimespec, and st_ctimespec
-** fields of type struct timespec.
-*/
-#if defined(_PR_TIMESPEC_HAS_TS_SEC)
-static void _MD_set_fileinfo_times(
- const struct stat *sb,
- PRFileInfo *info)
-{
- PRInt64 us, s2us;
-
- LL_I2L(s2us, PR_USEC_PER_SEC);
- LL_I2L(info->modifyTime, sb->st_mtimespec.ts_sec);
- LL_MUL(info->modifyTime, info->modifyTime, s2us);
- LL_I2L(us, sb->st_mtimespec.ts_nsec / 1000);
- LL_ADD(info->modifyTime, info->modifyTime, us);
- LL_I2L(info->creationTime, sb->st_ctimespec.ts_sec);
- LL_MUL(info->creationTime, info->creationTime, s2us);
- LL_I2L(us, sb->st_ctimespec.ts_nsec / 1000);
- LL_ADD(info->creationTime, info->creationTime, us);
-}
-
-static void _MD_set_fileinfo64_times(
- const _MDStat64 *sb,
- PRFileInfo64 *info)
-{
- PRInt64 us, s2us;
-
- LL_I2L(s2us, PR_USEC_PER_SEC);
- LL_I2L(info->modifyTime, sb->st_mtimespec.ts_sec);
- LL_MUL(info->modifyTime, info->modifyTime, s2us);
- LL_I2L(us, sb->st_mtimespec.ts_nsec / 1000);
- LL_ADD(info->modifyTime, info->modifyTime, us);
- LL_I2L(info->creationTime, sb->st_ctimespec.ts_sec);
- LL_MUL(info->creationTime, info->creationTime, s2us);
- LL_I2L(us, sb->st_ctimespec.ts_nsec / 1000);
- LL_ADD(info->creationTime, info->creationTime, us);
-}
-#else /* _PR_TIMESPEC_HAS_TS_SEC */
-/*
-** The POSIX timespec structure has tv_sec and tv_nsec.
-*/
-static void _MD_set_fileinfo_times(
- const struct stat *sb,
- PRFileInfo *info)
-{
- PRInt64 us, s2us;
-
- LL_I2L(s2us, PR_USEC_PER_SEC);
- LL_I2L(info->modifyTime, sb->st_mtimespec.tv_sec);
- LL_MUL(info->modifyTime, info->modifyTime, s2us);
- LL_I2L(us, sb->st_mtimespec.tv_nsec / 1000);
- LL_ADD(info->modifyTime, info->modifyTime, us);
- LL_I2L(info->creationTime, sb->st_ctimespec.tv_sec);
- LL_MUL(info->creationTime, info->creationTime, s2us);
- LL_I2L(us, sb->st_ctimespec.tv_nsec / 1000);
- LL_ADD(info->creationTime, info->creationTime, us);
-}
-
-static void _MD_set_fileinfo64_times(
- const _MDStat64 *sb,
- PRFileInfo64 *info)
-{
- PRInt64 us, s2us;
-
- LL_I2L(s2us, PR_USEC_PER_SEC);
- LL_I2L(info->modifyTime, sb->st_mtimespec.tv_sec);
- LL_MUL(info->modifyTime, info->modifyTime, s2us);
- LL_I2L(us, sb->st_mtimespec.tv_nsec / 1000);
- LL_ADD(info->modifyTime, info->modifyTime, us);
- LL_I2L(info->creationTime, sb->st_ctimespec.tv_sec);
- LL_MUL(info->creationTime, info->creationTime, s2us);
- LL_I2L(us, sb->st_ctimespec.tv_nsec / 1000);
- LL_ADD(info->creationTime, info->creationTime, us);
-}
-#endif /* _PR_TIMESPEC_HAS_TS_SEC */
-#elif defined(_PR_STAT_HAS_ONLY_ST_ATIME)
-/*
-** struct stat only has st_atime, st_mtime, and st_ctime fields
-** of type time_t.
-*/
-static void _MD_set_fileinfo_times(
- const struct stat *sb,
- PRFileInfo *info)
-{
- PRInt64 s, s2us;
- LL_I2L(s2us, PR_USEC_PER_SEC);
- LL_I2L(s, sb->st_mtime);
- LL_MUL(s, s, s2us);
- info->modifyTime = s;
- LL_I2L(s, sb->st_ctime);
- LL_MUL(s, s, s2us);
- info->creationTime = s;
-}
-
-static void _MD_set_fileinfo64_times(
- const _MDStat64 *sb,
- PRFileInfo64 *info)
-{
- PRInt64 s, s2us;
- LL_I2L(s2us, PR_USEC_PER_SEC);
- LL_I2L(s, sb->st_mtime);
- LL_MUL(s, s, s2us);
- info->modifyTime = s;
- LL_I2L(s, sb->st_ctime);
- LL_MUL(s, s, s2us);
- info->creationTime = s;
-}
-#else
-#error "I don't know yet"
-#endif
-
-static int _MD_convert_stat_to_fileinfo(
- const struct stat *sb,
- PRFileInfo *info)
-{
- if (S_IFREG & sb->st_mode)
- info->type = PR_FILE_FILE;
- else if (S_IFDIR & sb->st_mode)
- info->type = PR_FILE_DIRECTORY;
- else
- info->type = PR_FILE_OTHER;
-
-#if defined(_PR_HAVE_LARGE_OFF_T)
- if (0x7fffffffL < sb->st_size)
- {
- PR_SetError(PR_FILE_TOO_BIG_ERROR, 0);
- return -1;
- }
-#endif /* defined(_PR_HAVE_LARGE_OFF_T) */
- info->size = sb->st_size;
-
- _MD_set_fileinfo_times(sb, info);
- return 0;
-} /* _MD_convert_stat_to_fileinfo */
-
-static int _MD_convert_stat64_to_fileinfo64(
- const _MDStat64 *sb,
- PRFileInfo64 *info)
-{
- if (S_IFREG & sb->st_mode)
- info->type = PR_FILE_FILE;
- else if (S_IFDIR & sb->st_mode)
- info->type = PR_FILE_DIRECTORY;
- else
- info->type = PR_FILE_OTHER;
-
- LL_I2L(info->size, sb->st_size);
-
- _MD_set_fileinfo64_times(sb, info);
- return 0;
-} /* _MD_convert_stat64_to_fileinfo64 */
-
-PRInt32 _MD_getfileinfo(const char *fn, PRFileInfo *info)
-{
- PRInt32 rv;
- struct stat sb;
-
- rv = stat(fn, &sb);
- if (rv < 0)
- _PR_MD_MAP_STAT_ERROR(_MD_ERRNO());
- else if (NULL != info)
- rv = _MD_convert_stat_to_fileinfo(&sb, info);
- return rv;
-}
-
-PRInt32 _MD_getfileinfo64(const char *fn, PRFileInfo64 *info)
-{
- _MDStat64 sb;
- PRInt32 rv = _md_iovector._stat64(fn, &sb);
- if (rv < 0)
- _PR_MD_MAP_STAT_ERROR(_MD_ERRNO());
- else if (NULL != info)
- rv = _MD_convert_stat64_to_fileinfo64(&sb, info);
- return rv;
-}
-
-PRInt32 _MD_getopenfileinfo(const PRFileDesc *fd, PRFileInfo *info)
-{
- struct stat sb;
- PRInt32 rv = fstat(fd->secret->md.osfd, &sb);
- if (rv < 0)
- _PR_MD_MAP_FSTAT_ERROR(_MD_ERRNO());
- else if (NULL != info)
- rv = _MD_convert_stat_to_fileinfo(&sb, info);
- return rv;
-}
-
-PRInt32 _MD_getopenfileinfo64(const PRFileDesc *fd, PRFileInfo64 *info)
-{
- _MDStat64 sb;
- PRInt32 rv = _md_iovector._fstat64(fd->secret->md.osfd, &sb);
- if (rv < 0)
- _PR_MD_MAP_FSTAT_ERROR(_MD_ERRNO());
- else if (NULL != info)
- rv = _MD_convert_stat64_to_fileinfo64(&sb, info);
- return rv;
-}
-
-/*
- * _md_iovector._open64 must be initialized to 'open' so that _PR_InitLog can
- * open the log file during NSPR initialization, before _md_iovector is
- * initialized by _PR_MD_FINAL_INIT. This means the log file cannot be a
- * large file on some platforms.
- */
-#ifdef SYMBIAN
-struct _MD_IOVector _md_iovector; /* Will crash if NSPR_LOG_FILE is set. */
-#else
-struct _MD_IOVector _md_iovector = { open };
-#endif
-
-/*
-** These implementations are to emulate large file routines on systems that
-** don't have them. Their goal is to check in case overflow occurs. Otherwise
-** they will just operate as normal using 32-bit file routines.
-**
-** The checking might be pre- or post-op, depending on the semantics.
-*/
-
-#if defined(SOLARIS2_5)
-
-static PRIntn _MD_solaris25_fstat64(PRIntn osfd, _MDStat64 *buf)
-{
- PRInt32 rv;
- struct stat sb;
-
- rv = fstat(osfd, &sb);
- if (rv >= 0)
- {
- /*
- ** I'm only copying the fields that are immediately needed.
- ** If somebody else calls this function, some of the fields
- ** may not be defined.
- */
- (void)memset(buf, 0, sizeof(_MDStat64));
- buf->st_mode = sb.st_mode;
- buf->st_ctim = sb.st_ctim;
- buf->st_mtim = sb.st_mtim;
- buf->st_size = sb.st_size;
- }
- return rv;
-} /* _MD_solaris25_fstat64 */
-
-static PRIntn _MD_solaris25_stat64(const char *fn, _MDStat64 *buf)
-{
- PRInt32 rv;
- struct stat sb;
-
- rv = stat(fn, &sb);
- if (rv >= 0)
- {
- /*
- ** I'm only copying the fields that are immediately needed.
- ** If somebody else calls this function, some of the fields
- ** may not be defined.
- */
- (void)memset(buf, 0, sizeof(_MDStat64));
- buf->st_mode = sb.st_mode;
- buf->st_ctim = sb.st_ctim;
- buf->st_mtim = sb.st_mtim;
- buf->st_size = sb.st_size;
- }
- return rv;
-} /* _MD_solaris25_stat64 */
-#endif /* defined(SOLARIS2_5) */
-
-#if defined(_PR_NO_LARGE_FILES) || defined(SOLARIS2_5)
-
-static PROffset64 _MD_Unix_lseek64(PRIntn osfd, PROffset64 offset, PRIntn whence)
-{
- PRUint64 maxoff;
- PROffset64 rv = minus_one;
- LL_I2L(maxoff, 0x7fffffff);
- if (LL_CMP(offset, <=, maxoff))
- {
- off_t off;
- LL_L2I(off, offset);
- LL_I2L(rv, lseek(osfd, off, whence));
- }
- else errno = EFBIG; /* we can't go there */
- return rv;
-} /* _MD_Unix_lseek64 */
-
-static void* _MD_Unix_mmap64(
- void *addr, PRSize len, PRIntn prot, PRIntn flags,
- PRIntn fildes, PRInt64 offset)
-{
- PR_SetError(PR_FILE_TOO_BIG_ERROR, 0);
- return NULL;
-} /* _MD_Unix_mmap64 */
-#endif /* defined(_PR_NO_LARGE_FILES) || defined(SOLARIS2_5) */
-
-/* Android <= 19 doesn't have mmap64. */
-#if defined(ANDROID) && __ANDROID_API__ <= 19
-PR_IMPORT(void) *__mmap2(void *, size_t, int, int, int, size_t);
-
-#define ANDROID_PAGE_SIZE 4096
-
-static void *
-mmap64(void *addr, size_t len, int prot, int flags, int fd, loff_t offset)
-{
- if (offset & (ANDROID_PAGE_SIZE - 1)) {
- errno = EINVAL;
- return MAP_FAILED;
- }
- return __mmap2(addr, len, prot, flags, fd, offset / ANDROID_PAGE_SIZE);
-}
-#endif
-
-#if defined(OSF1) && defined(__GNUC__)
-
-/*
- * On OSF1 V5.0A, <sys/stat.h> defines stat and fstat as
- * macros when compiled under gcc, so it is rather tricky to
- * take the addresses of the real functions the macros expend
- * to. A simple solution is to define forwarder functions
- * and take the addresses of the forwarder functions instead.
- */
-
-static int stat_forwarder(const char *path, struct stat *buffer)
-{
- return stat(path, buffer);
-}
-
-static int fstat_forwarder(int filedes, struct stat *buffer)
-{
- return fstat(filedes, buffer);
-}
-
-#endif
-
-static void _PR_InitIOV(void)
-{
-#if defined(SOLARIS2_5)
- PRLibrary *lib;
- void *open64_func;
-
- open64_func = PR_FindSymbolAndLibrary("open64", &lib);
- if (NULL != open64_func)
- {
- PR_ASSERT(NULL != lib);
- _md_iovector._open64 = (_MD_Open64)open64_func;
- _md_iovector._mmap64 = (_MD_Mmap64)PR_FindSymbol(lib, "mmap64");
- _md_iovector._fstat64 = (_MD_Fstat64)PR_FindSymbol(lib, "fstat64");
- _md_iovector._stat64 = (_MD_Stat64)PR_FindSymbol(lib, "stat64");
- _md_iovector._lseek64 = (_MD_Lseek64)PR_FindSymbol(lib, "lseek64");
- (void)PR_UnloadLibrary(lib);
- }
- else
- {
- _md_iovector._open64 = open;
- _md_iovector._mmap64 = _MD_Unix_mmap64;
- _md_iovector._fstat64 = _MD_solaris25_fstat64;
- _md_iovector._stat64 = _MD_solaris25_stat64;
- _md_iovector._lseek64 = _MD_Unix_lseek64;
- }
-#elif defined(_PR_NO_LARGE_FILES)
- _md_iovector._open64 = open;
- _md_iovector._mmap64 = _MD_Unix_mmap64;
- _md_iovector._fstat64 = fstat;
- _md_iovector._stat64 = stat;
- _md_iovector._lseek64 = _MD_Unix_lseek64;
-#elif defined(_PR_HAVE_OFF64_T)
-#if defined(IRIX5_3) || defined(ANDROID)
- /*
- * Android doesn't have open64. We pass the O_LARGEFILE flag to open
- * in _MD_open.
- */
- _md_iovector._open64 = open;
-#else
- _md_iovector._open64 = open64;
-#endif
- _md_iovector._mmap64 = mmap64;
- _md_iovector._fstat64 = fstat64;
- _md_iovector._stat64 = stat64;
- _md_iovector._lseek64 = lseek64;
-#elif defined(_PR_HAVE_LARGE_OFF_T)
- _md_iovector._open64 = open;
- _md_iovector._mmap64 = mmap;
-#if defined(OSF1) && defined(__GNUC__)
- _md_iovector._fstat64 = fstat_forwarder;
- _md_iovector._stat64 = stat_forwarder;
-#else
- _md_iovector._fstat64 = fstat;
- _md_iovector._stat64 = stat;
-#endif
- _md_iovector._lseek64 = lseek;
-#else
-#error "I don't know yet"
-#endif
- LL_I2L(minus_one, -1);
-} /* _PR_InitIOV */
-
-void _PR_UnixInit(void)
-{
- struct sigaction sigact;
- int rv;
-
- sigemptyset(&timer_set);
-
-#if !defined(_PR_PTHREADS)
-
- sigaddset(&timer_set, SIGALRM);
- sigemptyset(&empty_set);
- intr_timeout_ticks =
- PR_SecondsToInterval(_PR_INTERRUPT_CHECK_INTERVAL_SECS);
-
-#if defined(SOLARIS) || defined(IRIX)
-
- if (getenv("NSPR_SIGSEGV_HANDLE")) {
- sigact.sa_handler = sigsegvhandler;
- sigact.sa_flags = 0;
- sigact.sa_mask = timer_set;
- sigaction(SIGSEGV, &sigact, 0);
- }
-
- if (getenv("NSPR_SIGABRT_HANDLE")) {
- sigact.sa_handler = sigaborthandler;
- sigact.sa_flags = 0;
- sigact.sa_mask = timer_set;
- sigaction(SIGABRT, &sigact, 0);
- }
-
- if (getenv("NSPR_SIGBUS_HANDLE")) {
- sigact.sa_handler = sigbushandler;
- sigact.sa_flags = 0;
- sigact.sa_mask = timer_set;
- sigaction(SIGBUS, &sigact, 0);
- }
-
-#endif
-#endif /* !defined(_PR_PTHREADS) */
-
- /*
- * Under HP-UX DCE threads, sigaction() installs a per-thread
- * handler, so we use sigvector() to install a process-wide
- * handler.
- */
-#if defined(HPUX) && defined(_PR_DCETHREADS)
- {
- struct sigvec vec;
-
- vec.sv_handler = SIG_IGN;
- vec.sv_mask = 0;
- vec.sv_flags = 0;
- rv = sigvector(SIGPIPE, &vec, NULL);
- PR_ASSERT(0 == rv);
- }
-#else
- sigact.sa_handler = SIG_IGN;
- sigemptyset(&sigact.sa_mask);
- sigact.sa_flags = 0;
- rv = sigaction(SIGPIPE, &sigact, 0);
- PR_ASSERT(0 == rv);
-#endif /* HPUX && _PR_DCETHREADS */
-
- _pr_rename_lock = PR_NewLock();
- PR_ASSERT(NULL != _pr_rename_lock);
- _pr_Xfe_mon = PR_NewMonitor();
- PR_ASSERT(NULL != _pr_Xfe_mon);
-
- _PR_InitIOV(); /* one last hack */
-}
-
-void _PR_UnixCleanup(void)
-{
- if (_pr_rename_lock) {
- PR_DestroyLock(_pr_rename_lock);
- _pr_rename_lock = NULL;
- }
- if (_pr_Xfe_mon) {
- PR_DestroyMonitor(_pr_Xfe_mon);
- _pr_Xfe_mon = NULL;
- }
-}
-
-#if !defined(_PR_PTHREADS)
-
-/*
- * Variables used by the GC code, initialized in _MD_InitSegs().
- */
-static PRInt32 _pr_zero_fd = -1;
-static PRLock *_pr_md_lock = NULL;
-
-/*
- * _MD_InitSegs --
- *
- * This is Unix's version of _PR_MD_INIT_SEGS(), which is
- * called by _PR_InitSegs(), which in turn is called by
- * PR_Init().
- */
-void _MD_InitSegs(void)
-{
-#ifdef DEBUG
- /*
- ** Disable using mmap(2) if NSPR_NO_MMAP is set
- */
- if (getenv("NSPR_NO_MMAP")) {
- _pr_zero_fd = -2;
- return;
- }
-#endif
- _pr_zero_fd = open("/dev/zero",O_RDWR , 0);
- /* Prevent the fd from being inherited by child processes */
- fcntl(_pr_zero_fd, F_SETFD, FD_CLOEXEC);
- _pr_md_lock = PR_NewLock();
-}
-
-PRStatus _MD_AllocSegment(PRSegment *seg, PRUint32 size, void *vaddr)
-{
- static char *lastaddr = (char*) _PR_STACK_VMBASE;
- PRStatus retval = PR_SUCCESS;
- int prot;
- void *rv;
-
- PR_ASSERT(seg != 0);
- PR_ASSERT(size != 0);
-
- PR_Lock(_pr_md_lock);
- if (_pr_zero_fd < 0) {
-from_heap:
- seg->vaddr = PR_MALLOC(size);
- if (!seg->vaddr) {
- retval = PR_FAILURE;
- }
- else {
- seg->size = size;
- }
- goto exit;
- }
-
- prot = PROT_READ|PROT_WRITE;
- /*
- * On Alpha Linux, the user-level thread stack needs
- * to be made executable because longjmp/signal seem
- * to put machine instructions on the stack.
- */
-#if defined(LINUX) && defined(__alpha)
- prot |= PROT_EXEC;
-#endif
- rv = mmap((vaddr != 0) ? vaddr : lastaddr, size, prot,
- _MD_MMAP_FLAGS,
- _pr_zero_fd, 0);
- if (rv == (void*)-1) {
- goto from_heap;
- }
- lastaddr += size;
- seg->vaddr = rv;
- seg->size = size;
- seg->flags = _PR_SEG_VM;
-
-exit:
- PR_Unlock(_pr_md_lock);
- return retval;
-}
-
-void _MD_FreeSegment(PRSegment *seg)
-{
- if (seg->flags & _PR_SEG_VM)
- (void) munmap(seg->vaddr, seg->size);
- else
- PR_DELETE(seg->vaddr);
-}
-
-#endif /* _PR_PTHREADS */
-
-/*
- *-----------------------------------------------------------------------
- *
- * PR_Now --
- *
- * Returns the current time in microseconds since the epoch.
- * The epoch is midnight January 1, 1970 GMT.
- * The implementation is machine dependent. This is the Unix
- * implementation.
- * Cf. time_t time(time_t *tp)
- *
- *-----------------------------------------------------------------------
- */
-
-PR_IMPLEMENT(PRTime)
-PR_Now(void)
-{
- struct timeval tv;
- PRInt64 s, us, s2us;
-
- GETTIMEOFDAY(&tv);
- LL_I2L(s2us, PR_USEC_PER_SEC);
- LL_I2L(s, tv.tv_sec);
- LL_I2L(us, tv.tv_usec);
- LL_MUL(s, s, s2us);
- LL_ADD(s, s, us);
- return s;
-}
-
-#if defined(_MD_INTERVAL_USE_GTOD)
-/*
- * This version of interval times is based on the time of day
- * capability offered by the system. This isn't valid for two reasons:
- * 1) The time of day is neither linear nor montonically increasing
- * 2) The units here are milliseconds. That's not appropriate for our use.
- */
-PRIntervalTime _PR_UNIX_GetInterval()
-{
- struct timeval time;
- PRIntervalTime ticks;
-
- (void)GETTIMEOFDAY(&time); /* fallicy of course */
- ticks = (PRUint32)time.tv_sec * PR_MSEC_PER_SEC; /* that's in milliseconds */
- ticks += (PRUint32)time.tv_usec / PR_USEC_PER_MSEC; /* so's that */
- return ticks;
-} /* _PR_UNIX_GetInterval */
-
-PRIntervalTime _PR_UNIX_TicksPerSecond()
-{
- return 1000; /* this needs some work :) */
-}
-#endif
-
-#if defined(_PR_HAVE_CLOCK_MONOTONIC)
-PRIntervalTime _PR_UNIX_GetInterval2()
-{
- struct timespec time;
- PRIntervalTime ticks;
-
- if (clock_gettime(CLOCK_MONOTONIC, &time) != 0) {
- fprintf(stderr, "clock_gettime failed: %d\n", errno);
- abort();
- }
-
- ticks = (PRUint32)time.tv_sec * PR_MSEC_PER_SEC;
- ticks += (PRUint32)time.tv_nsec / PR_NSEC_PER_MSEC;
- return ticks;
-}
-
-PRIntervalTime _PR_UNIX_TicksPerSecond2()
-{
- return 1000;
-}
-#endif
-
-#if !defined(_PR_PTHREADS)
-/*
- * Wait for I/O on multiple descriptors.
- *
- * Return 0 if timed out, return -1 if interrupted,
- * else return the number of ready descriptors.
- */
-PRInt32 _PR_WaitForMultipleFDs(
- _PRUnixPollDesc *unixpds,
- PRInt32 pdcnt,
- PRIntervalTime timeout)
-{
- PRPollQueue pq;
- PRIntn is;
- PRInt32 rv;
- _PRCPU *io_cpu;
- _PRUnixPollDesc *unixpd, *eunixpd;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- PR_ASSERT(!(me->flags & _PR_IDLE_THREAD));
-
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- return -1;
- }
-
- pq.pds = unixpds;
- pq.npds = pdcnt;
-
- _PR_INTSOFF(is);
- _PR_MD_IOQ_LOCK();
- _PR_THREAD_LOCK(me);
-
- pq.thr = me;
- io_cpu = me->cpu;
- pq.on_ioq = PR_TRUE;
- pq.timeout = timeout;
- _PR_ADD_TO_IOQ(pq, me->cpu);
-
-#if !defined(_PR_USE_POLL)
- eunixpd = unixpds + pdcnt;
- for (unixpd = unixpds; unixpd < eunixpd; unixpd++) {
- PRInt32 osfd = unixpd->osfd;
- if (unixpd->in_flags & _PR_UNIX_POLL_READ) {
- FD_SET(osfd, &_PR_FD_READ_SET(me->cpu));
- _PR_FD_READ_CNT(me->cpu)[osfd]++;
- }
- if (unixpd->in_flags & _PR_UNIX_POLL_WRITE) {
- FD_SET(osfd, &_PR_FD_WRITE_SET(me->cpu));
- (_PR_FD_WRITE_CNT(me->cpu))[osfd]++;
- }
- if (unixpd->in_flags & _PR_UNIX_POLL_EXCEPT) {
- FD_SET(osfd, &_PR_FD_EXCEPTION_SET(me->cpu));
- (_PR_FD_EXCEPTION_CNT(me->cpu))[osfd]++;
- }
- if (osfd > _PR_IOQ_MAX_OSFD(me->cpu)) {
- _PR_IOQ_MAX_OSFD(me->cpu) = osfd;
- }
- }
-#endif /* !defined(_PR_USE_POLL) */
-
- if (_PR_IOQ_TIMEOUT(me->cpu) > timeout) {
- _PR_IOQ_TIMEOUT(me->cpu) = timeout;
- }
-
- _PR_IOQ_OSFD_CNT(me->cpu) += pdcnt;
-
- _PR_SLEEPQ_LOCK(me->cpu);
- _PR_ADD_SLEEPQ(me, timeout);
- me->state = _PR_IO_WAIT;
- me->io_pending = PR_TRUE;
- me->io_suspended = PR_FALSE;
- _PR_SLEEPQ_UNLOCK(me->cpu);
- _PR_THREAD_UNLOCK(me);
- _PR_MD_IOQ_UNLOCK();
-
- _PR_MD_WAIT(me, timeout);
-
- me->io_pending = PR_FALSE;
- me->io_suspended = PR_FALSE;
-
- /*
- * This thread should run on the same cpu on which it was blocked; when
- * the IO request times out the fd sets and fd counts for the
- * cpu are updated below.
- */
- PR_ASSERT(me->cpu == io_cpu);
-
- /*
- ** If we timed out the pollq might still be on the ioq. Remove it
- ** before continuing.
- */
- if (pq.on_ioq) {
- _PR_MD_IOQ_LOCK();
- /*
- * Need to check pq.on_ioq again
- */
- if (pq.on_ioq) {
- PR_REMOVE_LINK(&pq.links);
-#ifndef _PR_USE_POLL
- eunixpd = unixpds + pdcnt;
- for (unixpd = unixpds; unixpd < eunixpd; unixpd++) {
- PRInt32 osfd = unixpd->osfd;
- PRInt16 in_flags = unixpd->in_flags;
-
- if (in_flags & _PR_UNIX_POLL_READ) {
- if (--(_PR_FD_READ_CNT(me->cpu))[osfd] == 0)
- FD_CLR(osfd, &_PR_FD_READ_SET(me->cpu));
- }
- if (in_flags & _PR_UNIX_POLL_WRITE) {
- if (--(_PR_FD_WRITE_CNT(me->cpu))[osfd] == 0)
- FD_CLR(osfd, &_PR_FD_WRITE_SET(me->cpu));
- }
- if (in_flags & _PR_UNIX_POLL_EXCEPT) {
- if (--(_PR_FD_EXCEPTION_CNT(me->cpu))[osfd] == 0)
- FD_CLR(osfd, &_PR_FD_EXCEPTION_SET(me->cpu));
- }
- }
-#endif /* _PR_USE_POLL */
- PR_ASSERT(pq.npds == pdcnt);
- _PR_IOQ_OSFD_CNT(me->cpu) -= pdcnt;
- PR_ASSERT(_PR_IOQ_OSFD_CNT(me->cpu) >= 0);
- }
- _PR_MD_IOQ_UNLOCK();
- }
- /* XXX Should we use _PR_FAST_INTSON or _PR_INTSON? */
- if (1 == pdcnt) {
- _PR_FAST_INTSON(is);
- } else {
- _PR_INTSON(is);
- }
-
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- return -1;
- }
-
- rv = 0;
- if (pq.on_ioq == PR_FALSE) {
- /* Count the number of ready descriptors */
- while (--pdcnt >= 0) {
- if (unixpds->out_flags != 0) {
- rv++;
- }
- unixpds++;
- }
- }
-
- return rv;
-}
-
-/*
- * Unblock threads waiting for I/O
- * used when interrupting threads
- *
- * NOTE: The thread lock should held when this function is called.
- * On return, the thread lock is released.
- */
-void _PR_Unblock_IO_Wait(PRThread *thr)
-{
- int pri = thr->priority;
- _PRCPU *cpu = thr->cpu;
-
- /*
- * GLOBAL threads wakeup periodically to check for interrupt
- */
- if (_PR_IS_NATIVE_THREAD(thr)) {
- _PR_THREAD_UNLOCK(thr);
- return;
- }
-
- PR_ASSERT(thr->flags & (_PR_ON_SLEEPQ | _PR_ON_PAUSEQ));
- _PR_SLEEPQ_LOCK(cpu);
- _PR_DEL_SLEEPQ(thr, PR_TRUE);
- _PR_SLEEPQ_UNLOCK(cpu);
-
- PR_ASSERT(!(thr->flags & _PR_IDLE_THREAD));
- thr->state = _PR_RUNNABLE;
- _PR_RUNQ_LOCK(cpu);
- _PR_ADD_RUNQ(thr, cpu, pri);
- _PR_RUNQ_UNLOCK(cpu);
- _PR_THREAD_UNLOCK(thr);
- _PR_MD_WAKEUP_WAITER(thr);
-}
-#endif /* !defined(_PR_PTHREADS) */
-
-/*
- * When a nonblocking connect has completed, determine whether it
- * succeeded or failed, and if it failed, what the error code is.
- *
- * The function returns the error code. An error code of 0 means
- * that the nonblocking connect succeeded.
- */
-
-int _MD_unix_get_nonblocking_connect_error(int osfd)
-{
-#if defined(NTO)
- /* Neutrino does not support the SO_ERROR socket option */
- PRInt32 rv;
- PRNetAddr addr;
- _PRSockLen_t addrlen = sizeof(addr);
-
- /* Test to see if we are using the Tiny TCP/IP Stack or the Full one. */
- struct statvfs superblock;
- rv = fstatvfs(osfd, &superblock);
- if (rv == 0) {
- if (strcmp(superblock.f_basetype, "ttcpip") == 0) {
- /* Using the Tiny Stack! */
- rv = getpeername(osfd, (struct sockaddr *) &addr,
- (_PRSockLen_t *) &addrlen);
- if (rv == -1) {
- int errno_copy = errno; /* make a copy so I don't
- * accidentally reset */
-
- if (errno_copy == ENOTCONN) {
- struct stat StatInfo;
- rv = fstat(osfd, &StatInfo);
- if (rv == 0) {
- time_t current_time = time(NULL);
-
- /*
- * this is a real hack, can't explain why it
- * works it just does
- */
- if (abs(current_time - StatInfo.st_atime) < 5) {
- return ECONNREFUSED;
- } else {
- return ETIMEDOUT;
- }
- } else {
- return ECONNREFUSED;
- }
- } else {
- return errno_copy;
- }
- } else {
- /* No Error */
- return 0;
- }
- } else {
- /* Have the FULL Stack which supports SO_ERROR */
- /* Hasn't been written yet, never been tested! */
- /* [email protected] */
-
- int err;
- _PRSockLen_t optlen = sizeof(err);
-
- if (getsockopt(osfd, SOL_SOCKET, SO_ERROR,
- (char *) &err, &optlen) == -1) {
- return errno;
- } else {
- return err;
- }
- }
- } else {
- return ECONNREFUSED;
- }
-#elif defined(UNIXWARE)
- /*
- * getsockopt() fails with EPIPE, so use getmsg() instead.
- */
-
- int rv;
- int flags = 0;
- rv = getmsg(osfd, NULL, NULL, &flags);
- PR_ASSERT(-1 == rv || 0 == rv);
- if (-1 == rv && errno != EAGAIN && errno != EWOULDBLOCK) {
- return errno;
- }
- return 0; /* no error */
-#else
- int err;
- _PRSockLen_t optlen = sizeof(err);
- if (getsockopt(osfd, SOL_SOCKET, SO_ERROR, (char *) &err, &optlen) == -1) {
- return errno;
- } else {
- return err;
- }
-#endif
-}
-
-/************************************************************************/
-
-/*
-** Special hacks for xlib. Xlib/Xt/Xm is not re-entrant nor is it thread
-** safe. Unfortunately, neither is mozilla. To make these programs work
-** in a pre-emptive threaded environment, we need to use a lock.
-*/
-
-void PR_XLock(void)
-{
- PR_EnterMonitor(_pr_Xfe_mon);
-}
-
-void PR_XUnlock(void)
-{
- PR_ExitMonitor(_pr_Xfe_mon);
-}
-
-PRBool PR_XIsLocked(void)
-{
- return (PR_InMonitor(_pr_Xfe_mon)) ? PR_TRUE : PR_FALSE;
-}
-
-void PR_XWait(int ms)
-{
- PR_Wait(_pr_Xfe_mon, PR_MillisecondsToInterval(ms));
-}
-
-void PR_XNotify(void)
-{
- PR_Notify(_pr_Xfe_mon);
-}
-
-void PR_XNotifyAll(void)
-{
- PR_NotifyAll(_pr_Xfe_mon);
-}
-
-#if defined(HAVE_FCNTL_FILE_LOCKING)
-
-PRStatus
-_MD_LockFile(PRInt32 f)
-{
- PRInt32 rv;
- struct flock arg;
-
- arg.l_type = F_WRLCK;
- arg.l_whence = SEEK_SET;
- arg.l_start = 0;
- arg.l_len = 0; /* until EOF */
- rv = fcntl(f, F_SETLKW, &arg);
- if (rv == 0)
- return PR_SUCCESS;
- _PR_MD_MAP_FLOCK_ERROR(_MD_ERRNO());
- return PR_FAILURE;
-}
-
-PRStatus
-_MD_TLockFile(PRInt32 f)
-{
- PRInt32 rv;
- struct flock arg;
-
- arg.l_type = F_WRLCK;
- arg.l_whence = SEEK_SET;
- arg.l_start = 0;
- arg.l_len = 0; /* until EOF */
- rv = fcntl(f, F_SETLK, &arg);
- if (rv == 0)
- return PR_SUCCESS;
- _PR_MD_MAP_FLOCK_ERROR(_MD_ERRNO());
- return PR_FAILURE;
-}
-
-PRStatus
-_MD_UnlockFile(PRInt32 f)
-{
- PRInt32 rv;
- struct flock arg;
-
- arg.l_type = F_UNLCK;
- arg.l_whence = SEEK_SET;
- arg.l_start = 0;
- arg.l_len = 0; /* until EOF */
- rv = fcntl(f, F_SETLK, &arg);
- if (rv == 0)
- return PR_SUCCESS;
- _PR_MD_MAP_FLOCK_ERROR(_MD_ERRNO());
- return PR_FAILURE;
-}
-
-#elif defined(HAVE_BSD_FLOCK)
-
-#include <sys/file.h>
-
-PRStatus
-_MD_LockFile(PRInt32 f)
-{
- PRInt32 rv;
- rv = flock(f, LOCK_EX);
- if (rv == 0)
- return PR_SUCCESS;
- _PR_MD_MAP_FLOCK_ERROR(_MD_ERRNO());
- return PR_FAILURE;
-}
-
-PRStatus
-_MD_TLockFile(PRInt32 f)
-{
- PRInt32 rv;
- rv = flock(f, LOCK_EX|LOCK_NB);
- if (rv == 0)
- return PR_SUCCESS;
- _PR_MD_MAP_FLOCK_ERROR(_MD_ERRNO());
- return PR_FAILURE;
-}
-
-PRStatus
-_MD_UnlockFile(PRInt32 f)
-{
- PRInt32 rv;
- rv = flock(f, LOCK_UN);
- if (rv == 0)
- return PR_SUCCESS;
- _PR_MD_MAP_FLOCK_ERROR(_MD_ERRNO());
- return PR_FAILURE;
-}
-#else
-
-PRStatus
-_MD_LockFile(PRInt32 f)
-{
- PRInt32 rv;
- rv = lockf(f, F_LOCK, 0);
- if (rv == 0)
- return PR_SUCCESS;
- _PR_MD_MAP_LOCKF_ERROR(_MD_ERRNO());
- return PR_FAILURE;
-}
-
-PRStatus
-_MD_TLockFile(PRInt32 f)
-{
- PRInt32 rv;
- rv = lockf(f, F_TLOCK, 0);
- if (rv == 0)
- return PR_SUCCESS;
- _PR_MD_MAP_LOCKF_ERROR(_MD_ERRNO());
- return PR_FAILURE;
-}
-
-PRStatus
-_MD_UnlockFile(PRInt32 f)
-{
- PRInt32 rv;
- rv = lockf(f, F_ULOCK, 0);
- if (rv == 0)
- return PR_SUCCESS;
- _PR_MD_MAP_LOCKF_ERROR(_MD_ERRNO());
- return PR_FAILURE;
-}
-#endif
-
-PRStatus _MD_gethostname(char *name, PRUint32 namelen)
-{
- PRIntn rv;
-
- rv = gethostname(name, namelen);
- if (0 == rv) {
- return PR_SUCCESS;
- }
- _PR_MD_MAP_GETHOSTNAME_ERROR(_MD_ERRNO());
- return PR_FAILURE;
-}
-
-PRStatus _MD_getsysinfo(PRSysInfo cmd, char *name, PRUint32 namelen)
-{
- struct utsname info;
-
- PR_ASSERT((cmd == PR_SI_SYSNAME) || (cmd == PR_SI_RELEASE));
-
- if (uname(&info) == -1) {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- return PR_FAILURE;
- }
- if (PR_SI_SYSNAME == cmd)
- (void)PR_snprintf(name, namelen, info.sysname);
- else if (PR_SI_RELEASE == cmd)
- (void)PR_snprintf(name, namelen, info.release);
- else
- return PR_FAILURE;
- return PR_SUCCESS;
-}
-
-/*
- *******************************************************************
- *
- * Memory-mapped files
- *
- *******************************************************************
- */
-
-PRStatus _MD_CreateFileMap(PRFileMap *fmap, PRInt64 size)
-{
- PRFileInfo info;
- PRUint32 sz;
-
- LL_L2UI(sz, size);
- if (sz) {
- if (PR_GetOpenFileInfo(fmap->fd, &info) == PR_FAILURE) {
- return PR_FAILURE;
- }
- if (sz > info.size) {
- /*
- * Need to extend the file
- */
- if (fmap->prot != PR_PROT_READWRITE) {
- PR_SetError(PR_NO_ACCESS_RIGHTS_ERROR, 0);
- return PR_FAILURE;
- }
- if (PR_Seek(fmap->fd, sz - 1, PR_SEEK_SET) == -1) {
- return PR_FAILURE;
- }
- if (PR_Write(fmap->fd, "", 1) != 1) {
- return PR_FAILURE;
- }
- }
- }
- if (fmap->prot == PR_PROT_READONLY) {
- fmap->md.prot = PROT_READ;
-#ifdef OSF1V4_MAP_PRIVATE_BUG
- /*
- * Use MAP_SHARED to work around a bug in OSF1 V4.0D
- * (QAR 70220 in the OSF_QAR database) that results in
- * corrupted data in the memory-mapped region. This
- * bug is fixed in V5.0.
- */
- fmap->md.flags = MAP_SHARED;
-#else
- fmap->md.flags = MAP_PRIVATE;
-#endif
- } else if (fmap->prot == PR_PROT_READWRITE) {
- fmap->md.prot = PROT_READ | PROT_WRITE;
- fmap->md.flags = MAP_SHARED;
- } else {
- PR_ASSERT(fmap->prot == PR_PROT_WRITECOPY);
- fmap->md.prot = PROT_READ | PROT_WRITE;
- fmap->md.flags = MAP_PRIVATE;
- }
- return PR_SUCCESS;
-}
-
-void * _MD_MemMap(
- PRFileMap *fmap,
- PRInt64 offset,
- PRUint32 len)
-{
- PRInt32 off;
- void *addr;
-
- LL_L2I(off, offset);
- if ((addr = mmap(0, len, fmap->md.prot, fmap->md.flags,
- fmap->fd->secret->md.osfd, off)) == (void *) -1) {
- _PR_MD_MAP_MMAP_ERROR(_MD_ERRNO());
- addr = NULL;
- }
- return addr;
-}
-
-PRStatus _MD_MemUnmap(void *addr, PRUint32 len)
-{
- if (munmap(addr, len) == 0) {
- return PR_SUCCESS;
- }
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- return PR_FAILURE;
-}
-
-PRStatus _MD_CloseFileMap(PRFileMap *fmap)
-{
- if ( PR_TRUE == fmap->md.isAnonFM ) {
- PRStatus rc = PR_Close( fmap->fd );
- if ( PR_FAILURE == rc ) {
- PR_LOG( _pr_io_lm, PR_LOG_DEBUG,
- ("_MD_CloseFileMap(): error closing anonymnous file map osfd"));
- return PR_FAILURE;
- }
- }
- PR_DELETE(fmap);
- return PR_SUCCESS;
-}
-
-PRStatus _MD_SyncMemMap(
- PRFileDesc *fd,
- void *addr,
- PRUint32 len)
-{
- /* msync(..., MS_SYNC) alone is sufficient to flush modified data to disk
- * synchronously. It is not necessary to call fsync. */
- if (msync(addr, len, MS_SYNC) == 0) {
- return PR_SUCCESS;
- }
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- return PR_FAILURE;
-}
-
-#if defined(_PR_NEED_FAKE_POLL)
-
-/*
- * Some platforms don't have poll(). For easier porting of code
- * that calls poll(), we emulate poll() using select().
- */
-
-int poll(struct pollfd *filedes, unsigned long nfds, int timeout)
-{
- int i;
- int rv;
- int maxfd;
- fd_set rd, wr, ex;
- struct timeval tv, *tvp;
-
- if (timeout < 0 && timeout != -1) {
- errno = EINVAL;
- return -1;
- }
-
- if (timeout == -1) {
- tvp = NULL;
- } else {
- tv.tv_sec = timeout / 1000;
- tv.tv_usec = (timeout % 1000) * 1000;
- tvp = &tv;
- }
-
- maxfd = -1;
- FD_ZERO(&rd);
- FD_ZERO(&wr);
- FD_ZERO(&ex);
-
- for (i = 0; i < nfds; i++) {
- int osfd = filedes[i].fd;
- int events = filedes[i].events;
- PRBool fdHasEvent = PR_FALSE;
-
- if (osfd < 0) {
- continue; /* Skip this osfd. */
- }
-
- /*
- * Map the poll events to the select fd_sets.
- * POLLIN, POLLRDNORM ===> readable
- * POLLOUT, POLLWRNORM ===> writable
- * POLLPRI, POLLRDBAND ===> exception
- * POLLNORM, POLLWRBAND (and POLLMSG on some platforms)
- * are ignored.
- *
- * The output events POLLERR and POLLHUP are never turned on.
- * POLLNVAL may be turned on.
- */
-
- if (events & (POLLIN | POLLRDNORM)) {
- FD_SET(osfd, &rd);
- fdHasEvent = PR_TRUE;
- }
- if (events & (POLLOUT | POLLWRNORM)) {
- FD_SET(osfd, &wr);
- fdHasEvent = PR_TRUE;
- }
- if (events & (POLLPRI | POLLRDBAND)) {
- FD_SET(osfd, &ex);
- fdHasEvent = PR_TRUE;
- }
- if (fdHasEvent && osfd > maxfd) {
- maxfd = osfd;
- }
- }
-
- rv = select(maxfd + 1, &rd, &wr, &ex, tvp);
-
- /* Compute poll results */
- if (rv > 0) {
- rv = 0;
- for (i = 0; i < nfds; i++) {
- PRBool fdHasEvent = PR_FALSE;
-
- filedes[i].revents = 0;
- if (filedes[i].fd < 0) {
- continue;
- }
- if (FD_ISSET(filedes[i].fd, &rd)) {
- if (filedes[i].events & POLLIN) {
- filedes[i].revents |= POLLIN;
- }
- if (filedes[i].events & POLLRDNORM) {
- filedes[i].revents |= POLLRDNORM;
- }
- fdHasEvent = PR_TRUE;
- }
- if (FD_ISSET(filedes[i].fd, &wr)) {
- if (filedes[i].events & POLLOUT) {
- filedes[i].revents |= POLLOUT;
- }
- if (filedes[i].events & POLLWRNORM) {
- filedes[i].revents |= POLLWRNORM;
- }
- fdHasEvent = PR_TRUE;
- }
- if (FD_ISSET(filedes[i].fd, &ex)) {
- if (filedes[i].events & POLLPRI) {
- filedes[i].revents |= POLLPRI;
- }
- if (filedes[i].events & POLLRDBAND) {
- filedes[i].revents |= POLLRDBAND;
- }
- fdHasEvent = PR_TRUE;
- }
- if (fdHasEvent) {
- rv++;
- }
- }
- PR_ASSERT(rv > 0);
- } else if (rv == -1 && errno == EBADF) {
- rv = 0;
- for (i = 0; i < nfds; i++) {
- filedes[i].revents = 0;
- if (filedes[i].fd < 0) {
- continue;
- }
- if (fcntl(filedes[i].fd, F_GETFL, 0) == -1) {
- filedes[i].revents = POLLNVAL;
- rv++;
- }
- }
- PR_ASSERT(rv > 0);
- }
- PR_ASSERT(-1 != timeout || rv != 0);
-
- return rv;
-}
-#endif /* _PR_NEED_FAKE_POLL */
diff --git a/nspr/pr/src/md/unix/unix_errors.c b/nspr/pr/src/md/unix/unix_errors.c
deleted file mode 100644
index bcea099..0000000
--- a/nspr/pr/src/md/unix/unix_errors.c
+++ /dev/null
@@ -1,829 +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/. */
-
-#include "primpl.h"
-#if defined(_PR_POLL_AVAILABLE)
-#include <poll.h>
-#endif
-#include <errno.h>
-
-void _MD_unix_map_default_error(int err)
-{
- PRErrorCode prError;
-
- switch (err ) {
- case EACCES:
- prError = PR_NO_ACCESS_RIGHTS_ERROR;
- break;
- case EADDRINUSE:
- prError = PR_ADDRESS_IN_USE_ERROR;
- break;
- case EADDRNOTAVAIL:
- prError = PR_ADDRESS_NOT_AVAILABLE_ERROR;
- break;
- case EAFNOSUPPORT:
- prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
- break;
- case EAGAIN:
- prError = PR_WOULD_BLOCK_ERROR;
- break;
- /*
- * On QNX and Neutrino, EALREADY is defined as EBUSY.
- */
-#if EALREADY != EBUSY
- case EALREADY:
- prError = PR_ALREADY_INITIATED_ERROR;
- break;
-#endif
- case EBADF:
- prError = PR_BAD_DESCRIPTOR_ERROR;
- break;
-#ifdef EBADMSG
- case EBADMSG:
- prError = PR_IO_ERROR;
- break;
-#endif
- case EBUSY:
- prError = PR_FILESYSTEM_MOUNTED_ERROR;
- break;
- case ECONNABORTED:
- prError = PR_CONNECT_ABORTED_ERROR;
- break;
- case ECONNREFUSED:
- prError = PR_CONNECT_REFUSED_ERROR;
- break;
- case ECONNRESET:
- prError = PR_CONNECT_RESET_ERROR;
- break;
- case EDEADLK:
- prError = PR_DEADLOCK_ERROR;
- break;
-#ifdef EDIRCORRUPTED
- case EDIRCORRUPTED:
- prError = PR_DIRECTORY_CORRUPTED_ERROR;
- break;
-#endif
-#ifdef EDQUOT
- case EDQUOT:
- prError = PR_NO_DEVICE_SPACE_ERROR;
- break;
-#endif
- case EEXIST:
- prError = PR_FILE_EXISTS_ERROR;
- break;
- case EFAULT:
- prError = PR_ACCESS_FAULT_ERROR;
- break;
- case EFBIG:
- prError = PR_FILE_TOO_BIG_ERROR;
- break;
- case EHOSTUNREACH:
- case EHOSTDOWN:
- prError = PR_HOST_UNREACHABLE_ERROR;
- break;
- case EINPROGRESS:
- prError = PR_IN_PROGRESS_ERROR;
- break;
- case EINTR:
- prError = PR_PENDING_INTERRUPT_ERROR;
- break;
- case EINVAL:
- prError = PR_INVALID_ARGUMENT_ERROR;
- break;
- case EIO:
- prError = PR_IO_ERROR;
- break;
- case EISCONN:
- prError = PR_IS_CONNECTED_ERROR;
- break;
- case EISDIR:
- prError = PR_IS_DIRECTORY_ERROR;
- break;
- case ELOOP:
- prError = PR_LOOP_ERROR;
- break;
- case EMFILE:
- prError = PR_PROC_DESC_TABLE_FULL_ERROR;
- break;
- case EMLINK:
- prError = PR_MAX_DIRECTORY_ENTRIES_ERROR;
- break;
- case EMSGSIZE:
- prError = PR_INVALID_ARGUMENT_ERROR;
- break;
-#ifdef EMULTIHOP
- case EMULTIHOP:
- prError = PR_REMOTE_FILE_ERROR;
- break;
-#endif
- case ENAMETOOLONG:
- prError = PR_NAME_TOO_LONG_ERROR;
- break;
- case ENETUNREACH:
- prError = PR_NETWORK_UNREACHABLE_ERROR;
- break;
- case ENFILE:
- prError = PR_SYS_DESC_TABLE_FULL_ERROR;
- break;
- /*
- * On SCO OpenServer 5, ENOBUFS is defined as ENOSR.
- */
-#if defined(ENOBUFS) && (ENOBUFS != ENOSR)
- case ENOBUFS:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
-#endif
- case ENODEV:
- prError = PR_FILE_NOT_FOUND_ERROR;
- break;
- case ENOENT:
- prError = PR_FILE_NOT_FOUND_ERROR;
- break;
- case ENOLCK:
- prError = PR_FILE_IS_LOCKED_ERROR;
- break;
-#ifdef ENOLINK
- case ENOLINK:
- prError = PR_REMOTE_FILE_ERROR;
- break;
-#endif
- case ENOMEM:
- prError = PR_OUT_OF_MEMORY_ERROR;
- break;
- case ENOPROTOOPT:
- prError = PR_INVALID_ARGUMENT_ERROR;
- break;
- case ENOSPC:
- prError = PR_NO_DEVICE_SPACE_ERROR;
- break;
-#ifdef ENOSR
- case ENOSR:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
-#endif
- case ENOSYS:
- prError = PR_NOT_IMPLEMENTED_ERROR;
- break;
- case ENOTCONN:
- prError = PR_NOT_CONNECTED_ERROR;
- break;
- case ENOTDIR:
- prError = PR_NOT_DIRECTORY_ERROR;
- break;
- case ENOTSOCK:
- prError = PR_NOT_SOCKET_ERROR;
- break;
- case ENXIO:
- prError = PR_FILE_NOT_FOUND_ERROR;
- break;
- case EOPNOTSUPP:
- prError = PR_NOT_TCP_SOCKET_ERROR;
- break;
-#ifdef EOVERFLOW
- case EOVERFLOW:
- prError = PR_BUFFER_OVERFLOW_ERROR;
- break;
-#endif
- case EPERM:
- prError = PR_NO_ACCESS_RIGHTS_ERROR;
- break;
- case EPIPE:
- prError = PR_CONNECT_RESET_ERROR;
- break;
-#ifdef EPROTO
- case EPROTO:
- prError = PR_IO_ERROR;
- break;
-#endif
- case EPROTONOSUPPORT:
- prError = PR_PROTOCOL_NOT_SUPPORTED_ERROR;
- break;
- case EPROTOTYPE:
- prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
- break;
- case ERANGE:
- prError = PR_INVALID_METHOD_ERROR;
- break;
- case EROFS:
- prError = PR_READ_ONLY_FILESYSTEM_ERROR;
- break;
- case ESPIPE:
- prError = PR_INVALID_METHOD_ERROR;
- break;
- case ETIMEDOUT:
- prError = PR_IO_TIMEOUT_ERROR;
- break;
-#if EWOULDBLOCK != EAGAIN
- case EWOULDBLOCK:
- prError = PR_WOULD_BLOCK_ERROR;
- break;
-#endif
- case EXDEV:
- prError = PR_NOT_SAME_DEVICE_ERROR;
- break;
- default:
- prError = PR_UNKNOWN_ERROR;
- break;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_opendir_error(int err)
-{
- _MD_unix_map_default_error(err);
-}
-
-void _MD_unix_map_closedir_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case EINVAL:
- prError = PR_BAD_DESCRIPTOR_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_readdir_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case 0:
- case ENOENT:
- prError = PR_NO_MORE_FILES_ERROR;
- break;
-#ifdef EOVERFLOW
- case EOVERFLOW:
- prError = PR_IO_ERROR;
- break;
-#endif
- case EINVAL:
- prError = PR_IO_ERROR;
- break;
- case ENXIO:
- prError = PR_IO_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_unlink_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case EPERM:
- prError = PR_IS_DIRECTORY_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_stat_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case ETIMEDOUT:
- prError = PR_REMOTE_FILE_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_fstat_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case ETIMEDOUT:
- prError = PR_REMOTE_FILE_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_rename_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case EEXIST:
- prError = PR_DIRECTORY_NOT_EMPTY_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_access_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case ETIMEDOUT:
- prError = PR_REMOTE_FILE_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_mkdir_error(int err)
-{
- _MD_unix_map_default_error(err);
-}
-
-void _MD_unix_map_rmdir_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- /*
- * On AIX 4.3, ENOTEMPTY is defined as EEXIST.
- */
-#if ENOTEMPTY != EEXIST
- case ENOTEMPTY:
- prError = PR_DIRECTORY_NOT_EMPTY_ERROR;
- break;
-#endif
- case EEXIST:
- prError = PR_DIRECTORY_NOT_EMPTY_ERROR;
- break;
- case EINVAL:
- prError = PR_DIRECTORY_NOT_EMPTY_ERROR;
- break;
- case ETIMEDOUT:
- prError = PR_REMOTE_FILE_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_read_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case EINVAL:
- prError = PR_INVALID_METHOD_ERROR;
- break;
- case ENXIO:
- prError = PR_INVALID_ARGUMENT_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_write_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case EINVAL:
- prError = PR_INVALID_METHOD_ERROR;
- break;
- case ENXIO:
- prError = PR_INVALID_METHOD_ERROR;
- break;
- case ETIMEDOUT:
- prError = PR_REMOTE_FILE_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_lseek_error(int err)
-{
- _MD_unix_map_default_error(err);
-}
-
-void _MD_unix_map_fsync_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case ETIMEDOUT:
- prError = PR_REMOTE_FILE_ERROR;
- break;
- case EINVAL:
- prError = PR_INVALID_METHOD_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_close_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case ETIMEDOUT:
- prError = PR_REMOTE_FILE_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_socket_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case ENOMEM:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_socketavailable_error(int err)
-{
- PR_SetError(PR_BAD_DESCRIPTOR_ERROR, err);
-}
-
-void _MD_unix_map_recv_error(int err)
-{
- _MD_unix_map_default_error(err);
-}
-
-void _MD_unix_map_recvfrom_error(int err)
-{
- _MD_unix_map_default_error(err);
-}
-
-void _MD_unix_map_send_error(int err)
-{
- _MD_unix_map_default_error(err);
-}
-
-void _MD_unix_map_sendto_error(int err)
-{
- _MD_unix_map_default_error(err);
-}
-
-void _MD_unix_map_writev_error(int err)
-{
- _MD_unix_map_default_error(err);
-}
-
-void _MD_unix_map_accept_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case ENODEV:
- prError = PR_NOT_TCP_SOCKET_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_connect_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
-#if defined(UNIXWARE)
- /*
- * On some platforms, if we connect to a port on the local host
- * (the loopback address) that no process is listening on, we get
- * EIO instead of ECONNREFUSED.
- */
- case EIO:
- prError = PR_CONNECT_REFUSED_ERROR;
- break;
-#endif
- case ENXIO:
- prError = PR_IO_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_bind_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case EINVAL:
- prError = PR_SOCKET_ADDRESS_IS_BOUND_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_listen_error(int err)
-{
- _MD_unix_map_default_error(err);
-}
-
-void _MD_unix_map_shutdown_error(int err)
-{
- _MD_unix_map_default_error(err);
-}
-
-void _MD_unix_map_socketpair_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case ENOMEM:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_getsockname_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case ENOMEM:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_getpeername_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case ENOMEM:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_getsockopt_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case EINVAL:
- prError = PR_BUFFER_OVERFLOW_ERROR;
- break;
- case ENOMEM:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_setsockopt_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case EINVAL:
- prError = PR_BUFFER_OVERFLOW_ERROR;
- break;
- case ENOMEM:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_open_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case EAGAIN:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
- case EBUSY:
- prError = PR_IO_ERROR;
- break;
- case ENODEV:
- prError = PR_FILE_NOT_FOUND_ERROR;
- break;
- case ENOMEM:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
-#ifdef EOVERFLOW
- case EOVERFLOW:
- prError = PR_FILE_TOO_BIG_ERROR;
- break;
-#endif
- case ETIMEDOUT:
- prError = PR_REMOTE_FILE_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_mmap_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case EAGAIN:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
- case EMFILE:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
- case ENODEV:
- prError = PR_OPERATION_NOT_SUPPORTED_ERROR;
- break;
- case ENXIO:
- prError = PR_INVALID_ARGUMENT_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_gethostname_error(int err)
-{
- _MD_unix_map_default_error(err);
-}
-
-void _MD_unix_map_select_error(int err)
-{
- _MD_unix_map_default_error(err);
-}
-
-#if defined(_PR_POLL_AVAILABLE) || defined(_PR_NEED_FAKE_POLL)
-void _MD_unix_map_poll_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case EAGAIN:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_poll_revents_error(int err)
-{
- if (err & POLLNVAL)
- PR_SetError(PR_BAD_DESCRIPTOR_ERROR, EBADF);
- else if (err & POLLHUP)
- PR_SetError(PR_CONNECT_RESET_ERROR, EPIPE);
- else if (err & POLLERR)
- PR_SetError(PR_IO_ERROR, EIO);
- else
- PR_SetError(PR_UNKNOWN_ERROR, err);
-}
-#endif /* _PR_POLL_AVAILABLE || _PR_NEED_FAKE_POLL */
-
-
-void _MD_unix_map_flock_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case EINVAL:
- prError = PR_BAD_DESCRIPTOR_ERROR;
- break;
- case EWOULDBLOCK:
- prError = PR_FILE_IS_LOCKED_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_unix_map_lockf_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case EACCES:
- prError = PR_FILE_IS_LOCKED_ERROR;
- break;
- case EDEADLK:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
- default:
- _MD_unix_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-#ifdef AIX
-void _MD_aix_map_sendfile_error(int err)
-{
- _MD_unix_map_default_error(err);
-}
-#endif /* AIX */
-
-#ifdef HPUX11
-void _MD_hpux_map_sendfile_error(int err)
-{
- _MD_unix_map_default_error(err);
-}
-#endif /* HPUX11 */
-
-#ifdef SOLARIS
-void _MD_solaris_map_sendfile_error(int err)
-{
- PRErrorCode prError;
-
- switch (err) {
- /*
- * Solaris defines a 0 return value for sendfile to mean end-of-file.
- */
- case 0:
- prError = PR_END_OF_FILE_ERROR;
- break;
-
- default:
- _MD_unix_map_default_error(err) ;
- return;
- }
- PR_SetError(prError, err);
-}
-#endif /* SOLARIS */
-
-#ifdef LINUX
-void _MD_linux_map_sendfile_error(int err)
-{
- _MD_unix_map_default_error(err) ;
-}
-#endif /* LINUX */
diff --git a/nspr/pr/src/md/unix/uxproces.c b/nspr/pr/src/md/unix/uxproces.c
deleted file mode 100644
index a3b35e5..0000000
--- a/nspr/pr/src/md/unix/uxproces.c
+++ /dev/null
@@ -1,885 +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/. */
-
-#include "primpl.h"
-
-#include <sys/types.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <signal.h>
-#include <sys/wait.h>
-#include <string.h>
-#if defined(AIX)
-#include <dlfcn.h> /* For dlopen, dlsym, dlclose */
-#endif
-
-#if defined(DARWIN)
-#if defined(HAVE_CRT_EXTERNS_H)
-#include <crt_externs.h>
-#endif
-#else
-PR_IMPORT_DATA(char **) environ;
-#endif
-
-/*
- * HP-UX 9 doesn't have the SA_RESTART flag.
- */
-#ifndef SA_RESTART
-#define SA_RESTART 0
-#endif
-
-/*
- **********************************************************************
- *
- * The Unix process routines
- *
- **********************************************************************
- */
-
-#define _PR_SIGNALED_EXITSTATUS 256
-
-typedef enum pr_PidState {
- _PR_PID_DETACHED,
- _PR_PID_REAPED,
- _PR_PID_WAITING
-} pr_PidState;
-
-typedef struct pr_PidRecord {
- pid_t pid;
- int exitStatus;
- pr_PidState state;
- PRCondVar *reapedCV;
- struct pr_PidRecord *next;
-} pr_PidRecord;
-
-/*
- * Irix sprocs and LinuxThreads are actually a kind of processes
- * that can share the virtual address space and file descriptors.
- */
-#if (defined(IRIX) && !defined(_PR_PTHREADS)) \
- || ((defined(LINUX) || defined(__GNU__) || defined(__GLIBC__)) \
- && defined(_PR_PTHREADS))
-#define _PR_SHARE_CLONES
-#endif
-
-/*
- * The macro _PR_NATIVE_THREADS indicates that we are
- * using native threads only, so waitpid() blocks just the
- * calling thread, not the process. In this case, the waitpid
- * daemon thread can safely block in waitpid(). So we don't
- * need to catch SIGCHLD, and the pipe to unblock PR_Poll() is
- * also not necessary.
- */
-
-#if defined(_PR_GLOBAL_THREADS_ONLY) \
- || (defined(_PR_PTHREADS) \
- && !defined(LINUX) && !defined(__GNU__) && !defined(__GLIBC__))
-#define _PR_NATIVE_THREADS
-#endif
-
-/*
- * All the static variables used by the Unix process routines are
- * collected in this structure.
- */
-
-static struct {
- PRCallOnceType once;
- PRThread *thread;
- PRLock *ml;
-#if defined(_PR_NATIVE_THREADS)
- PRInt32 numProcs;
- PRCondVar *cv;
-#else
- int pipefd[2];
-#endif
- pr_PidRecord **pidTable;
-
-#ifdef _PR_SHARE_CLONES
- struct pr_CreateProcOp *opHead, *opTail;
-#endif
-
-#ifdef AIX
- pid_t (*forkptr)(void); /* Newer versions of AIX (starting in 4.3.2)
- * have f_fork, which is faster than the
- * regular fork in a multithreaded process
- * because it skips calling the fork handlers.
- * So we look up the f_fork symbol to see if
- * it's available and fall back on fork.
- */
-#endif /* AIX */
-} pr_wp;
-
-#ifdef _PR_SHARE_CLONES
-static int pr_waitpid_daemon_exit;
-
-void
-_MD_unix_terminate_waitpid_daemon(void)
-{
- if (pr_wp.thread) {
- pr_waitpid_daemon_exit = 1;
- write(pr_wp.pipefd[1], "", 1);
- PR_JoinThread(pr_wp.thread);
- }
-}
-#endif
-
-static PRStatus _MD_InitProcesses(void);
-#if !defined(_PR_NATIVE_THREADS)
-static void pr_InstallSigchldHandler(void);
-#endif
-
-static PRProcess *
-ForkAndExec(
- const char *path,
- char *const *argv,
- char *const *envp,
- const PRProcessAttr *attr)
-{
- PRProcess *process;
- int nEnv, idx;
- char *const *childEnvp;
- char **newEnvp = NULL;
- int flags;
-
- process = PR_NEW(PRProcess);
- if (!process) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
-
- childEnvp = envp;
- if (attr && attr->fdInheritBuffer) {
- PRBool found = PR_FALSE;
-
- if (NULL == childEnvp) {
-#ifdef DARWIN
-#ifdef HAVE_CRT_EXTERNS_H
- childEnvp = *(_NSGetEnviron());
-#else
- /* _NSGetEnviron() is not available on iOS. */
- PR_DELETE(process);
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return NULL;
-#endif
-#else
- childEnvp = environ;
-#endif
- }
-
- for (nEnv = 0; childEnvp[nEnv]; nEnv++) {
- }
- newEnvp = (char **) PR_MALLOC((nEnv + 2) * sizeof(char *));
- if (NULL == newEnvp) {
- PR_DELETE(process);
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
- for (idx = 0; idx < nEnv; idx++) {
- newEnvp[idx] = childEnvp[idx];
- if (!found && !strncmp(newEnvp[idx], "NSPR_INHERIT_FDS=", 17)) {
- newEnvp[idx] = attr->fdInheritBuffer;
- found = PR_TRUE;
- }
- }
- if (!found) {
- newEnvp[idx++] = attr->fdInheritBuffer;
- }
- newEnvp[idx] = NULL;
- childEnvp = newEnvp;
- }
-
-#ifdef AIX
- process->md.pid = (*pr_wp.forkptr)();
-#elif defined(NTO) || defined(SYMBIAN)
- /*
- * fork() & exec() does not work in a multithreaded process.
- * Use spawn() instead.
- */
- {
- int fd_map[3] = { 0, 1, 2 };
-
- if (attr) {
- if (attr->stdinFd && attr->stdinFd->secret->md.osfd != 0) {
- fd_map[0] = dup(attr->stdinFd->secret->md.osfd);
- flags = fcntl(fd_map[0], F_GETFL, 0);
- if (flags & O_NONBLOCK)
- fcntl(fd_map[0], F_SETFL, flags & ~O_NONBLOCK);
- }
- if (attr->stdoutFd && attr->stdoutFd->secret->md.osfd != 1) {
- fd_map[1] = dup(attr->stdoutFd->secret->md.osfd);
- flags = fcntl(fd_map[1], F_GETFL, 0);
- if (flags & O_NONBLOCK)
- fcntl(fd_map[1], F_SETFL, flags & ~O_NONBLOCK);
- }
- if (attr->stderrFd && attr->stderrFd->secret->md.osfd != 2) {
- fd_map[2] = dup(attr->stderrFd->secret->md.osfd);
- flags = fcntl(fd_map[2], F_GETFL, 0);
- if (flags & O_NONBLOCK)
- fcntl(fd_map[2], F_SETFL, flags & ~O_NONBLOCK);
- }
-
- PR_ASSERT(attr->currentDirectory == NULL); /* not implemented */
- }
-
-#ifdef SYMBIAN
- /* In Symbian OS, we use posix_spawn instead of fork() and exec() */
- posix_spawn(&(process->md.pid), path, NULL, NULL, argv, childEnvp);
-#else
- process->md.pid = spawn(path, 3, fd_map, NULL, argv, childEnvp);
-#endif
-
- if (fd_map[0] != 0)
- close(fd_map[0]);
- if (fd_map[1] != 1)
- close(fd_map[1]);
- if (fd_map[2] != 2)
- close(fd_map[2]);
- }
-#else
- process->md.pid = fork();
-#endif
- if ((pid_t) -1 == process->md.pid) {
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, errno);
- PR_DELETE(process);
- if (newEnvp) {
- PR_DELETE(newEnvp);
- }
- return NULL;
- } else if (0 == process->md.pid) { /* the child process */
- /*
- * If the child process needs to exit, it must call _exit().
- * Do not call exit(), because exit() will flush and close
- * the standard I/O file descriptors, and hence corrupt
- * the parent process's standard I/O data structures.
- */
-
-#if !defined(NTO) && !defined(SYMBIAN)
- if (attr) {
- /* the osfd's to redirect stdin, stdout, and stderr to */
- int in_osfd = -1, out_osfd = -1, err_osfd = -1;
-
- if (attr->stdinFd
- && attr->stdinFd->secret->md.osfd != 0) {
- in_osfd = attr->stdinFd->secret->md.osfd;
- if (dup2(in_osfd, 0) != 0) {
- _exit(1); /* failed */
- }
- flags = fcntl(0, F_GETFL, 0);
- if (flags & O_NONBLOCK) {
- fcntl(0, F_SETFL, flags & ~O_NONBLOCK);
- }
- }
- if (attr->stdoutFd
- && attr->stdoutFd->secret->md.osfd != 1) {
- out_osfd = attr->stdoutFd->secret->md.osfd;
- if (dup2(out_osfd, 1) != 1) {
- _exit(1); /* failed */
- }
- flags = fcntl(1, F_GETFL, 0);
- if (flags & O_NONBLOCK) {
- fcntl(1, F_SETFL, flags & ~O_NONBLOCK);
- }
- }
- if (attr->stderrFd
- && attr->stderrFd->secret->md.osfd != 2) {
- err_osfd = attr->stderrFd->secret->md.osfd;
- if (dup2(err_osfd, 2) != 2) {
- _exit(1); /* failed */
- }
- flags = fcntl(2, F_GETFL, 0);
- if (flags & O_NONBLOCK) {
- fcntl(2, F_SETFL, flags & ~O_NONBLOCK);
- }
- }
- if (in_osfd != -1) {
- close(in_osfd);
- }
- if (out_osfd != -1 && out_osfd != in_osfd) {
- close(out_osfd);
- }
- if (err_osfd != -1 && err_osfd != in_osfd
- && err_osfd != out_osfd) {
- close(err_osfd);
- }
- if (attr->currentDirectory) {
- if (chdir(attr->currentDirectory) < 0) {
- _exit(1); /* failed */
- }
- }
- }
-
- if (childEnvp) {
- (void)execve(path, argv, childEnvp);
- } else {
- /* Inherit the environment of the parent. */
- (void)execv(path, argv);
- }
- /* Whoops! It returned. That's a bad sign. */
- _exit(1);
-#endif /* !NTO */
- }
-
- if (newEnvp) {
- PR_DELETE(newEnvp);
- }
-
-#if defined(_PR_NATIVE_THREADS)
- PR_Lock(pr_wp.ml);
- if (0 == pr_wp.numProcs++) {
- PR_NotifyCondVar(pr_wp.cv);
- }
- PR_Unlock(pr_wp.ml);
-#endif
- return process;
-}
-
-#ifdef _PR_SHARE_CLONES
-
-struct pr_CreateProcOp {
- const char *path;
- char *const *argv;
- char *const *envp;
- const PRProcessAttr *attr;
- PRProcess *process;
- PRErrorCode prerror;
- PRInt32 oserror;
- PRBool done;
- PRCondVar *doneCV;
- struct pr_CreateProcOp *next;
-};
-
-PRProcess *
-_MD_CreateUnixProcess(
- const char *path,
- char *const *argv,
- char *const *envp,
- const PRProcessAttr *attr)
-{
- struct pr_CreateProcOp *op;
- PRProcess *proc;
- int rv;
-
- if (PR_CallOnce(&pr_wp.once, _MD_InitProcesses) == PR_FAILURE) {
- return NULL;
- }
-
- op = PR_NEW(struct pr_CreateProcOp);
- if (NULL == op) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
- op->path = path;
- op->argv = argv;
- op->envp = envp;
- op->attr = attr;
- op->done = PR_FALSE;
- op->doneCV = PR_NewCondVar(pr_wp.ml);
- if (NULL == op->doneCV) {
- PR_DELETE(op);
- return NULL;
- }
- PR_Lock(pr_wp.ml);
-
- /* add to the tail of op queue */
- op->next = NULL;
- if (pr_wp.opTail) {
- pr_wp.opTail->next = op;
- pr_wp.opTail = op;
- } else {
- PR_ASSERT(NULL == pr_wp.opHead);
- pr_wp.opHead = pr_wp.opTail = op;
- }
-
- /* wake up the daemon thread */
- do {
- rv = write(pr_wp.pipefd[1], "", 1);
- } while (-1 == rv && EINTR == errno);
-
- while (op->done == PR_FALSE) {
- PR_WaitCondVar(op->doneCV, PR_INTERVAL_NO_TIMEOUT);
- }
- PR_Unlock(pr_wp.ml);
- PR_DestroyCondVar(op->doneCV);
- proc = op->process;
- if (!proc) {
- PR_SetError(op->prerror, op->oserror);
- }
- PR_DELETE(op);
- return proc;
-}
-
-#else /* ! _PR_SHARE_CLONES */
-
-PRProcess *
-_MD_CreateUnixProcess(
- const char *path,
- char *const *argv,
- char *const *envp,
- const PRProcessAttr *attr)
-{
- if (PR_CallOnce(&pr_wp.once, _MD_InitProcesses) == PR_FAILURE) {
- return NULL;
- }
- return ForkAndExec(path, argv, envp, attr);
-} /* _MD_CreateUnixProcess */
-
-#endif /* _PR_SHARE_CLONES */
-
-/*
- * The pid table is a hashtable.
- *
- * The number of buckets in the hashtable (NBUCKETS) must be a power of 2.
- */
-#define NBUCKETS_LOG2 6
-#define NBUCKETS (1 << NBUCKETS_LOG2)
-#define PID_HASH_MASK ((pid_t) (NBUCKETS - 1))
-
-static pr_PidRecord *
-FindPidTable(pid_t pid)
-{
- pr_PidRecord *pRec;
- int keyHash = (int) (pid & PID_HASH_MASK);
-
- pRec = pr_wp.pidTable[keyHash];
- while (pRec) {
- if (pRec->pid == pid) {
- break;
- }
- pRec = pRec->next;
- }
- return pRec;
-}
-
-static void
-InsertPidTable(pr_PidRecord *pRec)
-{
- int keyHash = (int) (pRec->pid & PID_HASH_MASK);
-
- pRec->next = pr_wp.pidTable[keyHash];
- pr_wp.pidTable[keyHash] = pRec;
-}
-
-static void
-DeletePidTable(pr_PidRecord *pRec)
-{
- int keyHash = (int) (pRec->pid & PID_HASH_MASK);
-
- if (pr_wp.pidTable[keyHash] == pRec) {
- pr_wp.pidTable[keyHash] = pRec->next;
- } else {
- pr_PidRecord *pred, *cur; /* predecessor and current */
-
- pred = pr_wp.pidTable[keyHash];
- cur = pred->next;
- while (cur) {
- if (cur == pRec) {
- pred->next = cur->next;
- break;
- }
- pred = cur;
- cur = cur->next;
- }
- PR_ASSERT(cur != NULL);
- }
-}
-
-static int
-ExtractExitStatus(int rawExitStatus)
-{
- /*
- * We did not specify the WCONTINUED and WUNTRACED options
- * for waitpid, so these two events should not be reported.
- */
- PR_ASSERT(!WIFSTOPPED(rawExitStatus));
-#ifdef WIFCONTINUED
- PR_ASSERT(!WIFCONTINUED(rawExitStatus));
-#endif
- if (WIFEXITED(rawExitStatus)) {
- return WEXITSTATUS(rawExitStatus);
- } else {
- PR_ASSERT(WIFSIGNALED(rawExitStatus));
- return _PR_SIGNALED_EXITSTATUS;
- }
-}
-
-static void
-ProcessReapedChildInternal(pid_t pid, int status)
-{
- pr_PidRecord *pRec;
-
- pRec = FindPidTable(pid);
- if (NULL == pRec) {
- pRec = PR_NEW(pr_PidRecord);
- pRec->pid = pid;
- pRec->state = _PR_PID_REAPED;
- pRec->exitStatus = ExtractExitStatus(status);
- pRec->reapedCV = NULL;
- InsertPidTable(pRec);
- } else {
- PR_ASSERT(pRec->state != _PR_PID_REAPED);
- if (_PR_PID_DETACHED == pRec->state) {
- PR_ASSERT(NULL == pRec->reapedCV);
- DeletePidTable(pRec);
- PR_DELETE(pRec);
- } else {
- PR_ASSERT(_PR_PID_WAITING == pRec->state);
- PR_ASSERT(NULL != pRec->reapedCV);
- pRec->exitStatus = ExtractExitStatus(status);
- pRec->state = _PR_PID_REAPED;
- PR_NotifyCondVar(pRec->reapedCV);
- }
- }
-}
-
-#if defined(_PR_NATIVE_THREADS)
-
-/*
- * If all the threads are native threads, the daemon thread is
- * simpler. We don't need to catch the SIGCHLD signal. We can
- * just have the daemon thread block in waitpid().
- */
-
-static void WaitPidDaemonThread(void *unused)
-{
- pid_t pid;
- int status;
-
- while (1) {
- PR_Lock(pr_wp.ml);
- while (0 == pr_wp.numProcs) {
- PR_WaitCondVar(pr_wp.cv, PR_INTERVAL_NO_TIMEOUT);
- }
- PR_Unlock(pr_wp.ml);
-
- while (1) {
- do {
- pid = waitpid((pid_t) -1, &status, 0);
- } while ((pid_t) -1 == pid && EINTR == errno);
-
- /*
- * waitpid() cannot return 0 because we did not invoke it
- * with the WNOHANG option.
- */
- PR_ASSERT(0 != pid);
-
- /*
- * The only possible error code is ECHILD. But if we do
- * our accounting correctly, we should only call waitpid()
- * when there is a child process to wait for.
- */
- PR_ASSERT((pid_t) -1 != pid);
- if ((pid_t) -1 == pid) {
- break;
- }
-
- PR_Lock(pr_wp.ml);
- ProcessReapedChildInternal(pid, status);
- pr_wp.numProcs--;
- while (0 == pr_wp.numProcs) {
- PR_WaitCondVar(pr_wp.cv, PR_INTERVAL_NO_TIMEOUT);
- }
- PR_Unlock(pr_wp.ml);
- }
- }
-}
-
-#else /* _PR_NATIVE_THREADS */
-
-static void WaitPidDaemonThread(void *unused)
-{
- PRPollDesc pd;
- PRFileDesc *fd;
- int rv;
- char buf[128];
- pid_t pid;
- int status;
-#ifdef _PR_SHARE_CLONES
- struct pr_CreateProcOp *op;
-#endif
-
-#ifdef _PR_SHARE_CLONES
- pr_InstallSigchldHandler();
-#endif
-
- fd = PR_ImportFile(pr_wp.pipefd[0]);
- PR_ASSERT(NULL != fd);
- pd.fd = fd;
- pd.in_flags = PR_POLL_READ;
-
- while (1) {
- rv = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT);
- PR_ASSERT(1 == rv);
-
-#ifdef _PR_SHARE_CLONES
- if (pr_waitpid_daemon_exit) {
- return;
- }
- PR_Lock(pr_wp.ml);
-#endif
-
- do {
- rv = read(pr_wp.pipefd[0], buf, sizeof(buf));
- } while (sizeof(buf) == rv || (-1 == rv && EINTR == errno));
-
-#ifdef _PR_SHARE_CLONES
- PR_Unlock(pr_wp.ml);
- while ((op = pr_wp.opHead) != NULL) {
- op->process = ForkAndExec(op->path, op->argv,
- op->envp, op->attr);
- if (NULL == op->process) {
- op->prerror = PR_GetError();
- op->oserror = PR_GetOSError();
- }
- PR_Lock(pr_wp.ml);
- pr_wp.opHead = op->next;
- if (NULL == pr_wp.opHead) {
- pr_wp.opTail = NULL;
- }
- op->done = PR_TRUE;
- PR_NotifyCondVar(op->doneCV);
- PR_Unlock(pr_wp.ml);
- }
-#endif
-
- while (1) {
- do {
- pid = waitpid((pid_t) -1, &status, WNOHANG);
- } while ((pid_t) -1 == pid && EINTR == errno);
- if (0 == pid) break;
- if ((pid_t) -1 == pid) {
- /* must be because we have no child processes */
- PR_ASSERT(ECHILD == errno);
- break;
- }
-
- PR_Lock(pr_wp.ml);
- ProcessReapedChildInternal(pid, status);
- PR_Unlock(pr_wp.ml);
- }
- }
-}
-
-static void pr_SigchldHandler(int sig)
-{
- int errnoCopy;
- int rv;
-
- errnoCopy = errno;
-
- do {
- rv = write(pr_wp.pipefd[1], "", 1);
- } while (-1 == rv && EINTR == errno);
-
-#ifdef DEBUG
- if (-1 == rv && EAGAIN != errno && EWOULDBLOCK != errno) {
- char *msg = "cannot write to pipe\n";
- write(2, msg, strlen(msg) + 1);
- _exit(1);
- }
-#endif
-
- errno = errnoCopy;
-}
-
-static void pr_InstallSigchldHandler()
-{
-#if defined(HPUX) && defined(_PR_DCETHREADS)
-#error "HP-UX DCE threads have their own SIGCHLD handler"
-#endif
-
- struct sigaction act, oact;
- int rv;
-
- act.sa_handler = pr_SigchldHandler;
- sigemptyset(&act.sa_mask);
- act.sa_flags = SA_NOCLDSTOP | SA_RESTART;
- rv = sigaction(SIGCHLD, &act, &oact);
- PR_ASSERT(0 == rv);
- /* Make sure we are not overriding someone else's SIGCHLD handler */
-#ifndef _PR_SHARE_CLONES
- PR_ASSERT(oact.sa_handler == SIG_DFL);
-#endif
-}
-
-#endif /* !defined(_PR_NATIVE_THREADS) */
-
-static PRStatus _MD_InitProcesses(void)
-{
-#if !defined(_PR_NATIVE_THREADS)
- int rv;
- int flags;
-#endif
-
-#ifdef AIX
- {
- void *handle = dlopen(NULL, RTLD_NOW | RTLD_GLOBAL);
- pr_wp.forkptr = (pid_t (*)(void)) dlsym(handle, "f_fork");
- if (!pr_wp.forkptr) {
- pr_wp.forkptr = fork;
- }
- dlclose(handle);
- }
-#endif /* AIX */
-
- pr_wp.ml = PR_NewLock();
- PR_ASSERT(NULL != pr_wp.ml);
-
-#if defined(_PR_NATIVE_THREADS)
- pr_wp.numProcs = 0;
- pr_wp.cv = PR_NewCondVar(pr_wp.ml);
- PR_ASSERT(NULL != pr_wp.cv);
-#else
- rv = pipe(pr_wp.pipefd);
- PR_ASSERT(0 == rv);
- flags = fcntl(pr_wp.pipefd[0], F_GETFL, 0);
- fcntl(pr_wp.pipefd[0], F_SETFL, flags | O_NONBLOCK);
- flags = fcntl(pr_wp.pipefd[1], F_GETFL, 0);
- fcntl(pr_wp.pipefd[1], F_SETFL, flags | O_NONBLOCK);
-
-#ifndef _PR_SHARE_CLONES
- pr_InstallSigchldHandler();
-#endif
-#endif /* !_PR_NATIVE_THREADS */
-
- pr_wp.thread = PR_CreateThread(PR_SYSTEM_THREAD,
- WaitPidDaemonThread, NULL, PR_PRIORITY_NORMAL,
-#ifdef _PR_SHARE_CLONES
- PR_GLOBAL_THREAD,
-#else
- PR_LOCAL_THREAD,
-#endif
- PR_JOINABLE_THREAD, 0);
- PR_ASSERT(NULL != pr_wp.thread);
-
- pr_wp.pidTable = (pr_PidRecord**)PR_CALLOC(NBUCKETS * sizeof(pr_PidRecord *));
- PR_ASSERT(NULL != pr_wp.pidTable);
- return PR_SUCCESS;
-}
-
-PRStatus _MD_DetachUnixProcess(PRProcess *process)
-{
- PRStatus retVal = PR_SUCCESS;
- pr_PidRecord *pRec;
-
- PR_Lock(pr_wp.ml);
- pRec = FindPidTable(process->md.pid);
- if (NULL == pRec) {
- pRec = PR_NEW(pr_PidRecord);
- if (NULL == pRec) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- retVal = PR_FAILURE;
- goto done;
- }
- pRec->pid = process->md.pid;
- pRec->state = _PR_PID_DETACHED;
- pRec->reapedCV = NULL;
- InsertPidTable(pRec);
- } else {
- PR_ASSERT(_PR_PID_REAPED == pRec->state);
- if (_PR_PID_REAPED != pRec->state) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- retVal = PR_FAILURE;
- } else {
- DeletePidTable(pRec);
- PR_ASSERT(NULL == pRec->reapedCV);
- PR_DELETE(pRec);
- }
- }
- PR_DELETE(process);
-
-done:
- PR_Unlock(pr_wp.ml);
- return retVal;
-}
-
-PRStatus _MD_WaitUnixProcess(
- PRProcess *process,
- PRInt32 *exitCode)
-{
- pr_PidRecord *pRec;
- PRStatus retVal = PR_SUCCESS;
- PRBool interrupted = PR_FALSE;
-
- PR_Lock(pr_wp.ml);
- pRec = FindPidTable(process->md.pid);
- if (NULL == pRec) {
- pRec = PR_NEW(pr_PidRecord);
- if (NULL == pRec) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- retVal = PR_FAILURE;
- goto done;
- }
- pRec->pid = process->md.pid;
- pRec->state = _PR_PID_WAITING;
- pRec->reapedCV = PR_NewCondVar(pr_wp.ml);
- if (NULL == pRec->reapedCV) {
- PR_DELETE(pRec);
- retVal = PR_FAILURE;
- goto done;
- }
- InsertPidTable(pRec);
- while (!interrupted && _PR_PID_REAPED != pRec->state) {
- if (PR_WaitCondVar(pRec->reapedCV,
- PR_INTERVAL_NO_TIMEOUT) == PR_FAILURE
- && PR_GetError() == PR_PENDING_INTERRUPT_ERROR) {
- interrupted = PR_TRUE;
- }
- }
- if (_PR_PID_REAPED == pRec->state) {
- if (exitCode) {
- *exitCode = pRec->exitStatus;
- }
- } else {
- PR_ASSERT(interrupted);
- retVal = PR_FAILURE;
- }
- DeletePidTable(pRec);
- PR_DestroyCondVar(pRec->reapedCV);
- PR_DELETE(pRec);
- } else {
- PR_ASSERT(_PR_PID_REAPED == pRec->state);
- PR_ASSERT(NULL == pRec->reapedCV);
- DeletePidTable(pRec);
- if (exitCode) {
- *exitCode = pRec->exitStatus;
- }
- PR_DELETE(pRec);
- }
- PR_DELETE(process);
-
-done:
- PR_Unlock(pr_wp.ml);
- return retVal;
-} /* _MD_WaitUnixProcess */
-
-PRStatus _MD_KillUnixProcess(PRProcess *process)
-{
- PRErrorCode prerror;
- PRInt32 oserror;
-
-#ifdef SYMBIAN
- /* In Symbian OS, we can not kill other process with Open C */
- PR_SetError(PR_OPERATION_NOT_SUPPORTED_ERROR, oserror);
- return PR_FAILURE;
-#else
- if (kill(process->md.pid, SIGKILL) == 0) {
- return PR_SUCCESS;
- }
- oserror = errno;
- switch (oserror) {
- case EPERM:
- prerror = PR_NO_ACCESS_RIGHTS_ERROR;
- break;
- case ESRCH:
- prerror = PR_INVALID_ARGUMENT_ERROR;
- break;
- default:
- prerror = PR_UNKNOWN_ERROR;
- break;
- }
- PR_SetError(prerror, oserror);
- return PR_FAILURE;
-#endif
-} /* _MD_KillUnixProcess */
diff --git a/nspr/pr/src/md/unix/uxrng.c b/nspr/pr/src/md/unix/uxrng.c
deleted file mode 100644
index da2f7e9..0000000
--- a/nspr/pr/src/md/unix/uxrng.c
+++ /dev/null
@@ -1,252 +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/. */
-
-
-#include "primpl.h"
-
-#include <string.h>
-#include <unistd.h>
-#include <errno.h>
-#include <sys/time.h>
-
-
-#if defined(SOLARIS)
-
-static size_t
-GetHighResClock(void *buf, size_t maxbytes)
-{
- hrtime_t t;
- t = gethrtime();
- if (t) {
- return _pr_CopyLowBits(buf, maxbytes, &t, sizeof(t));
- }
- return 0;
-}
-
-#elif defined(HPUX)
-
-#ifdef __ia64
-#include <ia64/sys/inline.h>
-
-static size_t
-GetHighResClock(void *buf, size_t maxbytes)
-{
- PRUint64 t;
-
-#ifdef __GNUC__
- __asm__ __volatile__("mov %0 = ar.itc" : "=r" (t));
-#else
- t = _Asm_mov_from_ar(_AREG44);
-#endif
- return _pr_CopyLowBits(buf, maxbytes, &t, sizeof(t));
-}
-#else
-static size_t
-GetHighResClock(void *buf, size_t maxbytes)
-{
- extern int ret_cr16();
- int cr16val;
-
- cr16val = ret_cr16();
- return(_pr_CopyLowBits(buf, maxbytes, &cr16val, sizeof(cr16val)));
-}
-#endif
-
-#elif defined(OSF1)
-
-#include <c_asm.h>
-
-/*
- * Use the "get the cycle counter" instruction on the alpha.
- * The low 32 bits completely turn over in less than a minute.
- * The high 32 bits are some non-counter gunk that changes sometimes.
- */
-static size_t
-GetHighResClock(void *buf, size_t maxbytes)
-{
- unsigned long t;
-
-#ifdef __GNUC__
- __asm__("rpcc %0" : "=r" (t));
-#else
- t = asm("rpcc %v0");
-#endif
- return _pr_CopyLowBits(buf, maxbytes, &t, sizeof(t));
-}
-
-#elif defined(AIX)
-
-static size_t
-GetHighResClock(void *buf, size_t maxbytes)
-{
- return 0;
-}
-
-#elif (defined(LINUX) || defined(FREEBSD) || defined(__FreeBSD_kernel__) \
- || defined(NETBSD) || defined(__NetBSD_kernel__) || defined(OPENBSD) \
- || defined(SYMBIAN) || defined(__GNU__))
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-
-static int fdDevURandom;
-static PRCallOnceType coOpenDevURandom;
-
-static PRStatus OpenDevURandom( void )
-{
- fdDevURandom = open( "/dev/urandom", O_RDONLY );
- return((-1 == fdDevURandom)? PR_FAILURE : PR_SUCCESS );
-} /* end OpenDevURandom() */
-
-static size_t GetDevURandom( void *buf, size_t size )
-{
- int bytesIn;
- int rc;
-
- rc = PR_CallOnce( &coOpenDevURandom, OpenDevURandom );
- if ( PR_FAILURE == rc ) {
- _PR_MD_MAP_OPEN_ERROR( errno );
- return(0);
- }
-
- bytesIn = read( fdDevURandom, buf, size );
- if ( -1 == bytesIn ) {
- _PR_MD_MAP_READ_ERROR( errno );
- return(0);
- }
-
- return( bytesIn );
-} /* end GetDevURandom() */
-
-static size_t
-GetHighResClock(void *buf, size_t maxbytes)
-{
- return(GetDevURandom( buf, maxbytes ));
-}
-
-#elif defined(IRIX)
-#include <fcntl.h>
-#undef PRIVATE
-#include <sys/mman.h>
-#include <sys/syssgi.h>
-#include <sys/immu.h>
-#include <sys/systeminfo.h>
-#include <sys/utsname.h>
-
-static size_t GetHighResClock(void *buf, size_t maxbuf)
-{
- unsigned phys_addr, raddr, cycleval;
- static volatile unsigned *iotimer_addr = NULL;
- static int tries = 0;
- static int cntr_size;
- int mfd;
- unsigned s0[2];
-
-#ifndef SGI_CYCLECNTR_SIZE
-#define SGI_CYCLECNTR_SIZE 165 /* Size user needs to use to read CC */
-#endif
-
- if (iotimer_addr == NULL) {
- if (tries++ > 1) {
- /* Don't keep trying if it didn't work */
- return 0;
- }
-
- /*
- ** For SGI machines we can use the cycle counter, if it has one,
- ** to generate some truly random numbers
- */
- phys_addr = syssgi(SGI_QUERY_CYCLECNTR, &cycleval);
- if (phys_addr) {
- int pgsz = getpagesize();
- int pgoffmask = pgsz - 1;
-
- raddr = phys_addr & ~pgoffmask;
- mfd = open("/dev/mmem", O_RDONLY);
- if (mfd < 0) {
- return 0;
- }
- iotimer_addr = (unsigned *)
- mmap(0, pgoffmask, PROT_READ, MAP_PRIVATE, mfd, (int)raddr);
- if (iotimer_addr == (unsigned*)-1) {
- close(mfd);
- iotimer_addr = NULL;
- return 0;
- }
- iotimer_addr = (unsigned*)
- ((__psint_t)iotimer_addr | (phys_addr & pgoffmask));
- /*
- * The file 'mfd' is purposefully not closed.
- */
- cntr_size = syssgi(SGI_CYCLECNTR_SIZE);
- if (cntr_size < 0) {
- struct utsname utsinfo;
-
- /*
- * We must be executing on a 6.0 or earlier system, since the
- * SGI_CYCLECNTR_SIZE call is not supported.
- *
- * The only pre-6.1 platforms with 64-bit counters are
- * IP19 and IP21 (Challenge, PowerChallenge, Onyx).
- */
- uname(&utsinfo);
- if (!strncmp(utsinfo.machine, "IP19", 4) ||
- !strncmp(utsinfo.machine, "IP21", 4))
- cntr_size = 64;
- else
- cntr_size = 32;
- }
- cntr_size /= 8; /* Convert from bits to bytes */
- }
- }
-
- s0[0] = *iotimer_addr;
- if (cntr_size > 4)
- s0[1] = *(iotimer_addr + 1);
- memcpy(buf, (char *)&s0[0], cntr_size);
- return _pr_CopyLowBits(buf, maxbuf, &s0, cntr_size);
-}
-
-#elif defined(SCO) || defined(UNIXWARE) || defined(BSDI) || defined(NTO) \
- || defined(QNX) || defined(DARWIN) || defined(RISCOS)
-#include <sys/times.h>
-
-static size_t
-GetHighResClock(void *buf, size_t maxbytes)
-{
- int ticks;
- struct tms buffer;
-
- ticks=times(&buffer);
- return _pr_CopyLowBits(buf, maxbytes, &ticks, sizeof(ticks));
-}
-#else
-#error! Platform undefined
-#endif /* defined(SOLARIS) */
-
-extern PRSize _PR_MD_GetRandomNoise( void *buf, PRSize size )
-{
- struct timeval tv;
- int n = 0;
- int s;
-
- n += GetHighResClock(buf, size);
- size -= n;
-
- GETTIMEOFDAY(&tv);
-
- if ( size > 0 ) {
- s = _pr_CopyLowBits((char*)buf+n, size, &tv.tv_usec, sizeof(tv.tv_usec));
- size -= s;
- n += s;
- }
- if ( size > 0 ) {
- s = _pr_CopyLowBits((char*)buf+n, size, &tv.tv_sec, sizeof(tv.tv_usec));
- size -= s;
- n += s;
- }
-
- return n;
-} /* end _PR_MD_GetRandomNoise() */
diff --git a/nspr/pr/src/md/unix/uxshm.c b/nspr/pr/src/md/unix/uxshm.c
deleted file mode 100644
index dec4e3a..0000000
--- a/nspr/pr/src/md/unix/uxshm.c
+++ /dev/null
@@ -1,643 +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/. */
-
-/*
-** uxshm.c -- Unix Implementations NSPR Named Shared Memory
-**
-**
-** lth. Jul-1999.
-**
-*/
-#include <string.h>
-#include <prshm.h>
-#include <prerr.h>
-#include <prmem.h>
-#include "primpl.h"
-#include <fcntl.h>
-
-extern PRLogModuleInfo *_pr_shm_lm;
-
-
-#define NSPR_IPC_SHM_KEY 'b'
-/*
-** Implementation for System V
-*/
-#if defined PR_HAVE_SYSV_NAMED_SHARED_MEMORY
-#include <sys/ipc.h>
-#include <sys/shm.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#define _MD_OPEN_SHARED_MEMORY _MD_OpenSharedMemory
-#define _MD_ATTACH_SHARED_MEMORY _MD_AttachSharedMemory
-#define _MD_DETACH_SHARED_MEMORY _MD_DetachSharedMemory
-#define _MD_CLOSE_SHARED_MEMORY _MD_CloseSharedMemory
-#define _MD_DELETE_SHARED_MEMORY _MD_DeleteSharedMemory
-
-extern PRSharedMemory * _MD_OpenSharedMemory(
- const char *name,
- PRSize size,
- PRIntn flags,
- PRIntn mode
-)
-{
- PRStatus rc = PR_SUCCESS;
- key_t key;
- PRSharedMemory *shm;
- char ipcname[PR_IPC_NAME_SIZE];
-
- rc = _PR_MakeNativeIPCName( name, ipcname, PR_IPC_NAME_SIZE, _PRIPCShm );
- if ( PR_FAILURE == rc )
- {
- _PR_MD_MAP_DEFAULT_ERROR( errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_OpenSharedMemory(): _PR_MakeNativeIPCName() failed: %s", name ));
- return( NULL );
- }
-
- shm = PR_NEWZAP( PRSharedMemory );
- if ( NULL == shm )
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0 );
- PR_LOG(_pr_shm_lm, PR_LOG_DEBUG, ( "PR_OpenSharedMemory: New PRSharedMemory out of memory"));
- return( NULL );
- }
-
- shm->ipcname = (char*)PR_MALLOC( strlen( ipcname ) + 1 );
- if ( NULL == shm->ipcname )
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0 );
- PR_LOG(_pr_shm_lm, PR_LOG_DEBUG, ( "PR_OpenSharedMemory: New shm->ipcname out of memory"));
- PR_DELETE( shm );
- return( NULL );
- }
-
- /* copy args to struct */
- strcpy( shm->ipcname, ipcname );
- shm->size = size;
- shm->mode = mode;
- shm->flags = flags;
- shm->ident = _PR_SHM_IDENT;
-
- /* create the file first */
- if ( flags & PR_SHM_CREATE ) {
- int osfd = open( shm->ipcname, (O_RDWR | O_CREAT), shm->mode );
- if ( -1 == osfd ) {
- _PR_MD_MAP_OPEN_ERROR( errno );
- PR_FREEIF( shm->ipcname );
- PR_DELETE( shm );
- return( NULL );
- }
- if ( close(osfd) == -1 ) {
- _PR_MD_MAP_CLOSE_ERROR( errno );
- PR_FREEIF( shm->ipcname );
- PR_DELETE( shm );
- return( NULL );
- }
- }
-
- /* hash the shm.name to an ID */
- key = ftok( shm->ipcname, NSPR_IPC_SHM_KEY );
- if ( -1 == key )
- {
- rc = PR_FAILURE;
- _PR_MD_MAP_DEFAULT_ERROR( errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_OpenSharedMemory(): ftok() failed on name: %s", shm->ipcname));
- PR_FREEIF( shm->ipcname );
- PR_DELETE( shm );
- return( NULL );
- }
-
- /* get the shared memory */
- if ( flags & PR_SHM_CREATE ) {
- shm->id = shmget( key, shm->size, ( shm->mode | IPC_CREAT|IPC_EXCL));
- if ( shm->id >= 0 ) {
- return( shm );
- }
- if ((errno == EEXIST) && (flags & PR_SHM_EXCL)) {
- PR_SetError( PR_FILE_EXISTS_ERROR, errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_OpenSharedMemory(): shmget() exclusive failed, errno: %d", errno));
- PR_FREEIF(shm->ipcname);
- PR_DELETE(shm);
- return(NULL);
- }
- }
-
- shm->id = shmget( key, shm->size, shm->mode );
- if ( -1 == shm->id ) {
- _PR_MD_MAP_DEFAULT_ERROR( errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_OpenSharedMemory(): shmget() failed, errno: %d", errno));
- PR_FREEIF(shm->ipcname);
- PR_DELETE(shm);
- return(NULL);
- }
-
- return( shm );
-} /* end _MD_OpenSharedMemory() */
-
-extern void * _MD_AttachSharedMemory( PRSharedMemory *shm, PRIntn flags )
-{
- void *addr;
- PRUint32 aFlags = shm->mode;
-
- PR_ASSERT( shm->ident == _PR_SHM_IDENT );
-
- aFlags |= (flags & PR_SHM_READONLY )? SHM_RDONLY : 0;
-
- addr = shmat( shm->id, NULL, aFlags );
- if ( (void*)-1 == addr )
- {
- _PR_MD_MAP_DEFAULT_ERROR( errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_AttachSharedMemory(): shmat() failed on name: %s, OsError: %d",
- shm->ipcname, PR_GetOSError() ));
- addr = NULL;
- }
-
- return addr;
-}
-
-extern PRStatus _MD_DetachSharedMemory( PRSharedMemory *shm, void *addr )
-{
- PRStatus rc = PR_SUCCESS;
- PRIntn urc;
-
- PR_ASSERT( shm->ident == _PR_SHM_IDENT );
-
- urc = shmdt( addr );
- if ( -1 == urc )
- {
- rc = PR_FAILURE;
- _PR_MD_MAP_DEFAULT_ERROR( errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_DetachSharedMemory(): shmdt() failed on name: %s", shm->ipcname ));
- }
-
- return rc;
-}
-
-extern PRStatus _MD_CloseSharedMemory( PRSharedMemory *shm )
-{
- PR_ASSERT( shm->ident == _PR_SHM_IDENT );
-
- PR_FREEIF(shm->ipcname);
- PR_DELETE(shm);
-
- return PR_SUCCESS;
-}
-
-extern PRStatus _MD_DeleteSharedMemory( const char *name )
-{
- PRStatus rc = PR_SUCCESS;
- key_t key;
- int id;
- PRIntn urc;
- char ipcname[PR_IPC_NAME_SIZE];
-
- rc = _PR_MakeNativeIPCName( name, ipcname, PR_IPC_NAME_SIZE, _PRIPCShm );
- if ( PR_FAILURE == rc )
- {
- PR_SetError( PR_UNKNOWN_ERROR , errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_DeleteSharedMemory(): _PR_MakeNativeIPCName() failed: %s", name ));
- return(PR_FAILURE);
- }
-
- /* create the file first */
- {
- int osfd = open( ipcname, (O_RDWR | O_CREAT), 0666 );
- if ( -1 == osfd ) {
- _PR_MD_MAP_OPEN_ERROR( errno );
- return( PR_FAILURE );
- }
- if ( close(osfd) == -1 ) {
- _PR_MD_MAP_CLOSE_ERROR( errno );
- return( PR_FAILURE );
- }
- }
-
- /* hash the shm.name to an ID */
- key = ftok( ipcname, NSPR_IPC_SHM_KEY );
- if ( -1 == key )
- {
- rc = PR_FAILURE;
- _PR_MD_MAP_DEFAULT_ERROR( errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_DeleteSharedMemory(): ftok() failed on name: %s", ipcname));
- }
-
-#ifdef SYMBIAN
- /* In Symbian OS the system imposed minimum is 1 byte, instead of ZERO */
- id = shmget( key, 1, 0 );
-#else
- id = shmget( key, 0, 0 );
-#endif
- if ( -1 == id ) {
- _PR_MD_MAP_DEFAULT_ERROR( errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_DeleteSharedMemory(): shmget() failed, errno: %d", errno));
- return(PR_FAILURE);
- }
-
- urc = shmctl( id, IPC_RMID, NULL );
- if ( -1 == urc )
- {
- _PR_MD_MAP_DEFAULT_ERROR( errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_DeleteSharedMemory(): shmctl() failed on name: %s", ipcname ));
- return(PR_FAILURE);
- }
-
- urc = unlink( ipcname );
- if ( -1 == urc ) {
- _PR_MD_MAP_UNLINK_ERROR( errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_DeleteSharedMemory(): unlink() failed: %s", ipcname ));
- return(PR_FAILURE);
- }
-
- return rc;
-} /* end _MD_DeleteSharedMemory() */
-
-/*
-** Implementation for Posix
-*/
-#elif defined PR_HAVE_POSIX_NAMED_SHARED_MEMORY
-#include <sys/mman.h>
-
-#define _MD_OPEN_SHARED_MEMORY _MD_OpenSharedMemory
-#define _MD_ATTACH_SHARED_MEMORY _MD_AttachSharedMemory
-#define _MD_DETACH_SHARED_MEMORY _MD_DetachSharedMemory
-#define _MD_CLOSE_SHARED_MEMORY _MD_CloseSharedMemory
-#define _MD_DELETE_SHARED_MEMORY _MD_DeleteSharedMemory
-
-struct _MDSharedMemory {
- int handle;
-};
-
-extern PRSharedMemory * _MD_OpenSharedMemory(
- const char *name,
- PRSize size,
- PRIntn flags,
- PRIntn mode
-)
-{
- PRStatus rc = PR_SUCCESS;
- PRInt32 end;
- PRSharedMemory *shm;
- char ipcname[PR_IPC_NAME_SIZE];
-
- rc = _PR_MakeNativeIPCName( name, ipcname, PR_IPC_NAME_SIZE, _PRIPCShm );
- if ( PR_FAILURE == rc )
- {
- PR_SetError( PR_UNKNOWN_ERROR , errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_OpenSharedMemory(): _PR_MakeNativeIPCName() failed: %s", name ));
- return( NULL );
- }
-
- shm = PR_NEWZAP( PRSharedMemory );
- if ( NULL == shm )
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0 );
- PR_LOG(_pr_shm_lm, PR_LOG_DEBUG, ( "PR_OpenSharedMemory: New PRSharedMemory out of memory"));
- return( NULL );
- }
-
- shm->ipcname = PR_MALLOC( strlen( ipcname ) + 1 );
- if ( NULL == shm->ipcname )
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0 );
- PR_LOG(_pr_shm_lm, PR_LOG_DEBUG, ( "PR_OpenSharedMemory: New shm->ipcname out of memory"));
- return( NULL );
- }
-
- /* copy args to struct */
- strcpy( shm->ipcname, ipcname );
- shm->size = size;
- shm->mode = mode;
- shm->flags = flags;
- shm->ident = _PR_SHM_IDENT;
-
- /*
- ** Create the shared memory
- */
- if ( flags & PR_SHM_CREATE ) {
- int oflag = (O_CREAT | O_RDWR);
-
- if ( flags & PR_SHM_EXCL )
- oflag |= O_EXCL;
- shm->id = shm_open( shm->ipcname, oflag, shm->mode );
- } else {
- shm->id = shm_open( shm->ipcname, O_RDWR, shm->mode );
- }
-
- if ( -1 == shm->id ) {
- _PR_MD_MAP_DEFAULT_ERROR( errno );
- PR_LOG(_pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_OpenSharedMemory(): shm_open failed: %s, OSError: %d",
- shm->ipcname, PR_GetOSError()));
- PR_DELETE( shm->ipcname );
- PR_DELETE( shm );
- return(NULL);
- }
-
- end = ftruncate( shm->id, shm->size );
- if ( -1 == end ) {
- _PR_MD_MAP_DEFAULT_ERROR( errno );
- PR_LOG(_pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_OpenSharedMemory(): ftruncate failed, OSError: %d",
- PR_GetOSError()));
- PR_DELETE( shm->ipcname );
- PR_DELETE( shm );
- return(NULL);
- }
-
- return(shm);
-} /* end _MD_OpenSharedMemory() */
-
-extern void * _MD_AttachSharedMemory( PRSharedMemory *shm, PRIntn flags )
-{
- void *addr;
- PRIntn prot = (PROT_READ | PROT_WRITE);
-
- PR_ASSERT( shm->ident == _PR_SHM_IDENT );
-
- if ( PR_SHM_READONLY == flags)
- prot ^= PROT_WRITE;
-
- addr = mmap( (void*)0, shm->size, prot, MAP_SHARED, shm->id, 0 );
- if ((void*)-1 == addr )
- {
- _PR_MD_MAP_DEFAULT_ERROR( errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_AttachSharedMemory(): mmap failed: %s, errno: %d",
- shm->ipcname, PR_GetOSError()));
- addr = NULL;
- } else {
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_AttachSharedMemory(): name: %s, attached at: %p", shm->ipcname, addr));
- }
-
- return addr;
-}
-
-extern PRStatus _MD_DetachSharedMemory( PRSharedMemory *shm, void *addr )
-{
- PRStatus rc = PR_SUCCESS;
- PRIntn urc;
-
- PR_ASSERT( shm->ident == _PR_SHM_IDENT );
-
- urc = munmap( addr, shm->size );
- if ( -1 == urc )
- {
- rc = PR_FAILURE;
- _PR_MD_MAP_DEFAULT_ERROR( errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_DetachSharedMemory(): munmap failed: %s, errno: %d",
- shm->ipcname, PR_GetOSError()));
- }
- return rc;
-}
-
-extern PRStatus _MD_CloseSharedMemory( PRSharedMemory *shm )
-{
- int urc;
-
- PR_ASSERT( shm->ident == _PR_SHM_IDENT );
-
- urc = close( shm->id );
- if ( -1 == urc ) {
- _PR_MD_MAP_CLOSE_ERROR( errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_CloseSharedMemory(): close() failed, error: %d", PR_GetOSError()));
- return(PR_FAILURE);
- }
- PR_DELETE( shm->ipcname );
- PR_DELETE( shm );
- return PR_SUCCESS;
-}
-
-extern PRStatus _MD_DeleteSharedMemory( const char *name )
-{
- PRStatus rc = PR_SUCCESS;
- PRUintn urc;
- char ipcname[PR_IPC_NAME_SIZE];
-
- rc = _PR_MakeNativeIPCName( name, ipcname, PR_IPC_NAME_SIZE, _PRIPCShm );
- if ( PR_FAILURE == rc )
- {
- PR_SetError( PR_UNKNOWN_ERROR , errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_OpenSharedMemory(): _PR_MakeNativeIPCName() failed: %s", name ));
- return rc;
- }
-
- urc = shm_unlink( ipcname );
- if ( -1 == urc ) {
- rc = PR_FAILURE;
- _PR_MD_MAP_DEFAULT_ERROR( errno );
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_DeleteSharedMemory(): shm_unlink failed: %s, errno: %d",
- ipcname, PR_GetOSError()));
- } else {
- PR_LOG( _pr_shm_lm, PR_LOG_DEBUG,
- ("_MD_DeleteSharedMemory(): %s, success", ipcname));
- }
-
- return rc;
-} /* end _MD_DeleteSharedMemory() */
-#endif
-
-
-
-/*
-** Unix implementation for anonymous memory (file) mapping
-*/
-extern PRLogModuleInfo *_pr_shma_lm;
-
-#include <unistd.h>
-
-extern PRFileMap* _md_OpenAnonFileMap(
- const char *dirName,
- PRSize size,
- PRFileMapProtect prot
-)
-{
- PRFileMap *fm = NULL;
- PRFileDesc *fd;
- int osfd;
- PRIntn urc;
- PRIntn mode = 0600;
- char *genName;
- pid_t pid = getpid(); /* for generating filename */
- PRThread *tid = PR_GetCurrentThread(); /* for generating filename */
- int incr; /* for generating filename */
- const int maxTries = 20; /* maximum # attempts at a unique filename */
- PRInt64 size64; /* 64-bit version of 'size' */
-
- /*
- ** generate a filename from input and runtime environment
- ** open the file, unlink the file.
- ** make maxTries number of attempts at uniqueness in the filename
- */
- for ( incr = 0; incr < maxTries ; incr++ ) {
-#if defined(SYMBIAN)
-#define NSPR_AFM_FILENAME "%s\\NSPR-AFM-%d-%p.%d"
-#else
-#define NSPR_AFM_FILENAME "%s/.NSPR-AFM-%d-%p.%d"
-#endif
- genName = PR_smprintf( NSPR_AFM_FILENAME,
- dirName, (int) pid, tid, incr );
- if ( NULL == genName ) {
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_OpenAnonFileMap(): PR_snprintf(): failed, generating filename"));
- goto Finished;
- }
-
- /* create the file */
- osfd = open( genName, (O_CREAT | O_EXCL | O_RDWR), mode );
- if ( -1 == osfd ) {
- if ( EEXIST == errno ) {
- PR_smprintf_free( genName );
- continue; /* name exists, try again */
- } else {
- _PR_MD_MAP_OPEN_ERROR( errno );
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_OpenAnonFileMap(): open(): failed, filename: %s, errno: %d",
- genName, PR_GetOSError()));
- PR_smprintf_free( genName );
- goto Finished;
- }
- }
- break; /* name generation and open successful, break; */
- } /* end for() */
-
- if ( incr == maxTries ) {
- PR_ASSERT( -1 == osfd );
- PR_ASSERT( EEXIST == errno );
- _PR_MD_MAP_OPEN_ERROR( errno );
- goto Finished;
- }
-
- urc = unlink( genName );
-#if defined(SYMBIAN) && defined(__WINS__)
- /* If it is being used by the system or another process, Symbian OS
- * Emulator(WINS) considers this an error. */
- if ( -1 == urc && EACCES != errno ) {
-#else
- if ( -1 == urc ) {
-#endif
- _PR_MD_MAP_UNLINK_ERROR( errno );
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_OpenAnonFileMap(): failed on unlink(), errno: %d", errno));
- PR_smprintf_free( genName );
- close( osfd );
- goto Finished;
- }
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_OpenAnonFileMap(): unlink(): %s", genName ));
-
- PR_smprintf_free( genName );
-
- fd = PR_ImportFile( osfd );
- if ( NULL == fd ) {
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_OpenAnonFileMap(): PR_ImportFile(): failed"));
- goto Finished;
- }
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_OpenAnonFileMap(): fd: %p", fd ));
-
- urc = ftruncate( fd->secret->md.osfd, size );
- if ( -1 == urc ) {
- _PR_MD_MAP_DEFAULT_ERROR( errno );
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_OpenAnonFileMap(): failed on ftruncate(), errno: %d", errno));
- PR_Close( fd );
- goto Finished;
- }
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_OpenAnonFileMap(): ftruncate(): size: %d", size ));
-
- LL_UI2L(size64, size); /* PRSize (size_t) is unsigned */
- fm = PR_CreateFileMap( fd, size64, prot );
- if ( NULL == fm ) {
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("PR_OpenAnonFileMap(): failed"));
- PR_Close( fd );
- goto Finished;
- }
- fm->md.isAnonFM = PR_TRUE; /* set fd close */
-
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_OpenAnonFileMap(): PR_CreateFileMap(): fm: %p", fm ));
-
-Finished:
- return(fm);
-} /* end md_OpenAnonFileMap() */
-
-/*
-** _md_ExportFileMapAsString()
-**
-**
-*/
-extern PRStatus _md_ExportFileMapAsString(
- PRFileMap *fm,
- PRSize bufSize,
- char *buf
-)
-{
- PRIntn written;
- PRIntn prot = (PRIntn)fm->prot;
-
- written = PR_snprintf( buf, bufSize, "%ld:%d",
- fm->fd->secret->md.osfd, prot );
-
- return((written == -1)? PR_FAILURE : PR_SUCCESS);
-} /* end _md_ExportFileMapAsString() */
-
-
-extern PRFileMap * _md_ImportFileMapFromString(
- const char *fmstring
-)
-{
- PRStatus rc;
- PRInt32 osfd;
- PRIntn prot; /* really: a PRFileMapProtect */
- PRFileDesc *fd;
- PRFileMap *fm = NULL; /* default return value */
- PRFileInfo64 info;
-
- PR_sscanf( fmstring, "%ld:%d", &osfd, &prot );
-
- /* import the os file descriptor */
- fd = PR_ImportFile( osfd );
- if ( NULL == fd ) {
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_ImportFileMapFromString(): PR_ImportFile() failed"));
- goto Finished;
- }
-
- rc = PR_GetOpenFileInfo64( fd, &info );
- if ( PR_FAILURE == rc ) {
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_ImportFileMapFromString(): PR_GetOpenFileInfo64() failed"));
- goto Finished;
- }
-
- fm = PR_CreateFileMap( fd, info.size, (PRFileMapProtect)prot );
- if ( NULL == fm ) {
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_ImportFileMapFromString(): PR_CreateFileMap() failed"));
- }
-
-Finished:
- return(fm);
-} /* end _md_ImportFileMapFromString() */
diff --git a/nspr/pr/src/md/unix/uxwrap.c b/nspr/pr/src/md/unix/uxwrap.c
deleted file mode 100644
index 3f8e149..0000000
--- a/nspr/pr/src/md/unix/uxwrap.c
+++ /dev/null
@@ -1,513 +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/. */
-
-/*
- *------------------------------------------------------------------------
- * File: uxwrap.c
- *
- * Our wrapped versions of the Unix select() and poll() system calls.
- *
- *------------------------------------------------------------------------
- */
-
-#include "primpl.h"
-
-#if defined(_PR_PTHREADS) || defined(_PR_GLOBAL_THREADS_ONLY) || defined(QNX)
-/* Do not wrap select() and poll(). */
-#else /* defined(_PR_PTHREADS) || defined(_PR_GLOBAL_THREADS_ONLY) */
-/* The include files for select() */
-#ifdef IRIX
-#include <unistd.h>
-#include <bstring.h>
-#endif
-
-#include <string.h>
-#include <sys/types.h>
-#include <sys/time.h>
-
-#define ZAP_SET(_to, _width) \
- PR_BEGIN_MACRO \
- memset(_to, 0, \
- ((_width + 8*sizeof(int)-1) / (8*sizeof(int))) \
- * sizeof(int) \
- ); \
- PR_END_MACRO
-
-/* see comments in ns/cmd/xfe/mozilla.c (look for "PR_XGetXtHackFD") */
-static int _pr_xt_hack_fd = -1;
-
-int PR_XGetXtHackFD(void)
-{
- int fds[2];
-
- if (_pr_xt_hack_fd == -1) {
- if (!pipe(fds)) {
- _pr_xt_hack_fd = fds[0];
- }
- }
- return _pr_xt_hack_fd;
-}
-
-static int (*_pr_xt_hack_okayToReleaseXLock)(void) = 0;
-
-void PR_SetXtHackOkayToReleaseXLockFn(int (*fn)(void))
-{
- _pr_xt_hack_okayToReleaseXLock = fn;
-}
-
-
-/*
- *-----------------------------------------------------------------------
- * select() --
- *
- * Wrap up the select system call so that we can deschedule
- * a thread that tries to wait for i/o.
- *
- *-----------------------------------------------------------------------
- */
-
-#if defined(HPUX9)
-int select(size_t width, int *rl, int *wl, int *el, const struct timeval *tv)
-#elif defined(AIX_RENAME_SELECT)
-int wrap_select(unsigned long width, void *rl, void *wl, void *el,
- struct timeval *tv)
-#elif defined(_PR_SELECT_CONST_TIMEVAL)
-int select(int width, fd_set *rd, fd_set *wr, fd_set *ex,
- const struct timeval *tv)
-#else
-int select(int width, fd_set *rd, fd_set *wr, fd_set *ex, struct timeval *tv)
-#endif
-{
- int osfd;
- _PRUnixPollDesc *unixpds, *unixpd, *eunixpd;
- PRInt32 pdcnt;
- PRIntervalTime timeout;
- int retVal;
-#if defined(HPUX9) || defined(AIX_RENAME_SELECT)
- fd_set *rd = (fd_set*) rl;
- fd_set *wr = (fd_set*) wl;
- fd_set *ex = (fd_set*) el;
-#endif
-
-#if 0
- /*
- * Easy special case: zero timeout. Simply call the native
- * select() with no fear of blocking.
- */
- if (tv != NULL && tv->tv_sec == 0 && tv->tv_usec == 0) {
-#if defined(HPUX9) || defined(AIX_RENAME_SELECT)
- return _MD_SELECT(width, rl, wl, el, tv);
-#else
- return _MD_SELECT(width, rd, wr, ex, tv);
-#endif
- }
-#endif
-
- if (!_pr_initialized) {
- _PR_ImplicitInitialization();
- }
-
-#ifndef _PR_LOCAL_THREADS_ONLY
- if (_PR_IS_NATIVE_THREAD(_PR_MD_CURRENT_THREAD())) {
- return _MD_SELECT(width, rd, wr, ex, tv);
- }
-#endif
-
- if (width < 0 || width > FD_SETSIZE) {
- errno = EINVAL;
- return -1;
- }
-
- /* Compute timeout */
- if (tv) {
- /*
- * These acceptable ranges for t_sec and t_usec are taken
- * from the select() man pages.
- */
- if (tv->tv_sec < 0 || tv->tv_sec > 100000000
- || tv->tv_usec < 0 || tv->tv_usec >= 1000000) {
- errno = EINVAL;
- return -1;
- }
-
- /* Convert microseconds to ticks */
- timeout = PR_MicrosecondsToInterval(1000000*tv->tv_sec + tv->tv_usec);
- } else {
- /* tv being a NULL pointer means blocking indefinitely */
- timeout = PR_INTERVAL_NO_TIMEOUT;
- }
-
- /* Check for no descriptors case (just doing a timeout) */
- if ((!rd && !wr && !ex) || !width) {
- PR_Sleep(timeout);
- return 0;
- }
-
- /*
- * Set up for PR_Poll(). The PRPollDesc array is allocated
- * dynamically. If this turns out to have high performance
- * penalty, one can change to use a large PRPollDesc array
- * on the stack, and allocate dynamically only when it turns
- * out to be not large enough.
- *
- * I allocate an array of size 'width', which is the maximum
- * number of fds we may need to poll.
- */
- unixpds = (_PRUnixPollDesc *) PR_CALLOC(width * sizeof(_PRUnixPollDesc));
- if (!unixpds) {
- errno = ENOMEM;
- return -1;
- }
-
- pdcnt = 0;
- unixpd = unixpds;
- for (osfd = 0; osfd < width; osfd++) {
- int in_flags = 0;
- if (rd && FD_ISSET(osfd, rd)) {
- in_flags |= _PR_UNIX_POLL_READ;
- }
- if (wr && FD_ISSET(osfd, wr)) {
- in_flags |= _PR_UNIX_POLL_WRITE;
- }
- if (ex && FD_ISSET(osfd, ex)) {
- in_flags |= _PR_UNIX_POLL_EXCEPT;
- }
- if (in_flags) {
- unixpd->osfd = osfd;
- unixpd->in_flags = in_flags;
- unixpd->out_flags = 0;
- unixpd++;
- pdcnt++;
- }
- }
-
- /*
- * see comments in mozilla/cmd/xfe/mozilla.c (look for
- * "PR_XGetXtHackFD")
- */
- {
- int needToLockXAgain;
-
- needToLockXAgain = 0;
- if (rd && (_pr_xt_hack_fd != -1)
- && FD_ISSET(_pr_xt_hack_fd, rd) && PR_XIsLocked()
- && (!_pr_xt_hack_okayToReleaseXLock
- || _pr_xt_hack_okayToReleaseXLock())) {
- PR_XUnlock();
- needToLockXAgain = 1;
- }
-
- /* This is the potentially blocking step */
- retVal = _PR_WaitForMultipleFDs(unixpds, pdcnt, timeout);
-
- if (needToLockXAgain) {
- PR_XLock();
- }
- }
-
- if (retVal > 0) {
- /* Compute select results */
- if (rd) ZAP_SET(rd, width);
- if (wr) ZAP_SET(wr, width);
- if (ex) ZAP_SET(ex, width);
-
- /*
- * The return value can be either the number of ready file
- * descriptors or the number of set bits in the three fd_set's.
- */
- retVal = 0; /* we're going to recompute */
- eunixpd = unixpds + pdcnt;
- for (unixpd = unixpds; unixpd < eunixpd; unixpd++) {
- if (unixpd->out_flags) {
- int nbits = 0; /* The number of set bits on for this fd */
-
- if (unixpd->out_flags & _PR_UNIX_POLL_NVAL) {
- errno = EBADF;
- PR_LOG(_pr_io_lm, PR_LOG_ERROR,
- ("select returns EBADF for %d", unixpd->osfd));
- retVal = -1;
- break;
- }
- /*
- * If a socket has a pending error, it is considered
- * both readable and writable. (See W. Richard Stevens,
- * Unix Network Programming, Vol. 1, 2nd Ed., Section 6.3,
- * pp. 153-154.) We also consider a socket readable if
- * it has a hangup condition.
- */
- if (rd && (unixpd->in_flags & _PR_UNIX_POLL_READ)
- && (unixpd->out_flags & (_PR_UNIX_POLL_READ
- | _PR_UNIX_POLL_ERR | _PR_UNIX_POLL_HUP))) {
- FD_SET(unixpd->osfd, rd);
- nbits++;
- }
- if (wr && (unixpd->in_flags & _PR_UNIX_POLL_WRITE)
- && (unixpd->out_flags & (_PR_UNIX_POLL_WRITE
- | _PR_UNIX_POLL_ERR))) {
- FD_SET(unixpd->osfd, wr);
- nbits++;
- }
- if (ex && (unixpd->in_flags & _PR_UNIX_POLL_WRITE)
- && (unixpd->out_flags & PR_POLL_EXCEPT)) {
- FD_SET(unixpd->osfd, ex);
- nbits++;
- }
- PR_ASSERT(nbits > 0);
-#if defined(HPUX) || defined(SOLARIS) || defined(OSF1) || defined(AIX)
- retVal += nbits;
-#else /* IRIX */
- retVal += 1;
-#endif
- }
- }
- }
-
- PR_ASSERT(tv || retVal != 0);
- PR_LOG(_pr_io_lm, PR_LOG_MIN, ("select returns %d", retVal));
- PR_DELETE(unixpds);
-
- return retVal;
-}
-
-/*
- * Redefine poll, when supported on platforms, for local threads
- */
-
-/*
- * I am commenting out the poll() wrapper for Linux for now
- * because it is difficult to define _MD_POLL that works on all
- * Linux varieties. People reported that glibc 2.0.7 on Debian
- * 2.0 Linux machines doesn't have the __syscall_poll symbol
- * defined. (WTC 30 Nov. 1998)
- */
-#if defined(_PR_POLL_AVAILABLE) && !defined(LINUX)
-
-/*
- *-----------------------------------------------------------------------
- * poll() --
- *
- * RETURN VALUES:
- * -1: fails, errno indicates the error.
- * 0: timed out, the revents bitmasks are not set.
- * positive value: the number of file descriptors for which poll()
- * has set the revents bitmask.
- *
- *-----------------------------------------------------------------------
- */
-
-#include <poll.h>
-
-#if defined(AIX_RENAME_SELECT)
-int wrap_poll(void *listptr, unsigned long nfds, long timeout)
-#elif (defined(AIX) && !defined(AIX_RENAME_SELECT))
-int poll(void *listptr, unsigned long nfds, long timeout)
-#elif defined(OSF1) || (defined(HPUX) && !defined(HPUX9))
-int poll(struct pollfd filedes[], unsigned int nfds, int timeout)
-#elif defined(HPUX9)
-int poll(struct pollfd filedes[], int nfds, int timeout)
-#elif defined(NETBSD)
-int poll(struct pollfd *filedes, nfds_t nfds, int timeout)
-#elif defined(OPENBSD)
-int poll(struct pollfd filedes[], nfds_t nfds, int timeout)
-#elif defined(FREEBSD)
-int poll(struct pollfd *filedes, unsigned nfds, int timeout)
-#else
-int poll(struct pollfd *filedes, unsigned long nfds, int timeout)
-#endif
-{
-#ifdef AIX
- struct pollfd *filedes = (struct pollfd *) listptr;
-#endif
- struct pollfd *pfd, *epfd;
- _PRUnixPollDesc *unixpds, *unixpd, *eunixpd;
- PRIntervalTime ticks;
- PRInt32 pdcnt;
- int ready;
-
- /*
- * Easy special case: zero timeout. Simply call the native
- * poll() with no fear of blocking.
- */
- if (timeout == 0) {
-#if defined(AIX)
- return _MD_POLL(listptr, nfds, timeout);
-#else
- return _MD_POLL(filedes, nfds, timeout);
-#endif
- }
-
- if (!_pr_initialized) {
- _PR_ImplicitInitialization();
- }
-
-#ifndef _PR_LOCAL_THREADS_ONLY
- if (_PR_IS_NATIVE_THREAD(_PR_MD_CURRENT_THREAD())) {
- return _MD_POLL(filedes, nfds, timeout);
- }
-#endif
-
- /* We do not support the pollmsg structures on AIX */
-#ifdef AIX
- PR_ASSERT((nfds & 0xff00) == 0);
-#endif
-
- if (timeout < 0 && timeout != -1) {
- errno = EINVAL;
- return -1;
- }
-
- /* Convert timeout from miliseconds to ticks */
- if (timeout == -1) {
- ticks = PR_INTERVAL_NO_TIMEOUT;
- } else {
- ticks = PR_MillisecondsToInterval(timeout);
- }
-
- /* Check for no descriptor case (just do a timeout) */
- if (nfds == 0) {
- PR_Sleep(ticks);
- return 0;
- }
-
- unixpds = (_PRUnixPollDesc *)
- PR_MALLOC(nfds * sizeof(_PRUnixPollDesc));
- if (NULL == unixpds) {
- errno = EAGAIN;
- return -1;
- }
-
- pdcnt = 0;
- epfd = filedes + nfds;
- unixpd = unixpds;
- for (pfd = filedes; pfd < epfd; pfd++) {
- /*
- * poll() ignores negative fd's.
- */
- if (pfd->fd >= 0) {
- unixpd->osfd = pfd->fd;
-#ifdef _PR_USE_POLL
- unixpd->in_flags = pfd->events;
-#else
- /*
- * Map the poll events to one of the three that can be
- * represented by the select fd_sets:
- * POLLIN, POLLRDNORM ===> readable
- * POLLOUT, POLLWRNORM ===> writable
- * POLLPRI, POLLRDBAND ===> exception
- * POLLNORM, POLLWRBAND (and POLLMSG on some platforms)
- * are ignored.
- *
- * The output events POLLERR and POLLHUP are never turned on.
- * POLLNVAL may be turned on.
- */
- unixpd->in_flags = 0;
- if (pfd->events & (POLLIN
-#ifdef POLLRDNORM
- | POLLRDNORM
-#endif
- )) {
- unixpd->in_flags |= _PR_UNIX_POLL_READ;
- }
- if (pfd->events & (POLLOUT
-#ifdef POLLWRNORM
- | POLLWRNORM
-#endif
- )) {
- unixpd->in_flags |= _PR_UNIX_POLL_WRITE;
- }
- if (pfd->events & (POLLPRI
-#ifdef POLLRDBAND
- | POLLRDBAND
-#endif
- )) {
- unixpd->in_flags |= PR_POLL_EXCEPT;
- }
-#endif /* _PR_USE_POLL */
- unixpd->out_flags = 0;
- unixpd++;
- pdcnt++;
- }
- }
-
- ready = _PR_WaitForMultipleFDs(unixpds, pdcnt, ticks);
- if (-1 == ready) {
- if (PR_GetError() == PR_PENDING_INTERRUPT_ERROR) {
- errno = EINTR; /* XXX we aren't interrupted by a signal, but... */
- } else {
- errno = PR_GetOSError();
- }
- }
- if (ready <= 0) {
- goto done;
- }
-
- /*
- * Copy the out_flags from the _PRUnixPollDesc structures to the
- * user's pollfd structures and free the allocated memory
- */
- unixpd = unixpds;
- for (pfd = filedes; pfd < epfd; pfd++) {
- pfd->revents = 0;
- if (pfd->fd >= 0) {
-#ifdef _PR_USE_POLL
- pfd->revents = unixpd->out_flags;
-#else
- if (0 != unixpd->out_flags) {
- if (unixpd->out_flags & _PR_UNIX_POLL_READ) {
- if (pfd->events & POLLIN) {
- pfd->revents |= POLLIN;
- }
-#ifdef POLLRDNORM
- if (pfd->events & POLLRDNORM) {
- pfd->revents |= POLLRDNORM;
- }
-#endif
- }
- if (unixpd->out_flags & _PR_UNIX_POLL_WRITE) {
- if (pfd->events & POLLOUT) {
- pfd->revents |= POLLOUT;
- }
-#ifdef POLLWRNORM
- if (pfd->events & POLLWRNORM) {
- pfd->revents |= POLLWRNORM;
- }
-#endif
- }
- if (unixpd->out_flags & _PR_UNIX_POLL_EXCEPT) {
- if (pfd->events & POLLPRI) {
- pfd->revents |= POLLPRI;
- }
-#ifdef POLLRDBAND
- if (pfd->events & POLLRDBAND) {
- pfd->revents |= POLLRDBAND;
- }
-#endif
- }
- if (unixpd->out_flags & _PR_UNIX_POLL_ERR) {
- pfd->revents |= POLLERR;
- }
- if (unixpd->out_flags & _PR_UNIX_POLL_NVAL) {
- pfd->revents |= POLLNVAL;
- }
- if (unixpd->out_flags & _PR_UNIX_POLL_HUP) {
- pfd->revents |= POLLHUP;
- }
- }
-#endif /* _PR_USE_POLL */
- unixpd++;
- }
- }
-
-done:
- PR_DELETE(unixpds);
- return ready;
-}
-
-#endif /* !defined(LINUX) */
-
-#endif /* defined(_PR_PTHREADS) || defined(_PR_GLOBAL_THREADS_ONLY) */
-
-/* uxwrap.c */
-
diff --git a/nspr/pr/src/md/windows/ntgc.c b/nspr/pr/src/md/windows/ntgc.c
deleted file mode 100644
index 55ac92f..0000000
--- a/nspr/pr/src/md/windows/ntgc.c
+++ /dev/null
@@ -1,98 +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/. */
-
-/*
- * GC related routines
- *
- */
-#include <windows.h>
-#include "primpl.h"
-
-PRWord *_MD_HomeGCRegisters(PRThread *t, int isCurrent, int *np)
-{
-#if defined(_X86_)
- CONTEXT context;
- context.ContextFlags = CONTEXT_INTEGER;
-
- if (_PR_IS_NATIVE_THREAD(t)) {
- context.ContextFlags |= CONTEXT_CONTROL;
- if (GetThreadContext(t->md.handle, &context)) {
- t->md.gcContext[0] = context.Eax;
- t->md.gcContext[1] = context.Ebx;
- t->md.gcContext[2] = context.Ecx;
- t->md.gcContext[3] = context.Edx;
- t->md.gcContext[4] = context.Esi;
- t->md.gcContext[5] = context.Edi;
- t->md.gcContext[6] = context.Esp;
- t->md.gcContext[7] = context.Ebp;
- *np = PR_NUM_GCREGS;
- } else {
- PR_ASSERT(0);/* XXX */
- }
- } else {
- /* WARNING WARNING WARNING WARNING WARNING WARNING WARNING
- *
- * This code is extremely machine dependant and completely
- * undocumented by MS. Its only known to work experimentally.
- * Ready for a walk on the wild * side?
- *
- * WARNING WARNING WARNING WARNING WARNING WARNING WARNING */
-
-#if !defined WIN95 // Win95 does not have fibers
- int *fiberData = t->md.fiber_id;
-
- /* I found these offsets by disassembling SwitchToFiber().
- * Are your palms sweating yet?
- */
-
- /*
- ** EAX is on the stack (ESP+0)
- ** EDX is on the stack (ESP+4)
- ** ECX is on the stack (ESP+8)
- */
- t->md.gcContext[0] = 0; /* context.Eax */
- t->md.gcContext[1] = fiberData[0x2e]; /* context.Ebx */
- t->md.gcContext[2] = 0; /* context.Ecx */
- t->md.gcContext[3] = 0; /* context.Edx */
- t->md.gcContext[4] = fiberData[0x2d]; /* context.Esi */
- t->md.gcContext[5] = fiberData[0x2c]; /* context.Edi */
- t->md.gcContext[6] = fiberData[0x36]; /* context.Esp */
- t->md.gcContext[7] = fiberData[0x32]; /* context.Ebp */
- *np = PR_NUM_GCREGS;
-#endif
- }
- return (PRWord *)&t->md.gcContext;
-#else
- PR_NOT_REACHED("not implemented");
- return NULL;
-#endif /* defined(_X86_) */
-}
-
-/* This function is not used right now, but is left as a reference.
- * If you ever need to get the fiberID from the currently running fiber,
- * this is it.
- */
-void *
-GetMyFiberID()
-{
-#if defined(_X86_) && !defined(__MINGW32__)
- void *fiberData;
-
- /* A pointer to our tib entry is found at FS:[18]
- * At offset 10h is the fiberData pointer. The context of the
- * fiber is stored in there.
- */
- __asm {
- mov EDX, FS:[18h]
- mov EAX, DWORD PTR [EDX+10h]
- mov [fiberData], EAX
- }
-
- return fiberData;
-#else
- PR_NOT_REACHED("not implemented");
- return NULL;
-#endif /* defined(_X86_) */
-}
diff --git a/nspr/pr/src/md/windows/ntinrval.c b/nspr/pr/src/md/windows/ntinrval.c
deleted file mode 100644
index 10aca11..0000000
--- a/nspr/pr/src/md/windows/ntinrval.c
+++ /dev/null
@@ -1,51 +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/. */
-
-/*
- * NT interval timers
- *
- */
-
-/* Mozilla's build system defines this globally. */
-#ifdef WIN32_LEAN_AND_MEAN
-#undef WIN32_LEAN_AND_MEAN
-#endif
-#include "primpl.h"
-
-#ifdef WINCE
-typedef DWORD (*IntervalFuncType)(void);
-static IntervalFuncType intervalFunc;
-#endif
-
-void
-_PR_MD_INTERVAL_INIT()
-{
-#ifdef WINCE
- HMODULE mmtimerlib = LoadLibraryW(L"mmtimer.dll"); /* XXX leaked! */
- if (mmtimerlib) {
- intervalFunc = (IntervalFuncType)GetProcAddress(mmtimerlib,
- "timeGetTime");
- } else {
- intervalFunc = &GetTickCount;
- }
-#endif
-}
-
-PRIntervalTime
-_PR_MD_GET_INTERVAL()
-{
- /* milliseconds since system start */
-#ifdef WINCE
- return (*intervalFunc)();
-#else
- return timeGetTime();
-#endif
-}
-
-PRIntervalTime
-_PR_MD_INTERVAL_PER_SEC()
-{
- return 1000;
-}
diff --git a/nspr/pr/src/md/windows/ntmisc.c b/nspr/pr/src/md/windows/ntmisc.c
deleted file mode 100644
index 12f8c1d..0000000
--- a/nspr/pr/src/md/windows/ntmisc.c
+++ /dev/null
@@ -1,1201 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* 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/. */
-
-/*
- * ntmisc.c
- *
- */
-
-#include "primpl.h"
-#include <math.h> /* for fabs() */
-#include <windows.h>
-
-char *_PR_MD_GET_ENV(const char *name)
-{
- return getenv(name);
-}
-
-/*
-** _PR_MD_PUT_ENV() -- add or change environment variable
-**
-**
-*/
-PRIntn _PR_MD_PUT_ENV(const char *name)
-{
- return(putenv(name));
-}
-
-
-/*
- **************************************************************************
- **************************************************************************
- **
- ** Date and time routines
- **
- **************************************************************************
- **************************************************************************
- */
-
-/*
- * The NSPR epoch (00:00:00 1 Jan 1970 UTC) in FILETIME.
- * We store the value in a PRTime variable for convenience.
- */
-#ifdef __GNUC__
-const PRTime _pr_filetime_offset = 116444736000000000LL;
-const PRTime _pr_filetime_divisor = 10LL;
-#else
-const PRTime _pr_filetime_offset = 116444736000000000i64;
-const PRTime _pr_filetime_divisor = 10i64;
-#endif
-
-#ifdef WINCE
-
-#define FILETIME_TO_INT64(ft) \
- (((PRInt64)ft.dwHighDateTime) << 32 | (PRInt64)ft.dwLowDateTime)
-
-static void
-LowResTime(LPFILETIME lpft)
-{
- GetCurrentFT(lpft);
-}
-
-typedef struct CalibrationData {
- long double freq; /* The performance counter frequency */
- long double offset; /* The low res 'epoch' */
- long double timer_offset; /* The high res 'epoch' */
-
- /* The last high res time that we returned since recalibrating */
- PRInt64 last;
-
- PRBool calibrated;
-
- CRITICAL_SECTION data_lock;
- CRITICAL_SECTION calibration_lock;
- PRInt64 granularity;
-} CalibrationData;
-
-static CalibrationData calibration;
-
-typedef void (*GetSystemTimeAsFileTimeFcn)(LPFILETIME);
-static GetSystemTimeAsFileTimeFcn ce6_GetSystemTimeAsFileTime = NULL;
-
-static void
-NowCalibrate(void)
-{
- FILETIME ft, ftStart;
- LARGE_INTEGER liFreq, now;
-
- if (calibration.freq == 0.0) {
- if(!QueryPerformanceFrequency(&liFreq)) {
- /* High-performance timer is unavailable */
- calibration.freq = -1.0;
- } else {
- calibration.freq = (long double) liFreq.QuadPart;
- }
- }
- if (calibration.freq > 0.0) {
- PRInt64 calibrationDelta = 0;
- /*
- * By wrapping a timeBegin/EndPeriod pair of calls around this loop,
- * the loop seems to take much less time (1 ms vs 15ms) on Vista.
- */
- timeBeginPeriod(1);
- LowResTime(&ftStart);
- do {
- LowResTime(&ft);
- } while (memcmp(&ftStart,&ft, sizeof(ft)) == 0);
- timeEndPeriod(1);
-
- calibration.granularity =
- (FILETIME_TO_INT64(ft) - FILETIME_TO_INT64(ftStart))/10;
-
- QueryPerformanceCounter(&now);
-
- calibration.offset = (long double) FILETIME_TO_INT64(ft);
- calibration.timer_offset = (long double) now.QuadPart;
- /*
- * The windows epoch is around 1600. The unix epoch is around 1970.
- * _pr_filetime_offset is the difference (in windows time units which
- * are 10 times more highres than the JS time unit)
- */
- calibration.offset -= _pr_filetime_offset;
- calibration.offset *= 0.1;
- calibration.last = 0;
-
- calibration.calibrated = PR_TRUE;
- }
-}
-
-#define CALIBRATIONLOCK_SPINCOUNT 0
-#define DATALOCK_SPINCOUNT 4096
-#define LASTLOCK_SPINCOUNT 4096
-
-void
-_MD_InitTime(void)
-{
- /* try for CE6 GetSystemTimeAsFileTime first */
- HANDLE h = GetModuleHandleW(L"coredll.dll");
- ce6_GetSystemTimeAsFileTime = (GetSystemTimeAsFileTimeFcn)
- GetProcAddressA(h, "GetSystemTimeAsFileTime");
-
- /* otherwise go the slow route */
- if (ce6_GetSystemTimeAsFileTime == NULL) {
- memset(&calibration, 0, sizeof(calibration));
- NowCalibrate();
- InitializeCriticalSection(&calibration.calibration_lock);
- InitializeCriticalSection(&calibration.data_lock);
- }
-}
-
-void
-_MD_CleanupTime(void)
-{
- if (ce6_GetSystemTimeAsFileTime == NULL) {
- DeleteCriticalSection(&calibration.calibration_lock);
- DeleteCriticalSection(&calibration.data_lock);
- }
-}
-
-#define MUTEX_SETSPINCOUNT(m, c)
-
-/*
- *-----------------------------------------------------------------------
- *
- * PR_Now --
- *
- * Returns the current time in microseconds since the epoch.
- * The epoch is midnight January 1, 1970 GMT.
- * The implementation is machine dependent. This is the
- * implementation for Windows.
- * Cf. time_t time(time_t *tp)
- *
- *-----------------------------------------------------------------------
- */
-
-PR_IMPLEMENT(PRTime)
-PR_Now(void)
-{
- long double lowresTime, highresTimerValue;
- FILETIME ft;
- LARGE_INTEGER now;
- PRBool calibrated = PR_FALSE;
- PRBool needsCalibration = PR_FALSE;
- PRInt64 returnedTime;
- long double cachedOffset = 0.0;
-
- if (ce6_GetSystemTimeAsFileTime) {
- union {
- FILETIME ft;
- PRTime prt;
- } currentTime;
-
- PR_ASSERT(sizeof(FILETIME) == sizeof(PRTime));
-
- ce6_GetSystemTimeAsFileTime(¤tTime.ft);
-
- /* written this way on purpose, since the second term becomes
- * a constant, and the entire expression is faster to execute.
- */
- return currentTime.prt/_pr_filetime_divisor -
- _pr_filetime_offset/_pr_filetime_divisor;
- }
-
- do {
- if (!calibration.calibrated || needsCalibration) {
- EnterCriticalSection(&calibration.calibration_lock);
- EnterCriticalSection(&calibration.data_lock);
-
- /* Recalibrate only if no one else did before us */
- if (calibration.offset == cachedOffset) {
- /*
- * Since calibration can take a while, make any other
- * threads immediately wait
- */
- MUTEX_SETSPINCOUNT(&calibration.data_lock, 0);
-
- NowCalibrate();
-
- calibrated = PR_TRUE;
-
- /* Restore spin count */
- MUTEX_SETSPINCOUNT(&calibration.data_lock, DATALOCK_SPINCOUNT);
- }
- LeaveCriticalSection(&calibration.data_lock);
- LeaveCriticalSection(&calibration.calibration_lock);
- }
-
- /* Calculate a low resolution time */
- LowResTime(&ft);
- lowresTime =
- ((long double)(FILETIME_TO_INT64(ft) - _pr_filetime_offset)) * 0.1;
-
- if (calibration.freq > 0.0) {
- long double highresTime, diff;
- DWORD timeAdjustment, timeIncrement;
- BOOL timeAdjustmentDisabled;
-
- /* Default to 15.625 ms if the syscall fails */
- long double skewThreshold = 15625.25;
-
- /* Grab high resolution time */
- QueryPerformanceCounter(&now);
- highresTimerValue = (long double)now.QuadPart;
-
- EnterCriticalSection(&calibration.data_lock);
- highresTime = calibration.offset + 1000000L *
- (highresTimerValue-calibration.timer_offset)/calibration.freq;
- cachedOffset = calibration.offset;
-
- /*
- * On some dual processor/core systems, we might get an earlier
- * time so we cache the last time that we returned.
- */
- calibration.last = PR_MAX(calibration.last,(PRInt64)highresTime);
- returnedTime = calibration.last;
- LeaveCriticalSection(&calibration.data_lock);
-
- /* Get an estimate of clock ticks per second from our own test */
- skewThreshold = calibration.granularity;
- /* Check for clock skew */
- diff = lowresTime - highresTime;
-
- /*
- * For some reason that I have not determined, the skew can be
- * up to twice a kernel tick. This does not seem to happen by
- * itself, but I have only seen it triggered by another program
- * doing some kind of file I/O. The symptoms are a negative diff
- * followed by an equally large positive diff.
- */
- if (fabs(diff) > 2*skewThreshold) {
- if (calibrated) {
- /*
- * If we already calibrated once this instance, and the
- * clock is still skewed, then either the processor(s) are
- * wildly changing clockspeed or the system is so busy that
- * we get switched out for long periods of time. In either
- * case, it would be infeasible to make use of high
- * resolution results for anything, so let's resort to old
- * behavior for this call. It's possible that in the
- * future, the user will want the high resolution timer, so
- * we don't disable it entirely.
- */
- returnedTime = (PRInt64)lowresTime;
- needsCalibration = PR_FALSE;
- } else {
- /*
- * It is possible that when we recalibrate, we will return
- * a value less than what we have returned before; this is
- * unavoidable. We cannot tell the different between a
- * faulty QueryPerformanceCounter implementation and user
- * changes to the operating system time. Since we must
- * respect user changes to the operating system time, we
- * cannot maintain the invariant that Date.now() never
- * decreases; the old implementation has this behavior as
- * well.
- */
- needsCalibration = PR_TRUE;
- }
- } else {
- /* No detectable clock skew */
- returnedTime = (PRInt64)highresTime;
- needsCalibration = PR_FALSE;
- }
- } else {
- /* No high resolution timer is available, so fall back */
- returnedTime = (PRInt64)lowresTime;
- }
- } while (needsCalibration);
-
- return returnedTime;
-}
-
-#else
-
-PR_IMPLEMENT(PRTime)
-PR_Now(void)
-{
- PRTime prt;
- FILETIME ft;
- SYSTEMTIME st;
-
- GetSystemTime(&st);
- SystemTimeToFileTime(&st, &ft);
- _PR_FileTimeToPRTime(&ft, &prt);
- return prt;
-}
-
-#endif
-
-/*
- ***********************************************************************
- ***********************************************************************
- *
- * Process creation routines
- *
- ***********************************************************************
- ***********************************************************************
- */
-
-/*
- * Assemble the command line by concatenating the argv array.
- * On success, this function returns 0 and the resulting command
- * line is returned in *cmdLine. On failure, it returns -1.
- */
-static int assembleCmdLine(char *const *argv, char **cmdLine)
-{
- char *const *arg;
- char *p, *q;
- size_t cmdLineSize;
- int numBackslashes;
- int i;
- int argNeedQuotes;
-
- /*
- * Find out how large the command line buffer should be.
- */
- cmdLineSize = 0;
- for (arg = argv; *arg; arg++) {
- /*
- * \ and " need to be escaped by a \. In the worst case,
- * every character is a \ or ", so the string of length
- * may double. If we quote an argument, that needs two ".
- * Finally, we need a space between arguments, and
- * a null byte at the end of command line.
- */
- cmdLineSize += 2 * strlen(*arg) /* \ and " need to be escaped */
- + 2 /* we quote every argument */
- + 1; /* space in between, or final null */
- }
- p = *cmdLine = PR_MALLOC((PRUint32) cmdLineSize);
- if (p == NULL) {
- return -1;
- }
-
- for (arg = argv; *arg; arg++) {
- /* Add a space to separates the arguments */
- if (arg != argv) {
- *p++ = ' ';
- }
- q = *arg;
- numBackslashes = 0;
- argNeedQuotes = 0;
-
- /*
- * If the argument is empty or contains white space, it needs to
- * be quoted.
- */
- if (**arg == '\0' || strpbrk(*arg, " \f\n\r\t\v")) {
- argNeedQuotes = 1;
- }
-
- if (argNeedQuotes) {
- *p++ = '"';
- }
- while (*q) {
- if (*q == '\\') {
- numBackslashes++;
- q++;
- } else if (*q == '"') {
- if (numBackslashes) {
- /*
- * Double the backslashes since they are followed
- * by a quote
- */
- for (i = 0; i < 2 * numBackslashes; i++) {
- *p++ = '\\';
- }
- numBackslashes = 0;
- }
- /* To escape the quote */
- *p++ = '\\';
- *p++ = *q++;
- } else {
- if (numBackslashes) {
- /*
- * Backslashes are not followed by a quote, so
- * don't need to double the backslashes.
- */
- for (i = 0; i < numBackslashes; i++) {
- *p++ = '\\';
- }
- numBackslashes = 0;
- }
- *p++ = *q++;
- }
- }
-
- /* Now we are at the end of this argument */
- if (numBackslashes) {
- /*
- * Double the backslashes if we have a quote string
- * delimiter at the end.
- */
- if (argNeedQuotes) {
- numBackslashes *= 2;
- }
- for (i = 0; i < numBackslashes; i++) {
- *p++ = '\\';
- }
- }
- if (argNeedQuotes) {
- *p++ = '"';
- }
- }
-
- *p = '\0';
- return 0;
-}
-
-/*
- * Assemble the environment block by concatenating the envp array
- * (preserving the terminating null byte in each array element)
- * and adding a null byte at the end.
- *
- * Returns 0 on success. The resulting environment block is returned
- * in *envBlock. Note that if envp is NULL, a NULL pointer is returned
- * in *envBlock. Returns -1 on failure.
- */
-static int assembleEnvBlock(char **envp, char **envBlock)
-{
- char *p;
- char *q;
- char **env;
- char *curEnv;
- char *cwdStart, *cwdEnd;
- size_t envBlockSize;
-
- if (envp == NULL) {
- *envBlock = NULL;
- return 0;
- }
-
-#ifdef WINCE
- {
- PRUnichar *wideCurEnv = mozce_GetEnvString();
- int len = WideCharToMultiByte(CP_ACP, 0, wideCurEnv, -1,
- NULL, 0, NULL, NULL);
- curEnv = (char *) PR_MALLOC(len * sizeof(char));
- WideCharToMultiByte(CP_ACP, 0, wideCurEnv, -1,
- curEnv, len, NULL, NULL);
- free(wideCurEnv);
- }
-#else
- curEnv = GetEnvironmentStrings();
-#endif
-
- cwdStart = curEnv;
- while (*cwdStart) {
- if (cwdStart[0] == '=' && cwdStart[1] != '\0'
- && cwdStart[2] == ':' && cwdStart[3] == '=') {
- break;
- }
- cwdStart += strlen(cwdStart) + 1;
- }
- cwdEnd = cwdStart;
- if (*cwdEnd) {
- cwdEnd += strlen(cwdEnd) + 1;
- while (*cwdEnd) {
- if (cwdEnd[0] != '=' || cwdEnd[1] == '\0'
- || cwdEnd[2] != ':' || cwdEnd[3] != '=') {
- break;
- }
- cwdEnd += strlen(cwdEnd) + 1;
- }
- }
- envBlockSize = cwdEnd - cwdStart;
-
- for (env = envp; *env; env++) {
- envBlockSize += strlen(*env) + 1;
- }
- envBlockSize++;
-
- p = *envBlock = PR_MALLOC((PRUint32) envBlockSize);
- if (p == NULL) {
-#ifdef WINCE
- PR_Free(curEnv);
-#else
- FreeEnvironmentStrings(curEnv);
-#endif
- return -1;
- }
-
- q = cwdStart;
- while (q < cwdEnd) {
- *p++ = *q++;
- }
-#ifdef WINCE
- PR_Free(curEnv);
-#else
- FreeEnvironmentStrings(curEnv);
-#endif
-
- for (env = envp; *env; env++) {
- q = *env;
- while (*q) {
- *p++ = *q++;
- }
- *p++ = '\0';
- }
- *p = '\0';
- return 0;
-}
-
-/*
- * For qsort. We sort (case-insensitive) the environment strings
- * before generating the environment block.
- */
-static int compare(const void *arg1, const void *arg2)
-{
- return _stricmp(* (char**)arg1, * (char**)arg2);
-}
-
-PRProcess * _PR_CreateWindowsProcess(
- const char *path,
- char *const *argv,
- char *const *envp,
- const PRProcessAttr *attr)
-{
-#ifdef WINCE
- STARTUPINFOW startupInfo;
- PRUnichar *wideCmdLine;
- PRUnichar *wideCwd;
- int len = 0;
-#else
- STARTUPINFO startupInfo;
-#endif
- DWORD creationFlags = 0;
- PROCESS_INFORMATION procInfo;
- BOOL retVal;
- char *cmdLine = NULL;
- char *envBlock = NULL;
- char **newEnvp = NULL;
- const char *cwd = NULL; /* current working directory */
- PRProcess *proc = NULL;
- PRBool hasFdInheritBuffer;
-
- proc = PR_NEW(PRProcess);
- if (!proc) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- goto errorExit;
- }
-
- if (assembleCmdLine(argv, &cmdLine) == -1) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- goto errorExit;
- }
-
-#ifndef WINCE
- /*
- * If attr->fdInheritBuffer is not NULL, we need to insert
- * it into the envp array, so envp cannot be NULL.
- */
- hasFdInheritBuffer = (attr && attr->fdInheritBuffer);
- if ((envp == NULL) && hasFdInheritBuffer) {
- envp = environ;
- }
-
- if (envp != NULL) {
- int idx;
- int numEnv;
- PRBool found = PR_FALSE;
-
- numEnv = 0;
- while (envp[numEnv]) {
- numEnv++;
- }
- newEnvp = (char **) PR_MALLOC((numEnv + 2) * sizeof(char *));
- for (idx = 0; idx < numEnv; idx++) {
- newEnvp[idx] = envp[idx];
- if (hasFdInheritBuffer && !found
- && !strncmp(newEnvp[idx], "NSPR_INHERIT_FDS=", 17)) {
- newEnvp[idx] = attr->fdInheritBuffer;
- found = PR_TRUE;
- }
- }
- if (hasFdInheritBuffer && !found) {
- newEnvp[idx++] = attr->fdInheritBuffer;
- }
- newEnvp[idx] = NULL;
- qsort((void *) newEnvp, (size_t) idx, sizeof(char *), compare);
- }
- if (assembleEnvBlock(newEnvp, &envBlock) == -1) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- goto errorExit;
- }
-
- ZeroMemory(&startupInfo, sizeof(startupInfo));
- startupInfo.cb = sizeof(startupInfo);
-
- if (attr) {
- PRBool redirected = PR_FALSE;
-
- /*
- * XXX the default value for stdin, stdout, and stderr
- * should probably be the console input and output, not
- * those of the parent process.
- */
- startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
- startupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
- startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
- if (attr->stdinFd) {
- startupInfo.hStdInput = (HANDLE) attr->stdinFd->secret->md.osfd;
- redirected = PR_TRUE;
- }
- if (attr->stdoutFd) {
- startupInfo.hStdOutput = (HANDLE) attr->stdoutFd->secret->md.osfd;
- redirected = PR_TRUE;
- /*
- * If stdout is redirected, we can assume that the process will
- * not write anything useful to the console windows, and therefore
- * automatically set the CREATE_NO_WINDOW flag.
- */
- creationFlags |= CREATE_NO_WINDOW;
- }
- if (attr->stderrFd) {
- startupInfo.hStdError = (HANDLE) attr->stderrFd->secret->md.osfd;
- redirected = PR_TRUE;
- }
- if (redirected) {
- startupInfo.dwFlags |= STARTF_USESTDHANDLES;
- }
- cwd = attr->currentDirectory;
- }
-#endif
-
-#ifdef WINCE
- len = MultiByteToWideChar(CP_ACP, 0, cmdLine, -1, NULL, 0);
- wideCmdLine = (PRUnichar *)PR_MALLOC(len * sizeof(PRUnichar));
- MultiByteToWideChar(CP_ACP, 0, cmdLine, -1, wideCmdLine, len);
- len = MultiByteToWideChar(CP_ACP, 0, cwd, -1, NULL, 0);
- wideCwd = PR_MALLOC(len * sizeof(PRUnichar));
- MultiByteToWideChar(CP_ACP, 0, cwd, -1, wideCwd, len);
- retVal = CreateProcessW(NULL,
- wideCmdLine,
- NULL, /* security attributes for the new
- * process */
- NULL, /* security attributes for the primary
- * thread in the new process */
- TRUE, /* inherit handles */
- creationFlags,
- envBlock, /* an environment block, consisting
- * of a null-terminated block of
- * null-terminated strings. Each
- * string is in the form:
- * name=value
- * XXX: usually NULL */
- wideCwd, /* current drive and directory */
- &startupInfo,
- &procInfo
- );
- PR_Free(wideCmdLine);
- PR_Free(wideCwd);
-#else
- retVal = CreateProcess(NULL,
- cmdLine,
- NULL, /* security attributes for the new
- * process */
- NULL, /* security attributes for the primary
- * thread in the new process */
- TRUE, /* inherit handles */
- creationFlags,
- envBlock, /* an environment block, consisting
- * of a null-terminated block of
- * null-terminated strings. Each
- * string is in the form:
- * name=value
- * XXX: usually NULL */
- cwd, /* current drive and directory */
- &startupInfo,
- &procInfo
- );
-#endif
-
- if (retVal == FALSE) {
- /* XXX what error code? */
- PR_SetError(PR_UNKNOWN_ERROR, GetLastError());
- goto errorExit;
- }
-
- CloseHandle(procInfo.hThread);
- proc->md.handle = procInfo.hProcess;
- proc->md.id = procInfo.dwProcessId;
-
- PR_DELETE(cmdLine);
- if (newEnvp) {
- PR_DELETE(newEnvp);
- }
- if (envBlock) {
- PR_DELETE(envBlock);
- }
- return proc;
-
-errorExit:
- if (cmdLine) {
- PR_DELETE(cmdLine);
- }
- if (newEnvp) {
- PR_DELETE(newEnvp);
- }
- if (envBlock) {
- PR_DELETE(envBlock);
- }
- if (proc) {
- PR_DELETE(proc);
- }
- return NULL;
-} /* _PR_CreateWindowsProcess */
-
-PRStatus _PR_DetachWindowsProcess(PRProcess *process)
-{
- CloseHandle(process->md.handle);
- PR_DELETE(process);
- return PR_SUCCESS;
-}
-
-/*
- * XXX: This implementation is a temporary quick solution.
- * It can be called by native threads only (not by fibers).
- */
-PRStatus _PR_WaitWindowsProcess(PRProcess *process,
- PRInt32 *exitCode)
-{
- DWORD dwRetVal;
-
- dwRetVal = WaitForSingleObject(process->md.handle, INFINITE);
- if (dwRetVal == WAIT_FAILED) {
- PR_SetError(PR_UNKNOWN_ERROR, GetLastError());
- return PR_FAILURE;
- }
- PR_ASSERT(dwRetVal == WAIT_OBJECT_0);
- if (exitCode != NULL &&
- GetExitCodeProcess(process->md.handle, exitCode) == FALSE) {
- PR_SetError(PR_UNKNOWN_ERROR, GetLastError());
- return PR_FAILURE;
- }
- CloseHandle(process->md.handle);
- PR_DELETE(process);
- return PR_SUCCESS;
-}
-
-PRStatus _PR_KillWindowsProcess(PRProcess *process)
-{
- /*
- * On Unix, if a process terminates normally, its exit code is
- * between 0 and 255. So here on Windows, we use the exit code
- * 256 to indicate that the process is killed.
- */
- if (TerminateProcess(process->md.handle, 256)) {
- return PR_SUCCESS;
- }
- PR_SetError(PR_UNKNOWN_ERROR, GetLastError());
- return PR_FAILURE;
-}
-
-PRStatus _MD_WindowsGetHostName(char *name, PRUint32 namelen)
-{
- PRIntn rv;
- PRInt32 syserror;
-
- rv = gethostname(name, (PRInt32) namelen);
- if (0 == rv) {
- return PR_SUCCESS;
- }
- syserror = WSAGetLastError();
- PR_ASSERT(WSANOTINITIALISED != syserror);
- _PR_MD_MAP_GETHOSTNAME_ERROR(syserror);
- return PR_FAILURE;
-}
-
-PRStatus _MD_WindowsGetSysInfo(PRSysInfo cmd, char *name, PRUint32 namelen)
-{
- OSVERSIONINFO osvi;
-
- PR_ASSERT((cmd == PR_SI_SYSNAME) || (cmd == PR_SI_RELEASE));
-
- ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
- osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
-
- if (! GetVersionEx (&osvi) ) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- return PR_FAILURE;
- }
-
- switch (osvi.dwPlatformId) {
- case VER_PLATFORM_WIN32_NT:
- if (PR_SI_SYSNAME == cmd)
- (void)PR_snprintf(name, namelen, "Windows_NT");
- else if (PR_SI_RELEASE == cmd)
- (void)PR_snprintf(name, namelen, "%d.%d",osvi.dwMajorVersion,
- osvi.dwMinorVersion);
- break;
- case VER_PLATFORM_WIN32_WINDOWS:
- if (PR_SI_SYSNAME == cmd) {
- if ((osvi.dwMajorVersion > 4) ||
- ((osvi.dwMajorVersion == 4) && (osvi.dwMinorVersion > 0)))
- (void)PR_snprintf(name, namelen, "Windows_98");
- else
- (void)PR_snprintf(name, namelen, "Windows_95");
- } else if (PR_SI_RELEASE == cmd) {
- (void)PR_snprintf(name, namelen, "%d.%d",osvi.dwMajorVersion,
- osvi.dwMinorVersion);
- }
- break;
-#ifdef VER_PLATFORM_WIN32_CE
- case VER_PLATFORM_WIN32_CE:
- if (PR_SI_SYSNAME == cmd)
- (void)PR_snprintf(name, namelen, "Windows_CE");
- else if (PR_SI_RELEASE == cmd)
- (void)PR_snprintf(name, namelen, "%d.%d",osvi.dwMajorVersion,
- osvi.dwMinorVersion);
- break;
-#endif
- default:
- if (PR_SI_SYSNAME == cmd)
- (void)PR_snprintf(name, namelen, "Windows_Unknown");
- else if (PR_SI_RELEASE == cmd)
- (void)PR_snprintf(name, namelen, "%d.%d",0,0);
- break;
- }
- return PR_SUCCESS;
-}
-
-PRStatus _MD_WindowsGetReleaseName(char *name, PRUint32 namelen)
-{
- OSVERSIONINFO osvi;
-
- ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
- osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
-
- if (! GetVersionEx (&osvi) ) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- return PR_FAILURE;
- }
-
- switch (osvi.dwPlatformId) {
- case VER_PLATFORM_WIN32_NT:
- case VER_PLATFORM_WIN32_WINDOWS:
- (void)PR_snprintf(name, namelen, "%d.%d",osvi.dwMajorVersion,
- osvi.dwMinorVersion);
- break;
- default:
- (void)PR_snprintf(name, namelen, "%d.%d",0,0);
- break;
- }
- return PR_SUCCESS;
-}
-
-/*
- **********************************************************************
- *
- * Memory-mapped files
- *
- **********************************************************************
- */
-
-PRStatus _MD_CreateFileMap(PRFileMap *fmap, PRInt64 size)
-{
- DWORD dwHi, dwLo;
- DWORD flProtect;
- PROsfd osfd;
-
- osfd = ( fmap->fd == (PRFileDesc*)-1 )? -1 : fmap->fd->secret->md.osfd;
-
- dwLo = (DWORD) (size & 0xffffffff);
- dwHi = (DWORD) (((PRUint64) size >> 32) & 0xffffffff);
-
- if (fmap->prot == PR_PROT_READONLY) {
- flProtect = PAGE_READONLY;
- fmap->md.dwAccess = FILE_MAP_READ;
- } else if (fmap->prot == PR_PROT_READWRITE) {
- flProtect = PAGE_READWRITE;
- fmap->md.dwAccess = FILE_MAP_WRITE;
- } else {
- PR_ASSERT(fmap->prot == PR_PROT_WRITECOPY);
-#ifdef WINCE
- /* WINCE does not have FILE_MAP_COPY. */
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-#else
- flProtect = PAGE_WRITECOPY;
- fmap->md.dwAccess = FILE_MAP_COPY;
-#endif
- }
-
- fmap->md.hFileMap = CreateFileMapping(
- (HANDLE) osfd,
- NULL,
- flProtect,
- dwHi,
- dwLo,
- NULL);
-
- if (fmap->md.hFileMap == NULL) {
- PR_SetError(PR_UNKNOWN_ERROR, GetLastError());
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-PRInt32 _MD_GetMemMapAlignment(void)
-{
- SYSTEM_INFO info;
- GetSystemInfo(&info);
- return info.dwAllocationGranularity;
-}
-
-extern PRLogModuleInfo *_pr_shma_lm;
-
-void * _MD_MemMap(
- PRFileMap *fmap,
- PROffset64 offset,
- PRUint32 len)
-{
- DWORD dwHi, dwLo;
- void *addr;
-
- dwLo = (DWORD) (offset & 0xffffffff);
- dwHi = (DWORD) (((PRUint64) offset >> 32) & 0xffffffff);
- if ((addr = MapViewOfFile(fmap->md.hFileMap, fmap->md.dwAccess,
- dwHi, dwLo, len)) == NULL) {
- {
- LPVOID lpMsgBuf;
-
- FormatMessage(
- FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
- NULL,
- GetLastError(),
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
- (LPTSTR) &lpMsgBuf,
- 0,
- NULL
- );
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG, ("md_memmap(): %s", lpMsgBuf ));
- }
- PR_SetError(PR_UNKNOWN_ERROR, GetLastError());
- }
- return addr;
-}
-
-PRStatus _MD_MemUnmap(void *addr, PRUint32 len)
-{
- if (UnmapViewOfFile(addr)) {
- return PR_SUCCESS;
- }
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- return PR_FAILURE;
-}
-
-PRStatus _MD_CloseFileMap(PRFileMap *fmap)
-{
- CloseHandle(fmap->md.hFileMap);
- PR_DELETE(fmap);
- return PR_SUCCESS;
-}
-
-PRStatus _MD_SyncMemMap(
- PRFileDesc *fd,
- void *addr,
- PRUint32 len)
-{
- PROsfd osfd = fd->secret->md.osfd;
-
- /* The FlushViewOfFile page on MSDN says:
- * To flush all the dirty pages plus the metadata for the file and
- * ensure that they are physically written to disk, call
- * FlushViewOfFile and then call the FlushFileBuffers function.
- */
- if (FlushViewOfFile(addr, len) && FlushFileBuffers((HANDLE) osfd)) {
- return PR_SUCCESS;
- }
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- return PR_FAILURE;
-}
-
-/*
- ***********************************************************************
- *
- * Atomic increment and decrement operations for x86 processors
- *
- * We don't use InterlockedIncrement and InterlockedDecrement
- * because on NT 3.51 and Win95, they return a number with
- * the same sign as the incremented/decremented result, rather
- * than the result itself. On NT 4.0 these functions do return
- * the incremented/decremented result.
- *
- * The result is returned in the eax register by the inline
- * assembly code. We disable the harmless "no return value"
- * warning (4035) for these two functions.
- *
- ***********************************************************************
- */
-
-#if defined(_M_IX86) || defined(_X86_)
-
-#pragma warning(disable: 4035)
-PRInt32 _PR_MD_ATOMIC_INCREMENT(PRInt32 *val)
-{
-#if defined(__GNUC__)
- PRInt32 result;
- asm volatile ("lock ; xadd %0, %1"
- : "=r"(result), "=m"(*val)
- : "0"(1), "m"(*val));
- return result + 1;
-#else
- __asm
- {
- mov ecx, val
- mov eax, 1
- lock xadd dword ptr [ecx], eax
- inc eax
- }
-#endif /* __GNUC__ */
-}
-#pragma warning(default: 4035)
-
-#pragma warning(disable: 4035)
-PRInt32 _PR_MD_ATOMIC_DECREMENT(PRInt32 *val)
-{
-#if defined(__GNUC__)
- PRInt32 result;
- asm volatile ("lock ; xadd %0, %1"
- : "=r"(result), "=m"(*val)
- : "0"(-1), "m"(*val));
- //asm volatile("lock ; xadd %0, %1" : "=m" (val), "=a" (result) : "-1" (1));
- return result - 1;
-#else
- __asm
- {
- mov ecx, val
- mov eax, 0ffffffffh
- lock xadd dword ptr [ecx], eax
- dec eax
- }
-#endif /* __GNUC__ */
-}
-#pragma warning(default: 4035)
-
-#pragma warning(disable: 4035)
-PRInt32 _PR_MD_ATOMIC_ADD(PRInt32 *intp, PRInt32 val)
-{
-#if defined(__GNUC__)
- PRInt32 result;
- //asm volatile("lock ; xadd %1, %0" : "=m" (intp), "=a" (result) : "1" (val));
- asm volatile ("lock ; xadd %0, %1"
- : "=r"(result), "=m"(*intp)
- : "0"(val), "m"(*intp));
- return result + val;
-#else
- __asm
- {
- mov ecx, intp
- mov eax, val
- mov edx, eax
- lock xadd dword ptr [ecx], eax
- add eax, edx
- }
-#endif /* __GNUC__ */
-}
-#pragma warning(default: 4035)
-
-#ifdef _PR_HAVE_ATOMIC_CAS
-
-#pragma warning(disable: 4035)
-void
-PR_StackPush(PRStack *stack, PRStackElem *stack_elem)
-{
-#if defined(__GNUC__)
- void **tos = (void **) stack;
- void *tmp;
-
- retry:
- if (*tos == (void *) -1)
- goto retry;
-
- __asm__("xchg %0,%1"
- : "=r" (tmp), "=m"(*tos)
- : "0" (-1), "m"(*tos));
-
- if (tmp == (void *) -1)
- goto retry;
-
- *(void **)stack_elem = tmp;
- __asm__("" : : : "memory");
- *tos = stack_elem;
-#else
- __asm
- {
- mov ebx, stack
- mov ecx, stack_elem
-retry: mov eax,[ebx]
- cmp eax,-1
- je retry
- mov eax,-1
- xchg dword ptr [ebx], eax
- cmp eax,-1
- je retry
- mov [ecx],eax
- mov [ebx],ecx
- }
-#endif /* __GNUC__ */
-}
-#pragma warning(default: 4035)
-
-#pragma warning(disable: 4035)
-PRStackElem *
-PR_StackPop(PRStack *stack)
-{
-#if defined(__GNUC__)
- void **tos = (void **) stack;
- void *tmp;
-
- retry:
- if (*tos == (void *) -1)
- goto retry;
-
- __asm__("xchg %0,%1"
- : "=r" (tmp), "=m"(*tos)
- : "0" (-1), "m"(*tos));
-
- if (tmp == (void *) -1)
- goto retry;
-
- if (tmp != (void *) 0)
- {
- void *next = *(void **)tmp;
- *tos = next;
- *(void **)tmp = 0;
- }
- else
- *tos = tmp;
-
- return tmp;
-#else
- __asm
- {
- mov ebx, stack
-retry: mov eax,[ebx]
- cmp eax,-1
- je retry
- mov eax,-1
- xchg dword ptr [ebx], eax
- cmp eax,-1
- je retry
- cmp eax,0
- je empty
- mov ecx,[eax]
- mov [ebx],ecx
- mov [eax],0
- jmp done
-empty:
- mov [ebx],eax
-done:
- }
-#endif /* __GNUC__ */
-}
-#pragma warning(default: 4035)
-
-#endif /* _PR_HAVE_ATOMIC_CAS */
-
-#endif /* x86 processors */
diff --git a/nspr/pr/src/md/windows/ntsec.c b/nspr/pr/src/md/windows/ntsec.c
deleted file mode 100644
index c0682e4..0000000
--- a/nspr/pr/src/md/windows/ntsec.c
+++ /dev/null
@@ -1,261 +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/. */
-
-#include "primpl.h"
-
-/*
- * ntsec.c
- *
- * Implement the POSIX-style mode bits (access permissions) for
- * files and other securable objects in Windows NT using Windows
- * NT's security descriptors with appropriate discretionary
- * access-control lists.
- */
-
-/*
- * The security identifiers (SIDs) for owner, primary group,
- * and the Everyone (World) group.
- *
- * These SIDs are looked up during NSPR initialization and
- * saved in this global structure (see _PR_NT_InitSids) so
- * that _PR_NT_MakeSecurityDescriptorACL doesn't need to
- * look them up every time.
- */
-static struct {
- PSID owner;
- PSID group;
- PSID everyone;
-} _pr_nt_sids;
-
-/*
- * Initialize the SIDs for owner, primary group, and the Everyone
- * group in the _pr_nt_sids structure.
- *
- * This function needs to be called by NSPR initialization.
- */
-void _PR_NT_InitSids(void)
-{
-#ifdef WINCE /* not supported */
- return;
-#else
- SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
- HANDLE hToken = NULL; /* initialized to an arbitrary value to
- * silence a Purify UMR warning */
- PSID infoBuffer[1024/sizeof(PSID)]; /* defined as an array of PSIDs
- * to force proper alignment */
- PTOKEN_OWNER pTokenOwner = (PTOKEN_OWNER) infoBuffer;
- PTOKEN_PRIMARY_GROUP pTokenPrimaryGroup
- = (PTOKEN_PRIMARY_GROUP) infoBuffer;
- DWORD dwLength;
- BOOL rv;
-
- /*
- * Look up and make a copy of the owner and primary group
- * SIDs in the access token of the calling process.
- */
- rv = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken);
- if (rv == 0) {
- /*
- * On non-NT systems, this function is not implemented
- * (error code ERROR_CALL_NOT_IMPLEMENTED), and neither are
- * the other security functions. There is no point in
- * going further.
- *
- * A process with insufficient access permissions may fail
- * with the error code ERROR_ACCESS_DENIED.
- */
- PR_LOG(_pr_io_lm, PR_LOG_DEBUG,
- ("_PR_NT_InitSids: OpenProcessToken() failed. Error: %d",
- GetLastError()));
- return;
- }
-
- rv = GetTokenInformation(hToken, TokenOwner, infoBuffer,
- sizeof(infoBuffer), &dwLength);
- PR_ASSERT(rv != 0);
- dwLength = GetLengthSid(pTokenOwner->Owner);
- _pr_nt_sids.owner = (PSID) PR_Malloc(dwLength);
- PR_ASSERT(_pr_nt_sids.owner != NULL);
- rv = CopySid(dwLength, _pr_nt_sids.owner, pTokenOwner->Owner);
- PR_ASSERT(rv != 0);
-
- rv = GetTokenInformation(hToken, TokenPrimaryGroup, infoBuffer,
- sizeof(infoBuffer), &dwLength);
- PR_ASSERT(rv != 0);
- dwLength = GetLengthSid(pTokenPrimaryGroup->PrimaryGroup);
- _pr_nt_sids.group = (PSID) PR_Malloc(dwLength);
- PR_ASSERT(_pr_nt_sids.group != NULL);
- rv = CopySid(dwLength, _pr_nt_sids.group,
- pTokenPrimaryGroup->PrimaryGroup);
- PR_ASSERT(rv != 0);
-
- rv = CloseHandle(hToken);
- PR_ASSERT(rv != 0);
-
- /* Create a well-known SID for the Everyone group. */
- rv = AllocateAndInitializeSid(&SIDAuthWorld, 1,
- SECURITY_WORLD_RID,
- 0, 0, 0, 0, 0, 0, 0,
- &_pr_nt_sids.everyone);
- PR_ASSERT(rv != 0);
-#endif
-}
-
-/*
- * Free the SIDs for owner, primary group, and the Everyone group
- * in the _pr_nt_sids structure.
- *
- * This function needs to be called by NSPR cleanup.
- */
-void
-_PR_NT_FreeSids(void)
-{
-#ifdef WINCE
- return;
-#else
- if (_pr_nt_sids.owner) {
- PR_Free(_pr_nt_sids.owner);
- }
- if (_pr_nt_sids.group) {
- PR_Free(_pr_nt_sids.group);
- }
- if (_pr_nt_sids.everyone) {
- FreeSid(_pr_nt_sids.everyone);
- }
-#endif
-}
-
-/*
- * Construct a security descriptor whose discretionary access-control
- * list implements the specified mode bits. The SIDs for owner, group,
- * and everyone are obtained from the global _pr_nt_sids structure.
- * Both the security descriptor and access-control list are returned
- * and should be freed by a _PR_NT_FreeSecurityDescriptorACL call.
- *
- * The accessTable array maps NSPR's read, write, and execute access
- * rights to the corresponding NT access rights for the securable
- * object.
- */
-PRStatus
-_PR_NT_MakeSecurityDescriptorACL(
- PRIntn mode,
- DWORD accessTable[],
- PSECURITY_DESCRIPTOR *resultSD,
- PACL *resultACL)
-{
-#ifdef WINCE
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-#else
- PSECURITY_DESCRIPTOR pSD = NULL;
- PACL pACL = NULL;
- DWORD cbACL; /* size of ACL */
- DWORD accessMask;
-
- if (_pr_nt_sids.owner == NULL) {
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
- }
-
- pSD = (PSECURITY_DESCRIPTOR) PR_Malloc(SECURITY_DESCRIPTOR_MIN_LENGTH);
- if (pSD == NULL) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- goto failed;
- }
- if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- goto failed;
- }
- if (!SetSecurityDescriptorOwner(pSD, _pr_nt_sids.owner, FALSE)) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- goto failed;
- }
- if (!SetSecurityDescriptorGroup(pSD, _pr_nt_sids.group, FALSE)) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- goto failed;
- }
-
- /*
- * Construct a discretionary access-control list with three
- * access-control entries, one each for owner, primary group,
- * and Everyone.
- */
-
- cbACL = sizeof(ACL)
- + 3 * (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD))
- + GetLengthSid(_pr_nt_sids.owner)
- + GetLengthSid(_pr_nt_sids.group)
- + GetLengthSid(_pr_nt_sids.everyone);
- pACL = (PACL) PR_Malloc(cbACL);
- if (pACL == NULL) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- goto failed;
- }
- if (!InitializeAcl(pACL, cbACL, ACL_REVISION)) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- goto failed;
- }
- accessMask = 0;
- if (mode & 00400) accessMask |= accessTable[0];
- if (mode & 00200) accessMask |= accessTable[1];
- if (mode & 00100) accessMask |= accessTable[2];
- if (accessMask && !AddAccessAllowedAce(pACL, ACL_REVISION, accessMask,
- _pr_nt_sids.owner)) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- goto failed;
- }
- accessMask = 0;
- if (mode & 00040) accessMask |= accessTable[0];
- if (mode & 00020) accessMask |= accessTable[1];
- if (mode & 00010) accessMask |= accessTable[2];
- if (accessMask && !AddAccessAllowedAce(pACL, ACL_REVISION, accessMask,
- _pr_nt_sids.group)) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- goto failed;
- }
- accessMask = 0;
- if (mode & 00004) accessMask |= accessTable[0];
- if (mode & 00002) accessMask |= accessTable[1];
- if (mode & 00001) accessMask |= accessTable[2];
- if (accessMask && !AddAccessAllowedAce(pACL, ACL_REVISION, accessMask,
- _pr_nt_sids.everyone)) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- goto failed;
- }
-
- if (!SetSecurityDescriptorDacl(pSD, TRUE, pACL, FALSE)) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- goto failed;
- }
-
- *resultSD = pSD;
- *resultACL = pACL;
- return PR_SUCCESS;
-
-failed:
- if (pSD) {
- PR_Free(pSD);
- }
- if (pACL) {
- PR_Free(pACL);
- }
- return PR_FAILURE;
-#endif
-}
-
-/*
- * Free the specified security descriptor and access-control list
- * previously created by _PR_NT_MakeSecurityDescriptorACL.
- */
-void
-_PR_NT_FreeSecurityDescriptorACL(PSECURITY_DESCRIPTOR pSD, PACL pACL)
-{
- if (pSD) {
- PR_Free(pSD);
- }
- if (pACL) {
- PR_Free(pACL);
- }
-}
diff --git a/nspr/pr/src/md/windows/ntsem.c b/nspr/pr/src/md/windows/ntsem.c
deleted file mode 100644
index f36a145..0000000
--- a/nspr/pr/src/md/windows/ntsem.c
+++ /dev/null
@@ -1,50 +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/. */
-
-/*
- * NT-specific semaphore handling code.
- *
- */
-
-
-#include "primpl.h"
-
-
-void
-_PR_MD_NEW_SEM(_MDSemaphore *md, PRUintn value)
-{
- md->sem = CreateSemaphore(NULL, value, 0x7fffffff, NULL);
-}
-
-void
-_PR_MD_DESTROY_SEM(_MDSemaphore *md)
-{
- CloseHandle(md->sem);
-}
-
-PRStatus
-_PR_MD_TIMED_WAIT_SEM(_MDSemaphore *md, PRIntervalTime ticks)
-{
- int rv;
-
- rv = WaitForSingleObject(md->sem, PR_IntervalToMilliseconds(ticks));
-
- if (rv == WAIT_OBJECT_0)
- return PR_SUCCESS;
- else
- return PR_FAILURE;
-}
-
-PRStatus
-_PR_MD_WAIT_SEM(_MDSemaphore *md)
-{
- return _PR_MD_TIMED_WAIT_SEM(md, PR_INTERVAL_NO_TIMEOUT);
-}
-
-void
-_PR_MD_POST_SEM(_MDSemaphore *md)
-{
- ReleaseSemaphore(md->sem, 1, NULL);
-}
diff --git a/nspr/pr/src/md/windows/w32ipcsem.c b/nspr/pr/src/md/windows/w32ipcsem.c
deleted file mode 100644
index 9545910..0000000
--- a/nspr/pr/src/md/windows/w32ipcsem.c
+++ /dev/null
@@ -1,228 +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/. */
-
-/*
- * File: w32ipcsem.c
- * Description: implements named semaphores for NT and WIN95.
- */
-
-#include "primpl.h"
-
-#ifdef WINCE
-static HANDLE OpenSemaphore(DWORD inDesiredAccess,
- BOOL inInheritHandle,
- const char *inName)
-{
- HANDLE retval = NULL;
- HANDLE semaphore = NULL;
- PRUnichar wideName[MAX_PATH]; /* name size is limited to MAX_PATH */
-
- MultiByteToWideChar(CP_ACP, 0, inName, -1, wideName, MAX_PATH);
- /* 0x7fffffff is the max count for our semaphore */
- semaphore = CreateSemaphoreW(NULL, 0, 0x7fffffff, wideName);
- if (NULL != semaphore) {
- DWORD lastErr = GetLastError();
-
- if (ERROR_ALREADY_EXISTS != lastErr)
- CloseHandle(semaphore);
- else
- retval = semaphore;
- }
- return retval;
-}
-#endif
-
-/*
- * NSPR-to-NT access right mapping table for semaphore objects.
- *
- * The SYNCHRONIZE access is required by WaitForSingleObject.
- * The SEMAPHORE_MODIFY_STATE access is required by ReleaseSemaphore.
- * The OR of these three access masks must equal SEMAPHORE_ALL_ACCESS.
- * This is because if a semaphore object with the specified name
- * exists, CreateSemaphore requests SEMAPHORE_ALL_ACCESS access to
- * the existing object.
- */
-static DWORD semAccessTable[] = {
- STANDARD_RIGHTS_REQUIRED|0x1, /* read (0x1 is "query state") */
- STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE|SEMAPHORE_MODIFY_STATE, /* write */
- 0 /* execute */
-};
-
-#ifndef _PR_GLOBAL_THREADS_ONLY
-
-/*
- * A fiber cannot call WaitForSingleObject because that
- * will block the other fibers running on the same thread.
- * If a fiber needs to wait on a (semaphore) handle, we
- * create a native thread to call WaitForSingleObject and
- * have the fiber join the native thread.
- */
-
-/*
- * Arguments, return value, and error code for WaitForSingleObject
- */
-struct WaitSingleArg {
- HANDLE handle;
- DWORD timeout;
- DWORD rv;
- DWORD error;
-};
-
-static void WaitSingleThread(void *arg)
-{
- struct WaitSingleArg *warg = (struct WaitSingleArg *) arg;
-
- warg->rv = WaitForSingleObject(warg->handle, warg->timeout);
- if (warg->rv == WAIT_FAILED) {
- warg->error = GetLastError();
- }
-}
-
-static DWORD FiberSafeWaitForSingleObject(
- HANDLE hHandle,
- DWORD dwMilliseconds
-)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if (_PR_IS_NATIVE_THREAD(me)) {
- return WaitForSingleObject(hHandle, dwMilliseconds);
- } else {
- PRThread *waitThread;
- struct WaitSingleArg warg;
- PRStatus rv;
-
- warg.handle = hHandle;
- warg.timeout = dwMilliseconds;
- waitThread = PR_CreateThread(
- PR_USER_THREAD, WaitSingleThread, &warg,
- PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0);
- if (waitThread == NULL) {
- return WAIT_FAILED;
- }
-
- rv = PR_JoinThread(waitThread);
- PR_ASSERT(rv == PR_SUCCESS);
- if (rv == PR_FAILURE) {
- return WAIT_FAILED;
- }
- if (warg.rv == WAIT_FAILED) {
- SetLastError(warg.error);
- }
- return warg.rv;
- }
-}
-
-#endif /* !_PR_GLOBAL_THREADS_ONLY */
-
-PRSem *_PR_MD_OPEN_SEMAPHORE(
- const char *osname, PRIntn flags, PRIntn mode, PRUintn value)
-{
- PRSem *sem;
- SECURITY_ATTRIBUTES sa;
- LPSECURITY_ATTRIBUTES lpSA = NULL;
- PSECURITY_DESCRIPTOR pSD = NULL;
- PACL pACL = NULL;
-
- sem = PR_NEW(PRSem);
- if (sem == NULL) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
- if (flags & PR_SEM_CREATE) {
- if (_PR_NT_MakeSecurityDescriptorACL(mode, semAccessTable,
- &pSD, &pACL) == PR_SUCCESS) {
- sa.nLength = sizeof(sa);
- sa.lpSecurityDescriptor = pSD;
- sa.bInheritHandle = FALSE;
- lpSA = &sa;
- }
-#ifdef WINCE
- {
- /* The size of a sem's name is limited to MAX_PATH. */
- PRUnichar wosname[MAX_PATH];
- MultiByteToWideChar(CP_ACP, 0, osname, -1, wosname, MAX_PATH);
- sem->sem = CreateSemaphoreW(lpSA, value, 0x7fffffff, wosname);
- }
-#else
- sem->sem = CreateSemaphoreA(lpSA, value, 0x7fffffff, osname);
-#endif
- if (lpSA != NULL) {
- _PR_NT_FreeSecurityDescriptorACL(pSD, pACL);
- }
- if (sem->sem == NULL) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- PR_DELETE(sem);
- return NULL;
- }
- if ((flags & PR_SEM_EXCL) && (GetLastError() == ERROR_ALREADY_EXISTS)) {
- PR_SetError(PR_FILE_EXISTS_ERROR, ERROR_ALREADY_EXISTS);
- CloseHandle(sem->sem);
- PR_DELETE(sem);
- return NULL;
- }
- } else {
- sem->sem = OpenSemaphore(
- SEMAPHORE_MODIFY_STATE|SYNCHRONIZE, FALSE, osname);
- if (sem->sem == NULL) {
- DWORD err = GetLastError();
-
- /*
- * If we open a nonexistent named semaphore, NT
- * returns ERROR_FILE_NOT_FOUND, while Win95
- * returns ERROR_INVALID_NAME
- */
- if (err == ERROR_INVALID_NAME) {
- PR_SetError(PR_FILE_NOT_FOUND_ERROR, err);
- } else {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- }
- PR_DELETE(sem);
- return NULL;
- }
- }
- return sem;
-}
-
-PRStatus _PR_MD_WAIT_SEMAPHORE(PRSem *sem)
-{
- DWORD rv;
-
-#ifdef _PR_GLOBAL_THREADS_ONLY
- rv = WaitForSingleObject(sem->sem, INFINITE);
-#else
- rv = FiberSafeWaitForSingleObject(sem->sem, INFINITE);
-#endif
- PR_ASSERT(rv == WAIT_FAILED || rv == WAIT_OBJECT_0);
- if (rv == WAIT_FAILED) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- return PR_FAILURE;
- }
- if (rv != WAIT_OBJECT_0) {
- /* Should not happen */
- PR_SetError(PR_UNKNOWN_ERROR, 0);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-PRStatus _PR_MD_POST_SEMAPHORE(PRSem *sem)
-{
- if (ReleaseSemaphore(sem->sem, 1, NULL) == FALSE) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-PRStatus _PR_MD_CLOSE_SEMAPHORE(PRSem *sem)
-{
- if (CloseHandle(sem->sem) == FALSE) {
- _PR_MD_MAP_CLOSE_ERROR(GetLastError());
- return PR_FAILURE;
- }
- PR_DELETE(sem);
- return PR_SUCCESS;
-}
diff --git a/nspr/pr/src/md/windows/w32poll.c b/nspr/pr/src/md/windows/w32poll.c
deleted file mode 100644
index 38e2ad9..0000000
--- a/nspr/pr/src/md/windows/w32poll.c
+++ /dev/null
@@ -1,325 +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/. */
-
-/*
- * This file implements _PR_MD_PR_POLL for Win32.
- */
-
-/* The default value of FD_SETSIZE is 64. */
-#define FD_SETSIZE 1024
-
-#include "primpl.h"
-
-#if !defined(_PR_GLOBAL_THREADS_ONLY)
-
-struct select_data_s {
- PRInt32 status;
- PRInt32 error;
- fd_set *rd, *wt, *ex;
- const struct timeval *tv;
-};
-
-static void
-_PR_MD_select_thread(void *cdata)
-{
- struct select_data_s *cd = (struct select_data_s *)cdata;
-
- cd->status = select(0, cd->rd, cd->wt, cd->ex, cd->tv);
-
- if (cd->status == SOCKET_ERROR) {
- cd->error = WSAGetLastError();
- }
-}
-
-int _PR_NTFiberSafeSelect(
- int nfds,
- fd_set *readfds,
- fd_set *writefds,
- fd_set *exceptfds,
- const struct timeval *timeout)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
- int ready;
-
- if (_PR_IS_NATIVE_THREAD(me)) {
- ready = _MD_SELECT(nfds, readfds, writefds, exceptfds, timeout);
- }
- else
- {
- /*
- ** Creating a new thread on each call!!
- ** I guess web server doesn't use non-block I/O.
- */
- PRThread *selectThread;
- struct select_data_s data;
- data.status = 0;
- data.error = 0;
- data.rd = readfds;
- data.wt = writefds;
- data.ex = exceptfds;
- data.tv = timeout;
-
- selectThread = PR_CreateThread(
- PR_USER_THREAD, _PR_MD_select_thread, &data,
- PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0);
- if (selectThread == NULL) return -1;
-
- PR_JoinThread(selectThread);
- ready = data.status;
- if (ready == SOCKET_ERROR) WSASetLastError(data.error);
- }
- return ready;
-}
-
-#endif /* !defined(_PR_GLOBAL_THREADS_ONLY) */
-
-PRInt32 _PR_MD_PR_POLL(PRPollDesc *pds, PRIntn npds, PRIntervalTime timeout)
-{
- int ready, err;
- fd_set rd, wt, ex;
- fd_set *rdp, *wtp, *exp;
- int nrd, nwt, nex;
- PRFileDesc *bottom;
- PRPollDesc *pd, *epd;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- struct timeval tv, *tvp = NULL;
-
- if (_PR_PENDING_INTERRUPT(me))
- {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- return -1;
- }
-
- /*
- ** Is it an empty set? If so, just sleep for the timeout and return
- */
- if (0 == npds)
- {
- PR_Sleep(timeout);
- return 0;
- }
-
- nrd = nwt = nex = 0;
- FD_ZERO(&rd);
- FD_ZERO(&wt);
- FD_ZERO(&ex);
-
- ready = 0;
- for (pd = pds, epd = pd + npds; pd < epd; pd++)
- {
- SOCKET osfd;
- PRInt16 in_flags_read = 0, in_flags_write = 0;
- PRInt16 out_flags_read = 0, out_flags_write = 0;
-
- if ((NULL != pd->fd) && (0 != pd->in_flags))
- {
- if (pd->in_flags & PR_POLL_READ)
- {
- in_flags_read = (pd->fd->methods->poll)(
- pd->fd, (PRInt16)(pd->in_flags & ~PR_POLL_WRITE),
- &out_flags_read);
- }
- if (pd->in_flags & PR_POLL_WRITE)
- {
- in_flags_write = (pd->fd->methods->poll)(
- pd->fd, (PRInt16)(pd->in_flags & ~PR_POLL_READ),
- &out_flags_write);
- }
- if ((0 != (in_flags_read & out_flags_read))
- || (0 != (in_flags_write & out_flags_write)))
- {
- /* this one's ready right now (buffered input) */
- if (0 == ready)
- {
- /*
- * We will have to return without calling the
- * system poll/select function. So zero the
- * out_flags fields of all the poll descriptors
- * before this one.
- */
- PRPollDesc *prev;
- for (prev = pds; prev < pd; prev++)
- {
- prev->out_flags = 0;
- }
- }
- ready += 1;
- pd->out_flags = out_flags_read | out_flags_write;
- }
- else
- {
- pd->out_flags = 0; /* pre-condition */
- /* make sure this is an NSPR supported stack */
- bottom = PR_GetIdentitiesLayer(pd->fd, PR_NSPR_IO_LAYER);
- PR_ASSERT(NULL != bottom); /* what to do about that? */
- if ((NULL != bottom)
- && (_PR_FILEDESC_OPEN == bottom->secret->state))
- {
- if (0 == ready)
- {
- osfd = (SOCKET) bottom->secret->md.osfd;
- if (in_flags_read & PR_POLL_READ)
- {
- pd->out_flags |= _PR_POLL_READ_SYS_READ;
- FD_SET(osfd, &rd);
- nrd++;
- }
- if (in_flags_read & PR_POLL_WRITE)
- {
- pd->out_flags |= _PR_POLL_READ_SYS_WRITE;
- FD_SET(osfd, &wt);
- nwt++;
- }
- if (in_flags_write & PR_POLL_READ)
- {
- pd->out_flags |= _PR_POLL_WRITE_SYS_READ;
- FD_SET(osfd, &rd);
- nrd++;
- }
- if (in_flags_write & PR_POLL_WRITE)
- {
- pd->out_flags |= _PR_POLL_WRITE_SYS_WRITE;
- FD_SET(osfd, &wt);
- nwt++;
- }
- if (pd->in_flags & PR_POLL_EXCEPT) {
- FD_SET(osfd, &ex);
- nex++;
- }
- }
- }
- else
- {
- if (0 == ready)
- {
- PRPollDesc *prev;
- for (prev = pds; prev < pd; prev++)
- {
- prev->out_flags = 0;
- }
- }
- ready += 1; /* this will cause an abrupt return */
- pd->out_flags = PR_POLL_NVAL; /* bogii */
- }
- }
- }
- else
- {
- pd->out_flags = 0;
- }
- }
-
- if (0 != ready) return ready; /* no need to block */
-
- /*
- * FD_SET does nothing if the fd_set's internal fd_array is full. If
- * nrd, nwt, or nex is greater than FD_SETSIZE, we know FD_SET must
- * have failed to insert an osfd into the corresponding fd_set, and
- * therefore we should fail.
- */
- if ((nrd > FD_SETSIZE) || (nwt > FD_SETSIZE) || (nex > FD_SETSIZE)) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return -1;
- }
-
- rdp = (0 == nrd) ? NULL : &rd;
- wtp = (0 == nwt) ? NULL : &wt;
- exp = (0 == nex) ? NULL : &ex;
-
- if ((NULL == rdp) && (NULL == wtp) && (NULL == exp)) {
- PR_Sleep(timeout);
- return 0;
- }
-
- if (timeout != PR_INTERVAL_NO_TIMEOUT)
- {
- PRInt32 ticksPerSecond = PR_TicksPerSecond();
- tv.tv_sec = timeout / ticksPerSecond;
- tv.tv_usec = PR_IntervalToMicroseconds( timeout % ticksPerSecond );
- tvp = &tv;
- }
-
-#if defined(_PR_GLOBAL_THREADS_ONLY)
- ready = _MD_SELECT(0, rdp, wtp, exp, tvp);
-#else
- ready = _PR_NTFiberSafeSelect(0, rdp, wtp, exp, tvp);
-#endif
-
- /*
- ** Now to unravel the select sets back into the client's poll
- ** descriptor list. Is this possibly an area for pissing away
- ** a few cycles or what?
- */
- if (ready > 0)
- {
- ready = 0;
- for (pd = pds, epd = pd + npds; pd < epd; pd++)
- {
- PRInt16 out_flags = 0;
- if ((NULL != pd->fd) && (0 != pd->in_flags))
- {
- SOCKET osfd;
- bottom = PR_GetIdentitiesLayer(pd->fd, PR_NSPR_IO_LAYER);
- PR_ASSERT(NULL != bottom);
-
- osfd = (SOCKET) bottom->secret->md.osfd;
-
- if (FD_ISSET(osfd, &rd))
- {
- if (pd->out_flags & _PR_POLL_READ_SYS_READ)
- out_flags |= PR_POLL_READ;
- if (pd->out_flags & _PR_POLL_WRITE_SYS_READ)
- out_flags |= PR_POLL_WRITE;
- }
- if (FD_ISSET(osfd, &wt))
- {
- if (pd->out_flags & _PR_POLL_READ_SYS_WRITE)
- out_flags |= PR_POLL_READ;
- if (pd->out_flags & _PR_POLL_WRITE_SYS_WRITE)
- out_flags |= PR_POLL_WRITE;
- }
- if (FD_ISSET(osfd, &ex)) out_flags |= PR_POLL_EXCEPT;
- }
- pd->out_flags = out_flags;
- if (out_flags) ready++;
- }
- PR_ASSERT(ready > 0);
- }
- else if (ready == SOCKET_ERROR)
- {
- err = WSAGetLastError();
- if (err == WSAENOTSOCK)
- {
- /* Find the bad fds */
- int optval;
- int optlen = sizeof(optval);
- ready = 0;
- for (pd = pds, epd = pd + npds; pd < epd; pd++)
- {
- pd->out_flags = 0;
- if ((NULL != pd->fd) && (0 != pd->in_flags))
- {
- bottom = PR_GetIdentitiesLayer(pd->fd, PR_NSPR_IO_LAYER);
- if (getsockopt(bottom->secret->md.osfd, SOL_SOCKET,
- SO_TYPE, (char *) &optval, &optlen) == -1)
- {
- PR_ASSERT(WSAGetLastError() == WSAENOTSOCK);
- if (WSAGetLastError() == WSAENOTSOCK)
- {
- pd->out_flags = PR_POLL_NVAL;
- ready++;
- }
- }
- }
- }
- PR_ASSERT(ready > 0);
- }
- else _PR_MD_MAP_SELECT_ERROR(err);
- }
-
- return ready;
-}
diff --git a/nspr/pr/src/md/windows/w32rng.c b/nspr/pr/src/md/windows/w32rng.c
deleted file mode 100644
index 633ae0d..0000000
--- a/nspr/pr/src/md/windows/w32rng.c
+++ /dev/null
@@ -1,75 +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/. */
-
-#include <windows.h>
-#include <time.h>
-#include <io.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <stdio.h>
-#include <primpl.h>
-
-static BOOL
-CurrentClockTickTime(LPDWORD lpdwHigh, LPDWORD lpdwLow)
-{
- LARGE_INTEGER liCount;
-
- if (!QueryPerformanceCounter(&liCount))
- return FALSE;
-
- *lpdwHigh = liCount.u.HighPart;
- *lpdwLow = liCount.u.LowPart;
- return TRUE;
-}
-
-extern PRSize _PR_MD_GetRandomNoise( void *buf, PRSize size )
-{
- DWORD dwHigh, dwLow, dwVal;
- size_t n = 0;
- size_t nBytes;
- time_t sTime;
-
- if (size <= 0)
- return 0;
-
- CurrentClockTickTime(&dwHigh, &dwLow);
-
- // get the maximally changing bits first
- nBytes = sizeof(dwLow) > size ? size : sizeof(dwLow);
- memcpy((char *)buf, &dwLow, nBytes);
- n += nBytes;
- size -= nBytes;
-
- if (size <= 0)
- return n;
-
- nBytes = sizeof(dwHigh) > size ? size : sizeof(dwHigh);
- memcpy(((char *)buf) + n, &dwHigh, nBytes);
- n += nBytes;
- size -= nBytes;
-
- if (size <= 0)
- return n;
-
- // get the number of milliseconds that have elapsed since Windows started
- dwVal = GetTickCount();
-
- nBytes = sizeof(dwVal) > size ? size : sizeof(dwVal);
- memcpy(((char *)buf) + n, &dwVal, nBytes);
- n += nBytes;
- size -= nBytes;
-
- if (size <= 0)
- return n;
-
- // get the time in seconds since midnight Jan 1, 1970
- time(&sTime);
- nBytes = sizeof(sTime) > size ? size : sizeof(sTime);
- memcpy(((char *)buf) + n, &sTime, nBytes);
- n += nBytes;
-
- return n;
-}
-
diff --git a/nspr/pr/src/md/windows/w32shm.c b/nspr/pr/src/md/windows/w32shm.c
deleted file mode 100644
index 8e8b1d6..0000000
--- a/nspr/pr/src/md/windows/w32shm.c
+++ /dev/null
@@ -1,347 +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/. */
-
-#include <private/primpl.h>
-#include <string.h>
-#include <prshm.h>
-#include <prerr.h>
-#include <prmem.h>
-
-#if defined(PR_HAVE_WIN32_NAMED_SHARED_MEMORY)
-
-extern PRLogModuleInfo *_pr_shm_lm;
-
-/*
- * NSPR-to-NT access right mapping table for file-mapping objects.
- *
- * The OR of these three access masks must equal FILE_MAP_ALL_ACCESS.
- * This is because if a file-mapping object with the specified name
- * exists, CreateFileMapping requests full access to the existing
- * object.
- */
-static DWORD filemapAccessTable[] = {
- FILE_MAP_ALL_ACCESS & ~FILE_MAP_WRITE, /* read */
- FILE_MAP_ALL_ACCESS & ~FILE_MAP_READ, /* write */
- 0 /* execute */
-};
-
-extern PRSharedMemory * _MD_OpenSharedMemory(
- const char *name,
- PRSize size,
- PRIntn flags,
- PRIntn mode
-)
-{
- char ipcname[PR_IPC_NAME_SIZE];
- PRStatus rc = PR_SUCCESS;
- DWORD dwHi, dwLo;
- PRSharedMemory *shm;
- DWORD flProtect = ( PAGE_READWRITE );
- SECURITY_ATTRIBUTES sa;
- LPSECURITY_ATTRIBUTES lpSA = NULL;
- PSECURITY_DESCRIPTOR pSD = NULL;
- PACL pACL = NULL;
-
- rc = _PR_MakeNativeIPCName( name, ipcname, PR_IPC_NAME_SIZE, _PRIPCShm );
- if ( PR_FAILURE == rc )
- {
- PR_SetError(PR_UNKNOWN_ERROR, 0 );
- PR_LOG(_pr_shm_lm, PR_LOG_DEBUG, ( "PR_OpenSharedMemory: name is invalid"));
- return(NULL);
- }
-
- shm = PR_NEWZAP( PRSharedMemory );
- if ( NULL == shm )
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0 );
- PR_LOG(_pr_shm_lm, PR_LOG_DEBUG, ( "PR_OpenSharedMemory: New PRSharedMemory out of memory"));
- return(NULL);
- }
-
- shm->ipcname = PR_MALLOC( (PRUint32) (strlen( ipcname ) + 1) );
- if ( NULL == shm->ipcname )
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0 );
- PR_LOG(_pr_shm_lm, PR_LOG_DEBUG, ( "PR_OpenSharedMemory: New shm->ipcname out of memory"));
- PR_DELETE(shm);
- return(NULL);
- }
-
- /* copy args to struct */
- strcpy( shm->ipcname, ipcname );
- shm->size = size;
- shm->mode = mode;
- shm->flags = flags;
- shm->ident = _PR_SHM_IDENT;
-
- if (flags & PR_SHM_CREATE ) {
- dwHi = (DWORD) (((PRUint64) shm->size >> 32) & 0xffffffff);
- dwLo = (DWORD) (shm->size & 0xffffffff);
-
- if (_PR_NT_MakeSecurityDescriptorACL(mode, filemapAccessTable,
- &pSD, &pACL) == PR_SUCCESS) {
- sa.nLength = sizeof(sa);
- sa.lpSecurityDescriptor = pSD;
- sa.bInheritHandle = FALSE;
- lpSA = &sa;
- }
-#ifdef WINCE
- {
- /*
- * This is assuming that the name will never be larger than
- * MAX_PATH. Should we dynamically allocate?
- */
- PRUnichar wideIpcName[MAX_PATH];
- MultiByteToWideChar(CP_ACP, 0, shm->ipcname, -1,
- wideIpcName, MAX_PATH);
- shm->handle = CreateFileMappingW(
- (HANDLE)-1 ,
- lpSA,
- flProtect,
- dwHi,
- dwLo,
- wideIpcName);
- }
-#else
- shm->handle = CreateFileMappingA(
- (HANDLE)-1 ,
- lpSA,
- flProtect,
- dwHi,
- dwLo,
- shm->ipcname);
-#endif
- if (lpSA != NULL) {
- _PR_NT_FreeSecurityDescriptorACL(pSD, pACL);
- }
-
- if ( NULL == shm->handle ) {
- PR_LOG(_pr_shm_lm, PR_LOG_DEBUG,
- ( "PR_OpenSharedMemory: CreateFileMapping() failed: %s",
- shm->ipcname ));
- _PR_MD_MAP_DEFAULT_ERROR( GetLastError());
- PR_FREEIF( shm->ipcname )
- PR_DELETE( shm );
- return(NULL);
- } else {
- if (( flags & PR_SHM_EXCL) && ( GetLastError() == ERROR_ALREADY_EXISTS )) {
- PR_LOG(_pr_shm_lm, PR_LOG_DEBUG,
- ( "PR_OpenSharedMemory: Request exclusive & already exists",
- shm->ipcname ));
- PR_SetError( PR_FILE_EXISTS_ERROR, ERROR_ALREADY_EXISTS );
- CloseHandle( shm->handle );
- PR_FREEIF( shm->ipcname )
- PR_DELETE( shm );
- return(NULL);
- } else {
- PR_LOG(_pr_shm_lm, PR_LOG_DEBUG,
- ( "PR_OpenSharedMemory: CreateFileMapping() success: %s, handle: %d",
- shm->ipcname, shm->handle ));
- return(shm);
- }
- }
- } else {
-#ifdef WINCE
- PR_SetError( PR_NOT_IMPLEMENTED_ERROR, 0 );
- shm->handle = NULL; /* OpenFileMapping not supported */
-#else
- shm->handle = OpenFileMapping( FILE_MAP_WRITE, TRUE, shm->ipcname );
-#endif
- if ( NULL == shm->handle ) {
- _PR_MD_MAP_DEFAULT_ERROR( GetLastError());
- PR_LOG(_pr_shm_lm, PR_LOG_DEBUG,
- ( "PR_OpenSharedMemory: OpenFileMapping() failed: %s, error: %d",
- shm->ipcname, PR_GetOSError()));
- PR_FREEIF( shm->ipcname );
- PR_DELETE( shm );
- return(NULL);
- } else {
- PR_LOG(_pr_shm_lm, PR_LOG_DEBUG,
- ( "PR_OpenSharedMemory: OpenFileMapping() success: %s, handle: %d",
- shm->ipcname, shm->handle ));
- return(shm);
- }
- }
- /* returns from separate paths */
-}
-
-extern void * _MD_AttachSharedMemory( PRSharedMemory *shm, PRIntn flags )
-{
- PRUint32 access = FILE_MAP_WRITE;
- void *addr;
-
- PR_ASSERT( shm->ident == _PR_SHM_IDENT );
-
- if ( PR_SHM_READONLY & flags )
- access = FILE_MAP_READ;
-
- addr = MapViewOfFile( shm->handle,
- access,
- 0, 0,
- shm->size );
-
- if ( NULL == addr ) {
- _PR_MD_MAP_DEFAULT_ERROR( GetLastError());
- PR_LOG( _pr_shm_lm, PR_LOG_ERROR,
- ("_MD_AttachSharedMemory: MapViewOfFile() failed. OSerror: %d", PR_GetOSError()));
- }
-
- return( addr );
-} /* end _MD_ATTACH_SHARED_MEMORY() */
-
-
-extern PRStatus _MD_DetachSharedMemory( PRSharedMemory *shm, void *addr )
-{
- PRStatus rc = PR_SUCCESS;
- BOOL wrc;
-
- PR_ASSERT( shm->ident == _PR_SHM_IDENT );
-
- wrc = UnmapViewOfFile( addr );
- if ( FALSE == wrc )
- {
- _PR_MD_MAP_DEFAULT_ERROR( GetLastError());
- PR_LOG( _pr_shm_lm, PR_LOG_ERROR,
- ("_MD_DetachSharedMemory: UnmapViewOfFile() failed. OSerror: %d", PR_GetOSError()));
- rc = PR_FAILURE;
- }
-
- return( rc );
-}
-
-
-extern PRStatus _MD_CloseSharedMemory( PRSharedMemory *shm )
-{
- PRStatus rc = PR_SUCCESS;
- BOOL wrc;
-
- PR_ASSERT( shm->ident == _PR_SHM_IDENT );
-
- wrc = CloseHandle( shm->handle );
- if ( FALSE == wrc )
- {
- _PR_MD_MAP_DEFAULT_ERROR( GetLastError());
- PR_LOG( _pr_shm_lm, PR_LOG_ERROR,
- ("_MD_CloseSharedMemory: CloseHandle() failed. OSerror: %d", PR_GetOSError()));
- rc = PR_FAILURE;
- }
- PR_FREEIF( shm->ipcname );
- PR_DELETE( shm );
-
- return( rc );
-} /* end _MD_CLOSE_SHARED_MEMORY() */
-
-extern PRStatus _MD_DeleteSharedMemory( const char *name )
-{
- return( PR_SUCCESS );
-}
-
-
-/*
-** Windows implementation of anonymous memory (file) map
-*/
-extern PRLogModuleInfo *_pr_shma_lm;
-
-extern PRFileMap* _md_OpenAnonFileMap(
- const char *dirName,
- PRSize size,
- PRFileMapProtect prot
-)
-{
- PRFileMap *fm;
- HANDLE hFileMap;
-
- fm = PR_CreateFileMap( (PRFileDesc*)-1, size, prot );
- if ( NULL == fm ) {
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_OpenAnonFileMap(): PR_CreateFileMap(): failed"));
- goto Finished;
- }
-
- /*
- ** Make fm->md.hFileMap inheritable. We can't use
- ** GetHandleInformation and SetHandleInformation
- ** because these two functions fail with
- ** ERROR_CALL_NOT_IMPLEMENTED on Win95.
- */
- if (DuplicateHandle(GetCurrentProcess(), fm->md.hFileMap,
- GetCurrentProcess(), &hFileMap,
- 0, TRUE /* inheritable */,
- DUPLICATE_SAME_ACCESS) == FALSE) {
- PR_SetError( PR_UNKNOWN_ERROR, GetLastError() );
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_OpenAnonFileMap(): DuplicateHandle(): failed"));
- PR_CloseFileMap( fm );
- fm = NULL;
- goto Finished;
- }
- CloseHandle(fm->md.hFileMap);
- fm->md.hFileMap = hFileMap;
-
-Finished:
- return(fm);
-} /* end md_OpenAnonFileMap() */
-
-/*
-** _md_ExportFileMapAsString()
-**
-*/
-extern PRStatus _md_ExportFileMapAsString(
- PRFileMap *fm,
- PRSize bufSize,
- char *buf
-)
-{
- PRIntn written;
-
- written = PR_snprintf( buf, (PRUint32) bufSize, "%d:%" PR_PRIdOSFD ":%ld",
- (PRIntn)fm->prot, (PROsfd)fm->md.hFileMap, (PRInt32)fm->md.dwAccess );
-
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_ExportFileMapAsString(): prot: %x, hFileMap: %x, dwAccess: %x",
- fm->prot, fm->md.hFileMap, fm->md.dwAccess ));
-
- return((written == -1)? PR_FAILURE : PR_SUCCESS);
-} /* end _md_ExportFileMapAsString() */
-
-
-/*
-** _md_ImportFileMapFromString()
-**
-*/
-extern PRFileMap * _md_ImportFileMapFromString(
- const char *fmstring
-)
-{
- PRIntn prot;
- PROsfd hFileMap;
- PRInt32 dwAccess;
- PRFileMap *fm = NULL;
-
- PR_sscanf( fmstring, "%d:%" PR_SCNdOSFD ":%ld",
- &prot, &hFileMap, &dwAccess );
-
- fm = PR_NEWZAP(PRFileMap);
- if ( NULL == fm ) {
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_ImportFileMapFromString(): PR_NEWZAP(): Failed"));
- return(fm);
- }
-
- fm->prot = (PRFileMapProtect)prot;
- fm->md.hFileMap = (HANDLE)hFileMap;
- fm->md.dwAccess = (DWORD)dwAccess;
- fm->fd = (PRFileDesc*)-1;
-
- PR_LOG( _pr_shma_lm, PR_LOG_DEBUG,
- ("_md_ImportFileMapFromString(): fm: %p, prot: %d, hFileMap: %8.8x, dwAccess: %8.8x, fd: %x",
- fm, prot, fm->md.hFileMap, fm->md.dwAccess, fm->fd));
- return(fm);
-} /* end _md_ImportFileMapFromString() */
-
-#else
-Error! Why is PR_HAVE_WIN32_NAMED_SHARED_MEMORY not defined?
-#endif /* PR_HAVE_WIN32_NAMED_SHARED_MEMORY */
-/* --- end w32shm.c --- */
diff --git a/nspr/pr/src/md/windows/w95cv.c b/nspr/pr/src/md/windows/w95cv.c
deleted file mode 100644
index 27b34e6..0000000
--- a/nspr/pr/src/md/windows/w95cv.c
+++ /dev/null
@@ -1,367 +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/. */
-
-/*
- * w95cv.c -- Windows 95 Machine-Dependent Code for Condition Variables
- *
- * We implement our own condition variable wait queue. Each thread
- * has a semaphore object (thread->md.blocked_sema) to block on while
- * waiting on a condition variable.
- *
- * We use a deferred condition notify algorithm. When PR_NotifyCondVar
- * or PR_NotifyAllCondVar is called, the condition notifies are simply
- * recorded in the _MDLock structure. We defer the condition notifies
- * until right after we unlock the lock. This way the awakened threads
- * have a better chance to reaquire the lock.
- */
-
-#include "primpl.h"
-
-/*
- * AddThreadToCVWaitQueueInternal --
- *
- * Add the thread to the end of the condition variable's wait queue.
- * The CV's lock must be locked when this function is called.
- */
-
-static void
-AddThreadToCVWaitQueueInternal(PRThread *thred, struct _MDCVar *cv)
-{
- PR_ASSERT((cv->waitTail != NULL && cv->waitHead != NULL)
- || (cv->waitTail == NULL && cv->waitHead == NULL));
- cv->nwait += 1;
- thred->md.inCVWaitQueue = PR_TRUE;
- thred->md.next = NULL;
- thred->md.prev = cv->waitTail;
- if (cv->waitHead == NULL) {
- cv->waitHead = thred;
- } else {
- cv->waitTail->md.next = thred;
- }
- cv->waitTail = thred;
-}
-
-/*
- * md_UnlockAndPostNotifies --
- *
- * Unlock the lock, and then do the deferred condition notifies.
- * If waitThred and waitCV are not NULL, waitThred is added to
- * the wait queue of waitCV before the lock is unlocked.
- *
- * This function is called by _PR_MD_WAIT_CV and _PR_MD_UNLOCK,
- * the two places where a lock is unlocked.
- */
-static void
-md_UnlockAndPostNotifies(
- _MDLock *lock,
- PRThread *waitThred,
- _MDCVar *waitCV)
-{
- PRIntn index;
- _MDNotified post;
- _MDNotified *notified, *prev = NULL;
-
- /*
- * Time to actually notify any conditions that were affected
- * while the lock was held. Get a copy of the list that's in
- * the lock structure and then zero the original. If it's
- * linked to other such structures, we own that storage.
- */
- post = lock->notified; /* a safe copy; we own the lock */
-
-#if defined(DEBUG)
- ZeroMemory(&lock->notified, sizeof(_MDNotified)); /* reset */
-#else
- lock->notified.length = 0; /* these are really sufficient */
- lock->notified.link = NULL;
-#endif
-
- /*
- * Figure out how many threads we need to wake up.
- */
- notified = &post; /* this is where we start */
- do {
- for (index = 0; index < notified->length; ++index) {
- _MDCVar *cv = notified->cv[index].cv;
- PRThread *thred;
- int i;
-
- /* Fast special case: no waiting threads */
- if (cv->waitHead == NULL) {
- notified->cv[index].notifyHead = NULL;
- continue;
- }
-
- /* General case */
- if (-1 == notified->cv[index].times) {
- /* broadcast */
- thred = cv->waitHead;
- while (thred != NULL) {
- thred->md.inCVWaitQueue = PR_FALSE;
- thred = thred->md.next;
- }
- notified->cv[index].notifyHead = cv->waitHead;
- cv->waitHead = cv->waitTail = NULL;
- cv->nwait = 0;
- } else {
- thred = cv->waitHead;
- i = notified->cv[index].times;
- while (thred != NULL && i > 0) {
- thred->md.inCVWaitQueue = PR_FALSE;
- thred = thred->md.next;
- i--;
- }
- notified->cv[index].notifyHead = cv->waitHead;
- cv->waitHead = thred;
- if (cv->waitHead == NULL) {
- cv->waitTail = NULL;
- } else {
- if (cv->waitHead->md.prev != NULL) {
- cv->waitHead->md.prev->md.next = NULL;
- cv->waitHead->md.prev = NULL;
- }
- }
- cv->nwait -= notified->cv[index].times - i;
- }
- }
- notified = notified->link;
- } while (NULL != notified);
-
- if (waitThred) {
- AddThreadToCVWaitQueueInternal(waitThred, waitCV);
- }
-
- /* Release the lock before notifying */
- LeaveCriticalSection(&lock->mutex);
-
- notified = &post; /* this is where we start */
- do {
- for (index = 0; index < notified->length; ++index) {
- PRThread *thred;
- PRThread *next;
-
- thred = notified->cv[index].notifyHead;
- while (thred != NULL) {
- BOOL rv;
-
- next = thred->md.next;
- thred->md.prev = thred->md.next = NULL;
-
- rv = ReleaseSemaphore(thred->md.blocked_sema, 1, NULL);
- PR_ASSERT(rv != 0);
- thred = next;
- }
- }
- prev = notified;
- notified = notified->link;
- if (&post != prev) PR_DELETE(prev);
- } while (NULL != notified);
-}
-
-/*
- * Notifies just get posted to the protecting mutex. The
- * actual notification is done when the lock is released so that
- * MP systems don't contend for a lock that they can't have.
- */
-static void md_PostNotifyToCvar(_MDCVar *cvar, _MDLock *lock,
- PRBool broadcast)
-{
- PRIntn index = 0;
- _MDNotified *notified = &lock->notified;
-
- while (1) {
- for (index = 0; index < notified->length; ++index) {
- if (notified->cv[index].cv == cvar) {
- if (broadcast) {
- notified->cv[index].times = -1;
- } else if (-1 != notified->cv[index].times) {
- notified->cv[index].times += 1;
- }
- return;
- }
- }
- /* if not full, enter new CV in this array */
- if (notified->length < _MD_CV_NOTIFIED_LENGTH) break;
-
- /* if there's no link, create an empty array and link it */
- if (NULL == notified->link) {
- notified->link = PR_NEWZAP(_MDNotified);
- }
-
- notified = notified->link;
- }
-
- /* A brand new entry in the array */
- notified->cv[index].times = (broadcast) ? -1 : 1;
- notified->cv[index].cv = cvar;
- notified->length += 1;
-}
-
-/*
- * _PR_MD_NEW_CV() -- Creating new condition variable
- * ... Solaris uses cond_init() in similar function.
- *
- * returns: -1 on failure
- * 0 when it succeeds.
- *
- */
-PRInt32
-_PR_MD_NEW_CV(_MDCVar *cv)
-{
- cv->magic = _MD_MAGIC_CV;
- /*
- * The waitHead, waitTail, and nwait fields are zeroed
- * when the PRCondVar structure is created.
- */
- return 0;
-}
-
-void _PR_MD_FREE_CV(_MDCVar *cv)
-{
- cv->magic = (PRUint32)-1;
- return;
-}
-
-/*
- * _PR_MD_WAIT_CV() -- Wait on condition variable
- */
-void _PR_MD_WAIT_CV(_MDCVar *cv, _MDLock *lock, PRIntervalTime timeout )
-{
- PRThread *thred = _PR_MD_CURRENT_THREAD();
- DWORD rv;
- DWORD msecs = (timeout == PR_INTERVAL_NO_TIMEOUT) ?
- INFINITE : PR_IntervalToMilliseconds(timeout);
-
- /*
- * If we have pending notifies, post them now.
- */
- if (0 != lock->notified.length) {
- md_UnlockAndPostNotifies(lock, thred, cv);
- } else {
- AddThreadToCVWaitQueueInternal(thred, cv);
- LeaveCriticalSection(&lock->mutex);
- }
-
- /* Wait for notification or timeout; don't really care which */
- rv = WaitForSingleObject(thred->md.blocked_sema, msecs);
-
- EnterCriticalSection(&(lock->mutex));
-
- PR_ASSERT(rv != WAIT_ABANDONED);
- PR_ASSERT(rv != WAIT_FAILED);
- PR_ASSERT(rv != WAIT_OBJECT_0 || thred->md.inCVWaitQueue == PR_FALSE);
-
- if (rv == WAIT_TIMEOUT) {
- if (thred->md.inCVWaitQueue) {
- PR_ASSERT((cv->waitTail != NULL && cv->waitHead != NULL)
- || (cv->waitTail == NULL && cv->waitHead == NULL));
- cv->nwait -= 1;
- thred->md.inCVWaitQueue = PR_FALSE;
- if (cv->waitHead == thred) {
- cv->waitHead = thred->md.next;
- if (cv->waitHead == NULL) {
- cv->waitTail = NULL;
- } else {
- cv->waitHead->md.prev = NULL;
- }
- } else {
- PR_ASSERT(thred->md.prev != NULL);
- thred->md.prev->md.next = thred->md.next;
- if (thred->md.next != NULL) {
- thred->md.next->md.prev = thred->md.prev;
- } else {
- PR_ASSERT(cv->waitTail == thred);
- cv->waitTail = thred->md.prev;
- }
- }
- thred->md.next = thred->md.prev = NULL;
- } else {
- /*
- * This thread must have been notified, but the
- * ReleaseSemaphore call happens after WaitForSingleObject
- * times out. Wait on the semaphore again to make it
- * non-signaled. We assume this wait won't take long.
- */
- rv = WaitForSingleObject(thred->md.blocked_sema, INFINITE);
- PR_ASSERT(rv == WAIT_OBJECT_0);
- }
- }
- PR_ASSERT(thred->md.inCVWaitQueue == PR_FALSE);
- return;
-} /* --- end _PR_MD_WAIT_CV() --- */
-
-void _PR_MD_NOTIFY_CV(_MDCVar *cv, _MDLock *lock)
-{
- md_PostNotifyToCvar(cv, lock, PR_FALSE);
- return;
-}
-
-void _PR_MD_NOTIFYALL_CV(_MDCVar *cv, _MDLock *lock)
-{
- md_PostNotifyToCvar(cv, lock, PR_TRUE);
- return;
-}
-
-typedef BOOL (WINAPI *INITIALIZECRITICALSECTIONEX)(
- CRITICAL_SECTION *lpCriticalSection,
- DWORD dwSpinCount,
- DWORD Flags);
-
-static INITIALIZECRITICALSECTIONEX sInitializeCriticalSectionEx;
-
-void _PR_MD_INIT_LOCKS(void)
-{
- /*
- * Starting with Windows Vista, every CRITICAL_SECTION allocates an extra
- * RTL_CRITICAL_SECTION_DEBUG object. Unfortunately, this debug object is
- * not reclaimed by DeleteCriticalSection(), causing an apparent memory
- * leak. This is a debugging "feature", not a bug. If we are running on
- * Vista or later, use InitializeCriticalSectionEx() to allocate
- * CRITICAL_SECTIONs without debug objects.
- */
- HMODULE hKernel32 = GetModuleHandle("kernel32.dll");
- PR_ASSERT(hKernel32);
- PR_ASSERT(!sInitializeCriticalSectionEx);
- sInitializeCriticalSectionEx = (INITIALIZECRITICALSECTIONEX)
- GetProcAddress(hKernel32, "InitializeCriticalSectionEx");
-}
-
-/*
- * By default, CRITICAL_SECTIONs are initialized with a spin count of 0.
- * Joe Duffy's "Concurrent Programming on Windows" book suggests 1500 is
- * a "reasonable starting point". On single-processor systems, the spin
- * count is ignored and the critical section spin count is set to 0.
- */
-#define LOCK_SPIN_COUNT 1500
-
-PRStatus _PR_MD_NEW_LOCK(_MDLock *lock)
-{
- CRITICAL_SECTION *cs = &lock->mutex;
- BOOL ok;
-
- if (sInitializeCriticalSectionEx) {
- ok = sInitializeCriticalSectionEx(cs, LOCK_SPIN_COUNT,
- CRITICAL_SECTION_NO_DEBUG_INFO);
- } else {
- ok = InitializeCriticalSectionAndSpinCount(cs, LOCK_SPIN_COUNT);
- }
- if (!ok) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- return PR_FAILURE;
- }
-
- lock->notified.length = 0;
- lock->notified.link = NULL;
- return PR_SUCCESS;
-}
-
-void _PR_MD_UNLOCK(_MDLock *lock)
-{
- if (0 != lock->notified.length) {
- md_UnlockAndPostNotifies(lock, NULL, NULL);
- } else {
- LeaveCriticalSection(&lock->mutex);
- }
-}
diff --git a/nspr/pr/src/md/windows/w95dllmain.c b/nspr/pr/src/md/windows/w95dllmain.c
deleted file mode 100644
index 90957c1..0000000
--- a/nspr/pr/src/md/windows/w95dllmain.c
+++ /dev/null
@@ -1,43 +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/. */
-
-#ifndef NSPR_STATIC /* See the end of w95thred.c. */
-
-/*
- * The DLL entry point (DllMain) for NSPR.
- *
- * This is used to detach threads that were automatically attached by
- * nspr.
- */
-
-#include <windows.h>
-#include <primpl.h>
-
-BOOL WINAPI DllMain(
- HINSTANCE hinstDLL,
- DWORD fdwReason,
- LPVOID lpvReserved)
-{
-PRThread *me;
-
- switch (fdwReason) {
- case DLL_PROCESS_ATTACH:
- break;
- case DLL_THREAD_ATTACH:
- break;
- case DLL_THREAD_DETACH:
- if (_pr_initialized) {
- me = _MD_GET_ATTACHED_THREAD();
- if ((me != NULL) && (me->flags & _PR_ATTACHED))
- _PRI_DetachThread();
- }
- break;
- case DLL_PROCESS_DETACH:
- break;
- }
- return TRUE;
-}
-
-#endif
diff --git a/nspr/pr/src/md/windows/w95io.c b/nspr/pr/src/md/windows/w95io.c
deleted file mode 100644
index 9bae6f8..0000000
--- a/nspr/pr/src/md/windows/w95io.c
+++ /dev/null
@@ -1,1373 +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/. */
-
-/* Windows 95 IO module
- *
- * Assumes synchronous I/O.
- *
- */
-
-#include "primpl.h"
-#include <direct.h>
-#include <mbstring.h>
-#ifdef MOZ_UNICODE
-#include <wchar.h>
-#endif /* MOZ_UNICODE */
-
-struct _MDLock _pr_ioq_lock;
-
-/*
- * NSPR-to-NT access right mapping table for files.
- */
-static DWORD fileAccessTable[] = {
- FILE_GENERIC_READ,
- FILE_GENERIC_WRITE,
- FILE_GENERIC_EXECUTE
-};
-
-/*
- * NSPR-to-NT access right mapping table for directories.
- */
-static DWORD dirAccessTable[] = {
- FILE_GENERIC_READ,
- FILE_GENERIC_WRITE|FILE_DELETE_CHILD,
- FILE_GENERIC_EXECUTE
-};
-
-static PRBool IsPrevCharSlash(const char *str, const char *current);
-
-void
-_PR_MD_INIT_IO()
-{
- WORD WSAVersion = 0x0101;
- WSADATA WSAData;
- int err;
-
- err = WSAStartup( WSAVersion, &WSAData );
- PR_ASSERT(0 == err);
-
-#ifdef DEBUG
- /* Doublecheck _pr_filetime_offset's hard-coded value is correct. */
- {
- SYSTEMTIME systime;
- union {
- PRTime prt;
- FILETIME ft;
- } filetime;
- BOOL rv;
-
- systime.wYear = 1970;
- systime.wMonth = 1;
- /* wDayOfWeek is ignored */
- systime.wDay = 1;
- systime.wHour = 0;
- systime.wMinute = 0;
- systime.wSecond = 0;
- systime.wMilliseconds = 0;
-
- rv = SystemTimeToFileTime(&systime, &filetime.ft);
- PR_ASSERT(0 != rv);
- PR_ASSERT(filetime.prt == _pr_filetime_offset);
- }
-#endif /* DEBUG */
-
- _PR_NT_InitSids();
-
- _PR_MD_InitSockets();
-}
-
-PRStatus
-_PR_MD_WAIT(PRThread *thread, PRIntervalTime ticks)
-{
- DWORD rv;
-
- PRUint32 msecs = (ticks == PR_INTERVAL_NO_TIMEOUT) ?
- INFINITE : PR_IntervalToMilliseconds(ticks);
- rv = WaitForSingleObject(thread->md.blocked_sema, msecs);
- switch(rv)
- {
- case WAIT_OBJECT_0:
- return PR_SUCCESS;
- case WAIT_TIMEOUT:
- _PR_THREAD_LOCK(thread);
- if (thread->state == _PR_IO_WAIT) {
- ;
- } else {
- if (thread->wait.cvar != NULL) {
- thread->wait.cvar = NULL;
- _PR_THREAD_UNLOCK(thread);
- } else {
- /* The CVAR was notified just as the timeout
- * occurred. This led to us being notified twice.
- * call WaitForSingleObject() to clear the semaphore.
- */
- _PR_THREAD_UNLOCK(thread);
- rv = WaitForSingleObject(thread->md.blocked_sema, 0);
- PR_ASSERT(rv == WAIT_OBJECT_0);
- }
- }
- return PR_SUCCESS;
- default:
- return PR_FAILURE;
- }
-}
-PRStatus
-_PR_MD_WAKEUP_WAITER(PRThread *thread)
-{
- if ( _PR_IS_NATIVE_THREAD(thread) )
- {
- if (ReleaseSemaphore(thread->md.blocked_sema, 1, NULL) == FALSE)
- return PR_FAILURE;
- else
- return PR_SUCCESS;
- }
-}
-
-
-/* --- FILE IO ----------------------------------------------------------- */
-/*
- * _PR_MD_OPEN() -- Open a file
- *
- * returns: a fileHandle
- *
- * The NSPR open flags (osflags) are translated into flags for Win95
- *
- * Mode seems to be passed in as a unix style file permissions argument
- * as in 0666, in the case of opening the logFile.
- *
- */
-PROsfd
-_PR_MD_OPEN(const char *name, PRIntn osflags, int mode)
-{
- HANDLE file;
- PRInt32 access = 0;
- PRInt32 flags = 0;
- PRInt32 flag6 = 0;
-
- if (osflags & PR_SYNC) flag6 = FILE_FLAG_WRITE_THROUGH;
-
- if (osflags & PR_RDONLY || osflags & PR_RDWR)
- access |= GENERIC_READ;
- if (osflags & PR_WRONLY || osflags & PR_RDWR)
- access |= GENERIC_WRITE;
-
- if ( osflags & PR_CREATE_FILE && osflags & PR_EXCL )
- flags = CREATE_NEW;
- else if (osflags & PR_CREATE_FILE) {
- if (osflags & PR_TRUNCATE)
- flags = CREATE_ALWAYS;
- else
- flags = OPEN_ALWAYS;
- } else {
- if (osflags & PR_TRUNCATE)
- flags = TRUNCATE_EXISTING;
- else
- flags = OPEN_EXISTING;
- }
-
- file = CreateFileA(name,
- access,
- FILE_SHARE_READ|FILE_SHARE_WRITE,
- NULL,
- flags,
- flag6,
- NULL);
- if (file == INVALID_HANDLE_VALUE) {
- _PR_MD_MAP_OPEN_ERROR(GetLastError());
- return -1;
- }
-
- return (PROsfd)file;
-}
-
-PROsfd
-_PR_MD_OPEN_FILE(const char *name, PRIntn osflags, int mode)
-{
- HANDLE file;
- PRInt32 access = 0;
- PRInt32 flags = 0;
- PRInt32 flag6 = 0;
- SECURITY_ATTRIBUTES sa;
- LPSECURITY_ATTRIBUTES lpSA = NULL;
- PSECURITY_DESCRIPTOR pSD = NULL;
- PACL pACL = NULL;
-
- if (osflags & PR_CREATE_FILE) {
- if (_PR_NT_MakeSecurityDescriptorACL(mode, fileAccessTable,
- &pSD, &pACL) == PR_SUCCESS) {
- sa.nLength = sizeof(sa);
- sa.lpSecurityDescriptor = pSD;
- sa.bInheritHandle = FALSE;
- lpSA = &sa;
- }
- }
-
- if (osflags & PR_SYNC) flag6 = FILE_FLAG_WRITE_THROUGH;
-
- if (osflags & PR_RDONLY || osflags & PR_RDWR)
- access |= GENERIC_READ;
- if (osflags & PR_WRONLY || osflags & PR_RDWR)
- access |= GENERIC_WRITE;
-
- if ( osflags & PR_CREATE_FILE && osflags & PR_EXCL )
- flags = CREATE_NEW;
- else if (osflags & PR_CREATE_FILE) {
- if (osflags & PR_TRUNCATE)
- flags = CREATE_ALWAYS;
- else
- flags = OPEN_ALWAYS;
- } else {
- if (osflags & PR_TRUNCATE)
- flags = TRUNCATE_EXISTING;
- else
- flags = OPEN_EXISTING;
- }
-
- file = CreateFileA(name,
- access,
- FILE_SHARE_READ|FILE_SHARE_WRITE,
- lpSA,
- flags,
- flag6,
- NULL);
- if (lpSA != NULL) {
- _PR_NT_FreeSecurityDescriptorACL(pSD, pACL);
- }
- if (file == INVALID_HANDLE_VALUE) {
- _PR_MD_MAP_OPEN_ERROR(GetLastError());
- return -1;
- }
-
- return (PROsfd)file;
-}
-
-PRInt32
-_PR_MD_READ(PRFileDesc *fd, void *buf, PRInt32 len)
-{
- PRUint32 bytes;
- int rv, err;
-
- rv = ReadFile((HANDLE)fd->secret->md.osfd,
- (LPVOID)buf,
- len,
- &bytes,
- NULL);
-
- if (rv == 0)
- {
- err = GetLastError();
- /* ERROR_HANDLE_EOF can only be returned by async io */
- PR_ASSERT(err != ERROR_HANDLE_EOF);
- if (err == ERROR_BROKEN_PIPE)
- return 0;
- else {
- _PR_MD_MAP_READ_ERROR(err);
- return -1;
- }
- }
- return bytes;
-}
-
-PRInt32
-_PR_MD_WRITE(PRFileDesc *fd, const void *buf, PRInt32 len)
-{
- PROsfd f = fd->secret->md.osfd;
- PRInt32 bytes;
- int rv;
-
- rv = WriteFile((HANDLE)f,
- buf,
- len,
- &bytes,
- NULL );
-
- if (rv == 0)
- {
- _PR_MD_MAP_WRITE_ERROR(GetLastError());
- return -1;
- }
- return bytes;
-} /* --- end _PR_MD_WRITE() --- */
-
-PROffset32
-_PR_MD_LSEEK(PRFileDesc *fd, PROffset32 offset, PRSeekWhence whence)
-{
- DWORD moveMethod;
- PROffset32 rv;
-
- switch (whence) {
- case PR_SEEK_SET:
- moveMethod = FILE_BEGIN;
- break;
- case PR_SEEK_CUR:
- moveMethod = FILE_CURRENT;
- break;
- case PR_SEEK_END:
- moveMethod = FILE_END;
- break;
- default:
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return -1;
- }
-
- rv = SetFilePointer((HANDLE)fd->secret->md.osfd, offset, NULL, moveMethod);
-
- /*
- * If the lpDistanceToMoveHigh argument (third argument) is
- * NULL, SetFilePointer returns 0xffffffff on failure.
- */
- if (-1 == rv) {
- _PR_MD_MAP_LSEEK_ERROR(GetLastError());
- }
- return rv;
-}
-
-PROffset64
-_PR_MD_LSEEK64(PRFileDesc *fd, PROffset64 offset, PRSeekWhence whence)
-{
- DWORD moveMethod;
- LARGE_INTEGER li;
- DWORD err;
-
- switch (whence) {
- case PR_SEEK_SET:
- moveMethod = FILE_BEGIN;
- break;
- case PR_SEEK_CUR:
- moveMethod = FILE_CURRENT;
- break;
- case PR_SEEK_END:
- moveMethod = FILE_END;
- break;
- default:
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return -1;
- }
-
- li.QuadPart = offset;
- li.LowPart = SetFilePointer((HANDLE)fd->secret->md.osfd,
- li.LowPart, &li.HighPart, moveMethod);
-
- if (0xffffffff == li.LowPart && (err = GetLastError()) != NO_ERROR) {
- _PR_MD_MAP_LSEEK_ERROR(err);
- li.QuadPart = -1;
- }
- return li.QuadPart;
-}
-
-/*
- * This is documented to succeed on read-only files, but Win32's
- * FlushFileBuffers functions fails with "access denied" in such a
- * case. So we only signal an error if the error is *not* "access
- * denied".
- */
-PRInt32
-_PR_MD_FSYNC(PRFileDesc *fd)
-{
- /*
- * From the documentation:
- *
- * On Windows NT, the function FlushFileBuffers fails if hFile
- * is a handle to console output. That is because console
- * output is not buffered. The function returns FALSE, and
- * GetLastError returns ERROR_INVALID_HANDLE.
- *
- * On the other hand, on Win95, it returns without error. I cannot
- * assume that 0, 1, and 2 are console, because if someone closes
- * System.out and then opens a file, they might get file descriptor
- * 1. An error on *that* version of 1 should be reported, whereas
- * an error on System.out (which was the original 1) should be
- * ignored. So I use isatty() to ensure that such an error was due
- * to this bogosity, and if it was, I ignore the error.
- */
-
- BOOL ok = FlushFileBuffers((HANDLE)fd->secret->md.osfd);
-
- if (!ok) {
- DWORD err = GetLastError();
- if (err != ERROR_ACCESS_DENIED) { // from winerror.h
- _PR_MD_MAP_FSYNC_ERROR(err);
- return -1;
- }
- }
- return 0;
-}
-
-PRInt32
-_MD_CloseFile(PROsfd osfd)
-{
- PRInt32 rv;
-
- rv = (CloseHandle((HANDLE)osfd))?0:-1;
- if (rv == -1)
- _PR_MD_MAP_CLOSE_ERROR(GetLastError());
- return rv;
-}
-
-
-/* --- DIR IO ------------------------------------------------------------ */
-#define GetFileFromDIR(d) (d)->d_entry.cFileName
-#define FileIsHidden(d) ((d)->d_entry.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
-
-static void FlipSlashes(char *cp, size_t len)
-{
- while (len-- > 0) {
- if (cp[0] == '/') {
- cp[0] = PR_DIRECTORY_SEPARATOR;
- }
- cp = _mbsinc(cp);
- }
-} /* end FlipSlashes() */
-
-
-/*
-**
-** Local implementations of standard Unix RTL functions which are not provided
-** by the VC RTL.
-**
-*/
-
-PRInt32
-_PR_MD_CLOSE_DIR(_MDDir *d)
-{
- if ( d ) {
- if (FindClose(d->d_hdl)) {
- d->magic = (PRUint32)-1;
- return 0;
- } else {
- _PR_MD_MAP_CLOSEDIR_ERROR(GetLastError());
- return -1;
- }
- }
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return -1;
-}
-
-
-PRStatus
-_PR_MD_OPEN_DIR(_MDDir *d, const char *name)
-{
- char filename[ MAX_PATH ];
- size_t len;
-
- len = strlen(name);
- /* Need 5 bytes for \*.* and the trailing null byte. */
- if (len + 5 > MAX_PATH) {
- PR_SetError(PR_NAME_TOO_LONG_ERROR, 0);
- return PR_FAILURE;
- }
- strcpy(filename, name);
-
- /*
- * If 'name' ends in a slash or backslash, do not append
- * another backslash.
- */
- if (IsPrevCharSlash(filename, filename + len)) {
- len--;
- }
- strcpy(&filename[len], "\\*.*");
- FlipSlashes( filename, strlen(filename) );
-
- d->d_hdl = FindFirstFileA( filename, &(d->d_entry) );
- if ( d->d_hdl == INVALID_HANDLE_VALUE ) {
- _PR_MD_MAP_OPENDIR_ERROR(GetLastError());
- return PR_FAILURE;
- }
- d->firstEntry = PR_TRUE;
- d->magic = _MD_MAGIC_DIR;
- return PR_SUCCESS;
-}
-
-char *
-_PR_MD_READ_DIR(_MDDir *d, PRIntn flags)
-{
- PRInt32 err;
- BOOL rv;
- char *fileName;
-
- if ( d ) {
- while (1) {
- if (d->firstEntry) {
- d->firstEntry = PR_FALSE;
- rv = 1;
- } else {
- rv = FindNextFileA(d->d_hdl, &(d->d_entry));
- }
- if (rv == 0) {
- break;
- }
- fileName = GetFileFromDIR(d);
- if ( (flags & PR_SKIP_DOT) &&
- (fileName[0] == '.') && (fileName[1] == '\0'))
- continue;
- if ( (flags & PR_SKIP_DOT_DOT) &&
- (fileName[0] == '.') && (fileName[1] == '.') &&
- (fileName[2] == '\0'))
- continue;
- if ( (flags & PR_SKIP_HIDDEN) && FileIsHidden(d))
- continue;
- return fileName;
- }
- err = GetLastError();
- PR_ASSERT(NO_ERROR != err);
- _PR_MD_MAP_READDIR_ERROR(err);
- return NULL;
- }
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return NULL;
-}
-
-PRInt32
-_PR_MD_DELETE(const char *name)
-{
- if (DeleteFileA(name)) {
- return 0;
- } else {
- _PR_MD_MAP_DELETE_ERROR(GetLastError());
- return -1;
- }
-}
-
-void
-_PR_FileTimeToPRTime(const FILETIME *filetime, PRTime *prtm)
-{
- PR_ASSERT(sizeof(FILETIME) == sizeof(PRTime));
- CopyMemory(prtm, filetime, sizeof(PRTime));
-#if defined(__MINGW32__)
- *prtm = (*prtm - _pr_filetime_offset) / 10LL;
-#else
- *prtm = (*prtm - _pr_filetime_offset) / 10i64;
-#endif
-
-#ifdef DEBUG
- /* Doublecheck our calculation. */
- {
- SYSTEMTIME systime;
- PRExplodedTime etm;
- PRTime cmp; /* for comparison */
- BOOL rv;
-
- rv = FileTimeToSystemTime(filetime, &systime);
- PR_ASSERT(0 != rv);
-
- /*
- * PR_ImplodeTime ignores wday and yday.
- */
- etm.tm_usec = systime.wMilliseconds * PR_USEC_PER_MSEC;
- etm.tm_sec = systime.wSecond;
- etm.tm_min = systime.wMinute;
- etm.tm_hour = systime.wHour;
- etm.tm_mday = systime.wDay;
- etm.tm_month = systime.wMonth - 1;
- etm.tm_year = systime.wYear;
- /*
- * It is not well-documented what time zone the FILETIME's
- * are in. WIN32_FIND_DATA is documented to be in UTC (GMT).
- * But BY_HANDLE_FILE_INFORMATION is unclear about this.
- * By our best judgement, we assume that FILETIME is in UTC.
- */
- etm.tm_params.tp_gmt_offset = 0;
- etm.tm_params.tp_dst_offset = 0;
- cmp = PR_ImplodeTime(&etm);
-
- /*
- * SYSTEMTIME is in milliseconds precision, so we convert PRTime's
- * microseconds to milliseconds before doing the comparison.
- */
- PR_ASSERT((cmp / PR_USEC_PER_MSEC) == (*prtm / PR_USEC_PER_MSEC));
- }
-#endif /* DEBUG */
-}
-
-PRInt32
-_PR_MD_STAT(const char *fn, struct stat *info)
-{
- PRInt32 rv;
-
- rv = _stat(fn, (struct _stat *)info);
- if (-1 == rv) {
- /*
- * Check for MSVC runtime library _stat() bug.
- * (It's really a bug in FindFirstFile().)
- * If a pathname ends in a backslash or slash,
- * e.g., c:\temp\ or c:/temp/, _stat() will fail.
- * Note: a pathname ending in a slash (e.g., c:/temp/)
- * can be handled by _stat() on NT but not on Win95.
- *
- * We remove the backslash or slash at the end and
- * try again.
- */
-
- size_t len = strlen(fn);
- if (len > 0 && len <= _MAX_PATH
- && IsPrevCharSlash(fn, fn + len)) {
- char newfn[_MAX_PATH + 1];
-
- strcpy(newfn, fn);
- newfn[len - 1] = '\0';
- rv = _stat(newfn, (struct _stat *)info);
- }
- }
-
- if (-1 == rv) {
- _PR_MD_MAP_STAT_ERROR(errno);
- }
- return rv;
-}
-
-#define _PR_IS_SLASH(ch) ((ch) == '/' || (ch) == '\\')
-
-static PRBool
-IsPrevCharSlash(const char *str, const char *current)
-{
- const char *prev;
-
- if (str >= current)
- return PR_FALSE;
- prev = _mbsdec(str, current);
- return (prev == current - 1) && _PR_IS_SLASH(*prev);
-}
-
-/*
- * IsRootDirectory --
- *
- * Return PR_TRUE if the pathname 'fn' is a valid root directory,
- * else return PR_FALSE. The char buffer pointed to by 'fn' must
- * be writable. During the execution of this function, the contents
- * of the buffer pointed to by 'fn' may be modified, but on return
- * the original contents will be restored. 'buflen' is the size of
- * the buffer pointed to by 'fn'.
- *
- * Root directories come in three formats:
- * 1. / or \, meaning the root directory of the current drive.
- * 2. C:/ or C:\, where C is a drive letter.
- * 3. \\<server name>\<share point name>\ or
- * \\<server name>\<share point name>, meaning the root directory
- * of a UNC (Universal Naming Convention) name.
- */
-
-static PRBool
-IsRootDirectory(char *fn, size_t buflen)
-{
- char *p;
- PRBool slashAdded = PR_FALSE;
- PRBool rv = PR_FALSE;
-
- if (_PR_IS_SLASH(fn[0]) && fn[1] == '\0') {
- return PR_TRUE;
- }
-
- if (isalpha(fn[0]) && fn[1] == ':' && _PR_IS_SLASH(fn[2])
- && fn[3] == '\0') {
- rv = GetDriveType(fn) > 1 ? PR_TRUE : PR_FALSE;
- return rv;
- }
-
- /* The UNC root directory */
-
- if (_PR_IS_SLASH(fn[0]) && _PR_IS_SLASH(fn[1])) {
- /* The 'server' part should have at least one character. */
- p = &fn[2];
- if (*p == '\0' || _PR_IS_SLASH(*p)) {
- return PR_FALSE;
- }
-
- /* look for the next slash */
- do {
- p = _mbsinc(p);
- } while (*p != '\0' && !_PR_IS_SLASH(*p));
- if (*p == '\0') {
- return PR_FALSE;
- }
-
- /* The 'share' part should have at least one character. */
- p++;
- if (*p == '\0' || _PR_IS_SLASH(*p)) {
- return PR_FALSE;
- }
-
- /* look for the final slash */
- do {
- p = _mbsinc(p);
- } while (*p != '\0' && !_PR_IS_SLASH(*p));
- if (_PR_IS_SLASH(*p) && p[1] != '\0') {
- return PR_FALSE;
- }
- if (*p == '\0') {
- /*
- * GetDriveType() doesn't work correctly if the
- * path is of the form \\server\share, so we add
- * a final slash temporarily.
- */
- if ((p + 1) < (fn + buflen)) {
- *p++ = '\\';
- *p = '\0';
- slashAdded = PR_TRUE;
- } else {
- return PR_FALSE; /* name too long */
- }
- }
- rv = GetDriveType(fn) > 1 ? PR_TRUE : PR_FALSE;
- /* restore the 'fn' buffer */
- if (slashAdded) {
- *--p = '\0';
- }
- }
- return rv;
-}
-
-PRInt32
-_PR_MD_GETFILEINFO64(const char *fn, PRFileInfo64 *info)
-{
- WIN32_FILE_ATTRIBUTE_DATA findFileData;
- BOOL rv;
-
- if (NULL == fn || '\0' == *fn) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return -1;
- }
-
- rv = GetFileAttributesEx(fn, GetFileExInfoStandard, &findFileData);
- if (!rv) {
- _PR_MD_MAP_OPENDIR_ERROR(GetLastError());
- return -1;
- }
-
- if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
- info->type = PR_FILE_DIRECTORY;
- } else {
- info->type = PR_FILE_FILE;
- }
-
- info->size = findFileData.nFileSizeHigh;
- info->size = (info->size << 32) + findFileData.nFileSizeLow;
-
- _PR_FileTimeToPRTime(&findFileData.ftLastWriteTime, &info->modifyTime);
-
- if (0 == findFileData.ftCreationTime.dwLowDateTime &&
- 0 == findFileData.ftCreationTime.dwHighDateTime) {
- info->creationTime = info->modifyTime;
- } else {
- _PR_FileTimeToPRTime(&findFileData.ftCreationTime,
- &info->creationTime);
- }
-
- return 0;
-}
-
-PRInt32
-_PR_MD_GETFILEINFO(const char *fn, PRFileInfo *info)
-{
- PRFileInfo64 info64;
- PRInt32 rv = _PR_MD_GETFILEINFO64(fn, &info64);
- if (0 == rv)
- {
- info->type = info64.type;
- info->size = (PRUint32) info64.size;
- info->modifyTime = info64.modifyTime;
- info->creationTime = info64.creationTime;
- }
- return rv;
-}
-
-PRInt32
-_PR_MD_GETOPENFILEINFO64(const PRFileDesc *fd, PRFileInfo64 *info)
-{
- int rv;
-
- BY_HANDLE_FILE_INFORMATION hinfo;
-
- rv = GetFileInformationByHandle((HANDLE)fd->secret->md.osfd, &hinfo);
- if (rv == FALSE) {
- _PR_MD_MAP_FSTAT_ERROR(GetLastError());
- return -1;
- }
-
- if (hinfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
- info->type = PR_FILE_DIRECTORY;
- else
- info->type = PR_FILE_FILE;
-
- info->size = hinfo.nFileSizeHigh;
- info->size = (info->size << 32) + hinfo.nFileSizeLow;
-
- _PR_FileTimeToPRTime(&hinfo.ftLastWriteTime, &(info->modifyTime) );
- _PR_FileTimeToPRTime(&hinfo.ftCreationTime, &(info->creationTime) );
-
- return 0;
-}
-
-PRInt32
-_PR_MD_GETOPENFILEINFO(const PRFileDesc *fd, PRFileInfo *info)
-{
- PRFileInfo64 info64;
- int rv = _PR_MD_GETOPENFILEINFO64(fd, &info64);
- if (0 == rv)
- {
- info->type = info64.type;
- info->modifyTime = info64.modifyTime;
- info->creationTime = info64.creationTime;
- LL_L2I(info->size, info64.size);
- }
- return rv;
-}
-
-PRStatus
-_PR_MD_SET_FD_INHERITABLE(PRFileDesc *fd, PRBool inheritable)
-{
- BOOL rv;
-
- /*
- * The SetHandleInformation function fails with the
- * ERROR_CALL_NOT_IMPLEMENTED error on Win95.
- */
- rv = SetHandleInformation(
- (HANDLE)fd->secret->md.osfd,
- HANDLE_FLAG_INHERIT,
- inheritable ? HANDLE_FLAG_INHERIT : 0);
- if (0 == rv) {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-void
-_PR_MD_INIT_FD_INHERITABLE(PRFileDesc *fd, PRBool imported)
-{
- if (imported) {
- fd->secret->inheritable = _PR_TRI_UNKNOWN;
- } else {
- fd->secret->inheritable = _PR_TRI_FALSE;
- }
-}
-
-void
-_PR_MD_QUERY_FD_INHERITABLE(PRFileDesc *fd)
-{
- DWORD flags;
-
- PR_ASSERT(_PR_TRI_UNKNOWN == fd->secret->inheritable);
- if (GetHandleInformation((HANDLE)fd->secret->md.osfd, &flags)) {
- if (flags & HANDLE_FLAG_INHERIT) {
- fd->secret->inheritable = _PR_TRI_TRUE;
- } else {
- fd->secret->inheritable = _PR_TRI_FALSE;
- }
- }
-}
-
-PRInt32
-_PR_MD_RENAME(const char *from, const char *to)
-{
- /* Does this work with dot-relative pathnames? */
- if (MoveFileA(from, to)) {
- return 0;
- } else {
- _PR_MD_MAP_RENAME_ERROR(GetLastError());
- return -1;
- }
-}
-
-PRInt32
-_PR_MD_ACCESS(const char *name, PRAccessHow how)
-{
-PRInt32 rv;
- switch (how) {
- case PR_ACCESS_WRITE_OK:
- rv = _access(name, 02);
- break;
- case PR_ACCESS_READ_OK:
- rv = _access(name, 04);
- break;
- case PR_ACCESS_EXISTS:
- return _access(name, 00);
- break;
- default:
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return -1;
- }
- if (rv < 0)
- _PR_MD_MAP_ACCESS_ERROR(errno);
- return rv;
-}
-
-PRInt32
-_PR_MD_MKDIR(const char *name, PRIntn mode)
-{
- /* XXXMB - how to translate the "mode"??? */
- if (CreateDirectoryA(name, NULL)) {
- return 0;
- } else {
- _PR_MD_MAP_MKDIR_ERROR(GetLastError());
- return -1;
- }
-}
-
-PRInt32
-_PR_MD_MAKE_DIR(const char *name, PRIntn mode)
-{
- BOOL rv;
- SECURITY_ATTRIBUTES sa;
- LPSECURITY_ATTRIBUTES lpSA = NULL;
- PSECURITY_DESCRIPTOR pSD = NULL;
- PACL pACL = NULL;
-
- if (_PR_NT_MakeSecurityDescriptorACL(mode, dirAccessTable,
- &pSD, &pACL) == PR_SUCCESS) {
- sa.nLength = sizeof(sa);
- sa.lpSecurityDescriptor = pSD;
- sa.bInheritHandle = FALSE;
- lpSA = &sa;
- }
- rv = CreateDirectoryA(name, lpSA);
- if (lpSA != NULL) {
- _PR_NT_FreeSecurityDescriptorACL(pSD, pACL);
- }
- if (rv) {
- return 0;
- } else {
- _PR_MD_MAP_MKDIR_ERROR(GetLastError());
- return -1;
- }
-}
-
-PRInt32
-_PR_MD_RMDIR(const char *name)
-{
- if (RemoveDirectoryA(name)) {
- return 0;
- } else {
- _PR_MD_MAP_RMDIR_ERROR(GetLastError());
- return -1;
- }
-}
-
-PRStatus
-_PR_MD_LOCKFILE(PROsfd f)
-{
- PRStatus rc = PR_SUCCESS;
- DWORD rv;
-
- rv = LockFile( (HANDLE)f,
- 0l, 0l,
- 0x0l, 0xffffffffl );
- if ( rv == 0 ) {
- DWORD err = GetLastError();
- _PR_MD_MAP_DEFAULT_ERROR(err);
- PR_LOG( _pr_io_lm, PR_LOG_ERROR,
- ("_PR_MD_LOCKFILE() failed. Error: %d", err ));
- rc = PR_FAILURE;
- }
-
- return rc;
-} /* end _PR_MD_LOCKFILE() */
-
-PRStatus
-_PR_MD_TLOCKFILE(PROsfd f)
-{
- PR_SetError( PR_NOT_IMPLEMENTED_ERROR, 0 );
- return PR_FAILURE;
-} /* end _PR_MD_TLOCKFILE() */
-
-
-PRStatus
-_PR_MD_UNLOCKFILE(PROsfd f)
-{
- PRInt32 rv;
-
- rv = UnlockFile( (HANDLE) f,
- 0l, 0l,
- 0x0l, 0xffffffffl );
-
- if ( rv )
- {
- return PR_SUCCESS;
- }
- else
- {
- _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
- return PR_FAILURE;
- }
-} /* end _PR_MD_UNLOCKFILE() */
-
-PRInt32
-_PR_MD_PIPEAVAILABLE(PRFileDesc *fd)
-{
- if (NULL == fd)
- PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
- else
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return -1;
-}
-
-#ifdef MOZ_UNICODE
-
-typedef HANDLE (WINAPI *CreateFileWFn) (LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE);
-static CreateFileWFn createFileW = CreateFileW;
-typedef HANDLE (WINAPI *FindFirstFileWFn) (LPCWSTR, LPWIN32_FIND_DATAW);
-static FindFirstFileWFn findFirstFileW = FindFirstFileW;
-typedef BOOL (WINAPI *FindNextFileWFn) (HANDLE, LPWIN32_FIND_DATAW);
-static FindNextFileWFn findNextFileW = FindNextFileW;
-typedef DWORD (WINAPI *GetFullPathNameWFn) (LPCWSTR, DWORD, LPWSTR, LPWSTR *);
-static GetFullPathNameWFn getFullPathNameW = GetFullPathNameW;
-typedef UINT (WINAPI *GetDriveTypeWFn) (LPCWSTR);
-static GetDriveTypeWFn getDriveTypeW = GetDriveTypeW;
-
-#endif /* MOZ_UNICODE */
-
-#ifdef MOZ_UNICODE
-
-/* ================ UTF16 Interfaces ================================ */
-static void FlipSlashesW(PRUnichar *cp, size_t len)
-{
- while (len-- > 0) {
- if (cp[0] == L'/') {
- cp[0] = L'\\';
- }
- cp++;
- }
-} /* end FlipSlashesW() */
-
-PROsfd
-_PR_MD_OPEN_FILE_UTF16(const PRUnichar *name, PRIntn osflags, int mode)
-{
- HANDLE file;
- PRInt32 access = 0;
- PRInt32 flags = 0;
- PRInt32 flag6 = 0;
- SECURITY_ATTRIBUTES sa;
- LPSECURITY_ATTRIBUTES lpSA = NULL;
- PSECURITY_DESCRIPTOR pSD = NULL;
- PACL pACL = NULL;
-
- if (osflags & PR_CREATE_FILE) {
- if (_PR_NT_MakeSecurityDescriptorACL(mode, fileAccessTable,
- &pSD, &pACL) == PR_SUCCESS) {
- sa.nLength = sizeof(sa);
- sa.lpSecurityDescriptor = pSD;
- sa.bInheritHandle = FALSE;
- lpSA = &sa;
- }
- }
-
- if (osflags & PR_SYNC) flag6 = FILE_FLAG_WRITE_THROUGH;
-
- if (osflags & PR_RDONLY || osflags & PR_RDWR)
- access |= GENERIC_READ;
- if (osflags & PR_WRONLY || osflags & PR_RDWR)
- access |= GENERIC_WRITE;
-
- if ( osflags & PR_CREATE_FILE && osflags & PR_EXCL )
- flags = CREATE_NEW;
- else if (osflags & PR_CREATE_FILE) {
- if (osflags & PR_TRUNCATE)
- flags = CREATE_ALWAYS;
- else
- flags = OPEN_ALWAYS;
- } else {
- if (osflags & PR_TRUNCATE)
- flags = TRUNCATE_EXISTING;
- else
- flags = OPEN_EXISTING;
- }
-
- file = createFileW(name,
- access,
- FILE_SHARE_READ|FILE_SHARE_WRITE,
- lpSA,
- flags,
- flag6,
- NULL);
- if (lpSA != NULL) {
- _PR_NT_FreeSecurityDescriptorACL(pSD, pACL);
- }
- if (file == INVALID_HANDLE_VALUE) {
- _PR_MD_MAP_OPEN_ERROR(GetLastError());
- return -1;
- }
-
- return (PROsfd)file;
-}
-
-PRStatus
-_PR_MD_OPEN_DIR_UTF16(_MDDirUTF16 *d, const PRUnichar *name)
-{
- PRUnichar filename[ MAX_PATH ];
- int len;
-
- len = wcslen(name);
- /* Need 5 bytes for \*.* and the trailing null byte. */
- if (len + 5 > MAX_PATH) {
- PR_SetError(PR_NAME_TOO_LONG_ERROR, 0);
- return PR_FAILURE;
- }
- wcscpy(filename, name);
-
- /*
- * If 'name' ends in a slash or backslash, do not append
- * another backslash.
- */
- if (filename[len - 1] == L'/' || filename[len - 1] == L'\\') {
- len--;
- }
- wcscpy(&filename[len], L"\\*.*");
- FlipSlashesW( filename, wcslen(filename) );
-
- d->d_hdl = findFirstFileW( filename, &(d->d_entry) );
- if ( d->d_hdl == INVALID_HANDLE_VALUE ) {
- _PR_MD_MAP_OPENDIR_ERROR(GetLastError());
- return PR_FAILURE;
- }
- d->firstEntry = PR_TRUE;
- d->magic = _MD_MAGIC_DIR;
- return PR_SUCCESS;
-}
-
-PRUnichar *
-_PR_MD_READ_DIR_UTF16(_MDDirUTF16 *d, PRIntn flags)
-{
- PRInt32 err;
- BOOL rv;
- PRUnichar *fileName;
-
- if ( d ) {
- while (1) {
- if (d->firstEntry) {
- d->firstEntry = PR_FALSE;
- rv = 1;
- } else {
- rv = findNextFileW(d->d_hdl, &(d->d_entry));
- }
- if (rv == 0) {
- break;
- }
- fileName = GetFileFromDIR(d);
- if ( (flags & PR_SKIP_DOT) &&
- (fileName[0] == L'.') && (fileName[1] == L'\0'))
- continue;
- if ( (flags & PR_SKIP_DOT_DOT) &&
- (fileName[0] == L'.') && (fileName[1] == L'.') &&
- (fileName[2] == L'\0'))
- continue;
- if ( (flags & PR_SKIP_HIDDEN) && FileIsHidden(d))
- continue;
- return fileName;
- }
- err = GetLastError();
- PR_ASSERT(NO_ERROR != err);
- _PR_MD_MAP_READDIR_ERROR(err);
- return NULL;
- }
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return NULL;
-}
-
-PRInt32
-_PR_MD_CLOSE_DIR_UTF16(_MDDirUTF16 *d)
-{
- if ( d ) {
- if (FindClose(d->d_hdl)) {
- d->magic = (PRUint32)-1;
- return 0;
- } else {
- _PR_MD_MAP_CLOSEDIR_ERROR(GetLastError());
- return -1;
- }
- }
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return -1;
-}
-
-#define _PR_IS_W_SLASH(ch) ((ch) == L'/' || (ch) == L'\\')
-
-/*
- * IsRootDirectoryW --
- *
- * Return PR_TRUE if the pathname 'fn' is a valid root directory,
- * else return PR_FALSE. The PRUnichar buffer pointed to by 'fn' must
- * be writable. During the execution of this function, the contents
- * of the buffer pointed to by 'fn' may be modified, but on return
- * the original contents will be restored. 'buflen' is the size of
- * the buffer pointed to by 'fn', in PRUnichars.
- *
- * Root directories come in three formats:
- * 1. / or \, meaning the root directory of the current drive.
- * 2. C:/ or C:\, where C is a drive letter.
- * 3. \\<server name>\<share point name>\ or
- * \\<server name>\<share point name>, meaning the root directory
- * of a UNC (Universal Naming Convention) name.
- */
-
-static PRBool
-IsRootDirectoryW(PRUnichar *fn, size_t buflen)
-{
- PRUnichar *p;
- PRBool slashAdded = PR_FALSE;
- PRBool rv = PR_FALSE;
-
- if (_PR_IS_W_SLASH(fn[0]) && fn[1] == L'\0') {
- return PR_TRUE;
- }
-
- if (iswalpha(fn[0]) && fn[1] == L':' && _PR_IS_W_SLASH(fn[2])
- && fn[3] == L'\0') {
- rv = getDriveTypeW(fn) > 1 ? PR_TRUE : PR_FALSE;
- return rv;
- }
-
- /* The UNC root directory */
-
- if (_PR_IS_W_SLASH(fn[0]) && _PR_IS_W_SLASH(fn[1])) {
- /* The 'server' part should have at least one character. */
- p = &fn[2];
- if (*p == L'\0' || _PR_IS_W_SLASH(*p)) {
- return PR_FALSE;
- }
-
- /* look for the next slash */
- do {
- p++;
- } while (*p != L'\0' && !_PR_IS_W_SLASH(*p));
- if (*p == L'\0') {
- return PR_FALSE;
- }
-
- /* The 'share' part should have at least one character. */
- p++;
- if (*p == L'\0' || _PR_IS_W_SLASH(*p)) {
- return PR_FALSE;
- }
-
- /* look for the final slash */
- do {
- p++;
- } while (*p != L'\0' && !_PR_IS_W_SLASH(*p));
- if (_PR_IS_W_SLASH(*p) && p[1] != L'\0') {
- return PR_FALSE;
- }
- if (*p == L'\0') {
- /*
- * GetDriveType() doesn't work correctly if the
- * path is of the form \\server\share, so we add
- * a final slash temporarily.
- */
- if ((p + 1) < (fn + buflen)) {
- *p++ = L'\\';
- *p = L'\0';
- slashAdded = PR_TRUE;
- } else {
- return PR_FALSE; /* name too long */
- }
- }
- rv = getDriveTypeW(fn) > 1 ? PR_TRUE : PR_FALSE;
- /* restore the 'fn' buffer */
- if (slashAdded) {
- *--p = L'\0';
- }
- }
- return rv;
-}
-
-PRInt32
-_PR_MD_GETFILEINFO64_UTF16(const PRUnichar *fn, PRFileInfo64 *info)
-{
- HANDLE hFindFile;
- WIN32_FIND_DATAW findFileData;
- PRUnichar pathbuf[MAX_PATH + 1];
-
- if (NULL == fn || L'\0' == *fn) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return -1;
- }
-
- /*
- * FindFirstFile() expands wildcard characters. So
- * we make sure the pathname contains no wildcard.
- */
- if (NULL != wcspbrk(fn, L"?*")) {
- PR_SetError(PR_FILE_NOT_FOUND_ERROR, 0);
- return -1;
- }
-
- hFindFile = findFirstFileW(fn, &findFileData);
- if (INVALID_HANDLE_VALUE == hFindFile) {
- DWORD len;
- PRUnichar *filePart;
-
- /*
- * FindFirstFile() does not work correctly on root directories.
- * It also doesn't work correctly on a pathname that ends in a
- * slash. So we first check to see if the pathname specifies a
- * root directory. If not, and if the pathname ends in a slash,
- * we remove the final slash and try again.
- */
-
- /*
- * If the pathname does not contain ., \, and /, it cannot be
- * a root directory or a pathname that ends in a slash.
- */
- if (NULL == wcspbrk(fn, L".\\/")) {
- _PR_MD_MAP_OPENDIR_ERROR(GetLastError());
- return -1;
- }
- len = getFullPathNameW(fn, sizeof(pathbuf)/sizeof(pathbuf[0]), pathbuf,
- &filePart);
- if (0 == len) {
- _PR_MD_MAP_OPENDIR_ERROR(GetLastError());
- return -1;
- }
- if (len > sizeof(pathbuf)/sizeof(pathbuf[0])) {
- PR_SetError(PR_NAME_TOO_LONG_ERROR, 0);
- return -1;
- }
- if (IsRootDirectoryW(pathbuf, sizeof(pathbuf)/sizeof(pathbuf[0]))) {
- info->type = PR_FILE_DIRECTORY;
- info->size = 0;
- /*
- * These timestamps don't make sense for root directories.
- */
- info->modifyTime = 0;
- info->creationTime = 0;
- return 0;
- }
- if (!_PR_IS_W_SLASH(pathbuf[len - 1])) {
- _PR_MD_MAP_OPENDIR_ERROR(GetLastError());
- return -1;
- } else {
- pathbuf[len - 1] = L'\0';
- hFindFile = findFirstFileW(pathbuf, &findFileData);
- if (INVALID_HANDLE_VALUE == hFindFile) {
- _PR_MD_MAP_OPENDIR_ERROR(GetLastError());
- return -1;
- }
- }
- }
-
- FindClose(hFindFile);
-
- if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
- info->type = PR_FILE_DIRECTORY;
- } else {
- info->type = PR_FILE_FILE;
- }
-
- info->size = findFileData.nFileSizeHigh;
- info->size = (info->size << 32) + findFileData.nFileSizeLow;
-
- _PR_FileTimeToPRTime(&findFileData.ftLastWriteTime, &info->modifyTime);
-
- if (0 == findFileData.ftCreationTime.dwLowDateTime &&
- 0 == findFileData.ftCreationTime.dwHighDateTime) {
- info->creationTime = info->modifyTime;
- } else {
- _PR_FileTimeToPRTime(&findFileData.ftCreationTime,
- &info->creationTime);
- }
-
- return 0;
-}
-/* ================ end of UTF16 Interfaces ================================ */
-#endif /* MOZ_UNICODE */
diff --git a/nspr/pr/src/md/windows/w95sock.c b/nspr/pr/src/md/windows/w95sock.c
deleted file mode 100644
index 1c3ddd9..0000000
--- a/nspr/pr/src/md/windows/w95sock.c
+++ /dev/null
@@ -1,669 +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/. */
-
-/* Win95 Sockets module
- *
- */
-
-#include "primpl.h"
-
-#define READ_FD 1
-#define WRITE_FD 2
-#define CONNECT_FD 3
-
-static PRInt32 socket_io_wait(
- PROsfd osfd,
- PRInt32 fd_type,
- PRIntervalTime timeout);
-
-
-/* --- SOCKET IO --------------------------------------------------------- */
-
-static PRBool socketFixInet6RcvBuf = PR_FALSE;
-
-void _PR_MD_InitSockets(void)
-{
- OSVERSIONINFO osvi;
-
- memset(&osvi, 0, sizeof(osvi));
- osvi.dwOSVersionInfoSize = sizeof(osvi);
- GetVersionEx(&osvi);
-
- if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
- {
- /* if Windows XP (32-bit) */
- socketFixInet6RcvBuf = PR_TRUE;
- }
-}
-
-void _PR_MD_CleanupSockets(void)
-{
- socketFixInet6RcvBuf = PR_FALSE;
-}
-
-PROsfd
-_PR_MD_SOCKET(int af, int type, int flags)
-{
- SOCKET sock;
- u_long one = 1;
-
- sock = socket(af, type, flags);
-
- if (sock == INVALID_SOCKET )
- {
- _PR_MD_MAP_SOCKET_ERROR(WSAGetLastError());
- return (PROsfd)sock;
- }
-
- /*
- ** Make the socket Non-Blocking
- */
- if (ioctlsocket( sock, FIONBIO, &one) != 0)
- {
- PR_SetError(PR_UNKNOWN_ERROR, WSAGetLastError());
- closesocket(sock);
- return -1;
- }
-
- if (af == AF_INET6 && socketFixInet6RcvBuf)
- {
- int bufsize;
- int len = sizeof(bufsize);
- int rv;
-
- /* Windows XP 32-bit returns an error on getpeername() for AF_INET6
- * sockets if the receive buffer size is greater than 65535 before
- * the connection is initiated. The default receive buffer size may
- * be 128000 so fix it here to always be <= 65535. See bug 513659
- * and IBM DB2 support technote "Receive/Send IPv6 Socket Size
- * Problem in Windows XP SP2 & SP3".
- */
- rv = getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)&bufsize, &len);
- if (rv == 0 && bufsize > 65535)
- {
- bufsize = 65535;
- setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)&bufsize, len);
- }
- }
-
- return (PROsfd)sock;
-}
-
-/*
-** _MD_CloseSocket() -- Close a socket
-**
-*/
-PRInt32
-_MD_CloseSocket(PROsfd osfd)
-{
- PRInt32 rv;
-
- rv = closesocket((SOCKET) osfd );
- if (rv < 0)
- _PR_MD_MAP_CLOSE_ERROR(WSAGetLastError());
-
- return rv;
-}
-
-PRInt32
-_MD_SocketAvailable(PRFileDesc *fd)
-{
- PRInt32 result;
-
- if (ioctlsocket(fd->secret->md.osfd, FIONREAD, &result) < 0) {
- PR_SetError(PR_BAD_DESCRIPTOR_ERROR, WSAGetLastError());
- return -1;
- }
- return result;
-}
-
-PROsfd _MD_Accept(
- PRFileDesc *fd,
- PRNetAddr *raddr,
- PRUint32 *rlen,
- PRIntervalTime timeout )
-{
- PROsfd osfd = fd->secret->md.osfd;
- SOCKET sock;
- PRInt32 rv, err;
-
- while ((sock = accept(osfd, (struct sockaddr *) raddr, rlen)) == -1)
- {
- err = WSAGetLastError();
- if ((err == WSAEWOULDBLOCK) && (!fd->secret->nonblocking))
- {
- if ((rv = socket_io_wait(osfd, READ_FD, timeout)) < 0)
- {
- break;
- }
- }
- else
- {
- _PR_MD_MAP_ACCEPT_ERROR(err);
- break;
- }
- }
- return(sock);
-} /* end _MD_accept() */
-
-PRInt32
-_PR_MD_CONNECT(PRFileDesc *fd, const PRNetAddr *addr, PRUint32 addrlen,
- PRIntervalTime timeout)
-{
- PROsfd osfd = fd->secret->md.osfd;
- PRInt32 rv;
- int err;
-
- if ((rv = connect(osfd, (struct sockaddr *) addr, addrlen)) == -1)
- {
- err = WSAGetLastError();
- if ((!fd->secret->nonblocking) && (err == WSAEWOULDBLOCK))
- {
- rv = socket_io_wait(osfd, CONNECT_FD, timeout);
- if ( rv < 0 )
- {
- return(-1);
- }
- else
- {
- PR_ASSERT(rv > 0);
- /* it's connected */
- return(0);
- }
- }
- _PR_MD_MAP_CONNECT_ERROR(err);
- }
- return rv;
-}
-
-PRInt32
-_PR_MD_BIND(PRFileDesc *fd, const PRNetAddr *addr, PRUint32 addrlen)
-{
- PRInt32 rv;
-
- rv = bind(fd->secret->md.osfd, (const struct sockaddr *)&(addr->inet), addrlen);
-
- if (rv == SOCKET_ERROR) {
- _PR_MD_MAP_BIND_ERROR(WSAGetLastError());
- return -1;
- }
-
- return 0;
-}
-
-PRInt32
-_PR_MD_LISTEN(PRFileDesc *fd, PRIntn backlog)
-{
- PRInt32 rv;
-
- rv = listen(fd->secret->md.osfd, backlog);
-
- if (rv == SOCKET_ERROR) {
- _PR_MD_MAP_DEFAULT_ERROR(WSAGetLastError());
- return -1;
- }
-
- return 0;
-}
-
-PRInt32
-_PR_MD_RECV(PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags,
- PRIntervalTime timeout)
-{
- PROsfd osfd = fd->secret->md.osfd;
- PRInt32 rv, err;
- int osflags;
-
- if (0 == flags) {
- osflags = 0;
- } else {
- PR_ASSERT(PR_MSG_PEEK == flags);
- osflags = MSG_PEEK;
- }
- while ((rv = recv( osfd, buf, amount, osflags)) == -1)
- {
- if (((err = WSAGetLastError()) == WSAEWOULDBLOCK)
- && (!fd->secret->nonblocking))
- {
- rv = socket_io_wait(osfd, READ_FD, timeout);
- if ( rv < 0 )
- {
- return -1;
- }
- }
- else
- {
- _PR_MD_MAP_RECV_ERROR(err);
- break;
- }
- } /* end while() */
- return(rv);
-}
-
-PRInt32
-_PR_MD_SEND(PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
- PRIntervalTime timeout)
-{
- PROsfd osfd = fd->secret->md.osfd;
- PRInt32 rv, err;
- PRInt32 bytesSent = 0;
-
- while(bytesSent < amount )
- {
- while ((rv = send( osfd, buf, amount, 0 )) == -1)
- {
- if (((err = WSAGetLastError()) == WSAEWOULDBLOCK)
- && (!fd->secret->nonblocking))
- {
- rv = socket_io_wait(osfd, WRITE_FD, timeout);
- if ( rv < 0 )
- {
- return -1;
- }
- }
- else
- {
- _PR_MD_MAP_SEND_ERROR(err);
- return -1;
- }
- }
- bytesSent += rv;
- if (fd->secret->nonblocking)
- {
- break;
- }
- if (bytesSent < amount)
- {
- rv = socket_io_wait(osfd, WRITE_FD, timeout);
- if ( rv < 0 )
- {
- return -1;
- }
- }
- }
- return bytesSent;
-}
-
-PRInt32
-_PR_MD_SENDTO(PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
- const PRNetAddr *addr, PRUint32 addrlen, PRIntervalTime timeout)
-{
- PROsfd osfd = fd->secret->md.osfd;
- PRInt32 rv, err;
- PRInt32 bytesSent = 0;
-
- while(bytesSent < amount)
- {
- while ((rv = sendto( osfd, buf, amount, 0, (struct sockaddr *) addr,
- addrlen)) == -1)
- {
- if (((err = WSAGetLastError()) == WSAEWOULDBLOCK)
- && (!fd->secret->nonblocking))
- {
- rv = socket_io_wait(osfd, WRITE_FD, timeout);
- if ( rv < 0 )
- {
- return -1;
- }
- }
- else
- {
- _PR_MD_MAP_SENDTO_ERROR(err);
- return -1;
- }
- }
- bytesSent += rv;
- if (fd->secret->nonblocking)
- {
- break;
- }
- if (bytesSent < amount)
- {
- rv = socket_io_wait(osfd, WRITE_FD, timeout);
- if (rv < 0)
- {
- return -1;
- }
- }
- }
- return bytesSent;
-}
-
-PRInt32
-_PR_MD_RECVFROM(PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags,
- PRNetAddr *addr, PRUint32 *addrlen, PRIntervalTime timeout)
-{
- PROsfd osfd = fd->secret->md.osfd;
- PRInt32 rv, err;
-
- while ((rv = recvfrom( osfd, buf, amount, 0, (struct sockaddr *) addr,
- addrlen)) == -1)
- {
- if (((err = WSAGetLastError()) == WSAEWOULDBLOCK)
- && (!fd->secret->nonblocking))
- {
- rv = socket_io_wait(osfd, READ_FD, timeout);
- if ( rv < 0)
- {
- return -1;
- }
- }
- else
- {
- _PR_MD_MAP_RECVFROM_ERROR(err);
- break;
- }
- }
- return(rv);
-}
-
-PRInt32
-_PR_MD_WRITEV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 iov_size, PRIntervalTime timeout)
-{
- int index;
- int sent = 0;
- int rv;
-
- for (index=0; index < iov_size; index++)
- {
- rv = _PR_MD_SEND(fd, iov[index].iov_base, iov[index].iov_len, 0, timeout);
- if (rv > 0)
- sent += rv;
- if ( rv != iov[index].iov_len )
- {
- if (rv < 0)
- {
- if (fd->secret->nonblocking
- && (PR_GetError() == PR_WOULD_BLOCK_ERROR)
- && (sent > 0))
- {
- return sent;
- }
- else
- {
- return -1;
- }
- }
- /* Only a nonblocking socket can have partial sends */
- PR_ASSERT(fd->secret->nonblocking);
- return sent;
- }
- }
- return sent;
-}
-
-PRInt32
-_PR_MD_SHUTDOWN(PRFileDesc *fd, PRIntn how)
-{
-PRInt32 rv;
-
- rv = shutdown(fd->secret->md.osfd, how);
- if (rv < 0)
- _PR_MD_MAP_SHUTDOWN_ERROR(WSAGetLastError());
- return rv;
-}
-
-PRStatus
-_PR_MD_GETSOCKNAME(PRFileDesc *fd, PRNetAddr *addr, PRUint32 *len)
-{
- PRInt32 rv;
-
- rv = getsockname((SOCKET)fd->secret->md.osfd, (struct sockaddr *)addr, len);
- if (rv==0) {
- return PR_SUCCESS;
- } else {
- _PR_MD_MAP_GETSOCKNAME_ERROR(WSAGetLastError());
- return PR_FAILURE;
- }
-}
-
-PRStatus
-_PR_MD_GETPEERNAME(PRFileDesc *fd, PRNetAddr *addr, PRUint32 *len)
-{
- PRInt32 rv;
-
- rv = getpeername((SOCKET)fd->secret->md.osfd, (struct sockaddr *)addr, len);
- if (rv==0) {
- return PR_SUCCESS;
- } else {
- _PR_MD_MAP_GETPEERNAME_ERROR(WSAGetLastError());
- return PR_FAILURE;
- }
-}
-
-PRStatus
-_PR_MD_GETSOCKOPT(PRFileDesc *fd, PRInt32 level, PRInt32 optname, char* optval, PRInt32* optlen)
-{
- PRInt32 rv;
-
- rv = getsockopt((SOCKET)fd->secret->md.osfd, level, optname, optval, optlen);
- if (rv==0) {
- return PR_SUCCESS;
- } else {
- _PR_MD_MAP_GETSOCKOPT_ERROR(WSAGetLastError());
- return PR_FAILURE;
- }
-}
-
-PRStatus
-_PR_MD_SETSOCKOPT(PRFileDesc *fd, PRInt32 level, PRInt32 optname, const char* optval, PRInt32 optlen)
-{
- PRInt32 rv;
-
- rv = setsockopt((SOCKET)fd->secret->md.osfd, level, optname, optval, optlen);
- if (rv==0) {
- return PR_SUCCESS;
- } else {
- _PR_MD_MAP_SETSOCKOPT_ERROR(WSAGetLastError());
- return PR_FAILURE;
- }
-}
-
-void
-_MD_MakeNonblock(PRFileDesc *f)
-{
- return; /* do nothing */
-}
-
-
-
-/*
- * socket_io_wait --
- *
- * Wait for socket i/o, periodically checking for interrupt.
- *
- * This function returns 1 on success. On failure, it returns
- * -1 and sets the error codes. It never returns 0.
- */
-#define _PR_INTERRUPT_CHECK_INTERVAL_SECS 5
-
-static PRInt32 socket_io_wait(
- PROsfd osfd,
- PRInt32 fd_type,
- PRIntervalTime timeout)
-{
- PRInt32 rv = -1;
- struct timeval tv;
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRIntervalTime elapsed, remaining;
- PRBool wait_for_remaining;
- fd_set rd_wr, ex;
- int err, len;
-
- switch (timeout) {
- case PR_INTERVAL_NO_WAIT:
- PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
- break;
- case PR_INTERVAL_NO_TIMEOUT:
- /*
- * This is a special case of the 'default' case below.
- * Please see the comments there.
- */
- tv.tv_sec = _PR_INTERRUPT_CHECK_INTERVAL_SECS;
- tv.tv_usec = 0;
- FD_ZERO(&rd_wr);
- FD_ZERO(&ex);
- do {
- FD_SET(osfd, &rd_wr);
- FD_SET(osfd, &ex);
- switch( fd_type )
- {
- case READ_FD:
- rv = _MD_SELECT(0, &rd_wr, NULL, NULL, &tv);
- break;
- case WRITE_FD:
- rv = _MD_SELECT(0, NULL, &rd_wr, NULL, &tv);
- break;
- case CONNECT_FD:
- rv = _MD_SELECT(0, NULL, &rd_wr, &ex, &tv);
- break;
- default:
- PR_ASSERT(0);
- break;
- } /* end switch() */
- if (rv == -1 )
- {
- _PR_MD_MAP_SELECT_ERROR(WSAGetLastError());
- break;
- }
- if ( rv > 0 && fd_type == CONNECT_FD )
- {
- /*
- * Call Sleep(0) to work around a Winsock timing bug.
- */
- Sleep(0);
- if (FD_ISSET((SOCKET)osfd, &ex))
- {
- len = sizeof(err);
- if (getsockopt(osfd, SOL_SOCKET, SO_ERROR,
- (char *) &err, &len) == SOCKET_ERROR)
- {
- _PR_MD_MAP_GETSOCKOPT_ERROR(WSAGetLastError());
- return -1;
- }
- if (err != 0)
- _PR_MD_MAP_CONNECT_ERROR(err);
- else
- PR_SetError(PR_UNKNOWN_ERROR, 0);
- return -1;
- }
- if (FD_ISSET((SOCKET)osfd, &rd_wr))
- {
- /* it's connected */
- return 1;
- }
- PR_ASSERT(0);
- }
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- rv = -1;
- break;
- }
- } while (rv == 0);
- break;
- default:
- remaining = timeout;
- FD_ZERO(&rd_wr);
- FD_ZERO(&ex);
- do {
- /*
- * We block in _MD_SELECT for at most
- * _PR_INTERRUPT_CHECK_INTERVAL_SECS seconds,
- * so that there is an upper limit on the delay
- * before the interrupt bit is checked.
- */
- wait_for_remaining = PR_TRUE;
- tv.tv_sec = PR_IntervalToSeconds(remaining);
- if (tv.tv_sec > _PR_INTERRUPT_CHECK_INTERVAL_SECS) {
- wait_for_remaining = PR_FALSE;
- tv.tv_sec = _PR_INTERRUPT_CHECK_INTERVAL_SECS;
- tv.tv_usec = 0;
- } else {
- tv.tv_usec = PR_IntervalToMicroseconds(
- remaining -
- PR_SecondsToInterval(tv.tv_sec));
- }
- FD_SET(osfd, &rd_wr);
- FD_SET(osfd, &ex);
- switch( fd_type )
- {
- case READ_FD:
- rv = _MD_SELECT(0, &rd_wr, NULL, NULL, &tv);
- break;
- case WRITE_FD:
- rv = _MD_SELECT(0, NULL, &rd_wr, NULL, &tv);
- break;
- case CONNECT_FD:
- rv = _MD_SELECT(0, NULL, &rd_wr, &ex, &tv);
- break;
- default:
- PR_ASSERT(0);
- break;
- } /* end switch() */
- if (rv == -1)
- {
- _PR_MD_MAP_SELECT_ERROR(WSAGetLastError());
- break;
- }
- if ( rv > 0 && fd_type == CONNECT_FD )
- {
- /*
- * Call Sleep(0) to work around a Winsock timing bug.
- */
- Sleep(0);
- if (FD_ISSET((SOCKET)osfd, &ex))
- {
- len = sizeof(err);
- if (getsockopt(osfd, SOL_SOCKET, SO_ERROR,
- (char *) &err, &len) == SOCKET_ERROR)
- {
- _PR_MD_MAP_GETSOCKOPT_ERROR(WSAGetLastError());
- return -1;
- }
- if (err != 0)
- _PR_MD_MAP_CONNECT_ERROR(err);
- else
- PR_SetError(PR_UNKNOWN_ERROR, 0);
- return -1;
- }
- if (FD_ISSET((SOCKET)osfd, &rd_wr))
- {
- /* it's connected */
- return 1;
- }
- PR_ASSERT(0);
- }
- if (_PR_PENDING_INTERRUPT(me)) {
- me->flags &= ~_PR_INTERRUPT;
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- rv = -1;
- break;
- }
- /*
- * We loop again if _MD_SELECT timed out and the
- * timeout deadline has not passed yet.
- */
- if (rv == 0 )
- {
- if (wait_for_remaining) {
- elapsed = remaining;
- } else {
- elapsed = PR_SecondsToInterval(tv.tv_sec)
- + PR_MicrosecondsToInterval(tv.tv_usec);
- }
- if (elapsed >= remaining) {
- PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
- rv = -1;
- break;
- } else {
- remaining = remaining - elapsed;
- }
- }
- } while (rv == 0 );
- break;
- }
- return(rv);
-} /* end socket_io_wait() */
diff --git a/nspr/pr/src/md/windows/w95thred.c b/nspr/pr/src/md/windows/w95thred.c
deleted file mode 100644
index 2741d94..0000000
--- a/nspr/pr/src/md/windows/w95thred.c
+++ /dev/null
@@ -1,442 +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/. */
-
-#include "primpl.h"
-#include <process.h> /* for _beginthreadex() */
-
-#if defined(_MSC_VER) && _MSC_VER <= 1200
-/*
- * VC++ 6.0 doesn't have DWORD_PTR.
- */
-
-typedef DWORD DWORD_PTR;
-#endif /* _MSC_VER <= 1200 */
-
-/* --- globals ------------------------------------------------ */
-#ifdef _PR_USE_STATIC_TLS
-__declspec(thread) struct PRThread *_pr_thread_last_run;
-__declspec(thread) struct PRThread *_pr_currentThread;
-__declspec(thread) struct _PRCPU *_pr_currentCPU;
-#else
-DWORD _pr_currentThreadIndex;
-DWORD _pr_lastThreadIndex;
-DWORD _pr_currentCPUIndex;
-#endif
-int _pr_intsOff = 0;
-_PRInterruptTable _pr_interruptTable[] = { { 0 } };
-
-void
-_PR_MD_EARLY_INIT()
-{
-#ifndef _PR_USE_STATIC_TLS
- _pr_currentThreadIndex = TlsAlloc();
- _pr_lastThreadIndex = TlsAlloc();
- _pr_currentCPUIndex = TlsAlloc();
-#endif
-}
-
-void _PR_MD_CLEANUP_BEFORE_EXIT(void)
-{
- _PR_NT_FreeSids();
-
- _PR_MD_CleanupSockets();
-
- WSACleanup();
-
-#ifndef _PR_USE_STATIC_TLS
- TlsFree(_pr_currentThreadIndex);
- TlsFree(_pr_lastThreadIndex);
- TlsFree(_pr_currentCPUIndex);
-#endif
-}
-
-PRStatus
-_PR_MD_INIT_THREAD(PRThread *thread)
-{
- if (thread->flags & (_PR_PRIMORDIAL | _PR_ATTACHED)) {
- /*
- ** Warning:
- ** --------
- ** NSPR requires a real handle to every thread.
- ** GetCurrentThread() returns a pseudo-handle which
- ** is not suitable for some thread operations (e.g.,
- ** suspending). Therefore, get a real handle from
- ** the pseudo handle via DuplicateHandle(...)
- */
- BOOL ok = DuplicateHandle(
- GetCurrentProcess(), /* Process of source handle */
- GetCurrentThread(), /* Pseudo Handle to dup */
- GetCurrentProcess(), /* Process of handle */
- &(thread->md.handle), /* resulting handle */
- 0L, /* access flags */
- FALSE, /* Inheritable */
- DUPLICATE_SAME_ACCESS); /* Options */
- if (!ok) {
- return PR_FAILURE;
- }
- thread->id = GetCurrentThreadId();
- thread->md.id = thread->id;
- }
-
- /* Create the blocking IO semaphore */
- thread->md.blocked_sema = CreateSemaphore(NULL, 0, 1, NULL);
- if (thread->md.blocked_sema == NULL)
- return PR_FAILURE;
- else
- return PR_SUCCESS;
-}
-
-static unsigned __stdcall
-pr_root(void *arg)
-{
- PRThread *thread = (PRThread *)arg;
- thread->md.start(thread);
- return 0;
-}
-
-PRStatus
-_PR_MD_CREATE_THREAD(PRThread *thread,
- void (*start)(void *),
- PRThreadPriority priority,
- PRThreadScope scope,
- PRThreadState state,
- PRUint32 stackSize)
-{
-
- thread->md.start = start;
- thread->md.handle = (HANDLE) _beginthreadex(
- NULL,
- thread->stack->stackSize,
- pr_root,
- (void *)thread,
- CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION,
- &(thread->id));
- if(!thread->md.handle) {
- return PR_FAILURE;
- }
-
- thread->md.id = thread->id;
- /*
- * On windows, a thread is created with a thread priority of
- * THREAD_PRIORITY_NORMAL.
- */
- if (priority != PR_PRIORITY_NORMAL) {
- _PR_MD_SET_PRIORITY(&(thread->md), priority);
- }
-
- /* Activate the thread */
- if ( ResumeThread( thread->md.handle ) != -1)
- return PR_SUCCESS;
-
- return PR_FAILURE;
-}
-
-void
-_PR_MD_YIELD(void)
-{
- /* Can NT really yield at all? */
- Sleep(0);
-}
-
-void
-_PR_MD_SET_PRIORITY(_MDThread *thread, PRThreadPriority newPri)
-{
- int nativePri;
- BOOL rv;
-
- if (newPri < PR_PRIORITY_FIRST) {
- newPri = PR_PRIORITY_FIRST;
- } else if (newPri > PR_PRIORITY_LAST) {
- newPri = PR_PRIORITY_LAST;
- }
- switch (newPri) {
- case PR_PRIORITY_LOW:
- nativePri = THREAD_PRIORITY_BELOW_NORMAL;
- break;
- case PR_PRIORITY_NORMAL:
- nativePri = THREAD_PRIORITY_NORMAL;
- break;
- case PR_PRIORITY_HIGH:
- nativePri = THREAD_PRIORITY_ABOVE_NORMAL;
- break;
- case PR_PRIORITY_URGENT:
- nativePri = THREAD_PRIORITY_HIGHEST;
- }
- rv = SetThreadPriority(thread->handle, nativePri);
- PR_ASSERT(rv);
- if (!rv) {
- PR_LOG(_pr_thread_lm, PR_LOG_MIN,
- ("PR_SetThreadPriority: can't set thread priority\n"));
- }
- return;
-}
-
-const DWORD MS_VC_EXCEPTION = 0x406D1388;
-
-#pragma pack(push,8)
-typedef struct tagTHREADNAME_INFO
-{
- DWORD dwType; // Must be 0x1000.
- LPCSTR szName; // Pointer to name (in user addr space).
- DWORD dwThreadID; // Thread ID (-1=caller thread).
- DWORD dwFlags; // Reserved for future use, must be zero.
-} THREADNAME_INFO;
-#pragma pack(pop)
-
-void
-_PR_MD_SET_CURRENT_THREAD_NAME(const char *name)
-{
-#ifdef _MSC_VER
- THREADNAME_INFO info;
-
- if (!IsDebuggerPresent())
- return;
-
- info.dwType = 0x1000;
- info.szName = (char*) name;
- info.dwThreadID = -1;
- info.dwFlags = 0;
-
- __try {
- RaiseException(MS_VC_EXCEPTION,
- 0,
- sizeof(info) / sizeof(ULONG_PTR),
- (ULONG_PTR*)&info);
- } __except(EXCEPTION_CONTINUE_EXECUTION) {
- }
-#endif
-}
-
-void
-_PR_MD_CLEAN_THREAD(PRThread *thread)
-{
- BOOL rv;
-
- if (thread->md.blocked_sema) {
- rv = CloseHandle(thread->md.blocked_sema);
- PR_ASSERT(rv);
- thread->md.blocked_sema = 0;
- }
-
- if (thread->md.handle) {
- rv = CloseHandle(thread->md.handle);
- PR_ASSERT(rv);
- thread->md.handle = 0;
- }
-}
-
-void
-_PR_MD_EXIT_THREAD(PRThread *thread)
-{
- _PR_MD_CLEAN_THREAD(thread);
- _PR_MD_SET_CURRENT_THREAD(NULL);
-}
-
-
-void
-_PR_MD_EXIT(PRIntn status)
-{
- _exit(status);
-}
-
-PRInt32 _PR_MD_SETTHREADAFFINITYMASK(PRThread *thread, PRUint32 mask )
-{
-#ifdef WINCE
- SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
- return -1;
-#else
- DWORD_PTR rv;
-
- rv = SetThreadAffinityMask(thread->md.handle, mask);
-
- return rv?0:-1;
-#endif
-}
-
-PRInt32 _PR_MD_GETTHREADAFFINITYMASK(PRThread *thread, PRUint32 *mask)
-{
-#ifdef WINCE
- SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
- return -1;
-#else
- BOOL rv;
- DWORD_PTR process_mask;
- DWORD_PTR system_mask;
-
- rv = GetProcessAffinityMask(GetCurrentProcess(),
- &process_mask, &system_mask);
- if (rv)
- *mask = (PRUint32)process_mask;
-
- return rv?0:-1;
-#endif
-}
-
-void
-_PR_MD_SUSPEND_CPU(_PRCPU *cpu)
-{
- _PR_MD_SUSPEND_THREAD(cpu->thread);
-}
-
-void
-_PR_MD_RESUME_CPU(_PRCPU *cpu)
-{
- _PR_MD_RESUME_THREAD(cpu->thread);
-}
-
-void
-_PR_MD_SUSPEND_THREAD(PRThread *thread)
-{
- if (_PR_IS_NATIVE_THREAD(thread)) {
- DWORD previousSuspendCount;
- /* XXXMB - SuspendThread() is not a blocking call; how do we
- * know when the thread is *REALLY* suspended?
- */
- previousSuspendCount = SuspendThread(thread->md.handle);
- PR_ASSERT(previousSuspendCount == 0);
- }
-}
-
-void
-_PR_MD_RESUME_THREAD(PRThread *thread)
-{
- if (_PR_IS_NATIVE_THREAD(thread)) {
- DWORD previousSuspendCount;
- previousSuspendCount = ResumeThread(thread->md.handle);
- PR_ASSERT(previousSuspendCount == 1);
- }
-}
-
-PRThread*
-_MD_CURRENT_THREAD(void)
-{
-PRThread *thread;
-
- thread = _MD_GET_ATTACHED_THREAD();
-
- if (NULL == thread) {
- thread = _PRI_AttachThread(
- PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, NULL, 0);
- }
- PR_ASSERT(thread != NULL);
- return thread;
-}
-
-#ifdef NSPR_STATIC
-
-// The following code is from Chromium src/base/thread_local_storage_win.cc,
-// r11329.
-
-// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Thread Termination Callbacks.
-// Windows doesn't support a per-thread destructor with its
-// TLS primitives. So, we build it manually by inserting a
-// function to be called on each thread's exit.
-// This magic is from http://www.codeproject.com/threads/tls.asp
-// and it works for VC++ 7.0 and later.
-
-// Force a reference to _tls_used to make the linker create the TLS directory
-// if it's not already there. (e.g. if __declspec(thread) is not used).
-// Force a reference to p_thread_callback_nspr to prevent whole program
-// optimization from discarding the variable.
-#ifdef _WIN64
-
-#pragma comment(linker, "/INCLUDE:_tls_used")
-#pragma comment(linker, "/INCLUDE:p_thread_callback_nspr")
-
-#else // _WIN64
-
-#pragma comment(linker, "/INCLUDE:__tls_used")
-#pragma comment(linker, "/INCLUDE:_p_thread_callback_nspr")
-
-#endif // _WIN64
-
-// Static callback function to call with each thread termination.
-static void NTAPI PR_OnThreadExit(PVOID module, DWORD reason, PVOID reserved)
-{
-PRThread *me;
-
- switch (reason) {
- case DLL_PROCESS_ATTACH:
- break;
- case DLL_THREAD_ATTACH:
- break;
- case DLL_THREAD_DETACH:
- if (_pr_initialized) {
- me = _MD_GET_ATTACHED_THREAD();
- if ((me != NULL) && (me->flags & _PR_ATTACHED))
- _PRI_DetachThread();
- }
- break;
- case DLL_PROCESS_DETACH:
- break;
- }
-}
-
-// .CRT$XLA to .CRT$XLZ is an array of PIMAGE_TLS_CALLBACK pointers that are
-// called automatically by the OS loader code (not the CRT) when the module is
-// loaded and on thread creation. They are NOT called if the module has been
-// loaded by a LoadLibrary() call. It must have implicitly been loaded at
-// process startup.
-// By implicitly loaded, I mean that it is directly referenced by the main EXE
-// or by one of its dependent DLLs. Delay-loaded DLL doesn't count as being
-// implicitly loaded.
-//
-// See VC\crt\src\tlssup.c for reference.
-
-// The linker must not discard p_thread_callback_nspr. (We force a reference
-// to this variable with a linker /INCLUDE:symbol pragma to ensure that.) If
-// this variable is discarded, the PR_OnThreadExit function will never be
-// called.
-#ifdef _WIN64
-
-// .CRT section is merged with .rdata on x64 so it must be constant data.
-#pragma const_seg(".CRT$XLB")
-// When defining a const variable, it must have external linkage to be sure the
-// linker doesn't discard it.
-extern const PIMAGE_TLS_CALLBACK p_thread_callback_nspr;
-const PIMAGE_TLS_CALLBACK p_thread_callback_nspr = PR_OnThreadExit;
-
-// Reset the default section.
-#pragma const_seg()
-
-#else // _WIN64
-
-#pragma data_seg(".CRT$XLB")
-PIMAGE_TLS_CALLBACK p_thread_callback_nspr = PR_OnThreadExit;
-
-// Reset the default section.
-#pragma data_seg()
-
-#endif // _WIN64
-
-#endif // NSPR_STATIC
diff --git a/nspr/pr/src/md/windows/win32_errors.c b/nspr/pr/src/md/windows/win32_errors.c
deleted file mode 100644
index d26820a..0000000
--- a/nspr/pr/src/md/windows/win32_errors.c
+++ /dev/null
@@ -1,533 +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/. */
-
-#include "prerror.h"
-#include "prlog.h"
-#include <errno.h>
-#include <windows.h>
-
-/*
- * On Win32, we map three kinds of error codes:
- * - GetLastError(): for Win32 functions
- * - WSAGetLastError(): for Winsock functions
- * - errno: for standard C library functions
- *
- * GetLastError() and WSAGetLastError() return error codes in
- * non-overlapping ranges, so their error codes (ERROR_* and
- * WSAE*) can be mapped by the same function. On the other hand,
- * errno and GetLastError() have overlapping ranges, so we need
- * to use a separate function to map errno.
- *
- * We do not check for WSAEINPROGRESS and WSAEINTR because we do not
- * use blocking Winsock 1.1 calls.
- *
- * Except for the 'socket' call, we do not check for WSAEINITIALISED.
- * It is assumed that if Winsock is not initialized, that fact will
- * be detected at the time we create new sockets.
- */
-
-static void _MD_win32_map_default_errno(PRInt32 err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case EACCES:
- prError = PR_NO_ACCESS_RIGHTS_ERROR;
- break;
- case ENOENT:
- prError = PR_FILE_NOT_FOUND_ERROR;
- break;
- default:
- prError = PR_UNKNOWN_ERROR;
- break;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_win32_map_default_error(PRInt32 err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case ERROR_ACCESS_DENIED:
- prError = PR_NO_ACCESS_RIGHTS_ERROR;
- break;
- case ERROR_ALREADY_EXISTS:
- prError = PR_FILE_EXISTS_ERROR;
- break;
- case ERROR_CALL_NOT_IMPLEMENTED:
- prError = PR_NOT_IMPLEMENTED_ERROR;
- break;
- case ERROR_DISK_CORRUPT:
- prError = PR_IO_ERROR;
- break;
- case ERROR_DISK_FULL:
- prError = PR_NO_DEVICE_SPACE_ERROR;
- break;
- case ERROR_DISK_OPERATION_FAILED:
- prError = PR_IO_ERROR;
- break;
- case ERROR_DRIVE_LOCKED:
- prError = PR_FILE_IS_LOCKED_ERROR;
- break;
- case ERROR_FILENAME_EXCED_RANGE:
- prError = PR_NAME_TOO_LONG_ERROR;
- break;
- case ERROR_FILE_CORRUPT:
- prError = PR_IO_ERROR;
- break;
- case ERROR_FILE_EXISTS:
- prError = PR_FILE_EXISTS_ERROR;
- break;
- case ERROR_FILE_INVALID:
- prError = PR_BAD_DESCRIPTOR_ERROR;
- break;
- case ERROR_FILE_NOT_FOUND:
- prError = PR_FILE_NOT_FOUND_ERROR;
- break;
- case ERROR_HANDLE_DISK_FULL:
- prError = PR_NO_DEVICE_SPACE_ERROR;
- break;
- case ERROR_INVALID_ADDRESS:
- prError = PR_ACCESS_FAULT_ERROR;
- break;
- case ERROR_INVALID_HANDLE:
- prError = PR_BAD_DESCRIPTOR_ERROR;
- break;
- case ERROR_INVALID_NAME:
- prError = PR_INVALID_ARGUMENT_ERROR;
- break;
- case ERROR_INVALID_PARAMETER:
- prError = PR_INVALID_ARGUMENT_ERROR;
- break;
- case ERROR_INVALID_USER_BUFFER:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
- case ERROR_LOCKED:
- prError = PR_FILE_IS_LOCKED_ERROR;
- break;
- case ERROR_NETNAME_DELETED:
- prError = PR_CONNECT_RESET_ERROR;
- break;
- case ERROR_NOACCESS:
- prError = PR_ACCESS_FAULT_ERROR;
- break;
- case ERROR_NOT_ENOUGH_MEMORY:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
- case ERROR_NOT_ENOUGH_QUOTA:
- prError = PR_OUT_OF_MEMORY_ERROR;
- break;
- case ERROR_NOT_READY:
- prError = PR_IO_ERROR;
- break;
- case ERROR_NO_MORE_FILES:
- prError = PR_NO_MORE_FILES_ERROR;
- break;
- case ERROR_OPEN_FAILED:
- prError = PR_IO_ERROR;
- break;
- case ERROR_OPEN_FILES:
- prError = PR_IO_ERROR;
- break;
- case ERROR_OPERATION_ABORTED:
- prError = PR_OPERATION_ABORTED_ERROR;
- break;
- case ERROR_OUTOFMEMORY:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
- case ERROR_PATH_BUSY:
- prError = PR_IO_ERROR;
- break;
- case ERROR_PATH_NOT_FOUND:
- prError = PR_FILE_NOT_FOUND_ERROR;
- break;
- case ERROR_SEEK_ON_DEVICE:
- prError = PR_IO_ERROR;
- break;
- case ERROR_SHARING_VIOLATION:
- prError = PR_FILE_IS_BUSY_ERROR;
- break;
- case ERROR_STACK_OVERFLOW:
- prError = PR_ACCESS_FAULT_ERROR;
- break;
- case ERROR_TOO_MANY_OPEN_FILES:
- prError = PR_SYS_DESC_TABLE_FULL_ERROR;
- break;
- case ERROR_WRITE_PROTECT:
- prError = PR_NO_ACCESS_RIGHTS_ERROR;
- break;
- case WSAEACCES:
- prError = PR_NO_ACCESS_RIGHTS_ERROR;
- break;
- case WSAEADDRINUSE:
- prError = PR_ADDRESS_IN_USE_ERROR;
- break;
- case WSAEADDRNOTAVAIL:
- prError = PR_ADDRESS_NOT_AVAILABLE_ERROR;
- break;
- case WSAEAFNOSUPPORT:
- prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
- break;
- case WSAEALREADY:
- prError = PR_ALREADY_INITIATED_ERROR;
- break;
- case WSAEBADF:
- prError = PR_BAD_DESCRIPTOR_ERROR;
- break;
- case WSAECONNABORTED:
- prError = PR_CONNECT_ABORTED_ERROR;
- break;
- case WSAECONNREFUSED:
- prError = PR_CONNECT_REFUSED_ERROR;
- break;
- case WSAECONNRESET:
- prError = PR_CONNECT_RESET_ERROR;
- break;
- case WSAEDESTADDRREQ:
- prError = PR_INVALID_ARGUMENT_ERROR;
- break;
- case WSAEFAULT:
- prError = PR_ACCESS_FAULT_ERROR;
- break;
- case WSAEHOSTUNREACH:
- prError = PR_HOST_UNREACHABLE_ERROR;
- break;
- case WSAEINVAL:
- prError = PR_INVALID_ARGUMENT_ERROR;
- break;
- case WSAEISCONN:
- prError = PR_IS_CONNECTED_ERROR;
- break;
- case WSAEMFILE:
- prError = PR_PROC_DESC_TABLE_FULL_ERROR;
- break;
- case WSAEMSGSIZE:
- prError = PR_BUFFER_OVERFLOW_ERROR;
- break;
- case WSAENETDOWN:
- prError = PR_NETWORK_DOWN_ERROR;
- break;
- case WSAENETRESET:
- prError = PR_CONNECT_ABORTED_ERROR;
- break;
- case WSAENETUNREACH:
- prError = PR_NETWORK_UNREACHABLE_ERROR;
- break;
- case WSAENOBUFS:
- prError = PR_INSUFFICIENT_RESOURCES_ERROR;
- break;
- case WSAENOPROTOOPT:
- prError = PR_INVALID_ARGUMENT_ERROR;
- break;
- case WSAENOTCONN:
- prError = PR_NOT_CONNECTED_ERROR;
- break;
- case WSAENOTSOCK:
- prError = PR_NOT_SOCKET_ERROR;
- break;
- case WSAEOPNOTSUPP:
- prError = PR_OPERATION_NOT_SUPPORTED_ERROR;
- break;
- case WSAEPROTONOSUPPORT:
- prError = PR_PROTOCOL_NOT_SUPPORTED_ERROR;
- break;
- case WSAEPROTOTYPE:
- prError = PR_INVALID_ARGUMENT_ERROR;
- break;
- case WSAESHUTDOWN:
- prError = PR_SOCKET_SHUTDOWN_ERROR;
- break;
- case WSAESOCKTNOSUPPORT:
- prError = PR_INVALID_ARGUMENT_ERROR;
- break;
- case WSAETIMEDOUT:
- prError = PR_CONNECT_ABORTED_ERROR;
- break;
- case WSAEWOULDBLOCK:
- prError = PR_WOULD_BLOCK_ERROR;
- break;
- default:
- prError = PR_UNKNOWN_ERROR;
- break;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_win32_map_opendir_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_closedir_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_unix_readdir_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_delete_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-/* The error code for stat() is in errno. */
-void _MD_win32_map_stat_error(PRInt32 err)
-{
- _MD_win32_map_default_errno(err);
-}
-
-void _MD_win32_map_fstat_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_rename_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-/* The error code for access() is in errno. */
-void _MD_win32_map_access_error(PRInt32 err)
-{
- _MD_win32_map_default_errno(err);
-}
-
-void _MD_win32_map_mkdir_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_rmdir_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_read_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_transmitfile_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_write_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_lseek_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_fsync_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-/*
- * For both CloseHandle() and closesocket().
- */
-void _MD_win32_map_close_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_socket_error(PRInt32 err)
-{
- PR_ASSERT(err != WSANOTINITIALISED);
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_recv_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_recvfrom_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_send_error(PRInt32 err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case WSAEMSGSIZE:
- prError = PR_INVALID_ARGUMENT_ERROR;
- break;
- default:
- _MD_win32_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_win32_map_sendto_error(PRInt32 err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case WSAEMSGSIZE:
- prError = PR_INVALID_ARGUMENT_ERROR;
- break;
- default:
- _MD_win32_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_win32_map_accept_error(PRInt32 err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case WSAEOPNOTSUPP:
- prError = PR_NOT_TCP_SOCKET_ERROR;
- break;
- case WSAEINVAL:
- prError = PR_INVALID_STATE_ERROR;
- break;
- default:
- _MD_win32_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_win32_map_acceptex_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_connect_error(PRInt32 err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case WSAEWOULDBLOCK:
- prError = PR_IN_PROGRESS_ERROR;
- break;
- case WSAEINVAL:
- prError = PR_ALREADY_INITIATED_ERROR;
- break;
- case WSAETIMEDOUT:
- prError = PR_IO_TIMEOUT_ERROR;
- break;
- default:
- _MD_win32_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_win32_map_bind_error(PRInt32 err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case WSAEINVAL:
- prError = PR_SOCKET_ADDRESS_IS_BOUND_ERROR;
- break;
- default:
- _MD_win32_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_win32_map_listen_error(PRInt32 err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case WSAEOPNOTSUPP:
- prError = PR_NOT_TCP_SOCKET_ERROR;
- break;
- case WSAEINVAL:
- prError = PR_INVALID_STATE_ERROR;
- break;
- default:
- _MD_win32_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_win32_map_shutdown_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_getsockname_error(PRInt32 err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case WSAEINVAL:
- prError = PR_INVALID_STATE_ERROR;
- break;
- default:
- _MD_win32_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_win32_map_getpeername_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_getsockopt_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_setsockopt_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_open_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-void _MD_win32_map_gethostname_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
-
-/* Win32 select() only works on sockets. So in this
-** context, WSAENOTSOCK is equivalent to EBADF on Unix.
-*/
-void _MD_win32_map_select_error(PRInt32 err)
-{
- PRErrorCode prError;
-
- switch (err) {
- case WSAENOTSOCK:
- prError = PR_BAD_DESCRIPTOR_ERROR;
- break;
- default:
- _MD_win32_map_default_error(err);
- return;
- }
- PR_SetError(prError, err);
-}
-
-void _MD_win32_map_lockf_error(PRInt32 err)
-{
- _MD_win32_map_default_error(err);
-}
diff --git a/nspr/pr/src/memory/prseg.c b/nspr/pr/src/memory/prseg.c
deleted file mode 100644
index ecad1d0..0000000
--- a/nspr/pr/src/memory/prseg.c
+++ /dev/null
@@ -1,61 +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/. */
-
-#include "primpl.h"
-
-#if defined(_PR_PTHREADS)
-
-/*
-** The pthreads version doesn't use these functions.
-*/
-void _PR_InitSegs(void)
-{
-}
-
-#else /* _PR_PTHREADS */
-
-void _PR_InitSegs(void)
-{
- _PR_MD_INIT_SEGS();
-}
-
-/*
-** Allocate a memory segment. The size value is rounded up to the native
-** system page size and a page aligned portion of memory is returned.
-** This memory is not part of the malloc heap. If "vaddr" is not NULL
-** then PR tries to allocate the segment at the desired virtual address.
-*/
-PRSegment* _PR_NewSegment(PRUint32 size, void *vaddr)
-{
- PRSegment *seg;
-
- /* calloc the data structure for the segment */
- seg = PR_NEWZAP(PRSegment);
-
- if (seg) {
- size = ((size + _pr_pageSize - 1) >> _pr_pageShift) << _pr_pageShift;
- /*
- ** Now, allocate the actual segment memory (or map under some OS)
- ** The OS specific code decides from where or how to allocate memory.
- */
- if (_PR_MD_ALLOC_SEGMENT(seg, size, vaddr) != PR_SUCCESS) {
- PR_DELETE(seg);
- return NULL;
- }
- }
-
- return seg;
-}
-
-/*
-** Free a memory segment.
-*/
-void _PR_DestroySegment(PRSegment *seg)
-{
- _PR_MD_FREE_SEGMENT(seg);
- PR_DELETE(seg);
-}
-
-#endif /* _PR_PTHREADS */
diff --git a/nspr/pr/src/memory/prshm.c b/nspr/pr/src/memory/prshm.c
deleted file mode 100644
index 59237e6..0000000
--- a/nspr/pr/src/memory/prshm.c
+++ /dev/null
@@ -1,124 +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/. */
-
-/*
-** prshm.c -- NSPR Named Shared Memory
-**
-** lth. Jul-1999.
-*/
-#include <string.h>
-#include "primpl.h"
-
-extern PRLogModuleInfo *_pr_shm_lm;
-
-
-#if defined PR_HAVE_SYSV_NAMED_SHARED_MEMORY
-/* SysV implementation is in pr/src/md/unix/uxshm.c */
-#elif defined PR_HAVE_POSIX_NAMED_SHARED_MEMORY
-/* Posix implementation is in pr/src/md/unix/uxshm.c */
-#elif defined PR_HAVE_WIN32_NAMED_SHARED_MEMORY
-/* Win32 implementation is in pr/src/md/windows/w32shm.c */
-#else
-/*
-** there is no named_shared_memory
-*/
-extern PRSharedMemory* _MD_OpenSharedMemory( const char *name, PRSize size, PRIntn flags, PRIntn mode )
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return NULL;
-}
-
-extern void * _MD_AttachSharedMemory( PRSharedMemory *shm, PRIntn flags )
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return NULL;
-}
-
-extern PRStatus _MD_DetachSharedMemory( PRSharedMemory *shm, void *addr )
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-}
-
-extern PRStatus _MD_CloseSharedMemory( PRSharedMemory *shm )
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-}
-
-extern PRStatus _MD_DeleteSharedMemory( const char *name )
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-}
-#endif /* HAVE_SYSV_NAMED_SHARED_MEMORY */
-
-/*
-** FUNCTION: PR_OpenSharedMemory()
-**
-*/
-PR_IMPLEMENT( PRSharedMemory * )
- PR_OpenSharedMemory(
- const char *name,
- PRSize size,
- PRIntn flags,
- PRIntn mode
-)
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
- return( _PR_MD_OPEN_SHARED_MEMORY( name, size, flags, mode ));
-} /* end PR_OpenSharedMemory() */
-
-/*
-** FUNCTION: PR_AttachSharedMemory()
-**
-*/
-PR_IMPLEMENT( void * )
- PR_AttachSharedMemory(
- PRSharedMemory *shm,
- PRIntn flags
-)
-{
- return( _PR_MD_ATTACH_SHARED_MEMORY( shm, flags ));
-} /* end PR_AttachSharedMemory() */
-
-/*
-** FUNCTION: PR_DetachSharedMemory()
-**
-*/
-PR_IMPLEMENT( PRStatus )
- PR_DetachSharedMemory(
- PRSharedMemory *shm,
- void *addr
-)
-{
- return( _PR_MD_DETACH_SHARED_MEMORY( shm, addr ));
-} /* end PR_DetachSharedMemory() */
-
-/*
-** FUNCTION: PR_CloseSharedMemory()
-**
-*/
-PR_IMPLEMENT( PRStatus )
- PR_CloseSharedMemory(
- PRSharedMemory *shm
-)
-{
- return( _PR_MD_CLOSE_SHARED_MEMORY( shm ));
-} /* end PR_CloseSharedMemory() */
-
-/*
-** FUNCTION: PR_DeleteSharedMemory()
-**
-*/
-PR_EXTERN( PRStatus )
- PR_DeleteSharedMemory(
- const char *name
-)
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
- return(_PR_MD_DELETE_SHARED_MEMORY( name ));
-} /* end PR_DestroySharedMemory() */
-/* end prshm.c */
diff --git a/nspr/pr/src/memory/prshma.c b/nspr/pr/src/memory/prshma.c
deleted file mode 100644
index c73d7ec..0000000
--- a/nspr/pr/src/memory/prshma.c
+++ /dev/null
@@ -1,110 +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/. */
-
-/*
-** prshma.h -- NSPR Anonymous Shared Memory
-**
-**
-*/
-
-#include "primpl.h"
-
-extern PRLogModuleInfo *_pr_shma_lm;
-
-#if defined(XP_UNIX)
-/* defined in pr/src/md/unix/uxshm.c */
-#elif defined(WIN32)
-/* defined in pr/src/md/windows/w32shm.c */
-#else
-extern PRFileMap * _PR_MD_OPEN_ANON_FILE_MAP( const char *dirName, PRSize size, PRFileMapProtect prot )
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return NULL;
-}
-extern PRStatus _PR_MD_EXPORT_FILE_MAP_AS_STRING(PRFileMap *fm, PRSize bufSize, char *buf)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-}
-extern PRFileMap * _PR_MD_IMPORT_FILE_MAP_FROM_STRING(const char *fmstring)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return NULL;
-}
-#endif
-
-/*
-** PR_OpenAnonFileMap() -- Creates an anonymous file-mapped shared memory
-**
-*/
-PR_IMPLEMENT(PRFileMap*)
-PR_OpenAnonFileMap(
- const char *dirName,
- PRSize size,
- PRFileMapProtect prot
-)
-{
- return(_PR_MD_OPEN_ANON_FILE_MAP( dirName, size, prot ));
-} /* end PR_OpenAnonFileMap() */
-
-/*
-** PR_ProcessAttrSetInheritableFileMap() -- Prepare FileMap for export
-** to my children processes via PR_CreateProcess()
-**
-**
-*/
-PR_IMPLEMENT( PRStatus)
-PR_ProcessAttrSetInheritableFileMap(
- PRProcessAttr *attr,
- PRFileMap *fm,
- const char *shmname
-)
-{
- PR_SetError( PR_NOT_IMPLEMENTED_ERROR, 0 );
- return( PR_FAILURE);
-} /* end PR_ProcessAttrSetInheritableFileMap() */
-
-/*
-** PR_GetInheritedFileMap() -- Import a PRFileMap previously exported
-** by my parent process via PR_CreateProcess()
-**
-*/
-PR_IMPLEMENT( PRFileMap *)
-PR_GetInheritedFileMap(
- const char *shmname
-)
-{
- PRFileMap *fm = NULL;
- PR_SetError( PR_NOT_IMPLEMENTED_ERROR, 0 );
- return( fm );
-} /* end PR_GetInhteritedFileMap() */
-
-/*
-** PR_ExportFileMapAsString() -- Creates a string identifying a PRFileMap
-**
-*/
-PR_IMPLEMENT( PRStatus )
-PR_ExportFileMapAsString(
- PRFileMap *fm,
- PRSize bufSize,
- char *buf
-)
-{
- return( _PR_MD_EXPORT_FILE_MAP_AS_STRING( fm, bufSize, buf ));
-} /* end PR_ExportFileMapAsString() */
-
-/*
-** PR_ImportFileMapFromString() -- Creates a PRFileMap from the identifying string
-**
-**
-*/
-PR_IMPLEMENT( PRFileMap * )
-PR_ImportFileMapFromString(
- const char *fmstring
-)
-{
- return( _PR_MD_IMPORT_FILE_MAP_FROM_STRING(fmstring));
-} /* end PR_ImportFileMapFromString() */
-/* end prshma.c */
diff --git a/nspr/pr/src/misc/pralarm.c b/nspr/pr/src/misc/pralarm.c
deleted file mode 100644
index 8f642bb..0000000
--- a/nspr/pr/src/misc/pralarm.c
+++ /dev/null
@@ -1,246 +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/. */
-
-#include "primpl.h"
-
-/**********************************************************************/
-/******************************* PRALARM ******************************/
-/**********************************************************************/
-
-#include "obsolete/pralarm.h"
-
-struct PRAlarmID { /* typedef'd in pralarm.h */
- PRCList list; /* circular list linkage */
- PRAlarm *alarm; /* back pointer to owning alarm */
- PRPeriodicAlarmFn function; /* function to call for notify */
- void *clientData; /* opaque client context */
- PRIntervalTime period; /* the client defined period */
- PRUint32 rate; /* rate of notification */
-
- PRUint32 accumulator; /* keeps track of # notifies */
- PRIntervalTime epoch; /* when timer was started */
- PRIntervalTime nextNotify; /* when we'll next do our thing */
- PRIntervalTime lastNotify; /* when we last did our thing */
-};
-
-typedef enum {alarm_active, alarm_inactive} _AlarmState;
-
-struct PRAlarm { /* typedef'd in pralarm.h */
- PRCList timers; /* base of alarm ids list */
- PRLock *lock; /* lock used to protect data */
- PRCondVar *cond; /* condition that used to wait */
- PRThread *notifier; /* thread to deliver notifies */
- PRAlarmID *current; /* current alarm being served */
- _AlarmState state; /* used to delete the alarm */
-};
-
-static PRAlarmID *pr_getNextAlarm(PRAlarm *alarm, PRAlarmID *id)
-{
-/*
- * Puts 'id' back into the sorted list iff it's not NULL.
- * Removes the first element from the list and returns it (or NULL).
- * List is "assumed" to be short.
- *
- * NB: Caller is providing locking
- */
- PRCList *timer;
- PRAlarmID *result = id;
- PRIntervalTime now = PR_IntervalNow();
-
- if (!PR_CLIST_IS_EMPTY(&alarm->timers))
- {
- if (id != NULL) /* have to put this id back in */
- {
- PRIntervalTime idDelta = now - id->nextNotify;
- timer = alarm->timers.next;
- do
- {
- result = (PRAlarmID*)timer;
- if ((PRIntervalTime)(now - result->nextNotify) > idDelta)
- {
- PR_INSERT_BEFORE(&id->list, &alarm->timers);
- break;
- }
- timer = timer->next;
- } while (timer != &alarm->timers);
- }
- result = (PRAlarmID*)(timer = PR_LIST_HEAD(&alarm->timers));
- PR_REMOVE_LINK(timer); /* remove it from the list */
- }
-
- return result;
-} /* pr_getNextAlarm */
-
-static PRIntervalTime pr_PredictNextNotifyTime(PRAlarmID *id)
-{
- PRIntervalTime delta;
- PRFloat64 baseRate = (PRFloat64)id->period / (PRFloat64)id->rate;
- PRFloat64 offsetFromEpoch = (PRFloat64)id->accumulator * baseRate;
-
- id->accumulator += 1; /* every call advances to next period */
- id->lastNotify = id->nextNotify; /* just keeping track of things */
- id->nextNotify = (PRIntervalTime)(offsetFromEpoch + 0.5);
-
- delta = id->nextNotify - id->lastNotify;
- return delta;
-} /* pr_PredictNextNotifyTime */
-
-static void PR_CALLBACK pr_alarmNotifier(void *arg)
-{
- /*
- * This is the root of the notifier thread. There is one such thread
- * for each PRAlarm. It may service an arbitrary (though assumed to be
- * small) number of alarms using the same thread and structure. It
- * continues to run until the alarm is destroyed.
- */
- PRAlarmID *id = NULL;
- PRAlarm *alarm = (PRAlarm*)arg;
- enum {notify, abort, scan} why = scan;
-
- while (why != abort)
- {
- PRIntervalTime pause;
-
- PR_Lock(alarm->lock);
- while (why == scan)
- {
- alarm->current = NULL; /* reset current id */
- if (alarm->state == alarm_inactive) why = abort; /* we're toast */
- else if (why == scan) /* the dominant case */
- {
- id = pr_getNextAlarm(alarm, id); /* even if it's the same */
- if (id == NULL) /* there are no alarms set */
- (void)PR_WaitCondVar(alarm->cond, PR_INTERVAL_NO_TIMEOUT);
- else
- {
- pause = id->nextNotify - (PR_IntervalNow() - id->epoch);
- if ((PRInt32)pause <= 0) /* is this one's time up? */
- {
- why = notify; /* set up to do our thing */
- alarm->current = id; /* id we're about to schedule */
- }
- else
- (void)PR_WaitCondVar(alarm->cond, pause); /* dally */
- }
- }
- }
- PR_Unlock(alarm->lock);
-
- if (why == notify)
- {
- (void)pr_PredictNextNotifyTime(id);
- if (!id->function(id, id->clientData, ~pause))
- {
- /*
- * Notified function decided not to continue. Free
- * the alarm id to make sure it doesn't get back on
- * the list.
- */
- PR_DELETE(id); /* free notifier object */
- id = NULL; /* so it doesn't get back into the list */
- }
- why = scan; /* so we can cycle through the loop again */
- }
- }
-
-} /* pr_alarm_notifier */
-
-PR_IMPLEMENT(PRAlarm*) PR_CreateAlarm(void)
-{
- PRAlarm *alarm = PR_NEWZAP(PRAlarm);
- if (alarm != NULL)
- {
- if ((alarm->lock = PR_NewLock()) == NULL) goto done;
- if ((alarm->cond = PR_NewCondVar(alarm->lock)) == NULL) goto done;
- alarm->state = alarm_active;
- PR_INIT_CLIST(&alarm->timers);
- alarm->notifier = PR_CreateThread(
- PR_USER_THREAD, pr_alarmNotifier, alarm,
- PR_GetThreadPriority(PR_GetCurrentThread()),
- PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0);
- if (alarm->notifier == NULL) goto done;
- }
- return alarm;
-
-done:
- if (alarm->cond != NULL) PR_DestroyCondVar(alarm->cond);
- if (alarm->lock != NULL) PR_DestroyLock(alarm->lock);
- PR_DELETE(alarm);
- return NULL;
-} /* CreateAlarm */
-
-PR_IMPLEMENT(PRStatus) PR_DestroyAlarm(PRAlarm *alarm)
-{
- PRStatus rv;
-
- PR_Lock(alarm->lock);
- alarm->state = alarm_inactive;
- rv = PR_NotifyCondVar(alarm->cond);
- PR_Unlock(alarm->lock);
-
- if (rv == PR_SUCCESS)
- rv = PR_JoinThread(alarm->notifier);
- if (rv == PR_SUCCESS)
- {
- PR_DestroyCondVar(alarm->cond);
- PR_DestroyLock(alarm->lock);
- PR_DELETE(alarm);
- }
- return rv;
-} /* PR_DestroyAlarm */
-
-PR_IMPLEMENT(PRAlarmID*) PR_SetAlarm(
- PRAlarm *alarm, PRIntervalTime period, PRUint32 rate,
- PRPeriodicAlarmFn function, void *clientData)
-{
- /*
- * Create a new periodic alarm an existing current structure.
- * Set up the context and compute the first notify time (immediate).
- * Link the new ID into the head of the list (since it's notifying
- * immediately).
- */
-
- PRAlarmID *id = PR_NEWZAP(PRAlarmID);
-
- if (!id)
- return NULL;
-
- id->alarm = alarm;
- PR_INIT_CLIST(&id->list);
- id->function = function;
- id->clientData = clientData;
- id->period = period;
- id->rate = rate;
- id->epoch = id->nextNotify = PR_IntervalNow();
- (void)pr_PredictNextNotifyTime(id);
-
- PR_Lock(alarm->lock);
- PR_INSERT_BEFORE(&id->list, &alarm->timers);
- PR_NotifyCondVar(alarm->cond);
- PR_Unlock(alarm->lock);
-
- return id;
-} /* PR_SetAlarm */
-
-PR_IMPLEMENT(PRStatus) PR_ResetAlarm(
- PRAlarmID *id, PRIntervalTime period, PRUint32 rate)
-{
- /*
- * Can only be called from within the notify routine. Doesn't
- * need locking because it can only be called from within the
- * notify routine.
- */
- if (id != id->alarm->current)
- return PR_FAILURE;
- id->period = period;
- id->rate = rate;
- id->accumulator = 1;
- id->epoch = PR_IntervalNow();
- (void)pr_PredictNextNotifyTime(id);
- return PR_SUCCESS;
-} /* PR_ResetAlarm */
-
-
-
diff --git a/nspr/pr/src/misc/pratom.c b/nspr/pr/src/misc/pratom.c
deleted file mode 100644
index 95bbee1..0000000
--- a/nspr/pr/src/misc/pratom.c
+++ /dev/null
@@ -1,379 +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/. */
-
-/*
-** PR Atomic operations
-*/
-
-
-#include "pratom.h"
-#include "primpl.h"
-
-#include <string.h>
-
-/*
- * The following is a fallback implementation that emulates
- * atomic operations for platforms without atomic operations.
- * If a platform has atomic operations, it should define the
- * macro _PR_HAVE_ATOMIC_OPS, and the following will not be
- * compiled in.
- */
-
-#if !defined(_PR_HAVE_ATOMIC_OPS)
-
-#if defined(_PR_PTHREADS) && !defined(_PR_DCETHREADS)
-/*
- * PR_AtomicDecrement() is used in NSPR's thread-specific data
- * destructor. Because thread-specific data destructors may be
- * invoked after a PR_Cleanup() call, we need an implementation
- * of the atomic routines that doesn't need NSPR to be initialized.
- */
-
-/*
- * We use a set of locks for all the emulated atomic operations.
- * By hashing on the address of the integer to be locked the
- * contention between multiple threads should be lessened.
- *
- * The number of atomic locks can be set by the environment variable
- * NSPR_ATOMIC_HASH_LOCKS
- */
-
-/*
- * lock counts should be a power of 2
- */
-#define DEFAULT_ATOMIC_LOCKS 16 /* should be in sync with the number of initializers
- below */
-#define MAX_ATOMIC_LOCKS (4 * 1024)
-
-static pthread_mutex_t static_atomic_locks[DEFAULT_ATOMIC_LOCKS] = {
- PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,
- PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,
- PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,
- PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,
- PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,
- PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,
- PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,
- PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER };
-
-#ifdef DEBUG
-static PRInt32 static_hash_lock_counts[DEFAULT_ATOMIC_LOCKS];
-static PRInt32 *hash_lock_counts = static_hash_lock_counts;
-#endif
-
-static PRUint32 num_atomic_locks = DEFAULT_ATOMIC_LOCKS;
-static pthread_mutex_t *atomic_locks = static_atomic_locks;
-static PRUint32 atomic_hash_mask = DEFAULT_ATOMIC_LOCKS - 1;
-
-#define _PR_HASH_FOR_LOCK(ptr) \
- ((PRUint32) (((PRUptrdiff) (ptr) >> 2) ^ \
- ((PRUptrdiff) (ptr) >> 8)) & \
- atomic_hash_mask)
-
-void _PR_MD_INIT_ATOMIC()
-{
-char *eval;
-int index;
-
-
- PR_ASSERT(PR_FloorLog2(MAX_ATOMIC_LOCKS) ==
- PR_CeilingLog2(MAX_ATOMIC_LOCKS));
-
- PR_ASSERT(PR_FloorLog2(DEFAULT_ATOMIC_LOCKS) ==
- PR_CeilingLog2(DEFAULT_ATOMIC_LOCKS));
-
- if (((eval = getenv("NSPR_ATOMIC_HASH_LOCKS")) != NULL) &&
- ((num_atomic_locks = atoi(eval)) != DEFAULT_ATOMIC_LOCKS)) {
-
- if (num_atomic_locks > MAX_ATOMIC_LOCKS)
- num_atomic_locks = MAX_ATOMIC_LOCKS;
- else if (num_atomic_locks < 1)
- num_atomic_locks = 1;
- else {
- num_atomic_locks = PR_FloorLog2(num_atomic_locks);
- num_atomic_locks = 1L << num_atomic_locks;
- }
- atomic_locks = (pthread_mutex_t *) PR_Malloc(sizeof(pthread_mutex_t) *
- num_atomic_locks);
- if (atomic_locks) {
- for (index = 0; index < num_atomic_locks; index++) {
- if (pthread_mutex_init(&atomic_locks[index], NULL)) {
- PR_DELETE(atomic_locks);
- atomic_locks = NULL;
- break;
- }
- }
- }
-#ifdef DEBUG
- if (atomic_locks) {
- hash_lock_counts = PR_CALLOC(num_atomic_locks * sizeof(PRInt32));
- if (hash_lock_counts == NULL) {
- PR_DELETE(atomic_locks);
- atomic_locks = NULL;
- }
- }
-#endif
- if (atomic_locks == NULL) {
- /*
- * Use statically allocated locks
- */
- atomic_locks = static_atomic_locks;
- num_atomic_locks = DEFAULT_ATOMIC_LOCKS;
- #ifdef DEBUG
- hash_lock_counts = static_hash_lock_counts;
- #endif
- }
- atomic_hash_mask = num_atomic_locks - 1;
- }
- PR_ASSERT(PR_FloorLog2(num_atomic_locks) ==
- PR_CeilingLog2(num_atomic_locks));
-}
-
-PRInt32
-_PR_MD_ATOMIC_INCREMENT(PRInt32 *val)
-{
- PRInt32 rv;
- PRInt32 idx = _PR_HASH_FOR_LOCK(val);
-
- pthread_mutex_lock(&atomic_locks[idx]);
- rv = ++(*val);
-#ifdef DEBUG
- hash_lock_counts[idx]++;
-#endif
- pthread_mutex_unlock(&atomic_locks[idx]);
- return rv;
-}
-
-PRInt32
-_PR_MD_ATOMIC_ADD(PRInt32 *ptr, PRInt32 val)
-{
- PRInt32 rv;
- PRInt32 idx = _PR_HASH_FOR_LOCK(ptr);
-
- pthread_mutex_lock(&atomic_locks[idx]);
- rv = ((*ptr) += val);
-#ifdef DEBUG
- hash_lock_counts[idx]++;
-#endif
- pthread_mutex_unlock(&atomic_locks[idx]);
- return rv;
-}
-
-PRInt32
-_PR_MD_ATOMIC_DECREMENT(PRInt32 *val)
-{
- PRInt32 rv;
- PRInt32 idx = _PR_HASH_FOR_LOCK(val);
-
- pthread_mutex_lock(&atomic_locks[idx]);
- rv = --(*val);
-#ifdef DEBUG
- hash_lock_counts[idx]++;
-#endif
- pthread_mutex_unlock(&atomic_locks[idx]);
- return rv;
-}
-
-PRInt32
-_PR_MD_ATOMIC_SET(PRInt32 *val, PRInt32 newval)
-{
- PRInt32 rv;
- PRInt32 idx = _PR_HASH_FOR_LOCK(val);
-
- pthread_mutex_lock(&atomic_locks[idx]);
- rv = *val;
- *val = newval;
-#ifdef DEBUG
- hash_lock_counts[idx]++;
-#endif
- pthread_mutex_unlock(&atomic_locks[idx]);
- return rv;
-}
-#else /* _PR_PTHREADS && !_PR_DCETHREADS */
-/*
- * We use a single lock for all the emulated atomic operations.
- * The lock contention should be acceptable.
- */
-static PRLock *atomic_lock = NULL;
-void _PR_MD_INIT_ATOMIC(void)
-{
- if (atomic_lock == NULL) {
- atomic_lock = PR_NewLock();
- }
-}
-
-PRInt32
-_PR_MD_ATOMIC_INCREMENT(PRInt32 *val)
-{
- PRInt32 rv;
-
- if (!_pr_initialized) {
- _PR_ImplicitInitialization();
- }
- PR_Lock(atomic_lock);
- rv = ++(*val);
- PR_Unlock(atomic_lock);
- return rv;
-}
-
-PRInt32
-_PR_MD_ATOMIC_ADD(PRInt32 *ptr, PRInt32 val)
-{
- PRInt32 rv;
-
- if (!_pr_initialized) {
- _PR_ImplicitInitialization();
- }
- PR_Lock(atomic_lock);
- rv = ((*ptr) += val);
- PR_Unlock(atomic_lock);
- return rv;
-}
-
-PRInt32
-_PR_MD_ATOMIC_DECREMENT(PRInt32 *val)
-{
- PRInt32 rv;
-
- if (!_pr_initialized) {
- _PR_ImplicitInitialization();
- }
- PR_Lock(atomic_lock);
- rv = --(*val);
- PR_Unlock(atomic_lock);
- return rv;
-}
-
-PRInt32
-_PR_MD_ATOMIC_SET(PRInt32 *val, PRInt32 newval)
-{
- PRInt32 rv;
-
- if (!_pr_initialized) {
- _PR_ImplicitInitialization();
- }
- PR_Lock(atomic_lock);
- rv = *val;
- *val = newval;
- PR_Unlock(atomic_lock);
- return rv;
-}
-#endif /* _PR_PTHREADS && !_PR_DCETHREADS */
-
-#endif /* !_PR_HAVE_ATOMIC_OPS */
-
-void _PR_InitAtomic(void)
-{
- _PR_MD_INIT_ATOMIC();
-}
-
-PR_IMPLEMENT(PRInt32)
-PR_AtomicIncrement(PRInt32 *val)
-{
- return _PR_MD_ATOMIC_INCREMENT(val);
-}
-
-PR_IMPLEMENT(PRInt32)
-PR_AtomicDecrement(PRInt32 *val)
-{
- return _PR_MD_ATOMIC_DECREMENT(val);
-}
-
-PR_IMPLEMENT(PRInt32)
-PR_AtomicSet(PRInt32 *val, PRInt32 newval)
-{
- return _PR_MD_ATOMIC_SET(val, newval);
-}
-
-PR_IMPLEMENT(PRInt32)
-PR_AtomicAdd(PRInt32 *ptr, PRInt32 val)
-{
- return _PR_MD_ATOMIC_ADD(ptr, val);
-}
-/*
- * For platforms, which don't support the CAS (compare-and-swap) instruction
- * (or an equivalent), the stack operations are implemented by use of PRLock
- */
-
-PR_IMPLEMENT(PRStack *)
-PR_CreateStack(const char *stack_name)
-{
-PRStack *stack;
-
- if (!_pr_initialized) {
- _PR_ImplicitInitialization();
- }
-
- if ((stack = PR_NEW(PRStack)) == NULL) {
- return NULL;
- }
- if (stack_name) {
- stack->prstk_name = (char *) PR_Malloc(strlen(stack_name) + 1);
- if (stack->prstk_name == NULL) {
- PR_DELETE(stack);
- return NULL;
- }
- strcpy(stack->prstk_name, stack_name);
- } else
- stack->prstk_name = NULL;
-
-#ifndef _PR_HAVE_ATOMIC_CAS
- stack->prstk_lock = PR_NewLock();
- if (stack->prstk_lock == NULL) {
- PR_Free(stack->prstk_name);
- PR_DELETE(stack);
- return NULL;
- }
-#endif /* !_PR_HAVE_ATOMIC_CAS */
-
- stack->prstk_head.prstk_elem_next = NULL;
-
- return stack;
-}
-
-PR_IMPLEMENT(PRStatus)
-PR_DestroyStack(PRStack *stack)
-{
- if (stack->prstk_head.prstk_elem_next != NULL) {
- PR_SetError(PR_INVALID_STATE_ERROR, 0);
- return PR_FAILURE;
- }
-
- if (stack->prstk_name)
- PR_Free(stack->prstk_name);
-#ifndef _PR_HAVE_ATOMIC_CAS
- PR_DestroyLock(stack->prstk_lock);
-#endif /* !_PR_HAVE_ATOMIC_CAS */
- PR_DELETE(stack);
-
- return PR_SUCCESS;
-}
-
-#ifndef _PR_HAVE_ATOMIC_CAS
-
-PR_IMPLEMENT(void)
-PR_StackPush(PRStack *stack, PRStackElem *stack_elem)
-{
- PR_Lock(stack->prstk_lock);
- stack_elem->prstk_elem_next = stack->prstk_head.prstk_elem_next;
- stack->prstk_head.prstk_elem_next = stack_elem;
- PR_Unlock(stack->prstk_lock);
- return;
-}
-
-PR_IMPLEMENT(PRStackElem *)
-PR_StackPop(PRStack *stack)
-{
-PRStackElem *element;
-
- PR_Lock(stack->prstk_lock);
- element = stack->prstk_head.prstk_elem_next;
- if (element != NULL) {
- stack->prstk_head.prstk_elem_next = element->prstk_elem_next;
- element->prstk_elem_next = NULL; /* debugging aid */
- }
- PR_Unlock(stack->prstk_lock);
- return element;
-}
-#endif /* !_PR_HAVE_ATOMIC_CAS */
diff --git a/nspr/pr/src/misc/praton.c b/nspr/pr/src/misc/praton.c
deleted file mode 100644
index bff0cd1..0000000
--- a/nspr/pr/src/misc/praton.c
+++ /dev/null
@@ -1,198 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/*******************************************************************************
- * The following function pr_inet_aton is based on the BSD function inet_aton
- * with some modifications. The license and copyright notices applying to this
- * function appear below. Modifications are also according to the license below.
- ******************************************************************************/
-
-#include "prnetdb.h"
-
-/*
- * Copyright (c) 1983, 1990, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-/*
- * Portions Copyright (c) 1993 by Digital Equipment Corporation.
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies, and that
- * the name of Digital Equipment Corporation not be used in advertising or
- * publicity pertaining to distribution of the document or software without
- * specific, written prior permission.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
- * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
- * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
- * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
- * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
- * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
- * SOFTWARE.
- */
-
-/*
- * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
- * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
- * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-#define XX 127
-static const unsigned char index_hex[256] = {
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,XX,XX, XX,XX,XX,XX,
- XX,10,11,12, 13,14,15,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,10,11,12, 13,14,15,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
-};
-
-static PRBool _isdigit(char c) { return c >= '0' && c <= '9'; }
-static PRBool _isxdigit(char c) { return index_hex[(unsigned char) c] != XX; }
-static PRBool _isspace(char c) { return c == ' ' || (c >= '\t' && c <= '\r'); }
-#undef XX
-
-int
-pr_inet_aton(const char *cp, PRUint32 *addr)
-{
- PRUint32 val;
- int base, n;
- char c;
- PRUint8 parts[4];
- PRUint8 *pp = parts;
- int digit;
-
- c = *cp;
- for (;;) {
- /*
- * Collect number up to ``.''.
- * Values are specified as for C:
- * 0x=hex, 0=octal, isdigit=decimal.
- */
- if (!_isdigit(c))
- return (0);
- val = 0; base = 10; digit = 0;
- if (c == '0') {
- c = *++cp;
- if (c == 'x' || c == 'X')
- base = 16, c = *++cp;
- else {
- base = 8;
- digit = 1;
- }
- }
- for (;;) {
- if (_isdigit(c)) {
- if (base == 8 && (c == '8' || c == '9'))
- return (0);
- val = (val * base) + (c - '0');
- c = *++cp;
- digit = 1;
- } else if (base == 16 && _isxdigit(c)) {
- val = (val << 4) + index_hex[(unsigned char) c];
- c = *++cp;
- digit = 1;
- } else
- break;
- }
- if (c == '.') {
- /*
- * Internet format:
- * a.b.c.d
- * a.b.c (with c treated as 16 bits)
- * a.b (with b treated as 24 bits)
- */
- if (pp >= parts + 3 || val > 0xffU)
- return (0);
- *pp++ = val;
- c = *++cp;
- } else
- break;
- }
- /*
- * Check for trailing characters.
- */
- if (c != '\0' && !_isspace(c))
- return (0);
- /*
- * Did we get a valid digit?
- */
- if (!digit)
- return (0);
- /*
- * Concoct the address according to
- * the number of parts specified.
- */
- n = pp - parts + 1;
- switch (n) {
- case 1: /*%< a -- 32 bits */
- break;
-
- case 2: /*%< a.b -- 8.24 bits */
- if (val > 0xffffffU)
- return (0);
- val |= parts[0] << 24;
- break;
-
- case 3: /*%< a.b.c -- 8.8.16 bits */
- if (val > 0xffffU)
- return (0);
- val |= (parts[0] << 24) | (parts[1] << 16);
- break;
-
- case 4: /*%< a.b.c.d -- 8.8.8.8 bits */
- if (val > 0xffU)
- return (0);
- val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
- break;
- }
- *addr = PR_htonl(val);
- return (1);
-}
-
diff --git a/nspr/pr/src/misc/prcountr.c b/nspr/pr/src/misc/prcountr.c
deleted file mode 100644
index 0f126ad..0000000
--- a/nspr/pr/src/misc/prcountr.c
+++ /dev/null
@@ -1,474 +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/. */
-
-/*
-** prcountr.c -- NSPR Instrumentation Counters
-**
-** Implement the interface defined in prcountr.h
-**
-** Design Notes:
-**
-** The Counter Facility (CF) has a single anchor: qNameList.
-** The anchor is a PRCList. qNameList is a list of links in QName
-** structures. From qNameList any QName structure and its
-** associated RName structure can be located.
-**
-** For each QName, a list of RName structures is anchored at
-** rnLink in the QName structure.
-**
-** The counter itself is embedded in the RName structure.
-**
-** For manipulating the counter database, single lock is used to
-** protect the entire list: counterLock.
-**
-** A PRCounterHandle, defined in prcountr.h, is really a pointer
-** to a RName structure. References by PRCounterHandle are
-** dead-reconed to the RName structure. The PRCounterHandle is
-** "overloaded" for traversing the QName structures; only the
-** function PR_FindNextQnameHandle() uses this overloading.
-**
-**
-** ToDo (lth): decide on how to lock or atomically update
-** individual counters. Candidates are: the global lock; a lock
-** per RName structure; Atomic operations (Note that there are
-** not adaquate atomic operations (yet) to achieve this goal). At
-** this writing (6/19/98) , the update of the counter variable in
-** a QName structure is unprotected.
-**
-*/
-
-#include "prcountr.h"
-#include "prclist.h"
-#include "prlock.h"
-#include "prlog.h"
-#include "prmem.h"
-#include <string.h>
-
-/*
-**
-*/
-typedef struct QName
-{
- PRCList link;
- PRCList rNameList;
- char name[PRCOUNTER_NAME_MAX+1];
-} QName;
-
-/*
-**
-*/
-typedef struct RName
-{
- PRCList link;
- QName *qName;
- PRLock *lock;
- volatile PRUint32 counter;
- char name[PRCOUNTER_NAME_MAX+1];
- char desc[PRCOUNTER_DESC_MAX+1];
-} RName;
-
-
-/*
-** Define the Counter Facility database
-*/
-static PRLock *counterLock;
-static PRCList qNameList;
-static PRLogModuleInfo *lm;
-
-/*
-** _PR_CounterInitialize() -- Initialize the Counter Facility
-**
-*/
-static void _PR_CounterInitialize( void )
-{
- /*
- ** This function should be called only once
- */
- PR_ASSERT( counterLock == NULL );
-
- counterLock = PR_NewLock();
- PR_INIT_CLIST( &qNameList );
- lm = PR_NewLogModule("counters");
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: Initialization complete"));
-
- return;
-} /* end _PR_CounterInitialize() */
-
-/*
-** PR_CreateCounter() -- Create a counter
-**
-** ValidateArguments
-** Lock
-** if (qName not already in database)
-** NewQname
-** if (rName already in database )
-** Assert
-** else NewRname
-** NewCounter
-** link 'em up
-** Unlock
-**
-*/
-PR_IMPLEMENT(PRCounterHandle)
- PR_CreateCounter(
- const char *qName,
- const char *rName,
- const char *description
-)
-{
- QName *qnp;
- RName *rnp;
- PRBool matchQname = PR_FALSE;
-
- /* Self initialize, if necessary */
- if ( counterLock == NULL )
- _PR_CounterInitialize();
-
- /* Validate input arguments */
- PR_ASSERT( strlen(qName) <= PRCOUNTER_NAME_MAX );
- PR_ASSERT( strlen(rName) <= PRCOUNTER_NAME_MAX );
- PR_ASSERT( strlen(description) <= PRCOUNTER_DESC_MAX );
-
- /* Lock the Facility */
- PR_Lock( counterLock );
-
- /* Do we already have a matching QName? */
- if (!PR_CLIST_IS_EMPTY( &qNameList ))
- {
- qnp = (QName *) PR_LIST_HEAD( &qNameList );
- do {
- if ( strcmp(qnp->name, qName) == 0)
- {
- matchQname = PR_TRUE;
- break;
- }
- qnp = (QName *)PR_NEXT_LINK( &qnp->link );
- } while( qnp != (QName *)&qNameList );
- }
- /*
- ** If we did not find a matching QName,
- ** allocate one and initialize it.
- ** link it onto the qNameList.
- **
- */
- if ( matchQname != PR_TRUE )
- {
- qnp = PR_NEWZAP( QName );
- PR_ASSERT( qnp != NULL );
- PR_INIT_CLIST( &qnp->link );
- PR_INIT_CLIST( &qnp->rNameList );
- strcpy( qnp->name, qName );
- PR_APPEND_LINK( &qnp->link, &qNameList );
- }
-
- /* Do we already have a matching RName? */
- if (!PR_CLIST_IS_EMPTY( &qnp->rNameList ))
- {
- rnp = (RName *) PR_LIST_HEAD( &qnp->rNameList );
- do {
- /*
- ** No duplicate RNames are allowed within a QName
- **
- */
- PR_ASSERT( strcmp(rnp->name, rName));
- rnp = (RName *)PR_NEXT_LINK( &rnp->link );
- } while( rnp != (RName *)&qnp->rNameList );
- }
-
- /* Get a new RName structure; initialize its members */
- rnp = PR_NEWZAP( RName );
- PR_ASSERT( rnp != NULL );
- PR_INIT_CLIST( &rnp->link );
- strcpy( rnp->name, rName );
- strcpy( rnp->desc, description );
- rnp->lock = PR_NewLock();
- if ( rnp->lock == NULL )
- {
- PR_ASSERT(0);
- }
-
- PR_APPEND_LINK( &rnp->link, &qnp->rNameList ); /* add RName to QName's rnList */
- rnp->qName = qnp; /* point the RName to the QName */
-
- /* Unlock the Facility */
- PR_Unlock( counterLock );
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: Create: QName: %s %p, RName: %s %p\n\t",
- qName, qnp, rName, rnp ));
-
- return((PRCounterHandle)rnp);
-} /* end PR_CreateCounter() */
-
-
-/*
-**
-*/
-PR_IMPLEMENT(void)
- PR_DestroyCounter(
- PRCounterHandle handle
-)
-{
- RName *rnp = (RName *)handle;
- QName *qnp = rnp->qName;
-
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: Deleting: QName: %s, RName: %s",
- qnp->name, rnp->name));
-
- /* Lock the Facility */
- PR_Lock( counterLock );
-
- /*
- ** Remove RName from the list of RNames in QName
- ** and free RName
- */
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: Deleting RName: %s, %p",
- rnp->name, rnp));
- PR_REMOVE_LINK( &rnp->link );
- PR_Free( rnp->lock );
- PR_DELETE( rnp );
-
- /*
- ** If this is the last RName within QName
- ** remove QName from the qNameList and free it
- */
- if ( PR_CLIST_IS_EMPTY( &qnp->rNameList ) )
- {
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: Deleting unused QName: %s, %p",
- qnp->name, qnp));
- PR_REMOVE_LINK( &qnp->link );
- PR_DELETE( qnp );
- }
-
- /* Unlock the Facility */
- PR_Unlock( counterLock );
- return;
-} /* end PR_DestroyCounter() */
-
-/*
-**
-*/
-PR_IMPLEMENT(PRCounterHandle)
- PR_GetCounterHandleFromName(
- const char *qName,
- const char *rName
-)
-{
- const char *qn, *rn, *desc;
- PRCounterHandle qh, rh = NULL;
- RName *rnp = NULL;
-
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: GetCounterHandleFromName:\n\t"
- "QName: %s, RName: %s", qName, rName ));
-
- qh = PR_FindNextCounterQname( NULL );
- while (qh != NULL)
- {
- rh = PR_FindNextCounterRname( NULL, qh );
- while ( rh != NULL )
- {
- PR_GetCounterNameFromHandle( rh, &qn, &rn, &desc );
- if ( (strcmp( qName, qn ) == 0)
- && (strcmp( rName, rn ) == 0 ))
- {
- rnp = (RName *)rh;
- goto foundIt;
- }
- rh = PR_FindNextCounterRname( rh, qh );
- }
- qh = PR_FindNextCounterQname( NULL );
- }
-
-foundIt:
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: GetConterHandleFromName: %p", rnp ));
- return(rh);
-} /* end PR_GetCounterHandleFromName() */
-
-/*
-**
-*/
-PR_IMPLEMENT(void)
- PR_GetCounterNameFromHandle(
- PRCounterHandle handle,
- const char **qName,
- const char **rName,
- const char **description
-)
-{
- RName *rnp = (RName *)handle;
- QName *qnp = rnp->qName;
-
- *qName = qnp->name;
- *rName = rnp->name;
- *description = rnp->desc;
-
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: GetConterNameFromHandle: "
- "QNp: %p, RNp: %p,\n\tQName: %s, RName: %s, Desc: %s",
- qnp, rnp, qnp->name, rnp->name, rnp->desc ));
-
- return;
-} /* end PR_GetCounterNameFromHandle() */
-
-
-/*
-**
-*/
-PR_IMPLEMENT(void)
- PR_IncrementCounter(
- PRCounterHandle handle
-)
-{
- PR_Lock(((RName *)handle)->lock);
- ((RName *)handle)->counter++;
- PR_Unlock(((RName *)handle)->lock);
-
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: Increment: %p, %ld",
- handle, ((RName *)handle)->counter ));
-
- return;
-} /* end PR_IncrementCounter() */
-
-
-
-/*
-**
-*/
-PR_IMPLEMENT(void)
- PR_DecrementCounter(
- PRCounterHandle handle
-)
-{
- PR_Lock(((RName *)handle)->lock);
- ((RName *)handle)->counter--;
- PR_Unlock(((RName *)handle)->lock);
-
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: Decrement: %p, %ld",
- handle, ((RName *)handle)->counter ));
-
- return;
-} /* end PR_DecrementCounter() */
-
-
-/*
-**
-*/
-PR_IMPLEMENT(void)
- PR_AddToCounter(
- PRCounterHandle handle,
- PRUint32 value
-)
-{
- PR_Lock(((RName *)handle)->lock);
- ((RName *)handle)->counter += value;
- PR_Unlock(((RName *)handle)->lock);
-
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: AddToCounter: %p, %ld",
- handle, ((RName *)handle)->counter ));
-
- return;
-} /* end PR_AddToCounter() */
-
-
-/*
-**
-*/
-PR_IMPLEMENT(void)
- PR_SubtractFromCounter(
- PRCounterHandle handle,
- PRUint32 value
-)
-{
- PR_Lock(((RName *)handle)->lock);
- ((RName *)handle)->counter -= value;
- PR_Unlock(((RName *)handle)->lock);
-
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: SubtractFromCounter: %p, %ld",
- handle, ((RName *)handle)->counter ));
-
- return;
-} /* end PR_SubtractFromCounter() */
-
-/*
-**
-*/
-PR_IMPLEMENT(PRUint32)
- PR_GetCounter(
- PRCounterHandle handle
-)
-{
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: GetCounter: %p, %ld",
- handle, ((RName *)handle)->counter ));
-
- return(((RName *)handle)->counter);
-} /* end PR_GetCounter() */
-
-/*
-**
-*/
-PR_IMPLEMENT(void)
- PR_SetCounter(
- PRCounterHandle handle,
- PRUint32 value
-)
-{
- ((RName *)handle)->counter = value;
-
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: SetCounter: %p, %ld",
- handle, ((RName *)handle)->counter ));
-
- return;
-} /* end PR_SetCounter() */
-
-/*
-**
-*/
-PR_IMPLEMENT(PRCounterHandle)
- PR_FindNextCounterQname(
- PRCounterHandle handle
-)
-{
- QName *qnp = (QName *)handle;
-
- if ( PR_CLIST_IS_EMPTY( &qNameList ))
- qnp = NULL;
- else if ( qnp == NULL )
- qnp = (QName *)PR_LIST_HEAD( &qNameList );
- else if ( PR_NEXT_LINK( &qnp->link ) == &qNameList )
- qnp = NULL;
- else
- qnp = (QName *)PR_NEXT_LINK( &qnp->link );
-
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: FindNextQname: Handle: %p, Returns: %p",
- handle, qnp ));
-
- return((PRCounterHandle)qnp);
-} /* end PR_FindNextCounterQname() */
-
-
-/*
-**
-*/
-PR_IMPLEMENT(PRCounterHandle)
- PR_FindNextCounterRname(
- PRCounterHandle rhandle,
- PRCounterHandle qhandle
-)
-{
- RName *rnp = (RName *)rhandle;
- QName *qnp = (QName *)qhandle;
-
-
- if ( PR_CLIST_IS_EMPTY( &qnp->rNameList ))
- rnp = NULL;
- else if ( rnp == NULL )
- rnp = (RName *)PR_LIST_HEAD( &qnp->rNameList );
- else if ( PR_NEXT_LINK( &rnp->link ) == &qnp->rNameList )
- rnp = NULL;
- else
- rnp = (RName *)PR_NEXT_LINK( &rnp->link );
-
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: FindNextRname: Rhandle: %p, QHandle: %p, Returns: %p",
- rhandle, qhandle, rnp ));
-
- return((PRCounterHandle)rnp);
-} /* end PR_FindNextCounterRname() */
diff --git a/nspr/pr/src/misc/prdtoa.c b/nspr/pr/src/misc/prdtoa.c
deleted file mode 100644
index 2276926..0000000
--- a/nspr/pr/src/misc/prdtoa.c
+++ /dev/null
@@ -1,3522 +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/. */
-
-/*
- * This file is based on the third-party code dtoa.c. We minimize our
- * modifications to third-party code to make it easy to merge new versions.
- * The author of dtoa.c was not willing to add the parentheses suggested by
- * GCC, so we suppress these warnings.
- */
-#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2)
-#pragma GCC diagnostic ignored "-Wparentheses"
-#endif
-
-#include "primpl.h"
-#include "prbit.h"
-
-#define MULTIPLE_THREADS
-#define ACQUIRE_DTOA_LOCK(n) PR_Lock(dtoa_lock[n])
-#define FREE_DTOA_LOCK(n) PR_Unlock(dtoa_lock[n])
-
-static PRLock *dtoa_lock[2];
-
-void _PR_InitDtoa(void)
-{
- dtoa_lock[0] = PR_NewLock();
- dtoa_lock[1] = PR_NewLock();
-}
-
-void _PR_CleanupDtoa(void)
-{
- PR_DestroyLock(dtoa_lock[0]);
- dtoa_lock[0] = NULL;
- PR_DestroyLock(dtoa_lock[1]);
- dtoa_lock[1] = NULL;
-
- /* FIXME: deal with freelist and p5s. */
-}
-
-#if !defined(__ARM_EABI__) \
- && (defined(__arm) || defined(__arm__) || defined(__arm26__) \
- || defined(__arm32__))
-#define IEEE_ARM
-#elif defined(IS_LITTLE_ENDIAN)
-#define IEEE_8087
-#else
-#define IEEE_MC68k
-#endif
-
-#define Long PRInt32
-#define ULong PRUint32
-#define NO_LONG_LONG
-
-#define No_Hex_NaN
-
-/****************************************************************
- *
- * The author of this software is David M. Gay.
- *
- * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose without fee is hereby granted, provided that this entire notice
- * is included in all copies of any software which is or includes a copy
- * or modification of this software and in all copies of the supporting
- * documentation for such software.
- *
- * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
- * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
- * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
- * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
- *
- ***************************************************************/
-
-/* Please send bug reports to David M. Gay (dmg at acm dot org,
- * with " at " changed at "@" and " dot " changed to "."). */
-
-/* On a machine with IEEE extended-precision registers, it is
- * necessary to specify double-precision (53-bit) rounding precision
- * before invoking strtod or dtoa. If the machine uses (the equivalent
- * of) Intel 80x87 arithmetic, the call
- * _control87(PC_53, MCW_PC);
- * does this with many compilers. Whether this or another call is
- * appropriate depends on the compiler; for this to work, it may be
- * necessary to #include "float.h" or another system-dependent header
- * file.
- */
-
-/* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
- *
- * This strtod returns a nearest machine number to the input decimal
- * string (or sets errno to ERANGE). With IEEE arithmetic, ties are
- * broken by the IEEE round-even rule. Otherwise ties are broken by
- * biased rounding (add half and chop).
- *
- * Inspired loosely by William D. Clinger's paper "How to Read Floating
- * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
- *
- * Modifications:
- *
- * 1. We only require IEEE, IBM, or VAX double-precision
- * arithmetic (not IEEE double-extended).
- * 2. We get by with floating-point arithmetic in a case that
- * Clinger missed -- when we're computing d * 10^n
- * for a small integer d and the integer n is not too
- * much larger than 22 (the maximum integer k for which
- * we can represent 10^k exactly), we may be able to
- * compute (d*10^k) * 10^(e-k) with just one roundoff.
- * 3. Rather than a bit-at-a-time adjustment of the binary
- * result in the hard case, we use floating-point
- * arithmetic to determine the adjustment to within
- * one bit; only in really hard cases do we need to
- * compute a second residual.
- * 4. Because of 3., we don't need a large table of powers of 10
- * for ten-to-e (just some small tables, e.g. of 10^k
- * for 0 <= k <= 22).
- */
-
-/*
- * #define IEEE_8087 for IEEE-arithmetic machines where the least
- * significant byte has the lowest address.
- * #define IEEE_MC68k for IEEE-arithmetic machines where the most
- * significant byte has the lowest address.
- * #define IEEE_ARM for IEEE-arithmetic machines where the two words
- * in a double are stored in big endian order but the two shorts
- * in a word are still stored in little endian order.
- * #define Long int on machines with 32-bit ints and 64-bit longs.
- * #define IBM for IBM mainframe-style floating-point arithmetic.
- * #define VAX for VAX-style floating-point arithmetic (D_floating).
- * #define No_leftright to omit left-right logic in fast floating-point
- * computation of dtoa.
- * #define Honor_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
- * and strtod and dtoa should round accordingly.
- * #define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
- * and Honor_FLT_ROUNDS is not #defined.
- * #define RND_PRODQUOT to use rnd_prod and rnd_quot (assembly routines
- * that use extended-precision instructions to compute rounded
- * products and quotients) with IBM.
- * #define ROUND_BIASED for IEEE-format with biased rounding.
- * #define Inaccurate_Divide for IEEE-format with correctly rounded
- * products but inaccurate quotients, e.g., for Intel i860.
- * #define NO_LONG_LONG on machines that do not have a "long long"
- * integer type (of >= 64 bits). On such machines, you can
- * #define Just_16 to store 16 bits per 32-bit Long when doing
- * high-precision integer arithmetic. Whether this speeds things
- * up or slows things down depends on the machine and the number
- * being converted. If long long is available and the name is
- * something other than "long long", #define Llong to be the name,
- * and if "unsigned Llong" does not work as an unsigned version of
- * Llong, #define #ULLong to be the corresponding unsigned type.
- * #define KR_headers for old-style C function headers.
- * #define Bad_float_h if your system lacks a float.h or if it does not
- * define some or all of DBL_DIG, DBL_MAX_10_EXP, DBL_MAX_EXP,
- * FLT_RADIX, FLT_ROUNDS, and DBL_MAX.
- * #define MALLOC your_malloc, where your_malloc(n) acts like malloc(n)
- * if memory is available and otherwise does something you deem
- * appropriate. If MALLOC is undefined, malloc will be invoked
- * directly -- and assumed always to succeed. Similarly, if you
- * want something other than the system's free() to be called to
- * recycle memory acquired from MALLOC, #define FREE to be the
- * name of the alternate routine. (FREE or free is only called in
- * pathological cases, e.g., in a dtoa call after a dtoa return in
- * mode 3 with thousands of digits requested.)
- * #define Omit_Private_Memory to omit logic (added Jan. 1998) for making
- * memory allocations from a private pool of memory when possible.
- * When used, the private pool is PRIVATE_MEM bytes long: 2304 bytes,
- * unless #defined to be a different length. This default length
- * suffices to get rid of MALLOC calls except for unusual cases,
- * such as decimal-to-binary conversion of a very long string of
- * digits. The longest string dtoa can return is about 751 bytes
- * long. For conversions by strtod of strings of 800 digits and
- * all dtoa conversions in single-threaded executions with 8-byte
- * pointers, PRIVATE_MEM >= 7400 appears to suffice; with 4-byte
- * pointers, PRIVATE_MEM >= 7112 appears adequate.
- * #define INFNAN_CHECK on IEEE systems to cause strtod to check for
- * Infinity and NaN (case insensitively). On some systems (e.g.,
- * some HP systems), it may be necessary to #define NAN_WORD0
- * appropriately -- to the most significant word of a quiet NaN.
- * (On HP Series 700/800 machines, -DNAN_WORD0=0x7ff40000 works.)
- * When INFNAN_CHECK is #defined and No_Hex_NaN is not #defined,
- * strtod also accepts (case insensitively) strings of the form
- * NaN(x), where x is a string of hexadecimal digits and spaces;
- * if there is only one string of hexadecimal digits, it is taken
- * for the 52 fraction bits of the resulting NaN; if there are two
- * or more strings of hex digits, the first is for the high 20 bits,
- * the second and subsequent for the low 32 bits, with intervening
- * white space ignored; but if this results in none of the 52
- * fraction bits being on (an IEEE Infinity symbol), then NAN_WORD0
- * and NAN_WORD1 are used instead.
- * #define MULTIPLE_THREADS if the system offers preemptively scheduled
- * multiple threads. In this case, you must provide (or suitably
- * #define) two locks, acquired by ACQUIRE_DTOA_LOCK(n) and freed
- * by FREE_DTOA_LOCK(n) for n = 0 or 1. (The second lock, accessed
- * in pow5mult, ensures lazy evaluation of only one copy of high
- * powers of 5; omitting this lock would introduce a small
- * probability of wasting memory, but would otherwise be harmless.)
- * You must also invoke freedtoa(s) to free the value s returned by
- * dtoa. You may do so whether or not MULTIPLE_THREADS is #defined.
- * #define NO_IEEE_Scale to disable new (Feb. 1997) logic in strtod that
- * avoids underflows on inputs whose result does not underflow.
- * If you #define NO_IEEE_Scale on a machine that uses IEEE-format
- * floating-point numbers and flushes underflows to zero rather
- * than implementing gradual underflow, then you must also #define
- * Sudden_Underflow.
- * #define USE_LOCALE to use the current locale's decimal_point value.
- * #define SET_INEXACT if IEEE arithmetic is being used and extra
- * computation should be done to set the inexact flag when the
- * result is inexact and avoid setting inexact when the result
- * is exact. In this case, dtoa.c must be compiled in
- * an environment, perhaps provided by #include "dtoa.c" in a
- * suitable wrapper, that defines two functions,
- * int get_inexact(void);
- * void clear_inexact(void);
- * such that get_inexact() returns a nonzero value if the
- * inexact bit is already set, and clear_inexact() sets the
- * inexact bit to 0. When SET_INEXACT is #defined, strtod
- * also does extra computations to set the underflow and overflow
- * flags when appropriate (i.e., when the result is tiny and
- * inexact or when it is a numeric value rounded to +-infinity).
- * #define NO_ERRNO if strtod should not assign errno = ERANGE when
- * the result overflows to +-Infinity or underflows to 0.
- */
-
-#ifndef Long
-#define Long long
-#endif
-#ifndef ULong
-typedef unsigned Long ULong;
-#endif
-
-#ifdef DEBUG
-#include "stdio.h"
-#define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
-#endif
-
-#include "stdlib.h"
-#include "string.h"
-
-#ifdef USE_LOCALE
-#include "locale.h"
-#endif
-
-#ifdef MALLOC
-#ifdef KR_headers
-extern char *MALLOC();
-#else
-extern void *MALLOC(size_t);
-#endif
-#else
-#define MALLOC malloc
-#endif
-
-#ifndef Omit_Private_Memory
-#ifndef PRIVATE_MEM
-#define PRIVATE_MEM 2304
-#endif
-#define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))
-static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
-#endif
-
-#undef IEEE_Arith
-#undef Avoid_Underflow
-#ifdef IEEE_MC68k
-#define IEEE_Arith
-#endif
-#ifdef IEEE_8087
-#define IEEE_Arith
-#endif
-#ifdef IEEE_ARM
-#define IEEE_Arith
-#endif
-
-#include "errno.h"
-
-#ifdef Bad_float_h
-
-#ifdef IEEE_Arith
-#define DBL_DIG 15
-#define DBL_MAX_10_EXP 308
-#define DBL_MAX_EXP 1024
-#define FLT_RADIX 2
-#endif /*IEEE_Arith*/
-
-#ifdef IBM
-#define DBL_DIG 16
-#define DBL_MAX_10_EXP 75
-#define DBL_MAX_EXP 63
-#define FLT_RADIX 16
-#define DBL_MAX 7.2370055773322621e+75
-#endif
-
-#ifdef VAX
-#define DBL_DIG 16
-#define DBL_MAX_10_EXP 38
-#define DBL_MAX_EXP 127
-#define FLT_RADIX 2
-#define DBL_MAX 1.7014118346046923e+38
-#endif
-
-#ifndef LONG_MAX
-#define LONG_MAX 2147483647
-#endif
-
-#else /* ifndef Bad_float_h */
-#include "float.h"
-/*
- * MacOS 10.2 defines the macro FLT_ROUNDS to an internal function
- * which does not exist on 10.1. We can safely #define it to 1 here
- * to allow 10.2 builds to run on 10.1, since we can't use fesetround()
- * (which does not exist on 10.1 either).
- */
-#if defined(XP_MACOSX) && (!defined(MAC_OS_X_VERSION_10_2) || \
- MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_2)
-#undef FLT_ROUNDS
-#define FLT_ROUNDS 1
-#endif /* DT < 10.2 */
-#endif /* Bad_float_h */
-
-#ifndef __MATH_H__
-#include "math.h"
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef CONST
-#ifdef KR_headers
-#define CONST /* blank */
-#else
-#define CONST const
-#endif
-#endif
-
-#if defined(IEEE_8087) + defined(IEEE_MC68k) + defined(IEEE_ARM) + defined(VAX) + defined(IBM) != 1
-Exactly one of IEEE_8087, IEEE_MC68k, IEEE_ARM, VAX, or IBM should be defined.
-#endif
-
-typedef union { double d; ULong L[2]; } U;
-
-#define dval(x) (x).d
-#ifdef IEEE_8087
-#define word0(x) (x).L[1]
-#define word1(x) (x).L[0]
-#else
-#define word0(x) (x).L[0]
-#define word1(x) (x).L[1]
-#endif
-
-/* The following definition of Storeinc is appropriate for MIPS processors.
- * An alternative that might be better on some machines is
- * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
- */
-#if defined(IEEE_8087) + defined(IEEE_ARM) + defined(VAX)
-#define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \
-((unsigned short *)a)[0] = (unsigned short)c, a++)
-#else
-#define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \
-((unsigned short *)a)[1] = (unsigned short)c, a++)
-#endif
-
-/* #define P DBL_MANT_DIG */
-/* Ten_pmax = floor(P*log(2)/log(5)) */
-/* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
-/* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
-/* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
-
-#ifdef IEEE_Arith
-#define Exp_shift 20
-#define Exp_shift1 20
-#define Exp_msk1 0x100000
-#define Exp_msk11 0x100000
-#define Exp_mask 0x7ff00000
-#define P 53
-#define Bias 1023
-#define Emin (-1022)
-#define Exp_1 0x3ff00000
-#define Exp_11 0x3ff00000
-#define Ebits 11
-#define Frac_mask 0xfffff
-#define Frac_mask1 0xfffff
-#define Ten_pmax 22
-#define Bletch 0x10
-#define Bndry_mask 0xfffff
-#define Bndry_mask1 0xfffff
-#define LSB 1
-#define Sign_bit 0x80000000
-#define Log2P 1
-#define Tiny0 0
-#define Tiny1 1
-#define Quick_max 14
-#define Int_max 14
-#ifndef NO_IEEE_Scale
-#define Avoid_Underflow
-#ifdef Flush_Denorm /* debugging option */
-#undef Sudden_Underflow
-#endif
-#endif
-
-#ifndef Flt_Rounds
-#ifdef FLT_ROUNDS
-#define Flt_Rounds FLT_ROUNDS
-#else
-#define Flt_Rounds 1
-#endif
-#endif /*Flt_Rounds*/
-
-#ifdef Honor_FLT_ROUNDS
-#define Rounding rounding
-#undef Check_FLT_ROUNDS
-#define Check_FLT_ROUNDS
-#else
-#define Rounding Flt_Rounds
-#endif
-
-#else /* ifndef IEEE_Arith */
-#undef Check_FLT_ROUNDS
-#undef Honor_FLT_ROUNDS
-#undef SET_INEXACT
-#undef Sudden_Underflow
-#define Sudden_Underflow
-#ifdef IBM
-#undef Flt_Rounds
-#define Flt_Rounds 0
-#define Exp_shift 24
-#define Exp_shift1 24
-#define Exp_msk1 0x1000000
-#define Exp_msk11 0x1000000
-#define Exp_mask 0x7f000000
-#define P 14
-#define Bias 65
-#define Exp_1 0x41000000
-#define Exp_11 0x41000000
-#define Ebits 8 /* exponent has 7 bits, but 8 is the right value in b2d */
-#define Frac_mask 0xffffff
-#define Frac_mask1 0xffffff
-#define Bletch 4
-#define Ten_pmax 22
-#define Bndry_mask 0xefffff
-#define Bndry_mask1 0xffffff
-#define LSB 1
-#define Sign_bit 0x80000000
-#define Log2P 4
-#define Tiny0 0x100000
-#define Tiny1 0
-#define Quick_max 14
-#define Int_max 15
-#else /* VAX */
-#undef Flt_Rounds
-#define Flt_Rounds 1
-#define Exp_shift 23
-#define Exp_shift1 7
-#define Exp_msk1 0x80
-#define Exp_msk11 0x800000
-#define Exp_mask 0x7f80
-#define P 56
-#define Bias 129
-#define Exp_1 0x40800000
-#define Exp_11 0x4080
-#define Ebits 8
-#define Frac_mask 0x7fffff
-#define Frac_mask1 0xffff007f
-#define Ten_pmax 24
-#define Bletch 2
-#define Bndry_mask 0xffff007f
-#define Bndry_mask1 0xffff007f
-#define LSB 0x10000
-#define Sign_bit 0x8000
-#define Log2P 1
-#define Tiny0 0x80
-#define Tiny1 0
-#define Quick_max 15
-#define Int_max 15
-#endif /* IBM, VAX */
-#endif /* IEEE_Arith */
-
-#ifndef IEEE_Arith
-#define ROUND_BIASED
-#endif
-
-#ifdef RND_PRODQUOT
-#define rounded_product(a,b) a = rnd_prod(a, b)
-#define rounded_quotient(a,b) a = rnd_quot(a, b)
-#ifdef KR_headers
-extern double rnd_prod(), rnd_quot();
-#else
-extern double rnd_prod(double, double), rnd_quot(double, double);
-#endif
-#else
-#define rounded_product(a,b) a *= b
-#define rounded_quotient(a,b) a /= b
-#endif
-
-#define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
-#define Big1 0xffffffff
-
-#ifndef Pack_32
-#define Pack_32
-#endif
-
-#ifdef KR_headers
-#define FFFFFFFF ((((unsigned long)0xffff)<<16)|(unsigned long)0xffff)
-#else
-#define FFFFFFFF 0xffffffffUL
-#endif
-
-#ifdef NO_LONG_LONG
-#undef ULLong
-#ifdef Just_16
-#undef Pack_32
-/* When Pack_32 is not defined, we store 16 bits per 32-bit Long.
- * This makes some inner loops simpler and sometimes saves work
- * during multiplications, but it often seems to make things slightly
- * slower. Hence the default is now to store 32 bits per Long.
- */
-#endif
-#else /* long long available */
-#ifndef Llong
-#define Llong long long
-#endif
-#ifndef ULLong
-#define ULLong unsigned Llong
-#endif
-#endif /* NO_LONG_LONG */
-
-#ifndef MULTIPLE_THREADS
-#define ACQUIRE_DTOA_LOCK(n) /*nothing*/
-#define FREE_DTOA_LOCK(n) /*nothing*/
-#endif
-
-#define Kmax 7
-
- struct
-Bigint {
- struct Bigint *next;
- int k, maxwds, sign, wds;
- ULong x[1];
- };
-
- typedef struct Bigint Bigint;
-
- static Bigint *freelist[Kmax+1];
-
- static Bigint *
-Balloc
-#ifdef KR_headers
- (k) int k;
-#else
- (int k)
-#endif
-{
- int x;
- Bigint *rv;
-#ifndef Omit_Private_Memory
- unsigned int len;
-#endif
-
- ACQUIRE_DTOA_LOCK(0);
- /* The k > Kmax case does not need ACQUIRE_DTOA_LOCK(0), */
- /* but this case seems very unlikely. */
- if (k <= Kmax && (rv = freelist[k]))
- freelist[k] = rv->next;
- else {
- x = 1 << k;
-#ifdef Omit_Private_Memory
- rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong));
-#else
- len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
- /sizeof(double);
- if (k <= Kmax && pmem_next - private_mem + len <= PRIVATE_mem) {
- rv = (Bigint*)pmem_next;
- pmem_next += len;
- }
- else
- rv = (Bigint*)MALLOC(len*sizeof(double));
-#endif
- rv->k = k;
- rv->maxwds = x;
- }
- FREE_DTOA_LOCK(0);
- rv->sign = rv->wds = 0;
- return rv;
- }
-
- static void
-Bfree
-#ifdef KR_headers
- (v) Bigint *v;
-#else
- (Bigint *v)
-#endif
-{
- if (v) {
- if (v->k > Kmax)
-#ifdef FREE
- FREE((void*)v);
-#else
- free((void*)v);
-#endif
- else {
- ACQUIRE_DTOA_LOCK(0);
- v->next = freelist[v->k];
- freelist[v->k] = v;
- FREE_DTOA_LOCK(0);
- }
- }
- }
-
-#define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
-y->wds*sizeof(Long) + 2*sizeof(int))
-
- static Bigint *
-multadd
-#ifdef KR_headers
- (b, m, a) Bigint *b; int m, a;
-#else
- (Bigint *b, int m, int a) /* multiply by m and add a */
-#endif
-{
- int i, wds;
-#ifdef ULLong
- ULong *x;
- ULLong carry, y;
-#else
- ULong carry, *x, y;
-#ifdef Pack_32
- ULong xi, z;
-#endif
-#endif
- Bigint *b1;
-
- wds = b->wds;
- x = b->x;
- i = 0;
- carry = a;
- do {
-#ifdef ULLong
- y = *x * (ULLong)m + carry;
- carry = y >> 32;
- *x++ = y & FFFFFFFF;
-#else
-#ifdef Pack_32
- xi = *x;
- y = (xi & 0xffff) * m + carry;
- z = (xi >> 16) * m + (y >> 16);
- carry = z >> 16;
- *x++ = (z << 16) + (y & 0xffff);
-#else
- y = *x * m + carry;
- carry = y >> 16;
- *x++ = y & 0xffff;
-#endif
-#endif
- }
- while(++i < wds);
- if (carry) {
- if (wds >= b->maxwds) {
- b1 = Balloc(b->k+1);
- Bcopy(b1, b);
- Bfree(b);
- b = b1;
- }
- b->x[wds++] = carry;
- b->wds = wds;
- }
- return b;
- }
-
- static Bigint *
-s2b
-#ifdef KR_headers
- (s, nd0, nd, y9) CONST char *s; int nd0, nd; ULong y9;
-#else
- (CONST char *s, int nd0, int nd, ULong y9)
-#endif
-{
- Bigint *b;
- int i, k;
- Long x, y;
-
- x = (nd + 8) / 9;
- for(k = 0, y = 1; x > y; y <<= 1, k++) ;
-#ifdef Pack_32
- b = Balloc(k);
- b->x[0] = y9;
- b->wds = 1;
-#else
- b = Balloc(k+1);
- b->x[0] = y9 & 0xffff;
- b->wds = (b->x[1] = y9 >> 16) ? 2 : 1;
-#endif
-
- i = 9;
- if (9 < nd0) {
- s += 9;
- do b = multadd(b, 10, *s++ - '0');
- while(++i < nd0);
- s++;
- }
- else
- s += 10;
- for(; i < nd; i++)
- b = multadd(b, 10, *s++ - '0');
- return b;
- }
-
- static int
-hi0bits
-#ifdef KR_headers
- (x) register ULong x;
-#else
- (register ULong x)
-#endif
-{
-#ifdef PR_HAVE_BUILTIN_BITSCAN32
- return( (!x) ? 32 : pr_bitscan_clz32(x) );
-#else
- register int k = 0;
-
- if (!(x & 0xffff0000)) {
- k = 16;
- x <<= 16;
- }
- if (!(x & 0xff000000)) {
- k += 8;
- x <<= 8;
- }
- if (!(x & 0xf0000000)) {
- k += 4;
- x <<= 4;
- }
- if (!(x & 0xc0000000)) {
- k += 2;
- x <<= 2;
- }
- if (!(x & 0x80000000)) {
- k++;
- if (!(x & 0x40000000))
- return 32;
- }
- return k;
-#endif /* PR_HAVE_BUILTIN_BITSCAN32 */
- }
-
- static int
-lo0bits
-#ifdef KR_headers
- (y) ULong *y;
-#else
- (ULong *y)
-#endif
-{
-#ifdef PR_HAVE_BUILTIN_BITSCAN32
- int k;
- ULong x = *y;
-
- if (x>1)
- *y = ( x >> (k = pr_bitscan_ctz32(x)) );
- else
- k = ((x ^ 1) << 5);
-#else
- register int k;
- register ULong x = *y;
-
- if (x & 7) {
- if (x & 1)
- return 0;
- if (x & 2) {
- *y = x >> 1;
- return 1;
- }
- *y = x >> 2;
- return 2;
- }
- k = 0;
- if (!(x & 0xffff)) {
- k = 16;
- x >>= 16;
- }
- if (!(x & 0xff)) {
- k += 8;
- x >>= 8;
- }
- if (!(x & 0xf)) {
- k += 4;
- x >>= 4;
- }
- if (!(x & 0x3)) {
- k += 2;
- x >>= 2;
- }
- if (!(x & 1)) {
- k++;
- x >>= 1;
- if (!x)
- return 32;
- }
- *y = x;
-#endif /* PR_HAVE_BUILTIN_BITSCAN32 */
- return k;
- }
-
- static Bigint *
-i2b
-#ifdef KR_headers
- (i) int i;
-#else
- (int i)
-#endif
-{
- Bigint *b;
-
- b = Balloc(1);
- b->x[0] = i;
- b->wds = 1;
- return b;
- }
-
- static Bigint *
-mult
-#ifdef KR_headers
- (a, b) Bigint *a, *b;
-#else
- (Bigint *a, Bigint *b)
-#endif
-{
- Bigint *c;
- int k, wa, wb, wc;
- ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
- ULong y;
-#ifdef ULLong
- ULLong carry, z;
-#else
- ULong carry, z;
-#ifdef Pack_32
- ULong z2;
-#endif
-#endif
-
- if (a->wds < b->wds) {
- c = a;
- a = b;
- b = c;
- }
- k = a->k;
- wa = a->wds;
- wb = b->wds;
- wc = wa + wb;
- if (wc > a->maxwds)
- k++;
- c = Balloc(k);
- for(x = c->x, xa = x + wc; x < xa; x++)
- *x = 0;
- xa = a->x;
- xae = xa + wa;
- xb = b->x;
- xbe = xb + wb;
- xc0 = c->x;
-#ifdef ULLong
- for(; xb < xbe; xc0++) {
- if (y = *xb++) {
- x = xa;
- xc = xc0;
- carry = 0;
- do {
- z = *x++ * (ULLong)y + *xc + carry;
- carry = z >> 32;
- *xc++ = z & FFFFFFFF;
- }
- while(x < xae);
- *xc = carry;
- }
- }
-#else
-#ifdef Pack_32
- for(; xb < xbe; xb++, xc0++) {
- if (y = *xb & 0xffff) {
- x = xa;
- xc = xc0;
- carry = 0;
- do {
- z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
- carry = z >> 16;
- z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
- carry = z2 >> 16;
- Storeinc(xc, z2, z);
- }
- while(x < xae);
- *xc = carry;
- }
- if (y = *xb >> 16) {
- x = xa;
- xc = xc0;
- carry = 0;
- z2 = *xc;
- do {
- z = (*x & 0xffff) * y + (*xc >> 16) + carry;
- carry = z >> 16;
- Storeinc(xc, z, z2);
- z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
- carry = z2 >> 16;
- }
- while(x < xae);
- *xc = z2;
- }
- }
-#else
- for(; xb < xbe; xc0++) {
- if (y = *xb++) {
- x = xa;
- xc = xc0;
- carry = 0;
- do {
- z = *x++ * y + *xc + carry;
- carry = z >> 16;
- *xc++ = z & 0xffff;
- }
- while(x < xae);
- *xc = carry;
- }
- }
-#endif
-#endif
- for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
- c->wds = wc;
- return c;
- }
-
- static Bigint *p5s;
-
- static Bigint *
-pow5mult
-#ifdef KR_headers
- (b, k) Bigint *b; int k;
-#else
- (Bigint *b, int k)
-#endif
-{
- Bigint *b1, *p5, *p51;
- int i;
- static int p05[3] = { 5, 25, 125 };
-
- if (i = k & 3)
- b = multadd(b, p05[i-1], 0);
-
- if (!(k >>= 2))
- return b;
- if (!(p5 = p5s)) {
- /* first time */
-#ifdef MULTIPLE_THREADS
- ACQUIRE_DTOA_LOCK(1);
- if (!(p5 = p5s)) {
- p5 = p5s = i2b(625);
- p5->next = 0;
- }
- FREE_DTOA_LOCK(1);
-#else
- p5 = p5s = i2b(625);
- p5->next = 0;
-#endif
- }
- for(;;) {
- if (k & 1) {
- b1 = mult(b, p5);
- Bfree(b);
- b = b1;
- }
- if (!(k >>= 1))
- break;
- if (!(p51 = p5->next)) {
-#ifdef MULTIPLE_THREADS
- ACQUIRE_DTOA_LOCK(1);
- if (!(p51 = p5->next)) {
- p51 = p5->next = mult(p5,p5);
- p51->next = 0;
- }
- FREE_DTOA_LOCK(1);
-#else
- p51 = p5->next = mult(p5,p5);
- p51->next = 0;
-#endif
- }
- p5 = p51;
- }
- return b;
- }
-
- static Bigint *
-lshift
-#ifdef KR_headers
- (b, k) Bigint *b; int k;
-#else
- (Bigint *b, int k)
-#endif
-{
- int i, k1, n, n1;
- Bigint *b1;
- ULong *x, *x1, *xe, z;
-
-#ifdef Pack_32
- n = k >> 5;
-#else
- n = k >> 4;
-#endif
- k1 = b->k;
- n1 = n + b->wds + 1;
- for(i = b->maxwds; n1 > i; i <<= 1)
- k1++;
- b1 = Balloc(k1);
- x1 = b1->x;
- for(i = 0; i < n; i++)
- *x1++ = 0;
- x = b->x;
- xe = x + b->wds;
-#ifdef Pack_32
- if (k &= 0x1f) {
- k1 = 32 - k;
- z = 0;
- do {
- *x1++ = *x << k | z;
- z = *x++ >> k1;
- }
- while(x < xe);
- if (*x1 = z)
- ++n1;
- }
-#else
- if (k &= 0xf) {
- k1 = 16 - k;
- z = 0;
- do {
- *x1++ = *x << k & 0xffff | z;
- z = *x++ >> k1;
- }
- while(x < xe);
- if (*x1 = z)
- ++n1;
- }
-#endif
- else do
- *x1++ = *x++;
- while(x < xe);
- b1->wds = n1 - 1;
- Bfree(b);
- return b1;
- }
-
- static int
-cmp
-#ifdef KR_headers
- (a, b) Bigint *a, *b;
-#else
- (Bigint *a, Bigint *b)
-#endif
-{
- ULong *xa, *xa0, *xb, *xb0;
- int i, j;
-
- i = a->wds;
- j = b->wds;
-#ifdef DEBUG
- if (i > 1 && !a->x[i-1])
- Bug("cmp called with a->x[a->wds-1] == 0");
- if (j > 1 && !b->x[j-1])
- Bug("cmp called with b->x[b->wds-1] == 0");
-#endif
- if (i -= j)
- return i;
- xa0 = a->x;
- xa = xa0 + j;
- xb0 = b->x;
- xb = xb0 + j;
- for(;;) {
- if (*--xa != *--xb)
- return *xa < *xb ? -1 : 1;
- if (xa <= xa0)
- break;
- }
- return 0;
- }
-
- static Bigint *
-diff
-#ifdef KR_headers
- (a, b) Bigint *a, *b;
-#else
- (Bigint *a, Bigint *b)
-#endif
-{
- Bigint *c;
- int i, wa, wb;
- ULong *xa, *xae, *xb, *xbe, *xc;
-#ifdef ULLong
- ULLong borrow, y;
-#else
- ULong borrow, y;
-#ifdef Pack_32
- ULong z;
-#endif
-#endif
-
- i = cmp(a,b);
- if (!i) {
- c = Balloc(0);
- c->wds = 1;
- c->x[0] = 0;
- return c;
- }
- if (i < 0) {
- c = a;
- a = b;
- b = c;
- i = 1;
- }
- else
- i = 0;
- c = Balloc(a->k);
- c->sign = i;
- wa = a->wds;
- xa = a->x;
- xae = xa + wa;
- wb = b->wds;
- xb = b->x;
- xbe = xb + wb;
- xc = c->x;
- borrow = 0;
-#ifdef ULLong
- do {
- y = (ULLong)*xa++ - *xb++ - borrow;
- borrow = y >> 32 & (ULong)1;
- *xc++ = y & FFFFFFFF;
- }
- while(xb < xbe);
- while(xa < xae) {
- y = *xa++ - borrow;
- borrow = y >> 32 & (ULong)1;
- *xc++ = y & FFFFFFFF;
- }
-#else
-#ifdef Pack_32
- do {
- y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
- borrow = (y & 0x10000) >> 16;
- z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
- borrow = (z & 0x10000) >> 16;
- Storeinc(xc, z, y);
- }
- while(xb < xbe);
- while(xa < xae) {
- y = (*xa & 0xffff) - borrow;
- borrow = (y & 0x10000) >> 16;
- z = (*xa++ >> 16) - borrow;
- borrow = (z & 0x10000) >> 16;
- Storeinc(xc, z, y);
- }
-#else
- do {
- y = *xa++ - *xb++ - borrow;
- borrow = (y & 0x10000) >> 16;
- *xc++ = y & 0xffff;
- }
- while(xb < xbe);
- while(xa < xae) {
- y = *xa++ - borrow;
- borrow = (y & 0x10000) >> 16;
- *xc++ = y & 0xffff;
- }
-#endif
-#endif
- while(!*--xc)
- wa--;
- c->wds = wa;
- return c;
- }
-
- static double
-ulp
-#ifdef KR_headers
- (dx) double dx;
-#else
- (double dx)
-#endif
-{
- register Long L;
- U x, a;
-
- dval(x) = dx;
- L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
-#ifndef Avoid_Underflow
-#ifndef Sudden_Underflow
- if (L > 0) {
-#endif
-#endif
-#ifdef IBM
- L |= Exp_msk1 >> 4;
-#endif
- word0(a) = L;
- word1(a) = 0;
-#ifndef Avoid_Underflow
-#ifndef Sudden_Underflow
- }
- else {
- L = -L >> Exp_shift;
- if (L < Exp_shift) {
- word0(a) = 0x80000 >> L;
- word1(a) = 0;
- }
- else {
- word0(a) = 0;
- L -= Exp_shift;
- word1(a) = L >= 31 ? 1 : 1 << 31 - L;
- }
- }
-#endif
-#endif
- return dval(a);
- }
-
- static double
-b2d
-#ifdef KR_headers
- (a, e) Bigint *a; int *e;
-#else
- (Bigint *a, int *e)
-#endif
-{
- ULong *xa, *xa0, w, y, z;
- int k;
- U d;
-#ifdef VAX
- ULong d0, d1;
-#else
-#define d0 word0(d)
-#define d1 word1(d)
-#endif
-
- xa0 = a->x;
- xa = xa0 + a->wds;
- y = *--xa;
-#ifdef DEBUG
- if (!y) Bug("zero y in b2d");
-#endif
- k = hi0bits(y);
- *e = 32 - k;
-#ifdef Pack_32
- if (k < Ebits) {
- d0 = Exp_1 | y >> Ebits - k;
- w = xa > xa0 ? *--xa : 0;
- d1 = y << (32-Ebits) + k | w >> Ebits - k;
- goto ret_d;
- }
- z = xa > xa0 ? *--xa : 0;
- if (k -= Ebits) {
- d0 = Exp_1 | y << k | z >> 32 - k;
- y = xa > xa0 ? *--xa : 0;
- d1 = z << k | y >> 32 - k;
- }
- else {
- d0 = Exp_1 | y;
- d1 = z;
- }
-#else
- if (k < Ebits + 16) {
- z = xa > xa0 ? *--xa : 0;
- d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
- w = xa > xa0 ? *--xa : 0;
- y = xa > xa0 ? *--xa : 0;
- d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
- goto ret_d;
- }
- z = xa > xa0 ? *--xa : 0;
- w = xa > xa0 ? *--xa : 0;
- k -= Ebits + 16;
- d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
- y = xa > xa0 ? *--xa : 0;
- d1 = w << k + 16 | y << k;
-#endif
- ret_d:
-#ifdef VAX
- word0(d) = d0 >> 16 | d0 << 16;
- word1(d) = d1 >> 16 | d1 << 16;
-#else
-#undef d0
-#undef d1
-#endif
- return dval(d);
- }
-
- static Bigint *
-d2b
-#ifdef KR_headers
- (dd, e, bits) double dd; int *e, *bits;
-#else
- (double dd, int *e, int *bits)
-#endif
-{
- U d;
- Bigint *b;
- int de, k;
- ULong *x, y, z;
-#ifndef Sudden_Underflow
- int i;
-#endif
-#ifdef VAX
- ULong d0, d1;
-#endif
-
- dval(d) = dd;
-#ifdef VAX
- d0 = word0(d) >> 16 | word0(d) << 16;
- d1 = word1(d) >> 16 | word1(d) << 16;
-#else
-#define d0 word0(d)
-#define d1 word1(d)
-#endif
-
-#ifdef Pack_32
- b = Balloc(1);
-#else
- b = Balloc(2);
-#endif
- x = b->x;
-
- z = d0 & Frac_mask;
- d0 &= 0x7fffffff; /* clear sign bit, which we ignore */
-#ifdef Sudden_Underflow
- de = (int)(d0 >> Exp_shift);
-#ifndef IBM
- z |= Exp_msk11;
-#endif
-#else
- if (de = (int)(d0 >> Exp_shift))
- z |= Exp_msk1;
-#endif
-#ifdef Pack_32
- if (y = d1) {
- if (k = lo0bits(&y)) {
- x[0] = y | z << 32 - k;
- z >>= k;
- }
- else
- x[0] = y;
-#ifndef Sudden_Underflow
- i =
-#endif
- b->wds = (x[1] = z) ? 2 : 1;
- }
- else {
- k = lo0bits(&z);
- x[0] = z;
-#ifndef Sudden_Underflow
- i =
-#endif
- b->wds = 1;
- k += 32;
- }
-#else
- if (y = d1) {
- if (k = lo0bits(&y))
- if (k >= 16) {
- x[0] = y | z << 32 - k & 0xffff;
- x[1] = z >> k - 16 & 0xffff;
- x[2] = z >> k;
- i = 2;
- }
- else {
- x[0] = y & 0xffff;
- x[1] = y >> 16 | z << 16 - k & 0xffff;
- x[2] = z >> k & 0xffff;
- x[3] = z >> k+16;
- i = 3;
- }
- else {
- x[0] = y & 0xffff;
- x[1] = y >> 16;
- x[2] = z & 0xffff;
- x[3] = z >> 16;
- i = 3;
- }
- }
- else {
-#ifdef DEBUG
- if (!z)
- Bug("Zero passed to d2b");
-#endif
- k = lo0bits(&z);
- if (k >= 16) {
- x[0] = z;
- i = 0;
- }
- else {
- x[0] = z & 0xffff;
- x[1] = z >> 16;
- i = 1;
- }
- k += 32;
- }
- while(!x[i])
- --i;
- b->wds = i + 1;
-#endif
-#ifndef Sudden_Underflow
- if (de) {
-#endif
-#ifdef IBM
- *e = (de - Bias - (P-1) << 2) + k;
- *bits = 4*P + 8 - k - hi0bits(word0(d) & Frac_mask);
-#else
- *e = de - Bias - (P-1) + k;
- *bits = P - k;
-#endif
-#ifndef Sudden_Underflow
- }
- else {
- *e = de - Bias - (P-1) + 1 + k;
-#ifdef Pack_32
- *bits = 32*i - hi0bits(x[i-1]);
-#else
- *bits = (i+2)*16 - hi0bits(x[i]);
-#endif
- }
-#endif
- return b;
- }
-#undef d0
-#undef d1
-
- static double
-ratio
-#ifdef KR_headers
- (a, b) Bigint *a, *b;
-#else
- (Bigint *a, Bigint *b)
-#endif
-{
- U da, db;
- int k, ka, kb;
-
- dval(da) = b2d(a, &ka);
- dval(db) = b2d(b, &kb);
-#ifdef Pack_32
- k = ka - kb + 32*(a->wds - b->wds);
-#else
- k = ka - kb + 16*(a->wds - b->wds);
-#endif
-#ifdef IBM
- if (k > 0) {
- word0(da) += (k >> 2)*Exp_msk1;
- if (k &= 3)
- dval(da) *= 1 << k;
- }
- else {
- k = -k;
- word0(db) += (k >> 2)*Exp_msk1;
- if (k &= 3)
- dval(db) *= 1 << k;
- }
-#else
- if (k > 0)
- word0(da) += k*Exp_msk1;
- else {
- k = -k;
- word0(db) += k*Exp_msk1;
- }
-#endif
- return dval(da) / dval(db);
- }
-
- static CONST double
-tens[] = {
- 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
- 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
- 1e20, 1e21, 1e22
-#ifdef VAX
- , 1e23, 1e24
-#endif
- };
-
- static CONST double
-#ifdef IEEE_Arith
-bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
-static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
-#ifdef Avoid_Underflow
- 9007199254740992.*9007199254740992.e-256
- /* = 2^106 * 1e-53 */
-#else
- 1e-256
-#endif
- };
-/* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
-/* flag unnecessarily. It leads to a song and dance at the end of strtod. */
-#define Scale_Bit 0x10
-#define n_bigtens 5
-#else
-#ifdef IBM
-bigtens[] = { 1e16, 1e32, 1e64 };
-static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64 };
-#define n_bigtens 3
-#else
-bigtens[] = { 1e16, 1e32 };
-static CONST double tinytens[] = { 1e-16, 1e-32 };
-#define n_bigtens 2
-#endif
-#endif
-
-#ifndef IEEE_Arith
-#undef INFNAN_CHECK
-#endif
-
-#ifdef INFNAN_CHECK
-
-#ifndef NAN_WORD0
-#define NAN_WORD0 0x7ff80000
-#endif
-
-#ifndef NAN_WORD1
-#define NAN_WORD1 0
-#endif
-
- static int
-match
-#ifdef KR_headers
- (sp, t) char **sp, *t;
-#else
- (CONST char **sp, char *t)
-#endif
-{
- int c, d;
- CONST char *s = *sp;
-
- while(d = *t++) {
- if ((c = *++s) >= 'A' && c <= 'Z')
- c += 'a' - 'A';
- if (c != d)
- return 0;
- }
- *sp = s + 1;
- return 1;
- }
-
-#ifndef No_Hex_NaN
- static void
-hexnan
-#ifdef KR_headers
- (rvp, sp) double *rvp; CONST char **sp;
-#else
- (double *rvp, CONST char **sp)
-#endif
-{
- ULong c, x[2];
- CONST char *s;
- int havedig, udx0, xshift;
-
- x[0] = x[1] = 0;
- havedig = xshift = 0;
- udx0 = 1;
- s = *sp;
- while(c = *(CONST unsigned char*)++s) {
- if (c >= '0' && c <= '9')
- c -= '0';
- else if (c >= 'a' && c <= 'f')
- c += 10 - 'a';
- else if (c >= 'A' && c <= 'F')
- c += 10 - 'A';
- else if (c <= ' ') {
- if (udx0 && havedig) {
- udx0 = 0;
- xshift = 1;
- }
- continue;
- }
- else if (/*(*/ c == ')' && havedig) {
- *sp = s + 1;
- break;
- }
- else
- return; /* invalid form: don't change *sp */
- havedig = 1;
- if (xshift) {
- xshift = 0;
- x[0] = x[1];
- x[1] = 0;
- }
- if (udx0)
- x[0] = (x[0] << 4) | (x[1] >> 28);
- x[1] = (x[1] << 4) | c;
- }
- if ((x[0] &= 0xfffff) || x[1]) {
- word0(*rvp) = Exp_mask | x[0];
- word1(*rvp) = x[1];
- }
- }
-#endif /*No_Hex_NaN*/
-#endif /* INFNAN_CHECK */
-
- PR_IMPLEMENT(double)
-PR_strtod
-#ifdef KR_headers
- (s00, se) CONST char *s00; char **se;
-#else
- (CONST char *s00, char **se)
-#endif
-{
-#ifdef Avoid_Underflow
- int scale;
-#endif
- int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, dsign,
- e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
- CONST char *s, *s0, *s1;
- double aadj, aadj1, adj;
- U aadj2, rv, rv0;
- Long L;
- ULong y, z;
- Bigint *bb, *bb1, *bd, *bd0, *bs, *delta;
-#ifdef SET_INEXACT
- int inexact, oldinexact;
-#endif
-#ifdef Honor_FLT_ROUNDS
- int rounding;
-#endif
-#ifdef USE_LOCALE
- CONST char *s2;
-#endif
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- sign = nz0 = nz = 0;
- dval(rv) = 0.;
- for(s = s00;;s++) switch(*s) {
- case '-':
- sign = 1;
- /* no break */
- case '+':
- if (*++s)
- goto break2;
- /* no break */
- case 0:
- goto ret0;
- case '\t':
- case '\n':
- case '\v':
- case '\f':
- case '\r':
- case ' ':
- continue;
- default:
- goto break2;
- }
- break2:
- if (*s == '0') {
- nz0 = 1;
- while(*++s == '0') ;
- if (!*s)
- goto ret;
- }
- s0 = s;
- y = z = 0;
- for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
- if (nd < 9)
- y = 10*y + c - '0';
- else if (nd < 16)
- z = 10*z + c - '0';
- nd0 = nd;
-#ifdef USE_LOCALE
- s1 = localeconv()->decimal_point;
- if (c == *s1) {
- c = '.';
- if (*++s1) {
- s2 = s;
- for(;;) {
- if (*++s2 != *s1) {
- c = 0;
- break;
- }
- if (!*++s1) {
- s = s2;
- break;
- }
- }
- }
- }
-#endif
- if (c == '.') {
- c = *++s;
- if (!nd) {
- for(; c == '0'; c = *++s)
- nz++;
- if (c > '0' && c <= '9') {
- s0 = s;
- nf += nz;
- nz = 0;
- goto have_dig;
- }
- goto dig_done;
- }
- for(; c >= '0' && c <= '9'; c = *++s) {
- have_dig:
- nz++;
- if (c -= '0') {
- nf += nz;
- for(i = 1; i < nz; i++)
- if (nd++ < 9)
- y *= 10;
- else if (nd <= DBL_DIG + 1)
- z *= 10;
- if (nd++ < 9)
- y = 10*y + c;
- else if (nd <= DBL_DIG + 1)
- z = 10*z + c;
- nz = 0;
- }
- }
- }
- dig_done:
- if (nd > 64 * 1024)
- goto ret0;
- e = 0;
- if (c == 'e' || c == 'E') {
- if (!nd && !nz && !nz0) {
- goto ret0;
- }
- s00 = s;
- esign = 0;
- switch(c = *++s) {
- case '-':
- esign = 1;
- case '+':
- c = *++s;
- }
- if (c >= '0' && c <= '9') {
- while(c == '0')
- c = *++s;
- if (c > '0' && c <= '9') {
- L = c - '0';
- s1 = s;
- while((c = *++s) >= '0' && c <= '9')
- L = 10*L + c - '0';
- if (s - s1 > 8 || L > 19999)
- /* Avoid confusion from exponents
- * so large that e might overflow.
- */
- e = 19999; /* safe for 16 bit ints */
- else
- e = (int)L;
- if (esign)
- e = -e;
- }
- else
- e = 0;
- }
- else
- s = s00;
- }
- if (!nd) {
- if (!nz && !nz0) {
-#ifdef INFNAN_CHECK
- /* Check for Nan and Infinity */
- switch(c) {
- case 'i':
- case 'I':
- if (match(&s,"nf")) {
- --s;
- if (!match(&s,"inity"))
- ++s;
- word0(rv) = 0x7ff00000;
- word1(rv) = 0;
- goto ret;
- }
- break;
- case 'n':
- case 'N':
- if (match(&s, "an")) {
- word0(rv) = NAN_WORD0;
- word1(rv) = NAN_WORD1;
-#ifndef No_Hex_NaN
- if (*s == '(') /*)*/
- hexnan(&rv, &s);
-#endif
- goto ret;
- }
- }
-#endif /* INFNAN_CHECK */
- ret0:
- s = s00;
- sign = 0;
- }
- goto ret;
- }
- e1 = e -= nf;
-
- /* Now we have nd0 digits, starting at s0, followed by a
- * decimal point, followed by nd-nd0 digits. The number we're
- * after is the integer represented by those digits times
- * 10**e */
-
- if (!nd0)
- nd0 = nd;
- k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
- dval(rv) = y;
- if (k > 9) {
-#ifdef SET_INEXACT
- if (k > DBL_DIG)
- oldinexact = get_inexact();
-#endif
- dval(rv) = tens[k - 9] * dval(rv) + z;
- }
- bd0 = 0;
- if (nd <= DBL_DIG
-#ifndef RND_PRODQUOT
-#ifndef Honor_FLT_ROUNDS
- && Flt_Rounds == 1
-#endif
-#endif
- ) {
- if (!e)
- goto ret;
- if (e > 0) {
- if (e <= Ten_pmax) {
-#ifdef VAX
- goto vax_ovfl_check;
-#else
-#ifdef Honor_FLT_ROUNDS
- /* round correctly FLT_ROUNDS = 2 or 3 */
- if (sign) {
- rv = -rv;
- sign = 0;
- }
-#endif
- /* rv = */ rounded_product(dval(rv), tens[e]);
- goto ret;
-#endif
- }
- i = DBL_DIG - nd;
- if (e <= Ten_pmax + i) {
- /* A fancier test would sometimes let us do
- * this for larger i values.
- */
-#ifdef Honor_FLT_ROUNDS
- /* round correctly FLT_ROUNDS = 2 or 3 */
- if (sign) {
- rv = -rv;
- sign = 0;
- }
-#endif
- e -= i;
- dval(rv) *= tens[i];
-#ifdef VAX
- /* VAX exponent range is so narrow we must
- * worry about overflow here...
- */
- vax_ovfl_check:
- word0(rv) -= P*Exp_msk1;
- /* rv = */ rounded_product(dval(rv), tens[e]);
- if ((word0(rv) & Exp_mask)
- > Exp_msk1*(DBL_MAX_EXP+Bias-1-P))
- goto ovfl;
- word0(rv) += P*Exp_msk1;
-#else
- /* rv = */ rounded_product(dval(rv), tens[e]);
-#endif
- goto ret;
- }
- }
-#ifndef Inaccurate_Divide
- else if (e >= -Ten_pmax) {
-#ifdef Honor_FLT_ROUNDS
- /* round correctly FLT_ROUNDS = 2 or 3 */
- if (sign) {
- rv = -rv;
- sign = 0;
- }
-#endif
- /* rv = */ rounded_quotient(dval(rv), tens[-e]);
- goto ret;
- }
-#endif
- }
- e1 += nd - k;
-
-#ifdef IEEE_Arith
-#ifdef SET_INEXACT
- inexact = 1;
- if (k <= DBL_DIG)
- oldinexact = get_inexact();
-#endif
-#ifdef Avoid_Underflow
- scale = 0;
-#endif
-#ifdef Honor_FLT_ROUNDS
- if ((rounding = Flt_Rounds) >= 2) {
- if (sign)
- rounding = rounding == 2 ? 0 : 2;
- else
- if (rounding != 2)
- rounding = 0;
- }
-#endif
-#endif /*IEEE_Arith*/
-
- /* Get starting approximation = rv * 10**e1 */
-
- if (e1 > 0) {
- if (i = e1 & 15)
- dval(rv) *= tens[i];
- if (e1 &= ~15) {
- if (e1 > DBL_MAX_10_EXP) {
- ovfl:
-#ifndef NO_ERRNO
- PR_SetError(PR_RANGE_ERROR, 0);
-#endif
- /* Can't trust HUGE_VAL */
-#ifdef IEEE_Arith
-#ifdef Honor_FLT_ROUNDS
- switch(rounding) {
- case 0: /* toward 0 */
- case 3: /* toward -infinity */
- word0(rv) = Big0;
- word1(rv) = Big1;
- break;
- default:
- word0(rv) = Exp_mask;
- word1(rv) = 0;
- }
-#else /*Honor_FLT_ROUNDS*/
- word0(rv) = Exp_mask;
- word1(rv) = 0;
-#endif /*Honor_FLT_ROUNDS*/
-#ifdef SET_INEXACT
- /* set overflow bit */
- dval(rv0) = 1e300;
- dval(rv0) *= dval(rv0);
-#endif
-#else /*IEEE_Arith*/
- word0(rv) = Big0;
- word1(rv) = Big1;
-#endif /*IEEE_Arith*/
- if (bd0)
- goto retfree;
- goto ret;
- }
- e1 >>= 4;
- for(j = 0; e1 > 1; j++, e1 >>= 1)
- if (e1 & 1)
- dval(rv) *= bigtens[j];
- /* The last multiplication could overflow. */
- word0(rv) -= P*Exp_msk1;
- dval(rv) *= bigtens[j];
- if ((z = word0(rv) & Exp_mask)
- > Exp_msk1*(DBL_MAX_EXP+Bias-P))
- goto ovfl;
- if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
- /* set to largest number */
- /* (Can't trust DBL_MAX) */
- word0(rv) = Big0;
- word1(rv) = Big1;
- }
- else
- word0(rv) += P*Exp_msk1;
- }
- }
- else if (e1 < 0) {
- e1 = -e1;
- if (i = e1 & 15)
- dval(rv) /= tens[i];
- if (e1 >>= 4) {
- if (e1 >= 1 << n_bigtens)
- goto undfl;
-#ifdef Avoid_Underflow
- if (e1 & Scale_Bit)
- scale = 2*P;
- for(j = 0; e1 > 0; j++, e1 >>= 1)
- if (e1 & 1)
- dval(rv) *= tinytens[j];
- if (scale && (j = 2*P + 1 - ((word0(rv) & Exp_mask)
- >> Exp_shift)) > 0) {
- /* scaled rv is denormal; zap j low bits */
- if (j >= 32) {
- word1(rv) = 0;
- if (j >= 53)
- word0(rv) = (P+2)*Exp_msk1;
- else
- word0(rv) &= 0xffffffff << j-32;
- }
- else
- word1(rv) &= 0xffffffff << j;
- }
-#else
- for(j = 0; e1 > 1; j++, e1 >>= 1)
- if (e1 & 1)
- dval(rv) *= tinytens[j];
- /* The last multiplication could underflow. */
- dval(rv0) = dval(rv);
- dval(rv) *= tinytens[j];
- if (!dval(rv)) {
- dval(rv) = 2.*dval(rv0);
- dval(rv) *= tinytens[j];
-#endif
- if (!dval(rv)) {
- undfl:
- dval(rv) = 0.;
-#ifndef NO_ERRNO
- PR_SetError(PR_RANGE_ERROR, 0);
-#endif
- if (bd0)
- goto retfree;
- goto ret;
- }
-#ifndef Avoid_Underflow
- word0(rv) = Tiny0;
- word1(rv) = Tiny1;
- /* The refinement below will clean
- * this approximation up.
- */
- }
-#endif
- }
- }
-
- /* Now the hard part -- adjusting rv to the correct value.*/
-
- /* Put digits into bd: true value = bd * 10^e */
-
- bd0 = s2b(s0, nd0, nd, y);
-
- for(;;) {
- bd = Balloc(bd0->k);
- Bcopy(bd, bd0);
- bb = d2b(dval(rv), &bbe, &bbbits); /* rv = bb * 2^bbe */
- bs = i2b(1);
-
- if (e >= 0) {
- bb2 = bb5 = 0;
- bd2 = bd5 = e;
- }
- else {
- bb2 = bb5 = -e;
- bd2 = bd5 = 0;
- }
- if (bbe >= 0)
- bb2 += bbe;
- else
- bd2 -= bbe;
- bs2 = bb2;
-#ifdef Honor_FLT_ROUNDS
- if (rounding != 1)
- bs2++;
-#endif
-#ifdef Avoid_Underflow
- j = bbe - scale;
- i = j + bbbits - 1; /* logb(rv) */
- if (i < Emin) /* denormal */
- j += P - Emin;
- else
- j = P + 1 - bbbits;
-#else /*Avoid_Underflow*/
-#ifdef Sudden_Underflow
-#ifdef IBM
- j = 1 + 4*P - 3 - bbbits + ((bbe + bbbits - 1) & 3);
-#else
- j = P + 1 - bbbits;
-#endif
-#else /*Sudden_Underflow*/
- j = bbe;
- i = j + bbbits - 1; /* logb(rv) */
- if (i < Emin) /* denormal */
- j += P - Emin;
- else
- j = P + 1 - bbbits;
-#endif /*Sudden_Underflow*/
-#endif /*Avoid_Underflow*/
- bb2 += j;
- bd2 += j;
-#ifdef Avoid_Underflow
- bd2 += scale;
-#endif
- i = bb2 < bd2 ? bb2 : bd2;
- if (i > bs2)
- i = bs2;
- if (i > 0) {
- bb2 -= i;
- bd2 -= i;
- bs2 -= i;
- }
- if (bb5 > 0) {
- bs = pow5mult(bs, bb5);
- bb1 = mult(bs, bb);
- Bfree(bb);
- bb = bb1;
- }
- if (bb2 > 0)
- bb = lshift(bb, bb2);
- if (bd5 > 0)
- bd = pow5mult(bd, bd5);
- if (bd2 > 0)
- bd = lshift(bd, bd2);
- if (bs2 > 0)
- bs = lshift(bs, bs2);
- delta = diff(bb, bd);
- dsign = delta->sign;
- delta->sign = 0;
- i = cmp(delta, bs);
-#ifdef Honor_FLT_ROUNDS
- if (rounding != 1) {
- if (i < 0) {
- /* Error is less than an ulp */
- if (!delta->x[0] && delta->wds <= 1) {
- /* exact */
-#ifdef SET_INEXACT
- inexact = 0;
-#endif
- break;
- }
- if (rounding) {
- if (dsign) {
- adj = 1.;
- goto apply_adj;
- }
- }
- else if (!dsign) {
- adj = -1.;
- if (!word1(rv)
- && !(word0(rv) & Frac_mask)) {
- y = word0(rv) & Exp_mask;
-#ifdef Avoid_Underflow
- if (!scale || y > 2*P*Exp_msk1)
-#else
- if (y)
-#endif
- {
- delta = lshift(delta,Log2P);
- if (cmp(delta, bs) <= 0)
- adj = -0.5;
- }
- }
- apply_adj:
-#ifdef Avoid_Underflow
- if (scale && (y = word0(rv) & Exp_mask)
- <= 2*P*Exp_msk1)
- word0(adj) += (2*P+1)*Exp_msk1 - y;
-#else
-#ifdef Sudden_Underflow
- if ((word0(rv) & Exp_mask) <=
- P*Exp_msk1) {
- word0(rv) += P*Exp_msk1;
- dval(rv) += adj*ulp(dval(rv));
- word0(rv) -= P*Exp_msk1;
- }
- else
-#endif /*Sudden_Underflow*/
-#endif /*Avoid_Underflow*/
- dval(rv) += adj*ulp(dval(rv));
- }
- break;
- }
- adj = ratio(delta, bs);
- if (adj < 1.)
- adj = 1.;
- if (adj <= 0x7ffffffe) {
- /* adj = rounding ? ceil(adj) : floor(adj); */
- y = adj;
- if (y != adj) {
- if (!((rounding>>1) ^ dsign))
- y++;
- adj = y;
- }
- }
-#ifdef Avoid_Underflow
- if (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
- word0(adj) += (2*P+1)*Exp_msk1 - y;
-#else
-#ifdef Sudden_Underflow
- if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
- word0(rv) += P*Exp_msk1;
- adj *= ulp(dval(rv));
- if (dsign)
- dval(rv) += adj;
- else
- dval(rv) -= adj;
- word0(rv) -= P*Exp_msk1;
- goto cont;
- }
-#endif /*Sudden_Underflow*/
-#endif /*Avoid_Underflow*/
- adj *= ulp(dval(rv));
- if (dsign)
- dval(rv) += adj;
- else
- dval(rv) -= adj;
- goto cont;
- }
-#endif /*Honor_FLT_ROUNDS*/
-
- if (i < 0) {
- /* Error is less than half an ulp -- check for
- * special case of mantissa a power of two.
- */
- if (dsign || word1(rv) || word0(rv) & Bndry_mask
-#ifdef IEEE_Arith
-#ifdef Avoid_Underflow
- || (word0(rv) & Exp_mask) <= (2*P+1)*Exp_msk1
-#else
- || (word0(rv) & Exp_mask) <= Exp_msk1
-#endif
-#endif
- ) {
-#ifdef SET_INEXACT
- if (!delta->x[0] && delta->wds <= 1)
- inexact = 0;
-#endif
- break;
- }
- if (!delta->x[0] && delta->wds <= 1) {
- /* exact result */
-#ifdef SET_INEXACT
- inexact = 0;
-#endif
- break;
- }
- delta = lshift(delta,Log2P);
- if (cmp(delta, bs) > 0)
- goto drop_down;
- break;
- }
- if (i == 0) {
- /* exactly half-way between */
- if (dsign) {
- if ((word0(rv) & Bndry_mask1) == Bndry_mask1
- && word1(rv) == (
-#ifdef Avoid_Underflow
- (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
- ? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
-#endif
- 0xffffffff)) {
- /*boundary case -- increment exponent*/
- word0(rv) = (word0(rv) & Exp_mask)
- + Exp_msk1
-#ifdef IBM
- | Exp_msk1 >> 4
-#endif
- ;
- word1(rv) = 0;
-#ifdef Avoid_Underflow
- dsign = 0;
-#endif
- break;
- }
- }
- else if (!(word0(rv) & Bndry_mask) && !word1(rv)) {
- drop_down:
- /* boundary case -- decrement exponent */
-#ifdef Sudden_Underflow /*{{*/
- L = word0(rv) & Exp_mask;
-#ifdef IBM
- if (L < Exp_msk1)
-#else
-#ifdef Avoid_Underflow
- if (L <= (scale ? (2*P+1)*Exp_msk1 : Exp_msk1))
-#else
- if (L <= Exp_msk1)
-#endif /*Avoid_Underflow*/
-#endif /*IBM*/
- goto undfl;
- L -= Exp_msk1;
-#else /*Sudden_Underflow}{*/
-#ifdef Avoid_Underflow
- if (scale) {
- L = word0(rv) & Exp_mask;
- if (L <= (2*P+1)*Exp_msk1) {
- if (L > (P+2)*Exp_msk1)
- /* round even ==> */
- /* accept rv */
- break;
- /* rv = smallest denormal */
- goto undfl;
- }
- }
-#endif /*Avoid_Underflow*/
- L = (word0(rv) & Exp_mask) - Exp_msk1;
-#endif /*Sudden_Underflow}}*/
- word0(rv) = L | Bndry_mask1;
- word1(rv) = 0xffffffff;
-#ifdef IBM
- goto cont;
-#else
- break;
-#endif
- }
-#ifndef ROUND_BIASED
- if (!(word1(rv) & LSB))
- break;
-#endif
- if (dsign)
- dval(rv) += ulp(dval(rv));
-#ifndef ROUND_BIASED
- else {
- dval(rv) -= ulp(dval(rv));
-#ifndef Sudden_Underflow
- if (!dval(rv))
- goto undfl;
-#endif
- }
-#ifdef Avoid_Underflow
- dsign = 1 - dsign;
-#endif
-#endif
- break;
- }
- if ((aadj = ratio(delta, bs)) <= 2.) {
- if (dsign)
- aadj = aadj1 = 1.;
- else if (word1(rv) || word0(rv) & Bndry_mask) {
-#ifndef Sudden_Underflow
- if (word1(rv) == Tiny1 && !word0(rv))
- goto undfl;
-#endif
- aadj = 1.;
- aadj1 = -1.;
- }
- else {
- /* special case -- power of FLT_RADIX to be */
- /* rounded down... */
-
- if (aadj < 2./FLT_RADIX)
- aadj = 1./FLT_RADIX;
- else
- aadj *= 0.5;
- aadj1 = -aadj;
- }
- }
- else {
- aadj *= 0.5;
- aadj1 = dsign ? aadj : -aadj;
-#ifdef Check_FLT_ROUNDS
- switch(Rounding) {
- case 2: /* towards +infinity */
- aadj1 -= 0.5;
- break;
- case 0: /* towards 0 */
- case 3: /* towards -infinity */
- aadj1 += 0.5;
- }
-#else
- if (Flt_Rounds == 0)
- aadj1 += 0.5;
-#endif /*Check_FLT_ROUNDS*/
- }
- y = word0(rv) & Exp_mask;
-
- /* Check for overflow */
-
- if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
- dval(rv0) = dval(rv);
- word0(rv) -= P*Exp_msk1;
- adj = aadj1 * ulp(dval(rv));
- dval(rv) += adj;
- if ((word0(rv) & Exp_mask) >=
- Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
- if (word0(rv0) == Big0 && word1(rv0) == Big1)
- goto ovfl;
- word0(rv) = Big0;
- word1(rv) = Big1;
- goto cont;
- }
- else
- word0(rv) += P*Exp_msk1;
- }
- else {
-#ifdef Avoid_Underflow
- if (scale && y <= 2*P*Exp_msk1) {
- if (aadj <= 0x7fffffff) {
- if ((z = aadj) <= 0)
- z = 1;
- aadj = z;
- aadj1 = dsign ? aadj : -aadj;
- }
- dval(aadj2) = aadj1;
- word0(aadj2) += (2*P+1)*Exp_msk1 - y;
- aadj1 = dval(aadj2);
- }
- adj = aadj1 * ulp(dval(rv));
- dval(rv) += adj;
-#else
-#ifdef Sudden_Underflow
- if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
- dval(rv0) = dval(rv);
- word0(rv) += P*Exp_msk1;
- adj = aadj1 * ulp(dval(rv));
- dval(rv) += adj;
-#ifdef IBM
- if ((word0(rv) & Exp_mask) < P*Exp_msk1)
-#else
- if ((word0(rv) & Exp_mask) <= P*Exp_msk1)
-#endif
- {
- if (word0(rv0) == Tiny0
- && word1(rv0) == Tiny1)
- goto undfl;
- word0(rv) = Tiny0;
- word1(rv) = Tiny1;
- goto cont;
- }
- else
- word0(rv) -= P*Exp_msk1;
- }
- else {
- adj = aadj1 * ulp(dval(rv));
- dval(rv) += adj;
- }
-#else /*Sudden_Underflow*/
- /* Compute adj so that the IEEE rounding rules will
- * correctly round rv + adj in some half-way cases.
- * If rv * ulp(rv) is denormalized (i.e.,
- * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
- * trouble from bits lost to denormalization;
- * example: 1.2e-307 .
- */
- if (y <= (P-1)*Exp_msk1 && aadj > 1.) {
- aadj1 = (double)(int)(aadj + 0.5);
- if (!dsign)
- aadj1 = -aadj1;
- }
- adj = aadj1 * ulp(dval(rv));
- dval(rv) += adj;
-#endif /*Sudden_Underflow*/
-#endif /*Avoid_Underflow*/
- }
- z = word0(rv) & Exp_mask;
-#ifndef SET_INEXACT
-#ifdef Avoid_Underflow
- if (!scale)
-#endif
- if (y == z) {
- /* Can we stop now? */
- L = (Long)aadj;
- aadj -= L;
- /* The tolerances below are conservative. */
- if (dsign || word1(rv) || word0(rv) & Bndry_mask) {
- if (aadj < .4999999 || aadj > .5000001)
- break;
- }
- else if (aadj < .4999999/FLT_RADIX)
- break;
- }
-#endif
- cont:
- Bfree(bb);
- Bfree(bd);
- Bfree(bs);
- Bfree(delta);
- }
-#ifdef SET_INEXACT
- if (inexact) {
- if (!oldinexact) {
- word0(rv0) = Exp_1 + (70 << Exp_shift);
- word1(rv0) = 0;
- dval(rv0) += 1.;
- }
- }
- else if (!oldinexact)
- clear_inexact();
-#endif
-#ifdef Avoid_Underflow
- if (scale) {
- word0(rv0) = Exp_1 - 2*P*Exp_msk1;
- word1(rv0) = 0;
- dval(rv) *= dval(rv0);
-#ifndef NO_ERRNO
- /* try to avoid the bug of testing an 8087 register value */
- if (word0(rv) == 0 && word1(rv) == 0)
- PR_SetError(PR_RANGE_ERROR, 0);
-#endif
- }
-#endif /* Avoid_Underflow */
-#ifdef SET_INEXACT
- if (inexact && !(word0(rv) & Exp_mask)) {
- /* set underflow bit */
- dval(rv0) = 1e-300;
- dval(rv0) *= dval(rv0);
- }
-#endif
- retfree:
- Bfree(bb);
- Bfree(bd);
- Bfree(bs);
- Bfree(bd0);
- Bfree(delta);
- ret:
- if (se)
- *se = (char *)s;
- return sign ? -dval(rv) : dval(rv);
- }
-
- static int
-quorem
-#ifdef KR_headers
- (b, S) Bigint *b, *S;
-#else
- (Bigint *b, Bigint *S)
-#endif
-{
- int n;
- ULong *bx, *bxe, q, *sx, *sxe;
-#ifdef ULLong
- ULLong borrow, carry, y, ys;
-#else
- ULong borrow, carry, y, ys;
-#ifdef Pack_32
- ULong si, z, zs;
-#endif
-#endif
-
- n = S->wds;
-#ifdef DEBUG
- /*debug*/ if (b->wds > n)
- /*debug*/ Bug("oversize b in quorem");
-#endif
- if (b->wds < n)
- return 0;
- sx = S->x;
- sxe = sx + --n;
- bx = b->x;
- bxe = bx + n;
- q = *bxe / (*sxe + 1); /* ensure q <= true quotient */
-#ifdef DEBUG
- /*debug*/ if (q > 9)
- /*debug*/ Bug("oversized quotient in quorem");
-#endif
- if (q) {
- borrow = 0;
- carry = 0;
- do {
-#ifdef ULLong
- ys = *sx++ * (ULLong)q + carry;
- carry = ys >> 32;
- y = *bx - (ys & FFFFFFFF) - borrow;
- borrow = y >> 32 & (ULong)1;
- *bx++ = y & FFFFFFFF;
-#else
-#ifdef Pack_32
- si = *sx++;
- ys = (si & 0xffff) * q + carry;
- zs = (si >> 16) * q + (ys >> 16);
- carry = zs >> 16;
- y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
- borrow = (y & 0x10000) >> 16;
- z = (*bx >> 16) - (zs & 0xffff) - borrow;
- borrow = (z & 0x10000) >> 16;
- Storeinc(bx, z, y);
-#else
- ys = *sx++ * q + carry;
- carry = ys >> 16;
- y = *bx - (ys & 0xffff) - borrow;
- borrow = (y & 0x10000) >> 16;
- *bx++ = y & 0xffff;
-#endif
-#endif
- }
- while(sx <= sxe);
- if (!*bxe) {
- bx = b->x;
- while(--bxe > bx && !*bxe)
- --n;
- b->wds = n;
- }
- }
- if (cmp(b, S) >= 0) {
- q++;
- borrow = 0;
- carry = 0;
- bx = b->x;
- sx = S->x;
- do {
-#ifdef ULLong
- ys = *sx++ + carry;
- carry = ys >> 32;
- y = *bx - (ys & FFFFFFFF) - borrow;
- borrow = y >> 32 & (ULong)1;
- *bx++ = y & FFFFFFFF;
-#else
-#ifdef Pack_32
- si = *sx++;
- ys = (si & 0xffff) + carry;
- zs = (si >> 16) + (ys >> 16);
- carry = zs >> 16;
- y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
- borrow = (y & 0x10000) >> 16;
- z = (*bx >> 16) - (zs & 0xffff) - borrow;
- borrow = (z & 0x10000) >> 16;
- Storeinc(bx, z, y);
-#else
- ys = *sx++ + carry;
- carry = ys >> 16;
- y = *bx - (ys & 0xffff) - borrow;
- borrow = (y & 0x10000) >> 16;
- *bx++ = y & 0xffff;
-#endif
-#endif
- }
- while(sx <= sxe);
- bx = b->x;
- bxe = bx + n;
- if (!*bxe) {
- while(--bxe > bx && !*bxe)
- --n;
- b->wds = n;
- }
- }
- return q;
- }
-
-#ifndef MULTIPLE_THREADS
- static char *dtoa_result;
-#endif
-
- static char *
-#ifdef KR_headers
-rv_alloc(i) int i;
-#else
-rv_alloc(int i)
-#endif
-{
- int j, k, *r;
-
- j = sizeof(ULong);
- for(k = 0;
- sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= i;
- j <<= 1)
- k++;
- r = (int*)Balloc(k);
- *r = k;
- return
-#ifndef MULTIPLE_THREADS
- dtoa_result =
-#endif
- (char *)(r+1);
- }
-
- static char *
-#ifdef KR_headers
-nrv_alloc(s, rve, n) char *s, **rve; int n;
-#else
-nrv_alloc(char *s, char **rve, int n)
-#endif
-{
- char *rv, *t;
-
- t = rv = rv_alloc(n);
- while(*t = *s++) t++;
- if (rve)
- *rve = t;
- return rv;
- }
-
-/* freedtoa(s) must be used to free values s returned by dtoa
- * when MULTIPLE_THREADS is #defined. It should be used in all cases,
- * but for consistency with earlier versions of dtoa, it is optional
- * when MULTIPLE_THREADS is not defined.
- */
-
- static void
-#ifdef KR_headers
-freedtoa(s) char *s;
-#else
-freedtoa(char *s)
-#endif
-{
- Bigint *b = (Bigint *)((int *)s - 1);
- b->maxwds = 1 << (b->k = *(int*)b);
- Bfree(b);
-#ifndef MULTIPLE_THREADS
- if (s == dtoa_result)
- dtoa_result = 0;
-#endif
- }
-
-/* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
- *
- * Inspired by "How to Print Floating-Point Numbers Accurately" by
- * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
- *
- * Modifications:
- * 1. Rather than iterating, we use a simple numeric overestimate
- * to determine k = floor(log10(d)). We scale relevant
- * quantities using O(log2(k)) rather than O(k) multiplications.
- * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
- * try to generate digits strictly left to right. Instead, we
- * compute with fewer bits and propagate the carry if necessary
- * when rounding the final digit up. This is often faster.
- * 3. Under the assumption that input will be rounded nearest,
- * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
- * That is, we allow equality in stopping tests when the
- * round-nearest rule will give the same floating-point value
- * as would satisfaction of the stopping test with strict
- * inequality.
- * 4. We remove common factors of powers of 2 from relevant
- * quantities.
- * 5. When converting floating-point integers less than 1e16,
- * we use floating-point arithmetic rather than resorting
- * to multiple-precision integers.
- * 6. When asked to produce fewer than 15 digits, we first try
- * to get by with floating-point arithmetic; we resort to
- * multiple-precision integer arithmetic only if we cannot
- * guarantee that the floating-point calculation has given
- * the correctly rounded result. For k requested digits and
- * "uniformly" distributed input, the probability is
- * something like 10^(k-15) that we must resort to the Long
- * calculation.
- */
-
- static char *
-dtoa
-#ifdef KR_headers
- (dd, mode, ndigits, decpt, sign, rve)
- double dd; int mode, ndigits, *decpt, *sign; char **rve;
-#else
- (double dd, int mode, int ndigits, int *decpt, int *sign, char **rve)
-#endif
-{
- /* Arguments ndigits, decpt, sign are similar to those
- of ecvt and fcvt; trailing zeros are suppressed from
- the returned string. If not null, *rve is set to point
- to the end of the return value. If d is +-Infinity or NaN,
- then *decpt is set to 9999.
-
- mode:
- 0 ==> shortest string that yields d when read in
- and rounded to nearest.
- 1 ==> like 0, but with Steele & White stopping rule;
- e.g. with IEEE P754 arithmetic , mode 0 gives
- 1e23 whereas mode 1 gives 9.999999999999999e22.
- 2 ==> max(1,ndigits) significant digits. This gives a
- return value similar to that of ecvt, except
- that trailing zeros are suppressed.
- 3 ==> through ndigits past the decimal point. This
- gives a return value similar to that from fcvt,
- except that trailing zeros are suppressed, and
- ndigits can be negative.
- 4,5 ==> similar to 2 and 3, respectively, but (in
- round-nearest mode) with the tests of mode 0 to
- possibly return a shorter string that rounds to d.
- With IEEE arithmetic and compilation with
- -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
- as modes 2 and 3 when FLT_ROUNDS != 1.
- 6-9 ==> Debugging modes similar to mode - 4: don't try
- fast floating-point estimate (if applicable).
-
- Values of mode other than 0-9 are treated as mode 0.
-
- Sufficient space is allocated to the return value
- to hold the suppressed trailing zeros.
- */
-
- int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
- j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
- spec_case, try_quick;
- Long L;
-#ifndef Sudden_Underflow
- int denorm;
- ULong x;
-#endif
- Bigint *b, *b1, *delta, *mlo, *mhi, *S;
- U d, d2, eps;
- double ds;
- char *s, *s0;
-#ifdef Honor_FLT_ROUNDS
- int rounding;
-#endif
-#ifdef SET_INEXACT
- int inexact, oldinexact;
-#endif
-
-#ifndef MULTIPLE_THREADS
- if (dtoa_result) {
- freedtoa(dtoa_result);
- dtoa_result = 0;
- }
-#endif
-
- dval(d) = dd;
- if (word0(d) & Sign_bit) {
- /* set sign for everything, including 0's and NaNs */
- *sign = 1;
- word0(d) &= ~Sign_bit; /* clear sign bit */
- }
- else
- *sign = 0;
-
-#if defined(IEEE_Arith) + defined(VAX)
-#ifdef IEEE_Arith
- if ((word0(d) & Exp_mask) == Exp_mask)
-#else
- if (word0(d) == 0x8000)
-#endif
- {
- /* Infinity or NaN */
- *decpt = 9999;
-#ifdef IEEE_Arith
- if (!word1(d) && !(word0(d) & 0xfffff))
- return nrv_alloc("Infinity", rve, 8);
-#endif
- return nrv_alloc("NaN", rve, 3);
- }
-#endif
-#ifdef IBM
- dval(d) += 0; /* normalize */
-#endif
- if (!dval(d)) {
- *decpt = 1;
- return nrv_alloc("0", rve, 1);
- }
-
-#ifdef SET_INEXACT
- try_quick = oldinexact = get_inexact();
- inexact = 1;
-#endif
-#ifdef Honor_FLT_ROUNDS
- if ((rounding = Flt_Rounds) >= 2) {
- if (*sign)
- rounding = rounding == 2 ? 0 : 2;
- else
- if (rounding != 2)
- rounding = 0;
- }
-#endif
-
- b = d2b(dval(d), &be, &bbits);
-#ifdef Sudden_Underflow
- i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
-#else
- if (i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1))) {
-#endif
- dval(d2) = dval(d);
- word0(d2) &= Frac_mask1;
- word0(d2) |= Exp_11;
-#ifdef IBM
- if (j = 11 - hi0bits(word0(d2) & Frac_mask))
- dval(d2) /= 1 << j;
-#endif
-
- /* log(x) ~=~ log(1.5) + (x-1.5)/1.5
- * log10(x) = log(x) / log(10)
- * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
- * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
- *
- * This suggests computing an approximation k to log10(d) by
- *
- * k = (i - Bias)*0.301029995663981
- * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
- *
- * We want k to be too large rather than too small.
- * The error in the first-order Taylor series approximation
- * is in our favor, so we just round up the constant enough
- * to compensate for any error in the multiplication of
- * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
- * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
- * adding 1e-13 to the constant term more than suffices.
- * Hence we adjust the constant term to 0.1760912590558.
- * (We could get a more accurate k by invoking log10,
- * but this is probably not worthwhile.)
- */
-
- i -= Bias;
-#ifdef IBM
- i <<= 2;
- i += j;
-#endif
-#ifndef Sudden_Underflow
- denorm = 0;
- }
- else {
- /* d is denormalized */
-
- i = bbits + be + (Bias + (P-1) - 1);
- x = i > 32 ? word0(d) << 64 - i | word1(d) >> i - 32
- : word1(d) << 32 - i;
- dval(d2) = x;
- word0(d2) -= 31*Exp_msk1; /* adjust exponent */
- i -= (Bias + (P-1) - 1) + 1;
- denorm = 1;
- }
-#endif
- ds = (dval(d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
- k = (int)ds;
- if (ds < 0. && ds != k)
- k--; /* want k = floor(ds) */
- k_check = 1;
- if (k >= 0 && k <= Ten_pmax) {
- if (dval(d) < tens[k])
- k--;
- k_check = 0;
- }
- j = bbits - i - 1;
- if (j >= 0) {
- b2 = 0;
- s2 = j;
- }
- else {
- b2 = -j;
- s2 = 0;
- }
- if (k >= 0) {
- b5 = 0;
- s5 = k;
- s2 += k;
- }
- else {
- b2 -= k;
- b5 = -k;
- s5 = 0;
- }
- if (mode < 0 || mode > 9)
- mode = 0;
-
-#ifndef SET_INEXACT
-#ifdef Check_FLT_ROUNDS
- try_quick = Rounding == 1;
-#else
- try_quick = 1;
-#endif
-#endif /*SET_INEXACT*/
-
- if (mode > 5) {
- mode -= 4;
- try_quick = 0;
- }
- leftright = 1;
- switch(mode) {
- case 0:
- case 1:
- ilim = ilim1 = -1;
- i = 18;
- ndigits = 0;
- break;
- case 2:
- leftright = 0;
- /* no break */
- case 4:
- if (ndigits <= 0)
- ndigits = 1;
- ilim = ilim1 = i = ndigits;
- break;
- case 3:
- leftright = 0;
- /* no break */
- case 5:
- i = ndigits + k + 1;
- ilim = i;
- ilim1 = i - 1;
- if (i <= 0)
- i = 1;
- }
- s = s0 = rv_alloc(i);
-
-#ifdef Honor_FLT_ROUNDS
- if (mode > 1 && rounding != 1)
- leftright = 0;
-#endif
-
- if (ilim >= 0 && ilim <= Quick_max && try_quick) {
-
- /* Try to get by with floating-point arithmetic. */
-
- i = 0;
- dval(d2) = dval(d);
- k0 = k;
- ilim0 = ilim;
- ieps = 2; /* conservative */
- if (k > 0) {
- ds = tens[k&0xf];
- j = k >> 4;
- if (j & Bletch) {
- /* prevent overflows */
- j &= Bletch - 1;
- dval(d) /= bigtens[n_bigtens-1];
- ieps++;
- }
- for(; j; j >>= 1, i++)
- if (j & 1) {
- ieps++;
- ds *= bigtens[i];
- }
- dval(d) /= ds;
- }
- else if (j1 = -k) {
- dval(d) *= tens[j1 & 0xf];
- for(j = j1 >> 4; j; j >>= 1, i++)
- if (j & 1) {
- ieps++;
- dval(d) *= bigtens[i];
- }
- }
- if (k_check && dval(d) < 1. && ilim > 0) {
- if (ilim1 <= 0)
- goto fast_failed;
- ilim = ilim1;
- k--;
- dval(d) *= 10.;
- ieps++;
- }
- dval(eps) = ieps*dval(d) + 7.;
- word0(eps) -= (P-1)*Exp_msk1;
- if (ilim == 0) {
- S = mhi = 0;
- dval(d) -= 5.;
- if (dval(d) > dval(eps))
- goto one_digit;
- if (dval(d) < -dval(eps))
- goto no_digits;
- goto fast_failed;
- }
-#ifndef No_leftright
- if (leftright) {
- /* Use Steele & White method of only
- * generating digits needed.
- */
- dval(eps) = 0.5/tens[ilim-1] - dval(eps);
- for(i = 0;;) {
- L = dval(d);
- dval(d) -= L;
- *s++ = '0' + (int)L;
- if (dval(d) < dval(eps))
- goto ret1;
- if (1. - dval(d) < dval(eps))
- goto bump_up;
- if (++i >= ilim)
- break;
- dval(eps) *= 10.;
- dval(d) *= 10.;
- }
- }
- else {
-#endif
- /* Generate ilim digits, then fix them up. */
- dval(eps) *= tens[ilim-1];
- for(i = 1;; i++, dval(d) *= 10.) {
- L = (Long)(dval(d));
- if (!(dval(d) -= L))
- ilim = i;
- *s++ = '0' + (int)L;
- if (i == ilim) {
- if (dval(d) > 0.5 + dval(eps))
- goto bump_up;
- else if (dval(d) < 0.5 - dval(eps)) {
- while(*--s == '0');
- s++;
- goto ret1;
- }
- break;
- }
- }
-#ifndef No_leftright
- }
-#endif
- fast_failed:
- s = s0;
- dval(d) = dval(d2);
- k = k0;
- ilim = ilim0;
- }
-
- /* Do we have a "small" integer? */
-
- if (be >= 0 && k <= Int_max) {
- /* Yes. */
- ds = tens[k];
- if (ndigits < 0 && ilim <= 0) {
- S = mhi = 0;
- if (ilim < 0 || dval(d) <= 5*ds)
- goto no_digits;
- goto one_digit;
- }
- for(i = 1; i <= k+1; i++, dval(d) *= 10.) {
- L = (Long)(dval(d) / ds);
- dval(d) -= L*ds;
-#ifdef Check_FLT_ROUNDS
- /* If FLT_ROUNDS == 2, L will usually be high by 1 */
- if (dval(d) < 0) {
- L--;
- dval(d) += ds;
- }
-#endif
- *s++ = '0' + (int)L;
- if (!dval(d)) {
-#ifdef SET_INEXACT
- inexact = 0;
-#endif
- break;
- }
- if (i == ilim) {
-#ifdef Honor_FLT_ROUNDS
- if (mode > 1)
- switch(rounding) {
- case 0: goto ret1;
- case 2: goto bump_up;
- }
-#endif
- dval(d) += dval(d);
- if (dval(d) > ds || dval(d) == ds && L & 1) {
- bump_up:
- while(*--s == '9')
- if (s == s0) {
- k++;
- *s = '0';
- break;
- }
- ++*s++;
- }
- break;
- }
- }
- goto ret1;
- }
-
- m2 = b2;
- m5 = b5;
- mhi = mlo = 0;
- if (leftright) {
- i =
-#ifndef Sudden_Underflow
- denorm ? be + (Bias + (P-1) - 1 + 1) :
-#endif
-#ifdef IBM
- 1 + 4*P - 3 - bbits + ((bbits + be - 1) & 3);
-#else
- 1 + P - bbits;
-#endif
- b2 += i;
- s2 += i;
- mhi = i2b(1);
- }
- if (m2 > 0 && s2 > 0) {
- i = m2 < s2 ? m2 : s2;
- b2 -= i;
- m2 -= i;
- s2 -= i;
- }
- if (b5 > 0) {
- if (leftright) {
- if (m5 > 0) {
- mhi = pow5mult(mhi, m5);
- b1 = mult(mhi, b);
- Bfree(b);
- b = b1;
- }
- if (j = b5 - m5)
- b = pow5mult(b, j);
- }
- else
- b = pow5mult(b, b5);
- }
- S = i2b(1);
- if (s5 > 0)
- S = pow5mult(S, s5);
-
- /* Check for special case that d is a normalized power of 2. */
-
- spec_case = 0;
- if ((mode < 2 || leftright)
-#ifdef Honor_FLT_ROUNDS
- && rounding == 1
-#endif
- ) {
- if (!word1(d) && !(word0(d) & Bndry_mask)
-#ifndef Sudden_Underflow
- && word0(d) & (Exp_mask & ~Exp_msk1)
-#endif
- ) {
- /* The special case */
- b2 += Log2P;
- s2 += Log2P;
- spec_case = 1;
- }
- }
-
- /* Arrange for convenient computation of quotients:
- * shift left if necessary so divisor has 4 leading 0 bits.
- *
- * Perhaps we should just compute leading 28 bits of S once
- * and for all and pass them and a shift to quorem, so it
- * can do shifts and ors to compute the numerator for q.
- */
-#ifdef Pack_32
- if (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f)
- i = 32 - i;
-#else
- if (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0xf)
- i = 16 - i;
-#endif
- if (i > 4) {
- i -= 4;
- b2 += i;
- m2 += i;
- s2 += i;
- }
- else if (i < 4) {
- i += 28;
- b2 += i;
- m2 += i;
- s2 += i;
- }
- if (b2 > 0)
- b = lshift(b, b2);
- if (s2 > 0)
- S = lshift(S, s2);
- if (k_check) {
- if (cmp(b,S) < 0) {
- k--;
- b = multadd(b, 10, 0); /* we botched the k estimate */
- if (leftright)
- mhi = multadd(mhi, 10, 0);
- ilim = ilim1;
- }
- }
- if (ilim <= 0 && (mode == 3 || mode == 5)) {
- if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) {
- /* no digits, fcvt style */
- no_digits:
- k = -1 - ndigits;
- goto ret;
- }
- one_digit:
- *s++ = '1';
- k++;
- goto ret;
- }
- if (leftright) {
- if (m2 > 0)
- mhi = lshift(mhi, m2);
-
- /* Compute mlo -- check for special case
- * that d is a normalized power of 2.
- */
-
- mlo = mhi;
- if (spec_case) {
- mhi = Balloc(mhi->k);
- Bcopy(mhi, mlo);
- mhi = lshift(mhi, Log2P);
- }
-
- for(i = 1;;i++) {
- dig = quorem(b,S) + '0';
- /* Do we yet have the shortest decimal string
- * that will round to d?
- */
- j = cmp(b, mlo);
- delta = diff(S, mhi);
- j1 = delta->sign ? 1 : cmp(b, delta);
- Bfree(delta);
-#ifndef ROUND_BIASED
- if (j1 == 0 && mode != 1 && !(word1(d) & 1)
-#ifdef Honor_FLT_ROUNDS
- && rounding >= 1
-#endif
- ) {
- if (dig == '9')
- goto round_9_up;
- if (j > 0)
- dig++;
-#ifdef SET_INEXACT
- else if (!b->x[0] && b->wds <= 1)
- inexact = 0;
-#endif
- *s++ = dig;
- goto ret;
- }
-#endif
- if (j < 0 || j == 0 && mode != 1
-#ifndef ROUND_BIASED
- && !(word1(d) & 1)
-#endif
- ) {
- if (!b->x[0] && b->wds <= 1) {
-#ifdef SET_INEXACT
- inexact = 0;
-#endif
- goto accept_dig;
- }
-#ifdef Honor_FLT_ROUNDS
- if (mode > 1)
- switch(rounding) {
- case 0: goto accept_dig;
- case 2: goto keep_dig;
- }
-#endif /*Honor_FLT_ROUNDS*/
- if (j1 > 0) {
- b = lshift(b, 1);
- j1 = cmp(b, S);
- if ((j1 > 0 || j1 == 0 && dig & 1)
- && dig++ == '9')
- goto round_9_up;
- }
- accept_dig:
- *s++ = dig;
- goto ret;
- }
- if (j1 > 0) {
-#ifdef Honor_FLT_ROUNDS
- if (!rounding)
- goto accept_dig;
-#endif
- if (dig == '9') { /* possible if i == 1 */
- round_9_up:
- *s++ = '9';
- goto roundoff;
- }
- *s++ = dig + 1;
- goto ret;
- }
-#ifdef Honor_FLT_ROUNDS
- keep_dig:
-#endif
- *s++ = dig;
- if (i == ilim)
- break;
- b = multadd(b, 10, 0);
- if (mlo == mhi)
- mlo = mhi = multadd(mhi, 10, 0);
- else {
- mlo = multadd(mlo, 10, 0);
- mhi = multadd(mhi, 10, 0);
- }
- }
- }
- else
- for(i = 1;; i++) {
- *s++ = dig = quorem(b,S) + '0';
- if (!b->x[0] && b->wds <= 1) {
-#ifdef SET_INEXACT
- inexact = 0;
-#endif
- goto ret;
- }
- if (i >= ilim)
- break;
- b = multadd(b, 10, 0);
- }
-
- /* Round off last digit */
-
-#ifdef Honor_FLT_ROUNDS
- switch(rounding) {
- case 0: goto trimzeros;
- case 2: goto roundoff;
- }
-#endif
- b = lshift(b, 1);
- j = cmp(b, S);
- if (j > 0 || j == 0 && dig & 1) {
- roundoff:
- while(*--s == '9')
- if (s == s0) {
- k++;
- *s++ = '1';
- goto ret;
- }
- ++*s++;
- }
- else {
-#ifdef Honor_FLT_ROUNDS
- trimzeros:
-#endif
- while(*--s == '0');
- s++;
- }
- ret:
- Bfree(S);
- if (mhi) {
- if (mlo && mlo != mhi)
- Bfree(mlo);
- Bfree(mhi);
- }
- ret1:
-#ifdef SET_INEXACT
- if (inexact) {
- if (!oldinexact) {
- word0(d) = Exp_1 + (70 << Exp_shift);
- word1(d) = 0;
- dval(d) += 1.;
- }
- }
- else if (!oldinexact)
- clear_inexact();
-#endif
- Bfree(b);
- *s = 0;
- *decpt = k + 1;
- if (rve)
- *rve = s;
- return s0;
- }
-#ifdef __cplusplus
-}
-#endif
-
-PR_IMPLEMENT(PRStatus)
-PR_dtoa(PRFloat64 d, PRIntn mode, PRIntn ndigits,
- PRIntn *decpt, PRIntn *sign, char **rve, char *buf, PRSize bufsize)
-{
- char *result;
- PRSize resultlen;
- PRStatus rv = PR_FAILURE;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (mode < 0 || mode > 3) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return rv;
- }
- result = dtoa(d, mode, ndigits, decpt, sign, rve);
- if (!result) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return rv;
- }
- resultlen = strlen(result)+1;
- if (bufsize < resultlen) {
- PR_SetError(PR_BUFFER_OVERFLOW_ERROR, 0);
- } else {
- memcpy(buf, result, resultlen);
- if (rve) {
- *rve = buf + (*rve - result);
- }
- rv = PR_SUCCESS;
- }
- freedtoa(result);
- return rv;
-}
-
-/*
-** conversion routines for floating point
-** prcsn - number of digits of precision to generate floating
-** point value.
-** This should be reparameterized so that you can send in a
-** prcn for the positive and negative ranges. For now,
-** conform to the ECMA JavaScript spec which says numbers
-** less than 1e-6 are in scientific notation.
-** Also, the ECMA spec says that there should always be a
-** '+' or '-' after the 'e' in scientific notation
-*/
-PR_IMPLEMENT(void)
-PR_cnvtf(char *buf, int bufsz, int prcsn, double dfval)
-{
- PRIntn decpt, sign, numdigits;
- char *num, *nump;
- char *bufp = buf;
- char *endnum;
- U fval;
-
- dval(fval) = dfval;
- /* If anything fails, we store an empty string in 'buf' */
- num = (char*)PR_MALLOC(bufsz);
- if (num == NULL) {
- buf[0] = '\0';
- return;
- }
- /* XXX Why use mode 1? */
- if (PR_dtoa(dval(fval),1,prcsn,&decpt,&sign,&endnum,num,bufsz)
- == PR_FAILURE) {
- buf[0] = '\0';
- goto done;
- }
- numdigits = endnum - num;
- nump = num;
-
- if (sign &&
- !(word0(fval) == Sign_bit && word1(fval) == 0) &&
- !((word0(fval) & Exp_mask) == Exp_mask &&
- (word1(fval) || (word0(fval) & 0xfffff)))) {
- *bufp++ = '-';
- }
-
- if (decpt == 9999) {
- while ((*bufp++ = *nump++) != 0) {} /* nothing to execute */
- goto done;
- }
-
- if (decpt > (prcsn+1) || decpt < -(prcsn-1) || decpt < -5) {
- *bufp++ = *nump++;
- if (numdigits != 1) {
- *bufp++ = '.';
- }
-
- while (*nump != '\0') {
- *bufp++ = *nump++;
- }
- *bufp++ = 'e';
- PR_snprintf(bufp, bufsz - (bufp - buf), "%+d", decpt-1);
- } else if (decpt >= 0) {
- if (decpt == 0) {
- *bufp++ = '0';
- } else {
- while (decpt--) {
- if (*nump != '\0') {
- *bufp++ = *nump++;
- } else {
- *bufp++ = '0';
- }
- }
- }
- if (*nump != '\0') {
- *bufp++ = '.';
- while (*nump != '\0') {
- *bufp++ = *nump++;
- }
- }
- *bufp++ = '\0';
- } else if (decpt < 0) {
- *bufp++ = '0';
- *bufp++ = '.';
- while (decpt++) {
- *bufp++ = '0';
- }
-
- while (*nump != '\0') {
- *bufp++ = *nump++;
- }
- *bufp++ = '\0';
- }
-done:
- PR_DELETE(num);
-}
diff --git a/nspr/pr/src/misc/prenv.c b/nspr/pr/src/misc/prenv.c
deleted file mode 100644
index cc2e198..0000000
--- a/nspr/pr/src/misc/prenv.c
+++ /dev/null
@@ -1,162 +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/. */
-
-#include <string.h>
-#include <stdlib.h>
-#include "primpl.h"
-#include "prmem.h"
-
-#if defined(XP_UNIX)
-#include <unistd.h>
-#if defined(DARWIN)
-#if defined(HAVE_CRT_EXTERNS_H)
-#include <crt_externs.h>
-#endif /* HAVE_CRT_EXTERNS_H */
-#else /* DARWIN */
-PR_IMPORT_DATA(char **) environ;
-#endif /* DARWIN */
-#endif /* XP_UNIX */
-
-#if !defined(HAVE_SECURE_GETENV) && defined(HAVE___SECURE_GETENV)
-#define secure_getenv __secure_getenv
-#define HAVE_SECURE_GETENV 1
-#endif
-
-/* Lock used to lock the environment */
-#if defined(_PR_NO_PREEMPT)
-#define _PR_NEW_LOCK_ENV()
-#define _PR_DELETE_LOCK_ENV()
-#define _PR_LOCK_ENV()
-#define _PR_UNLOCK_ENV()
-#elif defined(_PR_LOCAL_THREADS_ONLY)
-extern _PRCPU * _pr_primordialCPU;
-static PRIntn _is;
-#define _PR_NEW_LOCK_ENV()
-#define _PR_DELETE_LOCK_ENV()
-#define _PR_LOCK_ENV() if (_pr_primordialCPU) _PR_INTSOFF(_is);
-#define _PR_UNLOCK_ENV() if (_pr_primordialCPU) _PR_INTSON(_is);
-#else
-static PRLock *_pr_envLock = NULL;
-#define _PR_NEW_LOCK_ENV() {_pr_envLock = PR_NewLock();}
-#define _PR_DELETE_LOCK_ENV() \
- { if (_pr_envLock) { PR_DestroyLock(_pr_envLock); _pr_envLock = NULL; } }
-#define _PR_LOCK_ENV() { if (_pr_envLock) PR_Lock(_pr_envLock); }
-#define _PR_UNLOCK_ENV() { if (_pr_envLock) PR_Unlock(_pr_envLock); }
-#endif
-
-/************************************************************************/
-
-void _PR_InitEnv(void)
-{
- _PR_NEW_LOCK_ENV();
-}
-
-void _PR_CleanupEnv(void)
-{
- _PR_DELETE_LOCK_ENV();
-}
-
-PR_IMPLEMENT(char*) PR_GetEnv(const char *var)
-{
- char *ev;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- _PR_LOCK_ENV();
- ev = _PR_MD_GET_ENV(var);
- _PR_UNLOCK_ENV();
- return ev;
-}
-
-PR_IMPLEMENT(char*) PR_GetEnvSecure(const char *var)
-{
-#ifdef HAVE_SECURE_GETENV
- char *ev;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- _PR_LOCK_ENV();
- ev = secure_getenv(var);
- _PR_UNLOCK_ENV();
-
- return ev;
-#else
-#ifdef XP_UNIX
- /*
- ** Fall back to checking uids and gids. This won't detect any other
- ** privilege-granting mechanisms the platform may have. This also
- ** can't detect the case where the process already called
- ** setuid(geteuid()) and/or setgid(getegid()).
- */
- if (getuid() != geteuid() || getgid() != getegid()) {
- return NULL;
- }
-#endif /* XP_UNIX */
- return PR_GetEnv(var);
-#endif /* HAVE_SECURE_GETENV */
-}
-
-PR_IMPLEMENT(PRStatus) PR_SetEnv(const char *string)
-{
- PRIntn result;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (!strchr(string, '=')) return(PR_FAILURE);
-
- _PR_LOCK_ENV();
- result = _PR_MD_PUT_ENV((char*)string);
- _PR_UNLOCK_ENV();
- return result ? PR_FAILURE : PR_SUCCESS;
-}
-
-#if defined(XP_UNIX) && (!defined(DARWIN) || defined(HAVE_CRT_EXTERNS_H))
-PR_IMPLEMENT(char **) PR_DuplicateEnvironment(void)
-{
- char **the_environ, **result, **end, **src, **dst;
-
- _PR_LOCK_ENV();
-#ifdef DARWIN
- the_environ = *(_NSGetEnviron());
-#else
- the_environ = environ;
-#endif
-
- for (end = the_environ; *end != NULL; end++)
- /* empty loop body */;
-
- result = (char **)PR_Malloc(sizeof(char *) * (end - the_environ + 1));
- if (result != NULL) {
- for (src = the_environ, dst = result; src != end; src++, dst++) {
- size_t len;
-
- len = strlen(*src) + 1;
- *dst = PR_Malloc(len);
- if (*dst == NULL) {
- /* Allocation failed. Must clean up the half-copied env. */
- char **to_delete;
-
- for (to_delete = result; to_delete != dst; to_delete++) {
- PR_Free(*to_delete);
- }
- PR_Free(result);
- result = NULL;
- goto out;
- }
- memcpy(*dst, *src, len);
- }
- *dst = NULL;
- }
- out:
- _PR_UNLOCK_ENV();
- return result;
-}
-#else
-/* This platform doesn't support raw access to the environ block. */
-PR_IMPLEMENT(char **) PR_DuplicateEnvironment(void)
-{
- return NULL;
-}
-#endif
diff --git a/nspr/pr/src/misc/prerr.c b/nspr/pr/src/misc/prerr.c
deleted file mode 100644
index bc78c8f..0000000
--- a/nspr/pr/src/misc/prerr.c
+++ /dev/null
@@ -1,97 +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/. */
-
-/*
- *
- * prerr.c
- * This file is automatically generated; please do not edit it.
- */
-#include "prerror.h"
-static const struct PRErrorMessage text[] = {
- {"PR_OUT_OF_MEMORY_ERROR", "Memory allocation attempt failed"},
- {"PR_BAD_DESCRIPTOR_ERROR", "Invalid file descriptor"},
- {"PR_WOULD_BLOCK_ERROR", "The operation would have blocked"},
- {"PR_ACCESS_FAULT_ERROR", "Invalid memory address argument"},
- {"PR_INVALID_METHOD_ERROR", "Invalid function for file type"},
- {"PR_ILLEGAL_ACCESS_ERROR", "Invalid memory address argument"},
- {"PR_UNKNOWN_ERROR", "Some unknown error has occurred"},
- {"PR_PENDING_INTERRUPT_ERROR", "Operation interrupted by another thread"},
- {"PR_NOT_IMPLEMENTED_ERROR", "function not implemented"},
- {"PR_IO_ERROR", "I/O function error"},
- {"PR_IO_TIMEOUT_ERROR", "I/O operation timed out"},
- {"PR_IO_PENDING_ERROR", "I/O operation on busy file descriptor"},
- {"PR_DIRECTORY_OPEN_ERROR", "The directory could not be opened"},
- {"PR_INVALID_ARGUMENT_ERROR", "Invalid function argument"},
- {"PR_ADDRESS_NOT_AVAILABLE_ERROR", "Network address not available (in use?)"},
- {"PR_ADDRESS_NOT_SUPPORTED_ERROR", "Network address type not supported"},
- {"PR_IS_CONNECTED_ERROR", "Already connected"},
- {"PR_BAD_ADDRESS_ERROR", "Network address is invalid"},
- {"PR_ADDRESS_IN_USE_ERROR", "Local Network address is in use"},
- {"PR_CONNECT_REFUSED_ERROR", "Connection refused by peer"},
- {"PR_NETWORK_UNREACHABLE_ERROR", "Network address is presently unreachable"},
- {"PR_CONNECT_TIMEOUT_ERROR", "Connection attempt timed out"},
- {"PR_NOT_CONNECTED_ERROR", "Network file descriptor is not connected"},
- {"PR_LOAD_LIBRARY_ERROR", "Failure to load dynamic library"},
- {"PR_UNLOAD_LIBRARY_ERROR", "Failure to unload dynamic library"},
- {"PR_FIND_SYMBOL_ERROR", "Symbol not found in any of the loaded dynamic libraries"},
- {"PR_INSUFFICIENT_RESOURCES_ERROR", "Insufficient system resources"},
- {"PR_DIRECTORY_LOOKUP_ERROR", "A directory lookup on a network address has failed"},
- {"PR_TPD_RANGE_ERROR", "Attempt to access a TPD key that is out of range"},
- {"PR_PROC_DESC_TABLE_FULL_ERROR", "Process open FD table is full"},
- {"PR_SYS_DESC_TABLE_FULL_ERROR", "System open FD table is full"},
- {"PR_NOT_SOCKET_ERROR", "Network operation attempted on non-network file descriptor"},
- {"PR_NOT_TCP_SOCKET_ERROR", "TCP-specific function attempted on a non-TCP file descriptor"},
- {"PR_SOCKET_ADDRESS_IS_BOUND_ERROR", "TCP file descriptor is already bound"},
- {"PR_NO_ACCESS_RIGHTS_ERROR", "Access Denied"},
- {"PR_OPERATION_NOT_SUPPORTED_ERROR", "The requested operation is not supported by the platform"},
- {"PR_PROTOCOL_NOT_SUPPORTED_ERROR", "The host operating system does not support the protocol requested"},
- {"PR_REMOTE_FILE_ERROR", "Access to the remote file has been severed"},
- {"PR_BUFFER_OVERFLOW_ERROR", "The value requested is too large to be stored in the data buffer provided"},
- {"PR_CONNECT_RESET_ERROR", "TCP connection reset by peer"},
- {"PR_RANGE_ERROR", "Unused"},
- {"PR_DEADLOCK_ERROR", "The operation would have deadlocked"},
- {"PR_FILE_IS_LOCKED_ERROR", "The file is already locked"},
- {"PR_FILE_TOO_BIG_ERROR", "Write would result in file larger than the system allows"},
- {"PR_NO_DEVICE_SPACE_ERROR", "The device for storing the file is full"},
- {"PR_PIPE_ERROR", "Unused"},
- {"PR_NO_SEEK_DEVICE_ERROR", "Unused"},
- {"PR_IS_DIRECTORY_ERROR", "Cannot perform a normal file operation on a directory"},
- {"PR_LOOP_ERROR", "Symbolic link loop"},
- {"PR_NAME_TOO_LONG_ERROR", "File name is too long"},
- {"PR_FILE_NOT_FOUND_ERROR", "File not found"},
- {"PR_NOT_DIRECTORY_ERROR", "Cannot perform directory operation on a normal file"},
- {"PR_READ_ONLY_FILESYSTEM_ERROR", "Cannot write to a read-only file system"},
- {"PR_DIRECTORY_NOT_EMPTY_ERROR", "Cannot delete a directory that is not empty"},
- {"PR_FILESYSTEM_MOUNTED_ERROR", "Cannot delete or rename a file object while the file system is busy"},
- {"PR_NOT_SAME_DEVICE_ERROR", "Cannot rename a file to a file system on another device"},
- {"PR_DIRECTORY_CORRUPTED_ERROR", "The directory object in the file system is corrupted"},
- {"PR_FILE_EXISTS_ERROR", "Cannot create or rename a filename that already exists"},
- {"PR_MAX_DIRECTORY_ENTRIES_ERROR", "Directory is full. No additional filenames may be added"},
- {"PR_INVALID_DEVICE_STATE_ERROR", "The required device was in an invalid state"},
- {"PR_DEVICE_IS_LOCKED_ERROR", "The device is locked"},
- {"PR_NO_MORE_FILES_ERROR", "No more entries in the directory"},
- {"PR_END_OF_FILE_ERROR", "Encountered end of file"},
- {"PR_FILE_SEEK_ERROR", "Seek error"},
- {"PR_FILE_IS_BUSY_ERROR", "The file is busy"},
- {"PR_OPERATION_ABORTED_ERROR", "The I/O operation was aborted"},
- {"PR_IN_PROGRESS_ERROR", "Operation is still in progress (probably a non-blocking connect)"},
- {"PR_ALREADY_INITIATED_ERROR", "Operation has already been initiated (probably a non-blocking connect)"},
- {"PR_GROUP_EMPTY_ERROR", "The wait group is empty"},
- {"PR_INVALID_STATE_ERROR", "Object state improper for request"},
- {"PR_NETWORK_DOWN_ERROR", "Network is down"},
- {"PR_SOCKET_SHUTDOWN_ERROR", "Socket shutdown"},
- {"PR_CONNECT_ABORTED_ERROR", "Connection aborted"},
- {"PR_HOST_UNREACHABLE_ERROR", "Host is unreachable"},
- {"PR_LIBRARY_NOT_LOADED_ERROR", "The library is not loaded"},
- {"PR_CALL_ONCE_ERROR", "The one-time function was previously called and failed. Its error code is no longer available"},
- {"PR_MAX_ERROR", "Placeholder for the end of the list"},
- {0, 0}
-};
-
-static const struct PRErrorTable et = { text, "prerr", -6000L, 77 };
-
-void nspr_InitializePRErrorTable(void) {
- PR_ErrorInstallTable(&et);
-}
diff --git a/nspr/pr/src/misc/prerror.c b/nspr/pr/src/misc/prerror.c
deleted file mode 100644
index 19f7794..0000000
--- a/nspr/pr/src/misc/prerror.c
+++ /dev/null
@@ -1,75 +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/. */
-
-#include "primpl.h"
-
-#include <string.h>
-#include <stdlib.h>
-
-PR_IMPLEMENT(PRErrorCode) PR_GetError(void)
-{
- PRThread *thread = PR_GetCurrentThread();
- return thread->errorCode;
-}
-
-PR_IMPLEMENT(PRInt32) PR_GetOSError(void)
-{
- PRThread *thread = PR_GetCurrentThread();
- return thread->osErrorCode;
-}
-
-PR_IMPLEMENT(void) PR_SetError(PRErrorCode code, PRInt32 osErr)
-{
- PRThread *thread = PR_GetCurrentThread();
- thread->errorCode = code;
- thread->osErrorCode = osErr;
- thread->errorStringLength = 0;
-}
-
-PR_IMPLEMENT(void) PR_SetErrorText(PRIntn textLength, const char *text)
-{
- PRThread *thread = PR_GetCurrentThread();
-
- if (0 == textLength)
- {
- if (NULL != thread->errorString)
- PR_DELETE(thread->errorString);
- thread->errorStringSize = 0;
- }
- else
- {
- PRIntn size = textLength + 31; /* actual length to allocate. Plus a little extra */
- if (thread->errorStringSize < textLength+1) /* do we have room? */
- {
- if (NULL != thread->errorString)
- PR_DELETE(thread->errorString);
- thread->errorString = (char*)PR_MALLOC(size);
- if ( NULL == thread->errorString ) {
- thread->errorStringSize = 0;
- thread->errorStringLength = 0;
- return;
- }
- thread->errorStringSize = size;
- }
- memcpy(thread->errorString, text, textLength+1 );
- }
- thread->errorStringLength = textLength;
-}
-
-PR_IMPLEMENT(PRInt32) PR_GetErrorTextLength(void)
-{
- PRThread *thread = PR_GetCurrentThread();
- return thread->errorStringLength;
-} /* PR_GetErrorTextLength */
-
-PR_IMPLEMENT(PRInt32) PR_GetErrorText(char *text)
-{
- PRThread *thread = PR_GetCurrentThread();
- if (0 != thread->errorStringLength)
- memcpy(text, thread->errorString, thread->errorStringLength+1);
- return thread->errorStringLength;
-} /* PR_GetErrorText */
-
-
diff --git a/nspr/pr/src/misc/prerrortable.c b/nspr/pr/src/misc/prerrortable.c
deleted file mode 100644
index 285fde9..0000000
--- a/nspr/pr/src/misc/prerrortable.c
+++ /dev/null
@@ -1,205 +0,0 @@
-/* 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/. */
-
-
-
-
-/*
-
-Copyright 1987, 1988 by the Student Information Processing Board
- of the Massachusetts Institute of Technology
-
-Permission to use, copy, modify, and distribute this software
-and its documentation for any purpose and without fee is
-hereby granted, provided that the above copyright notice
-appear in all copies and that both that copyright notice and
-this permission notice appear in supporting documentation,
-and that the names of M.I.T. and the M.I.T. S.I.P.B. not be
-used in advertising or publicity pertaining to distribution
-of the software without specific, written prior permission.
-M.I.T. and the M.I.T. S.I.P.B. make no representations about
-the suitability of this software for any purpose. It is
-provided "as is" without express or implied warranty.
-
-*/
-
-#include <string.h>
-#include <assert.h>
-#include <errno.h>
-#include "prmem.h"
-#include "prerror.h"
-
-#define ERRCODE_RANGE 8 /* # of bits to shift table number */
-#define BITS_PER_CHAR 6 /* # bits to shift per character in name */
-
-#ifdef NEED_SYS_ERRLIST
-extern char const * const sys_errlist[];
-extern const int sys_nerr;
-#endif
-
-/* List of error tables */
-struct PRErrorTableList {
- struct PRErrorTableList *next;
- const struct PRErrorTable *table;
- struct PRErrorCallbackTablePrivate *table_private;
-};
-static struct PRErrorTableList * Table_List = (struct PRErrorTableList *) NULL;
-
-/* Supported languages */
-static const char * default_languages[] = { "i-default", "en", 0 };
-static const char * const * callback_languages = default_languages;
-
-/* Callback info */
-static struct PRErrorCallbackPrivate *callback_private = 0;
-static PRErrorCallbackLookupFn *callback_lookup = 0;
-static PRErrorCallbackNewTableFn *callback_newtable = 0;
-
-
-static const char char_set[] =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
-
-static const char *
-error_table_name (PRErrorCode num)
-{
- static char buf[6]; /* only used if internal code problems exist */
-
- long ch;
- int i;
- char *p;
-
- /* num = aa aaa abb bbb bcc ccc cdd ddd d?? ??? ??? */
- p = buf;
- num >>= ERRCODE_RANGE;
- /* num = ?? ??? ??? aaa aaa bbb bbb ccc ccc ddd ddd */
- num &= 077777777;
- /* num = 00 000 000 aaa aaa bbb bbb ccc ccc ddd ddd */
- for (i = 4; i >= 0; i--) {
- ch = (num >> BITS_PER_CHAR * i) & ((1 << BITS_PER_CHAR) - 1);
- if (ch != 0)
- *p++ = char_set[ch-1];
- }
- *p = '\0';
- return(buf);
-}
-
-PR_IMPLEMENT(const char *)
-PR_ErrorToString(PRErrorCode code, PRLanguageCode language)
-{
- /* static buffer only used if code is using inconsistent error message
- * numbers, so just ignore the possible thread contention
- */
- static char buffer[25];
-
- const char *msg;
- int offset;
- PRErrorCode table_num;
- struct PRErrorTableList *et;
- int started = 0;
- char *cp;
-
- for (et = Table_List; et; et = et->next) {
- if (et->table->base <= code &&
- et->table->base + et->table->n_msgs > code) {
- /* This is the right table */
- if (callback_lookup) {
- msg = callback_lookup(code, language, et->table,
- callback_private, et->table_private);
- if (msg) return msg;
- }
-
- return(et->table->msgs[code - et->table->base].en_text);
- }
- }
-
- if (code >= 0 && code < 256) {
- return strerror(code);
- }
-
- offset = (int) (code & ((1<<ERRCODE_RANGE)-1));
- table_num = code - offset;
- strcpy (buffer, "Unknown code ");
- if (table_num) {
- strcat(buffer, error_table_name (table_num));
- strcat(buffer, " ");
- }
- for (cp = buffer; *cp; cp++)
- ;
- if (offset >= 100) {
- *cp++ = (char)('0' + offset / 100);
- offset %= 100;
- started++;
- }
- if (started || offset >= 10) {
- *cp++ = (char)('0' + offset / 10);
- offset %= 10;
- }
- *cp++ = (char)('0' + offset);
- *cp = '\0';
- return(buffer);
-}
-
-PR_IMPLEMENT(const char *)
-PR_ErrorToName(PRErrorCode code)
-{
- struct PRErrorTableList *et;
-
- for (et = Table_List; et; et = et->next) {
- if (et->table->base <= code &&
- et->table->base + et->table->n_msgs > code) {
- /* This is the right table */
- return(et->table->msgs[code - et->table->base].name);
- }
- }
-
- return 0;
-}
-
-PR_IMPLEMENT(const char * const *)
-PR_ErrorLanguages(void)
-{
- return callback_languages;
-}
-
-PR_IMPLEMENT(PRErrorCode)
-PR_ErrorInstallTable(const struct PRErrorTable *table)
-{
- struct PRErrorTableList * new_et;
-
- new_et = (struct PRErrorTableList *)
- PR_Malloc(sizeof(struct PRErrorTableList));
- if (!new_et)
- return errno; /* oops */
- new_et->table = table;
- if (callback_newtable) {
- new_et->table_private = callback_newtable(table, callback_private);
- } else {
- new_et->table_private = 0;
- }
- new_et->next = Table_List;
- Table_List = new_et;
- return 0;
-}
-
-PR_IMPLEMENT(void)
-PR_ErrorInstallCallback(const char * const * languages,
- PRErrorCallbackLookupFn *lookup,
- PRErrorCallbackNewTableFn *newtable,
- struct PRErrorCallbackPrivate *cb_private)
-{
- struct PRErrorTableList *et;
-
- assert(strcmp(languages[0], "i-default") == 0);
- assert(strcmp(languages[1], "en") == 0);
-
- callback_languages = languages;
- callback_lookup = lookup;
- callback_newtable = newtable;
- callback_private = cb_private;
-
- if (callback_newtable) {
- for (et = Table_List; et; et = et->next) {
- et->table_private = callback_newtable(et->table, callback_private);
- }
- }
-}
diff --git a/nspr/pr/src/misc/prinit.c b/nspr/pr/src/misc/prinit.c
deleted file mode 100644
index 43048a0..0000000
--- a/nspr/pr/src/misc/prinit.c
+++ /dev/null
@@ -1,839 +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/. */
-
-#include "primpl.h"
-#include <ctype.h>
-#include <string.h>
-
-PRLogModuleInfo *_pr_clock_lm;
-PRLogModuleInfo *_pr_cmon_lm;
-PRLogModuleInfo *_pr_io_lm;
-PRLogModuleInfo *_pr_cvar_lm;
-PRLogModuleInfo *_pr_mon_lm;
-PRLogModuleInfo *_pr_linker_lm;
-PRLogModuleInfo *_pr_sched_lm;
-PRLogModuleInfo *_pr_thread_lm;
-PRLogModuleInfo *_pr_gc_lm;
-PRLogModuleInfo *_pr_shm_lm;
-PRLogModuleInfo *_pr_shma_lm;
-
-PRFileDesc *_pr_stdin;
-PRFileDesc *_pr_stdout;
-PRFileDesc *_pr_stderr;
-
-#if !defined(_PR_PTHREADS) && !defined(_PR_BTHREADS)
-
-PRCList _pr_active_local_threadQ =
- PR_INIT_STATIC_CLIST(&_pr_active_local_threadQ);
-PRCList _pr_active_global_threadQ =
- PR_INIT_STATIC_CLIST(&_pr_active_global_threadQ);
-
-_MDLock _pr_cpuLock; /* lock for the CPU Q */
-PRCList _pr_cpuQ = PR_INIT_STATIC_CLIST(&_pr_cpuQ);
-
-PRUint32 _pr_utid;
-
-PRInt32 _pr_userActive;
-PRInt32 _pr_systemActive;
-PRUintn _pr_maxPTDs;
-
-#ifdef _PR_LOCAL_THREADS_ONLY
-
-struct _PRCPU *_pr_currentCPU;
-PRThread *_pr_currentThread;
-PRThread *_pr_lastThread;
-PRInt32 _pr_intsOff;
-
-#endif /* _PR_LOCAL_THREADS_ONLY */
-
-/* Lock protecting all "termination" condition variables of all threads */
-PRLock *_pr_terminationCVLock;
-
-#endif /* !defined(_PR_PTHREADS) */
-
-PRLock *_pr_sleeplock; /* used in PR_Sleep(), classic and pthreads */
-
-static void _PR_InitCallOnce(void);
-
-PRBool _pr_initialized = PR_FALSE;
-
-
-PR_IMPLEMENT(PRBool) PR_VersionCheck(const char *importedVersion)
-{
- /*
- ** This is the secret handshake algorithm.
- **
- ** This release has a simple version compatibility
- ** check algorithm. This release is not backward
- ** compatible with previous major releases. It is
- ** not compatible with future major, minor, or
- ** patch releases.
- */
- int vmajor = 0, vminor = 0, vpatch = 0;
- const char *ptr = importedVersion;
-
- while (isdigit(*ptr)) {
- vmajor = 10 * vmajor + *ptr - '0';
- ptr++;
- }
- if (*ptr == '.') {
- ptr++;
- while (isdigit(*ptr)) {
- vminor = 10 * vminor + *ptr - '0';
- ptr++;
- }
- if (*ptr == '.') {
- ptr++;
- while (isdigit(*ptr)) {
- vpatch = 10 * vpatch + *ptr - '0';
- ptr++;
- }
- }
- }
-
- if (vmajor != PR_VMAJOR) {
- return PR_FALSE;
- }
- if (vmajor == PR_VMAJOR && vminor > PR_VMINOR) {
- return PR_FALSE;
- }
- if (vmajor == PR_VMAJOR && vminor == PR_VMINOR && vpatch > PR_VPATCH) {
- return PR_FALSE;
- }
- return PR_TRUE;
-} /* PR_VersionCheck */
-
-PR_IMPLEMENT(const char*) PR_GetVersion(void)
-{
- return PR_VERSION;
-}
-
-PR_IMPLEMENT(PRBool) PR_Initialized(void)
-{
- return _pr_initialized;
-}
-
-PRInt32 _native_threads_only = 0;
-
-#ifdef WINNT
-static void _pr_SetNativeThreadsOnlyMode(void)
-{
- HMODULE mainExe;
- PRBool *globalp;
- char *envp;
-
- mainExe = GetModuleHandle(NULL);
- PR_ASSERT(NULL != mainExe);
- globalp = (PRBool *) GetProcAddress(mainExe, "nspr_native_threads_only");
- if (globalp) {
- _native_threads_only = (*globalp != PR_FALSE);
- } else if (envp = getenv("NSPR_NATIVE_THREADS_ONLY")) {
- _native_threads_only = (atoi(envp) == 1);
- }
-}
-#endif
-
-static void _PR_InitStuff(void)
-{
-
- if (_pr_initialized) return;
- _pr_initialized = PR_TRUE;
-#ifdef _PR_ZONE_ALLOCATOR
- _PR_InitZones();
-#endif
-#ifdef WINNT
- _pr_SetNativeThreadsOnlyMode();
-#endif
-
-
- (void) PR_GetPageSize();
-
- _pr_clock_lm = PR_NewLogModule("clock");
- _pr_cmon_lm = PR_NewLogModule("cmon");
- _pr_io_lm = PR_NewLogModule("io");
- _pr_mon_lm = PR_NewLogModule("mon");
- _pr_linker_lm = PR_NewLogModule("linker");
- _pr_cvar_lm = PR_NewLogModule("cvar");
- _pr_sched_lm = PR_NewLogModule("sched");
- _pr_thread_lm = PR_NewLogModule("thread");
- _pr_gc_lm = PR_NewLogModule("gc");
- _pr_shm_lm = PR_NewLogModule("shm");
- _pr_shma_lm = PR_NewLogModule("shma");
-
- /* NOTE: These init's cannot depend on _PR_MD_CURRENT_THREAD() */
- _PR_MD_EARLY_INIT();
-
- _PR_InitLocks();
- _PR_InitAtomic();
- _PR_InitSegs();
- _PR_InitStacks();
- _PR_InitTPD();
- _PR_InitEnv();
- _PR_InitLayerCache();
- _PR_InitClock();
-
- _pr_sleeplock = PR_NewLock();
- PR_ASSERT(NULL != _pr_sleeplock);
-
- _PR_InitThreads(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
-
-#ifdef WIN16
- {
- PRInt32 top; /* artificial top of stack, win16 */
- _pr_top_of_task_stack = (char *) ⊤
- }
-#endif
-
-#ifndef _PR_GLOBAL_THREADS_ONLY
- _PR_InitCPUs();
-#endif
-
-/*
- * XXX: call _PR_InitMem only on those platforms for which nspr implements
- * malloc, for now.
- */
-#ifdef _PR_OVERRIDE_MALLOC
- _PR_InitMem();
-#endif
-
- _PR_InitCMon();
- _PR_InitIO();
- _PR_InitNet();
- _PR_InitTime();
- _PR_InitLog();
- _PR_InitLinker();
- _PR_InitCallOnce();
- _PR_InitDtoa();
- _PR_InitMW();
- _PR_InitRWLocks();
-
- nspr_InitializePRErrorTable();
-
- _PR_MD_FINAL_INIT();
-}
-
-void _PR_ImplicitInitialization(void)
-{
- _PR_InitStuff();
-
- /* Enable interrupts */
-#if !defined(_PR_PTHREADS) && !defined(_PR_GLOBAL_THREADS_ONLY)
- _PR_MD_START_INTERRUPTS();
-#endif
-
-}
-
-PR_IMPLEMENT(void) PR_DisableClockInterrupts(void)
-{
-#if !defined(_PR_PTHREADS) && !defined(_PR_BTHREADS)
- if (!_pr_initialized) {
- _PR_InitStuff();
- } else {
- _PR_MD_DISABLE_CLOCK_INTERRUPTS();
- }
-#endif
-}
-
-PR_IMPLEMENT(void) PR_EnableClockInterrupts(void)
-{
-#if !defined(_PR_PTHREADS) && !defined(_PR_BTHREADS)
- if (!_pr_initialized) {
- _PR_InitStuff();
- }
- _PR_MD_ENABLE_CLOCK_INTERRUPTS();
-#endif
-}
-
-PR_IMPLEMENT(void) PR_BlockClockInterrupts(void)
-{
-#if !defined(_PR_PTHREADS) && !defined(_PR_BTHREADS)
- _PR_MD_BLOCK_CLOCK_INTERRUPTS();
-#endif
-}
-
-PR_IMPLEMENT(void) PR_UnblockClockInterrupts(void)
-{
-#if !defined(_PR_PTHREADS) && !defined(_PR_BTHREADS)
- _PR_MD_UNBLOCK_CLOCK_INTERRUPTS();
-#endif
-}
-
-PR_IMPLEMENT(void) PR_Init(
- PRThreadType type, PRThreadPriority priority, PRUintn maxPTDs)
-{
- _PR_ImplicitInitialization();
-}
-
-PR_IMPLEMENT(PRIntn) PR_Initialize(
- PRPrimordialFn prmain, PRIntn argc, char **argv, PRUintn maxPTDs)
-{
- PRIntn rv;
- _PR_ImplicitInitialization();
- rv = prmain(argc, argv);
- PR_Cleanup();
- return rv;
-} /* PR_Initialize */
-
-/*
- *-----------------------------------------------------------------------
- *
- * _PR_CleanupBeforeExit --
- *
- * Perform the cleanup work before exiting the process.
- * We first do the cleanup generic to all platforms. Then
- * we call _PR_MD_CLEANUP_BEFORE_EXIT(), where platform-dependent
- * cleanup is done. This function is used by PR_Cleanup().
- *
- * See also: PR_Cleanup().
- *
- *-----------------------------------------------------------------------
- */
-#if defined(_PR_PTHREADS) || defined(_PR_BTHREADS)
- /* see ptthread.c */
-#else
-static void
-_PR_CleanupBeforeExit(void)
-{
-/*
-Do not make any calls here other than to destroy resources. For example,
-do not make any calls that eventually may end up in PR_Lock. Because the
-thread is destroyed, can not access current thread any more.
-*/
- _PR_CleanupTPD();
- if (_pr_terminationCVLock)
- /*
- * In light of the comment above, this looks real suspicious.
- * I'd go so far as to say it's just a problem waiting to happen.
- */
- PR_DestroyLock(_pr_terminationCVLock);
-
- _PR_MD_CLEANUP_BEFORE_EXIT();
-}
-#endif /* defined(_PR_PTHREADS) */
-
-/*
- *----------------------------------------------------------------------
- *
- * PR_Cleanup --
- *
- * Perform a graceful shutdown of the NSPR runtime. PR_Cleanup() may
- * only be called from the primordial thread, typically at the
- * end of the main() function. It returns when it has completed
- * its platform-dependent duty and the process must not make any other
- * NSPR library calls prior to exiting from main().
- *
- * PR_Cleanup() first blocks the primordial thread until all the
- * other user (non-system) threads, if any, have terminated.
- * Then it performs cleanup in preparation for exiting the process.
- * PR_Cleanup() does not exit the primordial thread (which would
- * in turn exit the process).
- *
- * PR_Cleanup() only responds when it is called by the primordial
- * thread. Calls by any other thread are silently ignored.
- *
- * See also: PR_ExitProcess()
- *
- *----------------------------------------------------------------------
- */
-#if defined(_PR_PTHREADS) || defined(_PR_BTHREADS)
- /* see ptthread.c */
-#else
-
-PR_IMPLEMENT(PRStatus) PR_Cleanup()
-{
- PRThread *me = PR_GetCurrentThread();
- PR_ASSERT((NULL != me) && (me->flags & _PR_PRIMORDIAL));
- if ((NULL != me) && (me->flags & _PR_PRIMORDIAL))
- {
- PR_LOG(_pr_thread_lm, PR_LOG_MIN, ("PR_Cleanup: shutting down NSPR"));
-
- /*
- * No more recycling of threads
- */
- _pr_recycleThreads = 0;
-
- /*
- * Wait for all other user (non-system/daemon) threads
- * to terminate.
- */
- PR_Lock(_pr_activeLock);
- while (_pr_userActive > _pr_primordialExitCount) {
- PR_WaitCondVar(_pr_primordialExitCVar, PR_INTERVAL_NO_TIMEOUT);
- }
- if (me->flags & _PR_SYSTEM) {
- _pr_systemActive--;
- } else {
- _pr_userActive--;
- }
- PR_Unlock(_pr_activeLock);
-
-#ifdef IRIX
- _PR_MD_PRE_CLEANUP(me);
- /*
- * The primordial thread must now be running on the primordial cpu
- */
- PR_ASSERT((_PR_IS_NATIVE_THREAD(me)) || (me->cpu->id == 0));
-#endif
-
- _PR_MD_EARLY_CLEANUP();
-
- _PR_CleanupMW();
- _PR_CleanupTime();
- _PR_CleanupDtoa();
- _PR_CleanupCallOnce();
- _PR_ShutdownLinker();
- _PR_CleanupNet();
- _PR_CleanupIO();
- /* Release the primordial thread's private data, etc. */
- _PR_CleanupThread(me);
-
- _PR_MD_STOP_INTERRUPTS();
-
- PR_LOG(_pr_thread_lm, PR_LOG_MIN,
- ("PR_Cleanup: clean up before destroying thread"));
- _PR_LogCleanup();
-
- /*
- * This part should look like the end of _PR_NativeRunThread
- * and _PR_UserRunThread.
- */
- if (_PR_IS_NATIVE_THREAD(me)) {
- _PR_MD_EXIT_THREAD(me);
- _PR_NativeDestroyThread(me);
- } else {
- _PR_UserDestroyThread(me);
- PR_DELETE(me->stack);
- PR_DELETE(me);
- }
-
- /*
- * XXX: We are freeing the heap memory here so that Purify won't
- * complain, but we should also free other kinds of resources
- * that are allocated by the _PR_InitXXX() functions.
- * Ideally, for each _PR_InitXXX(), there should be a corresponding
- * _PR_XXXCleanup() that we can call here.
- */
-#ifdef WINNT
- _PR_CleanupCPUs();
-#endif
- _PR_CleanupThreads();
- _PR_CleanupCMon();
- PR_DestroyLock(_pr_sleeplock);
- _pr_sleeplock = NULL;
- _PR_CleanupLayerCache();
- _PR_CleanupEnv();
- _PR_CleanupStacks();
- _PR_CleanupBeforeExit();
- _pr_initialized = PR_FALSE;
- return PR_SUCCESS;
- }
- return PR_FAILURE;
-}
-#endif /* defined(_PR_PTHREADS) */
-
-/*
- *------------------------------------------------------------------------
- * PR_ProcessExit --
- *
- * Cause an immediate, nongraceful, forced termination of the process.
- * It takes a PRIntn argument, which is the exit status code of the
- * process.
- *
- * See also: PR_Cleanup()
- *
- *------------------------------------------------------------------------
- */
-
-#if defined(_PR_PTHREADS) || defined(_PR_BTHREADS)
- /* see ptthread.c */
-#else
-PR_IMPLEMENT(void) PR_ProcessExit(PRIntn status)
-{
- _PR_MD_EXIT(status);
-}
-
-#endif /* defined(_PR_PTHREADS) */
-
-PR_IMPLEMENT(PRProcessAttr *)
-PR_NewProcessAttr(void)
-{
- PRProcessAttr *attr;
-
- attr = PR_NEWZAP(PRProcessAttr);
- if (!attr) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- }
- return attr;
-}
-
-PR_IMPLEMENT(void)
-PR_ResetProcessAttr(PRProcessAttr *attr)
-{
- PR_FREEIF(attr->currentDirectory);
- PR_FREEIF(attr->fdInheritBuffer);
- memset(attr, 0, sizeof(*attr));
-}
-
-PR_IMPLEMENT(void)
-PR_DestroyProcessAttr(PRProcessAttr *attr)
-{
- PR_FREEIF(attr->currentDirectory);
- PR_FREEIF(attr->fdInheritBuffer);
- PR_DELETE(attr);
-}
-
-PR_IMPLEMENT(void)
-PR_ProcessAttrSetStdioRedirect(
- PRProcessAttr *attr,
- PRSpecialFD stdioFd,
- PRFileDesc *redirectFd)
-{
- switch (stdioFd) {
- case PR_StandardInput:
- attr->stdinFd = redirectFd;
- break;
- case PR_StandardOutput:
- attr->stdoutFd = redirectFd;
- break;
- case PR_StandardError:
- attr->stderrFd = redirectFd;
- break;
- default:
- PR_ASSERT(0);
- }
-}
-
-/*
- * OBSOLETE
- */
-PR_IMPLEMENT(void)
-PR_SetStdioRedirect(
- PRProcessAttr *attr,
- PRSpecialFD stdioFd,
- PRFileDesc *redirectFd)
-{
-#if defined(DEBUG)
- static PRBool warn = PR_TRUE;
- if (warn) {
- warn = _PR_Obsolete("PR_SetStdioRedirect()",
- "PR_ProcessAttrSetStdioRedirect()");
- }
-#endif
- PR_ProcessAttrSetStdioRedirect(attr, stdioFd, redirectFd);
-}
-
-PR_IMPLEMENT(PRStatus)
-PR_ProcessAttrSetCurrentDirectory(
- PRProcessAttr *attr,
- const char *dir)
-{
- PR_FREEIF(attr->currentDirectory);
- attr->currentDirectory = (char *) PR_MALLOC(strlen(dir) + 1);
- if (!attr->currentDirectory) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return PR_FAILURE;
- }
- strcpy(attr->currentDirectory, dir);
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus)
-PR_ProcessAttrSetInheritableFD(
- PRProcessAttr *attr,
- PRFileDesc *fd,
- const char *name)
-{
- /* We malloc the fd inherit buffer in multiples of this number. */
-#define FD_INHERIT_BUFFER_INCR 128
- /* The length of "NSPR_INHERIT_FDS=" */
-#define NSPR_INHERIT_FDS_STRLEN 17
- /* The length of osfd (PROsfd) printed in hexadecimal with 0x prefix */
-#ifdef _WIN64
-#define OSFD_STRLEN 18
-#else
-#define OSFD_STRLEN 10
-#endif
- /* The length of fd type (PRDescType) printed in decimal */
-#define FD_TYPE_STRLEN 1
- PRSize newSize;
- int remainder;
- char *newBuffer;
- int nwritten;
- char *cur;
- int freeSize;
-
- if (fd->identity != PR_NSPR_IO_LAYER) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
- if (fd->secret->inheritable == _PR_TRI_UNKNOWN) {
- _PR_MD_QUERY_FD_INHERITABLE(fd);
- }
- if (fd->secret->inheritable != _PR_TRI_TRUE) {
- PR_SetError(PR_NO_ACCESS_RIGHTS_ERROR, 0);
- return PR_FAILURE;
- }
-
- /*
- * We also need to account for the : separators and the
- * terminating null byte.
- */
- if (NULL == attr->fdInheritBuffer) {
- /* The first time, we print "NSPR_INHERIT_FDS=<name>:<type>:<val>" */
- newSize = NSPR_INHERIT_FDS_STRLEN + strlen(name)
- + FD_TYPE_STRLEN + OSFD_STRLEN + 2 + 1;
- } else {
- /* At other times, we print ":<name>:<type>:<val>" */
- newSize = attr->fdInheritBufferUsed + strlen(name)
- + FD_TYPE_STRLEN + OSFD_STRLEN + 3 + 1;
- }
- if (newSize > attr->fdInheritBufferSize) {
- /* Make newSize a multiple of FD_INHERIT_BUFFER_INCR */
- remainder = newSize % FD_INHERIT_BUFFER_INCR;
- if (remainder != 0) {
- newSize += (FD_INHERIT_BUFFER_INCR - remainder);
- }
- if (NULL == attr->fdInheritBuffer) {
- newBuffer = (char *) PR_MALLOC(newSize);
- } else {
- newBuffer = (char *) PR_REALLOC(attr->fdInheritBuffer, newSize);
- }
- if (NULL == newBuffer) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return PR_FAILURE;
- }
- attr->fdInheritBuffer = newBuffer;
- attr->fdInheritBufferSize = newSize;
- }
- cur = attr->fdInheritBuffer + attr->fdInheritBufferUsed;
- freeSize = attr->fdInheritBufferSize - attr->fdInheritBufferUsed;
- if (0 == attr->fdInheritBufferUsed) {
- nwritten = PR_snprintf(cur, freeSize,
- "NSPR_INHERIT_FDS=%s:%d:0x%" PR_PRIxOSFD,
- name, (PRIntn)fd->methods->file_type, fd->secret->md.osfd);
- } else {
- nwritten = PR_snprintf(cur, freeSize, ":%s:%d:0x%" PR_PRIxOSFD,
- name, (PRIntn)fd->methods->file_type, fd->secret->md.osfd);
- }
- attr->fdInheritBufferUsed += nwritten;
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRFileDesc *) PR_GetInheritedFD(
- const char *name)
-{
- PRFileDesc *fd;
- const char *envVar;
- const char *ptr;
- int len = strlen(name);
- PROsfd osfd;
- int nColons;
- PRIntn fileType;
-
- envVar = PR_GetEnv("NSPR_INHERIT_FDS");
- if (NULL == envVar || '\0' == envVar[0]) {
- PR_SetError(PR_UNKNOWN_ERROR, 0);
- return NULL;
- }
-
- ptr = envVar;
- while (1) {
- if ((ptr[len] == ':') && (strncmp(ptr, name, len) == 0)) {
- ptr += len + 1;
- if (PR_sscanf(ptr, "%d:0x%" PR_SCNxOSFD, &fileType, &osfd) != 2) {
- PR_SetError(PR_UNKNOWN_ERROR, 0);
- return NULL;
- }
- switch ((PRDescType)fileType) {
- case PR_DESC_FILE:
- fd = PR_ImportFile(osfd);
- break;
- case PR_DESC_PIPE:
- fd = PR_ImportPipe(osfd);
- break;
- case PR_DESC_SOCKET_TCP:
- fd = PR_ImportTCPSocket(osfd);
- break;
- case PR_DESC_SOCKET_UDP:
- fd = PR_ImportUDPSocket(osfd);
- break;
- default:
- PR_ASSERT(0);
- PR_SetError(PR_UNKNOWN_ERROR, 0);
- fd = NULL;
- break;
- }
- if (fd) {
- /*
- * An inherited FD is inheritable by default.
- * The child process needs to call PR_SetFDInheritable
- * to make it non-inheritable if so desired.
- */
- fd->secret->inheritable = _PR_TRI_TRUE;
- }
- return fd;
- }
- /* Skip three colons */
- nColons = 0;
- while (*ptr) {
- if (*ptr == ':') {
- if (++nColons == 3) {
- break;
- }
- }
- ptr++;
- }
- if (*ptr == '\0') {
- PR_SetError(PR_UNKNOWN_ERROR, 0);
- return NULL;
- }
- ptr++;
- }
-}
-
-PR_IMPLEMENT(PRProcess*) PR_CreateProcess(
- const char *path,
- char *const *argv,
- char *const *envp,
- const PRProcessAttr *attr)
-{
- return _PR_MD_CREATE_PROCESS(path, argv, envp, attr);
-} /* PR_CreateProcess */
-
-PR_IMPLEMENT(PRStatus) PR_CreateProcessDetached(
- const char *path,
- char *const *argv,
- char *const *envp,
- const PRProcessAttr *attr)
-{
- PRProcess *process;
- PRStatus rv;
-
- process = PR_CreateProcess(path, argv, envp, attr);
- if (NULL == process) {
- return PR_FAILURE;
- }
- rv = PR_DetachProcess(process);
- PR_ASSERT(PR_SUCCESS == rv);
- if (rv == PR_FAILURE) {
- PR_DELETE(process);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus) PR_DetachProcess(PRProcess *process)
-{
- return _PR_MD_DETACH_PROCESS(process);
-}
-
-PR_IMPLEMENT(PRStatus) PR_WaitProcess(PRProcess *process, PRInt32 *exitCode)
-{
- return _PR_MD_WAIT_PROCESS(process, exitCode);
-} /* PR_WaitProcess */
-
-PR_IMPLEMENT(PRStatus) PR_KillProcess(PRProcess *process)
-{
- return _PR_MD_KILL_PROCESS(process);
-}
-
-/*
- ********************************************************************
- *
- * Module initialization
- *
- ********************************************************************
- */
-
-static struct {
- PRLock *ml;
- PRCondVar *cv;
-} mod_init;
-
-static void _PR_InitCallOnce(void) {
- mod_init.ml = PR_NewLock();
- PR_ASSERT(NULL != mod_init.ml);
- mod_init.cv = PR_NewCondVar(mod_init.ml);
- PR_ASSERT(NULL != mod_init.cv);
-}
-
-void _PR_CleanupCallOnce()
-{
- PR_DestroyLock(mod_init.ml);
- mod_init.ml = NULL;
- PR_DestroyCondVar(mod_init.cv);
- mod_init.cv = NULL;
-}
-
-PR_IMPLEMENT(PRStatus) PR_CallOnce(
- PRCallOnceType *once,
- PRCallOnceFN func)
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (!once->initialized) {
- if (PR_ATOMIC_SET(&once->inProgress, 1) == 0) {
- once->status = (*func)();
- PR_Lock(mod_init.ml);
- once->initialized = 1;
- PR_NotifyAllCondVar(mod_init.cv);
- PR_Unlock(mod_init.ml);
- } else {
- PR_Lock(mod_init.ml);
- while (!once->initialized) {
- PR_WaitCondVar(mod_init.cv, PR_INTERVAL_NO_TIMEOUT);
- }
- PR_Unlock(mod_init.ml);
- }
- } else {
- if (PR_SUCCESS != once->status) {
- PR_SetError(PR_CALL_ONCE_ERROR, 0);
- }
- }
- return once->status;
-}
-
-PR_IMPLEMENT(PRStatus) PR_CallOnceWithArg(
- PRCallOnceType *once,
- PRCallOnceWithArgFN func,
- void *arg)
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (!once->initialized) {
- if (PR_ATOMIC_SET(&once->inProgress, 1) == 0) {
- once->status = (*func)(arg);
- PR_Lock(mod_init.ml);
- once->initialized = 1;
- PR_NotifyAllCondVar(mod_init.cv);
- PR_Unlock(mod_init.ml);
- } else {
- PR_Lock(mod_init.ml);
- while (!once->initialized) {
- PR_WaitCondVar(mod_init.cv, PR_INTERVAL_NO_TIMEOUT);
- }
- PR_Unlock(mod_init.ml);
- }
- } else {
- if (PR_SUCCESS != once->status) {
- PR_SetError(PR_CALL_ONCE_ERROR, 0);
- }
- }
- return once->status;
-}
-
-PRBool _PR_Obsolete(const char *obsolete, const char *preferred)
-{
-#if defined(DEBUG)
- PR_fprintf(
- PR_STDERR, "'%s' is obsolete. Use '%s' instead.\n",
- obsolete, (NULL == preferred) ? "something else" : preferred);
-#endif
- return PR_FALSE;
-} /* _PR_Obsolete */
-
-/* prinit.c */
-
-
diff --git a/nspr/pr/src/misc/prinrval.c b/nspr/pr/src/misc/prinrval.c
deleted file mode 100644
index 50a938b..0000000
--- a/nspr/pr/src/misc/prinrval.c
+++ /dev/null
@@ -1,118 +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/. */
-
-/*
- * file: prinrval.c
- * description: implementation for the kernel interval timing functions
- */
-
-#include "primpl.h"
-
-/*
- *-----------------------------------------------------------------------
- *
- * _PR_InitClock --
- *
- *
- *-----------------------------------------------------------------------
- */
-
-void _PR_InitClock(void)
-{
- _PR_MD_INTERVAL_INIT();
-#ifdef DEBUG
- {
- PRIntervalTime ticksPerSec = PR_TicksPerSecond();
-
- PR_ASSERT(ticksPerSec >= PR_INTERVAL_MIN);
- PR_ASSERT(ticksPerSec <= PR_INTERVAL_MAX);
- }
-#endif /* DEBUG */
-}
-
-PR_IMPLEMENT(PRIntervalTime) PR_IntervalNow(void)
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
- return _PR_MD_GET_INTERVAL();
-} /* PR_IntervalNow */
-
-PR_EXTERN(PRUint32) PR_TicksPerSecond(void)
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
- return _PR_MD_INTERVAL_PER_SEC();
-} /* PR_TicksPerSecond */
-
-PR_IMPLEMENT(PRIntervalTime) PR_SecondsToInterval(PRUint32 seconds)
-{
- return seconds * PR_TicksPerSecond();
-} /* PR_SecondsToInterval */
-
-PR_IMPLEMENT(PRIntervalTime) PR_MillisecondsToInterval(PRUint32 milli)
-{
- PRIntervalTime ticks;
- PRUint64 tock, tps, msecPerSec, rounding;
- LL_UI2L(tock, milli);
- LL_I2L(msecPerSec, PR_MSEC_PER_SEC);
- LL_I2L(rounding, (PR_MSEC_PER_SEC >> 1));
- LL_I2L(tps, PR_TicksPerSecond());
- LL_MUL(tock, tock, tps);
- LL_ADD(tock, tock, rounding);
- LL_DIV(tock, tock, msecPerSec);
- LL_L2UI(ticks, tock);
- return ticks;
-} /* PR_MillisecondsToInterval */
-
-PR_IMPLEMENT(PRIntervalTime) PR_MicrosecondsToInterval(PRUint32 micro)
-{
- PRIntervalTime ticks;
- PRUint64 tock, tps, usecPerSec, rounding;
- LL_UI2L(tock, micro);
- LL_I2L(usecPerSec, PR_USEC_PER_SEC);
- LL_I2L(rounding, (PR_USEC_PER_SEC >> 1));
- LL_I2L(tps, PR_TicksPerSecond());
- LL_MUL(tock, tock, tps);
- LL_ADD(tock, tock, rounding);
- LL_DIV(tock, tock, usecPerSec);
- LL_L2UI(ticks, tock);
- return ticks;
-} /* PR_MicrosecondsToInterval */
-
-PR_IMPLEMENT(PRUint32) PR_IntervalToSeconds(PRIntervalTime ticks)
-{
- return ticks / PR_TicksPerSecond();
-} /* PR_IntervalToSeconds */
-
-PR_IMPLEMENT(PRUint32) PR_IntervalToMilliseconds(PRIntervalTime ticks)
-{
- PRUint32 milli;
- PRUint64 tock, tps, msecPerSec, rounding;
- LL_UI2L(tock, ticks);
- LL_I2L(msecPerSec, PR_MSEC_PER_SEC);
- LL_I2L(tps, PR_TicksPerSecond());
- LL_USHR(rounding, tps, 1);
- LL_MUL(tock, tock, msecPerSec);
- LL_ADD(tock, tock, rounding);
- LL_DIV(tock, tock, tps);
- LL_L2UI(milli, tock);
- return milli;
-} /* PR_IntervalToMilliseconds */
-
-PR_IMPLEMENT(PRUint32) PR_IntervalToMicroseconds(PRIntervalTime ticks)
-{
- PRUint32 micro;
- PRUint64 tock, tps, usecPerSec, rounding;
- LL_UI2L(tock, ticks);
- LL_I2L(usecPerSec, PR_USEC_PER_SEC);
- LL_I2L(tps, PR_TicksPerSecond());
- LL_USHR(rounding, tps, 1);
- LL_MUL(tock, tock, usecPerSec);
- LL_ADD(tock, tock, rounding);
- LL_DIV(tock, tock, tps);
- LL_L2UI(micro, tock);
- return micro;
-} /* PR_IntervalToMicroseconds */
-
-/* prinrval.c */
-
diff --git a/nspr/pr/src/misc/pripc.c b/nspr/pr/src/misc/pripc.c
deleted file mode 100644
index e41a2af..0000000
--- a/nspr/pr/src/misc/pripc.c
+++ /dev/null
@@ -1,100 +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/. */
-
-/*
- * File: pripc.c
- *
- * Description: functions for IPC support
- */
-
-#include "primpl.h"
-
-#include <string.h>
-
-/*
- * A POSIX IPC name must begin with a '/'.
- * A POSIX IPC name on Solaris cannot contain any '/' except
- * the required leading '/'.
- * A POSIX IPC name on HP-UX and OSF1 must be a valid pathname
- * in the file system.
- *
- * The ftok() function for System V IPC requires a valid pathname
- * in the file system.
- *
- * A Win32 IPC name cannot contain '\'.
- */
-
-static void _pr_ConvertSemName(char *result)
-{
-#ifdef _PR_HAVE_POSIX_SEMAPHORES
-#if defined(SOLARIS)
- char *p;
-
- /* Convert '/' to '_' except for the leading '/' */
- for (p = result+1; *p; p++) {
- if (*p == '/') {
- *p = '_';
- }
- }
- return;
-#else
- return;
-#endif
-#elif defined(_PR_HAVE_SYSV_SEMAPHORES)
- return;
-#elif defined(WIN32)
- return;
-#endif
-}
-
-static void _pr_ConvertShmName(char *result)
-{
-#if defined(PR_HAVE_POSIX_NAMED_SHARED_MEMORY)
-#if defined(SOLARIS)
- char *p;
-
- /* Convert '/' to '_' except for the leading '/' */
- for (p = result+1; *p; p++) {
- if (*p == '/') {
- *p = '_';
- }
- }
- return;
-#else
- return;
-#endif
-#elif defined(PR_HAVE_SYSV_NAMED_SHARED_MEMORY)
- return;
-#elif defined(WIN32)
- return;
-#else
- return;
-#endif
-}
-
-PRStatus _PR_MakeNativeIPCName(
- const char *name,
- char *result,
- PRIntn size,
- _PRIPCType type)
-{
- if (strlen(name) >= (PRSize)size) {
- PR_SetError(PR_BUFFER_OVERFLOW_ERROR, 0);
- return PR_FAILURE;
- }
- strcpy(result, name);
- switch (type) {
- case _PRIPCSem:
- _pr_ConvertSemName(result);
- break;
- case _PRIPCShm:
- _pr_ConvertShmName(result);
- break;
- default:
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
diff --git a/nspr/pr/src/misc/pripcsem.c b/nspr/pr/src/misc/pripcsem.c
deleted file mode 100644
index a176897..0000000
--- a/nspr/pr/src/misc/pripcsem.c
+++ /dev/null
@@ -1,98 +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/. */
-
-/*
- * File: pripcsem.c
- *
- * Description: implements the named semaphores API in prsemipc.h
- * for classic NSPR. If _PR_HAVE_NAMED_SEMAPHORES is not defined,
- * the named semaphore functions all fail with the error code
- * PR_NOT_IMPLEMENTED_ERROR.
- */
-
-#include "primpl.h"
-
-#ifdef _PR_PTHREADS
-
-#error "This file should not be compiled for the pthreads version"
-
-#else
-
-#ifndef _PR_HAVE_NAMED_SEMAPHORES
-
-PRSem * _PR_MD_OPEN_SEMAPHORE(
- const char *osname, PRIntn flags, PRIntn mode, PRUintn value)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return NULL;
-}
-
-PRStatus _PR_MD_WAIT_SEMAPHORE(PRSem *sem)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-}
-
-PRStatus _PR_MD_POST_SEMAPHORE(PRSem *sem)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-}
-
-PRStatus _PR_MD_CLOSE_SEMAPHORE(PRSem *sem)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-}
-
-PRStatus _PR_MD_DELETE_SEMAPHORE(const char *osname)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-}
-
-#endif /* !_PR_HAVE_NAMED_SEMAPHORES */
-
-PR_IMPLEMENT(PRSem *) PR_OpenSemaphore(
- const char *name, PRIntn flags, PRIntn mode, PRUintn value)
-{
- char osname[PR_IPC_NAME_SIZE];
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- if (_PR_MakeNativeIPCName(name, osname, sizeof(osname), _PRIPCSem)
- == PR_FAILURE) {
- return NULL;
- }
- return _PR_MD_OPEN_SEMAPHORE(osname, flags, mode, value);
-}
-
-PR_IMPLEMENT(PRStatus) PR_WaitSemaphore(PRSem *sem)
-{
- return _PR_MD_WAIT_SEMAPHORE(sem);
-}
-
-PR_IMPLEMENT(PRStatus) PR_PostSemaphore(PRSem *sem)
-{
- return _PR_MD_POST_SEMAPHORE(sem);
-}
-
-PR_IMPLEMENT(PRStatus) PR_CloseSemaphore(PRSem *sem)
-{
- return _PR_MD_CLOSE_SEMAPHORE(sem);
-}
-
-PR_IMPLEMENT(PRStatus) PR_DeleteSemaphore(const char *name)
-{
- char osname[PR_IPC_NAME_SIZE];
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- if (_PR_MakeNativeIPCName(name, osname, sizeof(osname), _PRIPCSem)
- == PR_FAILURE) {
- return PR_FAILURE;
- }
- return _PR_MD_DELETE_SEMAPHORE(osname);
-}
-
-#endif /* _PR_PTHREADS */
diff --git a/nspr/pr/src/misc/prlog2.c b/nspr/pr/src/misc/prlog2.c
deleted file mode 100644
index 2d476cd..0000000
--- a/nspr/pr/src/misc/prlog2.c
+++ /dev/null
@@ -1,27 +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/. */
-
-#include "prbit.h"
-
-/*
-** Compute the log of the least power of 2 greater than or equal to n
-*/
-PR_IMPLEMENT(PRIntn) PR_CeilingLog2(PRUint32 n)
-{
- PRIntn log2;
- PR_CEILING_LOG2(log2, n);
- return log2;
-}
-
-/*
-** Compute the log of the greatest power of 2 less than or equal to n.
-** This really just finds the highest set bit in the word.
-*/
-PR_IMPLEMENT(PRIntn) PR_FloorLog2(PRUint32 n)
-{
- PRIntn log2;
- PR_FLOOR_LOG2(log2, n);
- return log2;
-}
diff --git a/nspr/pr/src/misc/prlong.c b/nspr/pr/src/misc/prlong.c
deleted file mode 100644
index 701d081..0000000
--- a/nspr/pr/src/misc/prlong.c
+++ /dev/null
@@ -1,239 +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/. */
-
-#include "prlong.h"
-
-static PRInt64 ll_zero = LL_INIT( 0x00000000,0x00000000 );
-static PRInt64 ll_maxint = LL_INIT( 0x7fffffff, 0xffffffff );
-static PRInt64 ll_minint = LL_INIT( 0x80000000, 0x00000000 );
-static PRUint64 ll_maxuint = LL_INIT( 0xffffffff, 0xffffffff );
-
-PR_IMPLEMENT(PRInt64) LL_Zero(void) { return ll_zero; }
-PR_IMPLEMENT(PRInt64) LL_MaxInt(void) { return ll_maxint; }
-PR_IMPLEMENT(PRInt64) LL_MinInt(void) { return ll_minint; }
-PR_IMPLEMENT(PRUint64) LL_MaxUint(void) { return ll_maxuint; }
-
-#ifndef HAVE_LONG_LONG
-/*
-** Divide 64-bit a by 32-bit b, which must be normalized so its high bit is 1.
-*/
-static void norm_udivmod32(PRUint32 *qp, PRUint32 *rp, PRUint64 a, PRUint32 b)
-{
- PRUint32 d1, d0, q1, q0;
- PRUint32 r1, r0, m;
-
- d1 = _hi16(b);
- d0 = _lo16(b);
- r1 = a.hi % d1;
- q1 = a.hi / d1;
- m = q1 * d0;
- r1 = (r1 << 16) | _hi16(a.lo);
- if (r1 < m) {
- q1--, r1 += b;
- if (r1 >= b /* i.e., we didn't get a carry when adding to r1 */
- && r1 < m) {
- q1--, r1 += b;
- }
- }
- r1 -= m;
- r0 = r1 % d1;
- q0 = r1 / d1;
- m = q0 * d0;
- r0 = (r0 << 16) | _lo16(a.lo);
- if (r0 < m) {
- q0--, r0 += b;
- if (r0 >= b
- && r0 < m) {
- q0--, r0 += b;
- }
- }
- *qp = (q1 << 16) | q0;
- *rp = r0 - m;
-}
-
-static PRUint32 CountLeadingZeros(PRUint32 a)
-{
- PRUint32 t;
- PRUint32 r = 32;
-
- if ((t = a >> 16) != 0)
- r -= 16, a = t;
- if ((t = a >> 8) != 0)
- r -= 8, a = t;
- if ((t = a >> 4) != 0)
- r -= 4, a = t;
- if ((t = a >> 2) != 0)
- r -= 2, a = t;
- if ((t = a >> 1) != 0)
- r -= 1, a = t;
- if (a & 1)
- r--;
- return r;
-}
-
-PR_IMPLEMENT(void) ll_udivmod(PRUint64 *qp, PRUint64 *rp, PRUint64 a, PRUint64 b)
-{
- PRUint32 n0, n1, n2;
- PRUint32 q0, q1;
- PRUint32 rsh, lsh;
-
- n0 = a.lo;
- n1 = a.hi;
-
- if (b.hi == 0) {
- if (b.lo > n1) {
- /* (0 q0) = (n1 n0) / (0 D0) */
-
- lsh = CountLeadingZeros(b.lo);
-
- if (lsh) {
- /*
- * Normalize, i.e. make the most significant bit of the
- * denominator be set.
- */
- b.lo = b.lo << lsh;
- n1 = (n1 << lsh) | (n0 >> (32 - lsh));
- n0 = n0 << lsh;
- }
-
- a.lo = n0, a.hi = n1;
- norm_udivmod32(&q0, &n0, a, b.lo);
- q1 = 0;
-
- /* remainder is in n0 >> lsh */
- } else {
- /* (q1 q0) = (n1 n0) / (0 d0) */
-
- if (b.lo == 0) /* user wants to divide by zero! */
- b.lo = 1 / b.lo; /* so go ahead and crash */
-
- lsh = CountLeadingZeros(b.lo);
-
- if (lsh == 0) {
- /*
- * From (n1 >= b.lo)
- * && (the most significant bit of b.lo is set),
- * conclude that
- * (the most significant bit of n1 is set)
- * && (the leading quotient digit q1 = 1).
- *
- * This special case is necessary, not an optimization
- * (Shifts counts of 32 are undefined).
- */
- n1 -= b.lo;
- q1 = 1;
- } else {
- /*
- * Normalize.
- */
- rsh = 32 - lsh;
-
- b.lo = b.lo << lsh;
- n2 = n1 >> rsh;
- n1 = (n1 << lsh) | (n0 >> rsh);
- n0 = n0 << lsh;
-
- a.lo = n1, a.hi = n2;
- norm_udivmod32(&q1, &n1, a, b.lo);
- }
-
- /* n1 != b.lo... */
-
- a.lo = n0, a.hi = n1;
- norm_udivmod32(&q0, &n0, a, b.lo);
-
- /* remainder in n0 >> lsh */
- }
-
- if (rp) {
- rp->lo = n0 >> lsh;
- rp->hi = 0;
- }
- } else {
- if (b.hi > n1) {
- /* (0 0) = (n1 n0) / (D1 d0) */
-
- q0 = 0;
- q1 = 0;
-
- /* remainder in (n1 n0) */
- if (rp) {
- rp->lo = n0;
- rp->hi = n1;
- }
- } else {
- /* (0 q0) = (n1 n0) / (d1 d0) */
-
- lsh = CountLeadingZeros(b.hi);
- if (lsh == 0) {
- /*
- * From (n1 >= b.hi)
- * && (the most significant bit of b.hi is set),
- * conclude that
- * (the most significant bit of n1 is set)
- * && (the quotient digit q0 = 0 or 1).
- *
- * This special case is necessary, not an optimization.
- */
-
- /*
- * The condition on the next line takes advantage of that
- * n1 >= b.hi (true due to control flow).
- */
- if (n1 > b.hi || n0 >= b.lo) {
- q0 = 1;
- a.lo = n0, a.hi = n1;
- LL_SUB(a, a, b);
- } else {
- q0 = 0;
- }
- q1 = 0;
-
- if (rp) {
- rp->lo = n0;
- rp->hi = n1;
- }
- } else {
- PRInt64 m;
-
- /*
- * Normalize.
- */
- rsh = 32 - lsh;
-
- b.hi = (b.hi << lsh) | (b.lo >> rsh);
- b.lo = b.lo << lsh;
- n2 = n1 >> rsh;
- n1 = (n1 << lsh) | (n0 >> rsh);
- n0 = n0 << lsh;
-
- a.lo = n1, a.hi = n2;
- norm_udivmod32(&q0, &n1, a, b.hi);
- LL_MUL32(m, q0, b.lo);
-
- if ((m.hi > n1) || ((m.hi == n1) && (m.lo > n0))) {
- q0--;
- LL_SUB(m, m, b);
- }
-
- q1 = 0;
-
- /* Remainder is ((n1 n0) - (m1 m0)) >> lsh */
- if (rp) {
- a.lo = n0, a.hi = n1;
- LL_SUB(a, a, m);
- rp->lo = (a.hi << rsh) | (a.lo >> lsh);
- rp->hi = a.hi >> lsh;
- }
- }
- }
- }
-
- if (qp) {
- qp->lo = q0;
- qp->hi = q1;
- }
-}
-#endif /* !HAVE_LONG_LONG */
diff --git a/nspr/pr/src/misc/prnetdb.c b/nspr/pr/src/misc/prnetdb.c
deleted file mode 100644
index b2f6e43..0000000
--- a/nspr/pr/src/misc/prnetdb.c
+++ /dev/null
@@ -1,2342 +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/. */
-
-#include "primpl.h"
-
-#include <string.h>
-
-/*
- * On Unix, the error code for gethostbyname() and gethostbyaddr()
- * is returned in the global variable h_errno, instead of the usual
- * errno.
- */
-#if defined(XP_UNIX)
-#if defined(_PR_NEED_H_ERRNO)
-extern int h_errno;
-#endif
-#define _MD_GETHOST_ERRNO() h_errno
-#else
-#define _MD_GETHOST_ERRNO() _MD_ERRNO()
-#endif
-
-/*
- * The meaning of the macros related to gethostbyname, gethostbyaddr,
- * and gethostbyname2 is defined below.
- * - _PR_HAVE_THREADSAFE_GETHOST: the gethostbyXXX functions return
- * the result in thread specific storage. For example, AIX, HP-UX,
- * and OSF1.
- * - _PR_HAVE_GETHOST_R: have the gethostbyXXX_r functions. See next
- * two macros.
- * - _PR_HAVE_GETHOST_R_INT: the gethostbyXXX_r functions return an
- * int. For example, Linux glibc.
- * - _PR_HAVE_GETHOST_R_POINTER: the gethostbyXXX_r functions return
- * a struct hostent* pointer. For example, Solaris and IRIX.
- */
-#if defined(_PR_NO_PREEMPT) || defined(_PR_HAVE_GETHOST_R) \
- || defined(_PR_HAVE_THREADSAFE_GETHOST)
-#define _PR_NO_DNS_LOCK
-#endif
-
-#if defined(_PR_NO_DNS_LOCK)
-#define LOCK_DNS()
-#define UNLOCK_DNS()
-#else
-PRLock *_pr_dnsLock = NULL;
-#define LOCK_DNS() PR_Lock(_pr_dnsLock)
-#define UNLOCK_DNS() PR_Unlock(_pr_dnsLock)
-#endif /* defined(_PR_NO_DNS_LOCK) */
-
-/*
- * Some platforms have the reentrant getprotobyname_r() and
- * getprotobynumber_r(). However, they come in three flavors.
- * Some return a pointer to struct protoent, others return
- * an int, and glibc's flavor takes five arguments.
- */
-#if defined(XP_BEOS) && defined(BONE_VERSION)
-#include <arpa/inet.h> /* pick up define for inet_addr */
-#include <sys/socket.h>
-#define _PR_HAVE_GETPROTO_R
-#define _PR_HAVE_GETPROTO_R_POINTER
-#endif
-
-#if defined(SOLARIS) || (defined(BSDI) && defined(_REENTRANT)) \
- || (defined(LINUX) && defined(_REENTRANT) \
- && defined(__GLIBC__) && __GLIBC__ < 2)
-#define _PR_HAVE_GETPROTO_R
-#define _PR_HAVE_GETPROTO_R_POINTER
-#endif
-
-#if defined(OSF1) \
- || defined(AIX4_3_PLUS) || (defined(AIX) && defined(_THREAD_SAFE)) \
- || (defined(HPUX10_10) && defined(_REENTRANT)) \
- || (defined(HPUX10_20) && defined(_REENTRANT)) \
- || defined(OPENBSD)
-#define _PR_HAVE_GETPROTO_R
-#define _PR_HAVE_GETPROTO_R_INT
-#endif
-
-#if __FreeBSD_version >= 602000
-#define _PR_HAVE_GETPROTO_R
-#define _PR_HAVE_5_ARG_GETPROTO_R
-#endif
-
-/* BeOS has glibc but not the glibc-style getprotobyxxx_r functions. */
-#if (defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(XP_BEOS))
-#define _PR_HAVE_GETPROTO_R
-#define _PR_HAVE_5_ARG_GETPROTO_R
-#endif
-
-#if !defined(_PR_HAVE_GETPROTO_R)
-PRLock* _getproto_lock = NULL;
-#endif
-
-#if defined(_PR_INET6_PROBE)
-extern PRBool _pr_ipv6_is_present(void);
-#endif
-
-#define _PR_IN6_IS_ADDR_UNSPECIFIED(a) \
- (((a)->pr_s6_addr32[0] == 0) && \
- ((a)->pr_s6_addr32[1] == 0) && \
- ((a)->pr_s6_addr32[2] == 0) && \
- ((a)->pr_s6_addr32[3] == 0))
-
-#define _PR_IN6_IS_ADDR_LOOPBACK(a) \
- (((a)->pr_s6_addr32[0] == 0) && \
- ((a)->pr_s6_addr32[1] == 0) && \
- ((a)->pr_s6_addr32[2] == 0) && \
- ((a)->pr_s6_addr[12] == 0) && \
- ((a)->pr_s6_addr[13] == 0) && \
- ((a)->pr_s6_addr[14] == 0) && \
- ((a)->pr_s6_addr[15] == 0x1U))
-
-const PRIPv6Addr _pr_in6addr_any = {{{ 0, 0, 0, 0,
- 0, 0, 0, 0,
- 0, 0, 0, 0,
- 0, 0, 0, 0 }}};
-
-const PRIPv6Addr _pr_in6addr_loopback = {{{ 0, 0, 0, 0,
- 0, 0, 0, 0,
- 0, 0, 0, 0,
- 0, 0, 0, 0x1U }}};
-/*
- * The values at bytes 10 and 11 are compared using pointers to
- * 8-bit fields, and not 32-bit fields, to make the comparison work on
- * both big-endian and little-endian systems
- */
-
-#define _PR_IN6_IS_ADDR_V4MAPPED(a) \
- (((a)->pr_s6_addr32[0] == 0) && \
- ((a)->pr_s6_addr32[1] == 0) && \
- ((a)->pr_s6_addr[8] == 0) && \
- ((a)->pr_s6_addr[9] == 0) && \
- ((a)->pr_s6_addr[10] == 0xff) && \
- ((a)->pr_s6_addr[11] == 0xff))
-
-#define _PR_IN6_IS_ADDR_V4COMPAT(a) \
- (((a)->pr_s6_addr32[0] == 0) && \
- ((a)->pr_s6_addr32[1] == 0) && \
- ((a)->pr_s6_addr32[2] == 0))
-
-#define _PR_IN6_V4MAPPED_TO_IPADDR(a) ((a)->pr_s6_addr32[3])
-
-#if defined(_PR_INET6) && defined(_PR_HAVE_GETHOSTBYNAME2)
-
-/*
- * The _pr_QueryNetIfs() function finds out if the system has
- * IPv4 or IPv6 source addresses configured and sets _pr_have_inet_if
- * and _pr_have_inet6_if accordingly.
- *
- * We have an implementation using SIOCGIFCONF ioctl and a
- * default implementation that simply sets _pr_have_inet_if
- * and _pr_have_inet6_if to true. A better implementation
- * would be to use the routing sockets (see Chapter 17 of
- * W. Richard Stevens' Unix Network Programming, Vol. 1, 2nd. Ed.)
- */
-
-static PRLock *_pr_query_ifs_lock = NULL;
-static PRBool _pr_have_inet_if = PR_FALSE;
-static PRBool _pr_have_inet6_if = PR_FALSE;
-
-#undef DEBUG_QUERY_IFS
-
-#if defined(AIX) \
- || (defined(DARWIN) && (!defined(HAVE_GETIFADDRS) \
- || (defined(XP_MACOSX) && (!defined(MAC_OS_X_VERSION_10_2) || \
- MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_2))))
-
-/*
- * Use SIOCGIFCONF ioctl on platforms that don't have routing
- * sockets. Warning: whether SIOCGIFCONF ioctl returns AF_INET6
- * network interfaces is not portable.
- *
- * The _pr_QueryNetIfs() function is derived from the code in
- * src/lib/libc/net/getifaddrs.c in BSD Unix and the code in
- * Section 16.6 of W. Richard Stevens' Unix Network Programming,
- * Vol. 1, 2nd. Ed.
- */
-
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <net/if.h>
-
-#ifdef DEBUG_QUERY_IFS
-static void
-_pr_PrintIfreq(struct ifreq *ifr)
-{
- PRNetAddr addr;
- struct sockaddr *sa;
- const char* family;
- char addrstr[64];
-
- sa = &ifr->ifr_addr;
- if (sa->sa_family == AF_INET) {
- struct sockaddr_in *sin = (struct sockaddr_in *)sa;
- family = "inet";
- memcpy(&addr.inet.ip, &sin->sin_addr, sizeof(sin->sin_addr));
- } else if (sa->sa_family == AF_INET6) {
- struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
- family = "inet6";
- memcpy(&addr.ipv6.ip, &sin6->sin6_addr, sizeof(sin6->sin6_addr));
- } else {
- return; /* skip if not AF_INET or AF_INET6 */
- }
- addr.raw.family = sa->sa_family;
- PR_NetAddrToString(&addr, addrstr, sizeof(addrstr));
- printf("%s: %s %s\n", ifr->ifr_name, family, addrstr);
-}
-#endif
-
-static void
-_pr_QueryNetIfs(void)
-{
- int sock;
- int rv;
- struct ifconf ifc;
- struct ifreq *ifr;
- struct ifreq *lifr;
- PRUint32 len, lastlen;
- char *buf;
-
- if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
- return;
- }
-
- /* Issue SIOCGIFCONF request in a loop. */
- lastlen = 0;
- len = 100 * sizeof(struct ifreq); /* initial buffer size guess */
- for (;;) {
- buf = (char *)PR_Malloc(len);
- if (NULL == buf) {
- close(sock);
- return;
- }
- ifc.ifc_buf = buf;
- ifc.ifc_len = len;
- rv = ioctl(sock, SIOCGIFCONF, &ifc);
- if (rv < 0) {
- if (errno != EINVAL || lastlen != 0) {
- close(sock);
- PR_Free(buf);
- return;
- }
- } else {
- if (ifc.ifc_len == lastlen)
- break; /* success, len has not changed */
- lastlen = ifc.ifc_len;
- }
- len += 10 * sizeof(struct ifreq); /* increment */
- PR_Free(buf);
- }
- close(sock);
-
- ifr = ifc.ifc_req;
- lifr = (struct ifreq *)&ifc.ifc_buf[ifc.ifc_len];
-
- while (ifr < lifr) {
- struct sockaddr *sa;
- int sa_len;
-
-#ifdef DEBUG_QUERY_IFS
- _pr_PrintIfreq(ifr);
-#endif
- sa = &ifr->ifr_addr;
- if (sa->sa_family == AF_INET) {
- struct sockaddr_in *sin = (struct sockaddr_in *) sa;
- if (sin->sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
- _pr_have_inet_if = PR_TRUE;
- }
- } else if (sa->sa_family == AF_INET6) {
- struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
- if (!IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr)
- && !IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
- _pr_have_inet6_if = PR_TRUE;
- }
- }
-
-#ifdef _PR_HAVE_SOCKADDR_LEN
- sa_len = PR_MAX(sa->sa_len, sizeof(struct sockaddr));
-#else
- switch (sa->sa_family) {
-#ifdef AF_LINK
- case AF_LINK:
- sa_len = sizeof(struct sockaddr_dl);
- break;
-#endif
- case AF_INET6:
- sa_len = sizeof(struct sockaddr_in6);
- break;
- default:
- sa_len = sizeof(struct sockaddr);
- break;
- }
-#endif
- ifr = (struct ifreq *)(((char *)sa) + sa_len);
- }
- PR_Free(buf);
-}
-
-#elif (defined(DARWIN) && defined(HAVE_GETIFADDRS)) || defined(FREEBSD) \
- || defined(NETBSD) || defined(OPENBSD)
-
-/*
- * Use the BSD getifaddrs function.
- */
-
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <ifaddrs.h>
-#include <netinet/in.h>
-
-#ifdef DEBUG_QUERY_IFS
-static void
-_pr_PrintIfaddrs(struct ifaddrs *ifa)
-{
- struct sockaddr *sa;
- const char* family;
- void *addrp;
- char addrstr[64];
-
- sa = ifa->ifa_addr;
- if (sa->sa_family == AF_INET) {
- struct sockaddr_in *sin = (struct sockaddr_in *)sa;
- family = "inet";
- addrp = &sin->sin_addr;
- } else if (sa->sa_family == AF_INET6) {
- struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
- family = "inet6";
- addrp = &sin6->sin6_addr;
- } else {
- return; /* skip if not AF_INET or AF_INET6 */
- }
- inet_ntop(sa->sa_family, addrp, addrstr, sizeof(addrstr));
- printf("%s: %s %s\n", ifa->ifa_name, family, addrstr);
-}
-#endif
-
-static void
-_pr_QueryNetIfs(void)
-{
- struct ifaddrs *ifp;
- struct ifaddrs *ifa;
-
- if (getifaddrs(&ifp) == -1) {
- return;
- }
- for (ifa = ifp; ifa; ifa = ifa->ifa_next) {
- struct sockaddr *sa;
-
-#ifdef DEBUG_QUERY_IFS
- _pr_PrintIfaddrs(ifa);
-#endif
- sa = ifa->ifa_addr;
- if (sa->sa_family == AF_INET) {
- struct sockaddr_in *sin = (struct sockaddr_in *) sa;
- if (sin->sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
- _pr_have_inet_if = 1;
- }
- } else if (sa->sa_family == AF_INET6) {
- struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
- if (!IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr)
- && !IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
- _pr_have_inet6_if = 1;
- }
- }
- }
- freeifaddrs(ifp);
-}
-
-#else /* default */
-
-/*
- * Emulate the code in NSPR 4.2 or older. PR_GetIPNodeByName behaves
- * as if the system had both IPv4 and IPv6 source addresses configured.
- */
-static void
-_pr_QueryNetIfs(void)
-{
- _pr_have_inet_if = PR_TRUE;
- _pr_have_inet6_if = PR_TRUE;
-}
-
-#endif
-
-#endif /* _PR_INET6 && _PR_HAVE_GETHOSTBYNAME2 */
-
-void _PR_InitNet(void)
-{
-#if defined(XP_UNIX)
-#ifdef HAVE_NETCONFIG
- /*
- * This one-liner prevents the endless re-open's and re-read's of
- * /etc/netconfig on EACH and EVERY call to accept(), connect(), etc.
- */
- (void)setnetconfig();
-#endif
-#endif
-#if !defined(_PR_NO_DNS_LOCK)
- _pr_dnsLock = PR_NewLock();
-#endif
-#if !defined(_PR_HAVE_GETPROTO_R)
- _getproto_lock = PR_NewLock();
-#endif
-#if defined(_PR_INET6) && defined(_PR_HAVE_GETHOSTBYNAME2)
- _pr_query_ifs_lock = PR_NewLock();
-#endif
-}
-
-void _PR_CleanupNet(void)
-{
-#if !defined(_PR_NO_DNS_LOCK)
- if (_pr_dnsLock) {
- PR_DestroyLock(_pr_dnsLock);
- _pr_dnsLock = NULL;
- }
-#endif
-#if !defined(_PR_HAVE_GETPROTO_R)
- if (_getproto_lock) {
- PR_DestroyLock(_getproto_lock);
- _getproto_lock = NULL;
- }
-#endif
-#if defined(_PR_INET6) && defined(_PR_HAVE_GETHOSTBYNAME2)
- if (_pr_query_ifs_lock) {
- PR_DestroyLock(_pr_query_ifs_lock);
- _pr_query_ifs_lock = NULL;
- }
-#endif
-}
-
-/*
-** Allocate space from the buffer, aligning it to "align" before doing
-** the allocation. "align" must be a power of 2.
-*/
-static char *Alloc(PRIntn amount, char **bufp, PRIntn *buflenp, PRIntn align)
-{
- char *buf = *bufp;
- PRIntn buflen = *buflenp;
-
- if (align && ((long)buf & (align - 1))) {
- PRIntn skip = align - ((ptrdiff_t)buf & (align - 1));
- if (buflen < skip) {
- return 0;
- }
- buf += skip;
- buflen -= skip;
- }
- if (buflen < amount) {
- return 0;
- }
- *bufp = buf + amount;
- *buflenp = buflen - amount;
- return buf;
-}
-
-typedef enum _PRIPAddrConversion {
- _PRIPAddrNoConversion,
- _PRIPAddrIPv4Mapped,
- _PRIPAddrIPv4Compat
-} _PRIPAddrConversion;
-
-/*
-** Convert an IPv4 address (v4) to an IPv4-mapped IPv6 address (v6).
-*/
-static void MakeIPv4MappedAddr(const char *v4, char *v6)
-{
- memset(v6, 0, 10);
- memset(v6 + 10, 0xff, 2);
- memcpy(v6 + 12, v4, 4);
-}
-
-/*
-** Convert an IPv4 address (v4) to an IPv4-compatible IPv6 address (v6).
-*/
-static void MakeIPv4CompatAddr(const char *v4, char *v6)
-{
- memset(v6, 0, 12);
- memcpy(v6 + 12, v4, 4);
-}
-
-/*
-** Copy a hostent, and all of the memory that it refers to into
-** (hopefully) stacked buffers.
-*/
-static PRStatus CopyHostent(
- struct hostent *from,
- char **buf,
- PRIntn *bufsize,
- _PRIPAddrConversion conversion,
- PRHostEnt *to)
-{
- PRIntn len, na;
- char **ap;
-
- if (conversion != _PRIPAddrNoConversion
- && from->h_addrtype == AF_INET) {
- PR_ASSERT(from->h_length == 4);
- to->h_addrtype = PR_AF_INET6;
- to->h_length = 16;
- } else {
-#if defined(_PR_INET6) || defined(_PR_INET6_PROBE)
- if (AF_INET6 == from->h_addrtype)
- to->h_addrtype = PR_AF_INET6;
- else
-#endif
- to->h_addrtype = from->h_addrtype;
- to->h_length = from->h_length;
- }
-
- /* Copy the official name */
- if (!from->h_name) return PR_FAILURE;
- len = strlen(from->h_name) + 1;
- to->h_name = Alloc(len, buf, bufsize, 0);
- if (!to->h_name) return PR_FAILURE;
- memcpy(to->h_name, from->h_name, len);
-
- /* Count the aliases, then allocate storage for the pointers */
- if (!from->h_aliases) {
- na = 1;
- } else {
- for (na = 1, ap = from->h_aliases; *ap != 0; na++, ap++){;} /* nothing to execute */
- }
- to->h_aliases = (char**)Alloc(
- na * sizeof(char*), buf, bufsize, sizeof(char**));
- if (!to->h_aliases) return PR_FAILURE;
-
- /* Copy the aliases, one at a time */
- if (!from->h_aliases) {
- to->h_aliases[0] = 0;
- } else {
- for (na = 0, ap = from->h_aliases; *ap != 0; na++, ap++) {
- len = strlen(*ap) + 1;
- to->h_aliases[na] = Alloc(len, buf, bufsize, 0);
- if (!to->h_aliases[na]) return PR_FAILURE;
- memcpy(to->h_aliases[na], *ap, len);
- }
- to->h_aliases[na] = 0;
- }
-
- /* Count the addresses, then allocate storage for the pointers */
- for (na = 1, ap = from->h_addr_list; *ap != 0; na++, ap++){;} /* nothing to execute */
- to->h_addr_list = (char**)Alloc(
- na * sizeof(char*), buf, bufsize, sizeof(char**));
- if (!to->h_addr_list) return PR_FAILURE;
-
- /* Copy the addresses, one at a time */
- for (na = 0, ap = from->h_addr_list; *ap != 0; na++, ap++) {
- to->h_addr_list[na] = Alloc(to->h_length, buf, bufsize, 0);
- if (!to->h_addr_list[na]) return PR_FAILURE;
- if (conversion != _PRIPAddrNoConversion
- && from->h_addrtype == AF_INET) {
- if (conversion == _PRIPAddrIPv4Mapped) {
- MakeIPv4MappedAddr(*ap, to->h_addr_list[na]);
- } else {
- PR_ASSERT(conversion == _PRIPAddrIPv4Compat);
- MakeIPv4CompatAddr(*ap, to->h_addr_list[na]);
- }
- } else {
- memcpy(to->h_addr_list[na], *ap, to->h_length);
- }
- }
- to->h_addr_list[na] = 0;
- return PR_SUCCESS;
-}
-
-#ifdef SYMBIAN
-/* Set p_aliases by hand because Symbian's getprotobyname() returns NULL. */
-static void AssignAliases(struct protoent *Protoent, char** aliases)
-{
- if (NULL == Protoent->p_aliases) {
- if (0 == strcmp(Protoent->p_name, "ip"))
- aliases[0] = "IP";
- else if (0 == strcmp(Protoent->p_name, "tcp"))
- aliases[0] = "TCP";
- else if (0 == strcmp(Protoent->p_name, "udp"))
- aliases[0] = "UDP";
- else
- aliases[0] = "UNKNOWN";
- aliases[1] = NULL;
- Protoent->p_aliases = aliases;
- }
-}
-#endif
-
-#if !defined(_PR_HAVE_GETPROTO_R)
-/*
-** Copy a protoent, and all of the memory that it refers to into
-** (hopefully) stacked buffers.
-*/
-static PRStatus CopyProtoent(
- struct protoent *from, char *buf, PRIntn bufsize, PRProtoEnt *to)
-{
- PRIntn len, na;
- char **ap;
-
- /* Do the easy stuff */
- to->p_num = from->p_proto;
-
- /* Copy the official name */
- if (!from->p_name) return PR_FAILURE;
- len = strlen(from->p_name) + 1;
- to->p_name = Alloc(len, &buf, &bufsize, 0);
- if (!to->p_name) return PR_FAILURE;
- memcpy(to->p_name, from->p_name, len);
-
- /* Count the aliases, then allocate storage for the pointers */
- for (na = 1, ap = from->p_aliases; *ap != 0; na++, ap++){;} /* nothing to execute */
- to->p_aliases = (char**)Alloc(
- na * sizeof(char*), &buf, &bufsize, sizeof(char**));
- if (!to->p_aliases) return PR_FAILURE;
-
- /* Copy the aliases, one at a time */
- for (na = 0, ap = from->p_aliases; *ap != 0; na++, ap++) {
- len = strlen(*ap) + 1;
- to->p_aliases[na] = Alloc(len, &buf, &bufsize, 0);
- if (!to->p_aliases[na]) return PR_FAILURE;
- memcpy(to->p_aliases[na], *ap, len);
- }
- to->p_aliases[na] = 0;
-
- return PR_SUCCESS;
-}
-#endif /* !defined(_PR_HAVE_GETPROTO_R) */
-
-/*
- * #################################################################
- * NOTE: tmphe, tmpbuf, bufsize, h, and h_err are local variables
- * or arguments of PR_GetHostByName, PR_GetIPNodeByName, and
- * PR_GetHostByAddr. DO NOT CHANGE THE NAMES OF THESE LOCAL
- * VARIABLES OR ARGUMENTS.
- * #################################################################
- */
-#if defined(_PR_HAVE_GETHOST_R_INT)
-
-#define GETHOSTBYNAME(name) \
- (gethostbyname_r(name, &tmphe, tmpbuf, bufsize, &h, &h_err), h)
-#define GETHOSTBYNAME2(name, af) \
- (gethostbyname2_r(name, af, &tmphe, tmpbuf, bufsize, &h, &h_err), h)
-#define GETHOSTBYADDR(addr, addrlen, af) \
- (gethostbyaddr_r(addr, addrlen, af, \
- &tmphe, tmpbuf, bufsize, &h, &h_err), h)
-
-#elif defined(_PR_HAVE_GETHOST_R_POINTER)
-
-#define GETHOSTBYNAME(name) \
- gethostbyname_r(name, &tmphe, tmpbuf, bufsize, &h_err)
-#define GETHOSTBYNAME2(name, af) \
- gethostbyname2_r(name, af, &tmphe, tmpbuf, bufsize, &h_err)
-#define GETHOSTBYADDR(addr, addrlen, af) \
- gethostbyaddr_r(addr, addrlen, af, &tmphe, tmpbuf, bufsize, &h_err)
-
-#else
-
-#define GETHOSTBYNAME(name) gethostbyname(name)
-#define GETHOSTBYNAME2(name, af) gethostbyname2(name, af)
-#define GETHOSTBYADDR(addr, addrlen, af) gethostbyaddr(addr, addrlen, af)
-
-#endif /* definition of GETHOSTBYXXX */
-
-PR_IMPLEMENT(PRStatus) PR_GetHostByName(
- const char *name, char *buf, PRIntn bufsize, PRHostEnt *hp)
-{
- struct hostent *h;
- PRStatus rv = PR_FAILURE;
-#if defined(_PR_HAVE_GETHOST_R)
- char localbuf[PR_NETDB_BUF_SIZE];
- char *tmpbuf;
- struct hostent tmphe;
- int h_err;
-#endif
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
-#if defined(_PR_HAVE_GETHOST_R)
- tmpbuf = localbuf;
- if (bufsize > sizeof(localbuf))
- {
- tmpbuf = (char *)PR_Malloc(bufsize);
- if (NULL == tmpbuf)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return rv;
- }
- }
-#endif
-
- LOCK_DNS();
-
- h = GETHOSTBYNAME(name);
-
- if (NULL == h)
- {
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, _MD_GETHOST_ERRNO());
- }
- else
- {
- _PRIPAddrConversion conversion = _PRIPAddrNoConversion;
- rv = CopyHostent(h, &buf, &bufsize, conversion, hp);
- if (PR_SUCCESS != rv)
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
- }
- UNLOCK_DNS();
-#if defined(_PR_HAVE_GETHOST_R)
- if (tmpbuf != localbuf)
- PR_Free(tmpbuf);
-#endif
- return rv;
-}
-
-#if !defined(_PR_INET6) && \
- defined(_PR_INET6_PROBE) && defined(_PR_HAVE_GETIPNODEBYNAME)
-typedef struct hostent * (*_pr_getipnodebyname_t)(const char *, int,
- int, int *);
-typedef struct hostent * (*_pr_getipnodebyaddr_t)(const void *, size_t,
- int, int *);
-typedef void (*_pr_freehostent_t)(struct hostent *);
-static void * _pr_getipnodebyname_fp;
-static void * _pr_getipnodebyaddr_fp;
-static void * _pr_freehostent_fp;
-
-/*
- * Look up the addresses of getipnodebyname, getipnodebyaddr,
- * and freehostent.
- */
-PRStatus
-_pr_find_getipnodebyname(void)
-{
- PRLibrary *lib;
- PRStatus rv;
-#define GETIPNODEBYNAME "getipnodebyname"
-#define GETIPNODEBYADDR "getipnodebyaddr"
-#define FREEHOSTENT "freehostent"
-
- _pr_getipnodebyname_fp = PR_FindSymbolAndLibrary(GETIPNODEBYNAME, &lib);
- if (NULL != _pr_getipnodebyname_fp) {
- _pr_freehostent_fp = PR_FindSymbol(lib, FREEHOSTENT);
- if (NULL != _pr_freehostent_fp) {
- _pr_getipnodebyaddr_fp = PR_FindSymbol(lib, GETIPNODEBYADDR);
- if (NULL != _pr_getipnodebyaddr_fp)
- rv = PR_SUCCESS;
- else
- rv = PR_FAILURE;
- } else
- rv = PR_FAILURE;
- (void)PR_UnloadLibrary(lib);
- } else
- rv = PR_FAILURE;
- return rv;
-}
-#endif
-
-#if defined(_PR_INET6) && defined(_PR_HAVE_GETHOSTBYNAME2)
-/*
-** Append the V4 addresses to the end of the list
-*/
-static PRStatus AppendV4AddrsToHostent(
- struct hostent *from,
- char **buf,
- PRIntn *bufsize,
- PRHostEnt *to)
-{
- PRIntn na, na_old;
- char **ap;
- char **new_addr_list;
-
- /* Count the addresses, then grow storage for the pointers */
- for (na_old = 0, ap = to->h_addr_list; *ap != 0; na_old++, ap++)
- {;} /* nothing to execute */
- for (na = na_old + 1, ap = from->h_addr_list; *ap != 0; na++, ap++)
- {;} /* nothing to execute */
- new_addr_list = (char**)Alloc(
- na * sizeof(char*), buf, bufsize, sizeof(char**));
- if (!new_addr_list) return PR_FAILURE;
-
- /* Copy the V6 addresses, one at a time */
- for (na = 0, ap = to->h_addr_list; *ap != 0; na++, ap++) {
- new_addr_list[na] = to->h_addr_list[na];
- }
- to->h_addr_list = new_addr_list;
-
- /* Copy the V4 addresses, one at a time */
- for (ap = from->h_addr_list; *ap != 0; na++, ap++) {
- to->h_addr_list[na] = Alloc(to->h_length, buf, bufsize, 0);
- if (!to->h_addr_list[na]) return PR_FAILURE;
- MakeIPv4MappedAddr(*ap, to->h_addr_list[na]);
- }
- to->h_addr_list[na] = 0;
- return PR_SUCCESS;
-}
-#endif
-
-PR_IMPLEMENT(PRStatus) PR_GetIPNodeByName(
- const char *name, PRUint16 af, PRIntn flags,
- char *buf, PRIntn bufsize, PRHostEnt *hp)
-{
- struct hostent *h = 0;
- PRStatus rv = PR_FAILURE;
-#if defined(_PR_HAVE_GETHOST_R)
- char localbuf[PR_NETDB_BUF_SIZE];
- char *tmpbuf;
- struct hostent tmphe;
- int h_err;
-#endif
-#if defined(_PR_HAVE_GETIPNODEBYNAME)
- PRUint16 md_af = af;
- int error_num;
- int tmp_flags = 0;
-#endif
-#if defined(_PR_HAVE_GETHOSTBYNAME2)
- PRBool did_af_inet = PR_FALSE;
-#endif
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (af != PR_AF_INET && af != PR_AF_INET6) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
-
-#if defined(_PR_INET6) && defined(_PR_HAVE_GETHOSTBYNAME2)
- PR_Lock(_pr_query_ifs_lock);
- /*
- * Keep querying the presence of IPv4 and IPv6 interfaces until
- * at least one is up. This allows us to detect the local
- * machine going from offline to online.
- */
- if (!_pr_have_inet_if && !_pr_have_inet6_if) {
- _pr_QueryNetIfs();
-#ifdef DEBUG_QUERY_IFS
- if (_pr_have_inet_if)
- printf("Have IPv4 source address\n");
- if (_pr_have_inet6_if)
- printf("Have IPv6 source address\n");
-#endif
- }
- PR_Unlock(_pr_query_ifs_lock);
-#endif
-
-#if defined(_PR_HAVE_GETIPNODEBYNAME)
- if (flags & PR_AI_V4MAPPED)
- tmp_flags |= AI_V4MAPPED;
- if (flags & PR_AI_ADDRCONFIG)
- tmp_flags |= AI_ADDRCONFIG;
- if (flags & PR_AI_ALL)
- tmp_flags |= AI_ALL;
- if (af == PR_AF_INET6)
- md_af = AF_INET6;
- else
- md_af = af;
-#endif
-
-#if defined(_PR_HAVE_GETHOST_R)
- tmpbuf = localbuf;
- if (bufsize > sizeof(localbuf))
- {
- tmpbuf = (char *)PR_Malloc(bufsize);
- if (NULL == tmpbuf)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return rv;
- }
- }
-#endif
-
- /* Do not need to lock the DNS lock if getipnodebyname() is called */
-#ifdef _PR_INET6
-#ifdef _PR_HAVE_GETHOSTBYNAME2
- LOCK_DNS();
- if (af == PR_AF_INET6)
- {
- if ((flags & PR_AI_ADDRCONFIG) == 0 || _pr_have_inet6_if)
- {
-#ifdef _PR_INET6_PROBE
- if (_pr_ipv6_is_present())
-#endif
- h = GETHOSTBYNAME2(name, AF_INET6);
- }
- if ((NULL == h) && (flags & PR_AI_V4MAPPED)
- && ((flags & PR_AI_ADDRCONFIG) == 0 || _pr_have_inet_if))
- {
- did_af_inet = PR_TRUE;
- h = GETHOSTBYNAME2(name, AF_INET);
- }
- }
- else
- {
- if ((flags & PR_AI_ADDRCONFIG) == 0 || _pr_have_inet_if)
- {
- did_af_inet = PR_TRUE;
- h = GETHOSTBYNAME2(name, af);
- }
- }
-#elif defined(_PR_HAVE_GETIPNODEBYNAME)
- h = getipnodebyname(name, md_af, tmp_flags, &error_num);
-#else
-#error "Unknown name-to-address translation function"
-#endif /* _PR_HAVE_GETHOSTBYNAME2 */
-#elif defined(_PR_INET6_PROBE) && defined(_PR_HAVE_GETIPNODEBYNAME)
- if (_pr_ipv6_is_present())
- {
-#ifdef PR_GETIPNODE_NOT_THREADSAFE
- LOCK_DNS();
-#endif
- h = (*((_pr_getipnodebyname_t)_pr_getipnodebyname_fp))(name, md_af, tmp_flags, &error_num);
- }
- else
- {
- LOCK_DNS();
- h = GETHOSTBYNAME(name);
- }
-#else /* _PR_INET6 */
- LOCK_DNS();
- h = GETHOSTBYNAME(name);
-#endif /* _PR_INET6 */
-
- if (NULL == h)
- {
-#if defined(_PR_INET6) && defined(_PR_HAVE_GETIPNODEBYNAME)
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, error_num);
-#elif defined(_PR_INET6_PROBE) && defined(_PR_HAVE_GETIPNODEBYNAME)
- if (_pr_ipv6_is_present())
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, error_num);
- else
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, _MD_GETHOST_ERRNO());
-#else
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, _MD_GETHOST_ERRNO());
-#endif
- }
- else
- {
- _PRIPAddrConversion conversion = _PRIPAddrNoConversion;
-
- if (af == PR_AF_INET6) conversion = _PRIPAddrIPv4Mapped;
- rv = CopyHostent(h, &buf, &bufsize, conversion, hp);
- if (PR_SUCCESS != rv)
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
-#if defined(_PR_INET6) && defined(_PR_HAVE_GETIPNODEBYNAME)
- freehostent(h);
-#elif defined(_PR_INET6_PROBE) && defined(_PR_HAVE_GETIPNODEBYNAME)
- if (_pr_ipv6_is_present())
- (*((_pr_freehostent_t)_pr_freehostent_fp))(h);
-#endif
-#if defined(_PR_INET6) && defined(_PR_HAVE_GETHOSTBYNAME2)
- if ((PR_SUCCESS == rv) && (flags & PR_AI_V4MAPPED)
- && ((flags & PR_AI_ALL)
- || ((flags & PR_AI_ADDRCONFIG) && _pr_have_inet_if))
- && !did_af_inet && (h = GETHOSTBYNAME2(name, AF_INET)) != 0) {
- rv = AppendV4AddrsToHostent(h, &buf, &bufsize, hp);
- if (PR_SUCCESS != rv)
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
- }
-#endif
- }
-
- /* Must match the convoluted logic above for LOCK_DNS() */
-#ifdef _PR_INET6
-#ifdef _PR_HAVE_GETHOSTBYNAME2
- UNLOCK_DNS();
-#endif /* _PR_HAVE_GETHOSTBYNAME2 */
-#elif defined(_PR_INET6_PROBE) && defined(_PR_HAVE_GETIPNODEBYNAME)
-#ifdef PR_GETIPNODE_NOT_THREADSAFE
- UNLOCK_DNS();
-#else
- if (!_pr_ipv6_is_present())
- UNLOCK_DNS();
-#endif
-#else /* _PR_INET6 */
- UNLOCK_DNS();
-#endif /* _PR_INET6 */
-
-#if defined(_PR_HAVE_GETHOST_R)
- if (tmpbuf != localbuf)
- PR_Free(tmpbuf);
-#endif
-
- return rv;
-}
-
-PR_IMPLEMENT(PRStatus) PR_GetHostByAddr(
- const PRNetAddr *hostaddr, char *buf, PRIntn bufsize, PRHostEnt *hostentry)
-{
- struct hostent *h;
- PRStatus rv = PR_FAILURE;
- const void *addr;
- PRUint32 tmp_ip;
- int addrlen;
- PRInt32 af;
-#if defined(_PR_HAVE_GETHOST_R)
- char localbuf[PR_NETDB_BUF_SIZE];
- char *tmpbuf;
- struct hostent tmphe;
- int h_err;
-#endif
-#if defined(_PR_HAVE_GETIPNODEBYADDR)
- int error_num;
-#endif
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (hostaddr->raw.family == PR_AF_INET6)
- {
-#if defined(_PR_INET6_PROBE)
- af = _pr_ipv6_is_present() ? AF_INET6 : AF_INET;
-#elif defined(_PR_INET6)
- af = AF_INET6;
-#else
- af = AF_INET;
-#endif
-#if defined(_PR_GHBA_DISALLOW_V4MAPPED)
- if (_PR_IN6_IS_ADDR_V4MAPPED(&hostaddr->ipv6.ip))
- af = AF_INET;
-#endif
- }
- else
- {
- PR_ASSERT(hostaddr->raw.family == AF_INET);
- af = AF_INET;
- }
- if (hostaddr->raw.family == PR_AF_INET6) {
-#if defined(_PR_INET6) || defined(_PR_INET6_PROBE)
- if (af == AF_INET6) {
- addr = &hostaddr->ipv6.ip;
- addrlen = sizeof(hostaddr->ipv6.ip);
- }
- else
-#endif
- {
- PR_ASSERT(af == AF_INET);
- if (!_PR_IN6_IS_ADDR_V4MAPPED(&hostaddr->ipv6.ip)) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return rv;
- }
- tmp_ip = _PR_IN6_V4MAPPED_TO_IPADDR((PRIPv6Addr *)
- &hostaddr->ipv6.ip);
- addr = &tmp_ip;
- addrlen = sizeof(tmp_ip);
- }
- } else {
- PR_ASSERT(hostaddr->raw.family == AF_INET);
- PR_ASSERT(af == AF_INET);
- addr = &hostaddr->inet.ip;
- addrlen = sizeof(hostaddr->inet.ip);
- }
-
-#if defined(_PR_HAVE_GETHOST_R)
- tmpbuf = localbuf;
- if (bufsize > sizeof(localbuf))
- {
- tmpbuf = (char *)PR_Malloc(bufsize);
- if (NULL == tmpbuf)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return rv;
- }
- }
-#endif
-
- /* Do not need to lock the DNS lock if getipnodebyaddr() is called */
-#if defined(_PR_HAVE_GETIPNODEBYADDR) && defined(_PR_INET6)
- h = getipnodebyaddr(addr, addrlen, af, &error_num);
-#elif defined(_PR_HAVE_GETIPNODEBYADDR) && defined(_PR_INET6_PROBE)
- if (_pr_ipv6_is_present())
- {
-#ifdef PR_GETIPNODE_NOT_THREADSAFE
- LOCK_DNS();
-#endif
- h = (*((_pr_getipnodebyaddr_t)_pr_getipnodebyaddr_fp))(addr, addrlen,
- af, &error_num);
- }
- else
- {
- LOCK_DNS();
- h = GETHOSTBYADDR(addr, addrlen, af);
- }
-#else /* _PR_HAVE_GETIPNODEBYADDR */
- LOCK_DNS();
- h = GETHOSTBYADDR(addr, addrlen, af);
-#endif /* _PR_HAVE_GETIPNODEBYADDR */
- if (NULL == h)
- {
-#if defined(_PR_INET6) && defined(_PR_HAVE_GETIPNODEBYADDR)
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, error_num);
-#elif defined(_PR_INET6_PROBE) && defined(_PR_HAVE_GETIPNODEBYADDR)
- if (_pr_ipv6_is_present())
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, error_num);
- else
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, _MD_GETHOST_ERRNO());
-#else
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, _MD_GETHOST_ERRNO());
-#endif
- }
- else
- {
- _PRIPAddrConversion conversion = _PRIPAddrNoConversion;
- if (hostaddr->raw.family == PR_AF_INET6) {
- if (af == AF_INET) {
- if (_PR_IN6_IS_ADDR_V4MAPPED((PRIPv6Addr*)
- &hostaddr->ipv6.ip)) {
- conversion = _PRIPAddrIPv4Mapped;
- } else if (_PR_IN6_IS_ADDR_V4COMPAT((PRIPv6Addr *)
- &hostaddr->ipv6.ip)) {
- conversion = _PRIPAddrIPv4Compat;
- }
- }
- }
- rv = CopyHostent(h, &buf, &bufsize, conversion, hostentry);
- if (PR_SUCCESS != rv) {
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
- }
-#if defined(_PR_INET6) && defined(_PR_HAVE_GETIPNODEBYADDR)
- freehostent(h);
-#elif defined(_PR_INET6_PROBE) && defined(_PR_HAVE_GETIPNODEBYADDR)
- if (_pr_ipv6_is_present())
- (*((_pr_freehostent_t)_pr_freehostent_fp))(h);
-#endif
- }
-
- /* Must match the convoluted logic above for LOCK_DNS() */
-#if defined(_PR_HAVE_GETIPNODEBYADDR) && defined(_PR_INET6)
-#elif defined(_PR_HAVE_GETIPNODEBYADDR) && defined(_PR_INET6_PROBE)
-#ifdef PR_GETIPNODE_NOT_THREADSAFE
- UNLOCK_DNS();
-#else
- if (!_pr_ipv6_is_present())
- UNLOCK_DNS();
-#endif
-#else /* _PR_HAVE_GETIPNODEBYADDR */
- UNLOCK_DNS();
-#endif /* _PR_HAVE_GETIPNODEBYADDR */
-
-#if defined(_PR_HAVE_GETHOST_R)
- if (tmpbuf != localbuf)
- PR_Free(tmpbuf);
-#endif
-
- return rv;
-}
-
-/******************************************************************************/
-/*
- * Some systems define a reentrant version of getprotobyname(). Too bad
- * the signature isn't always the same. But hey, they tried. If there
- * is such a definition, use it. Otherwise, grab a lock and do it here.
- */
-/******************************************************************************/
-
-#if !defined(_PR_HAVE_GETPROTO_R)
-/*
- * This may seem like a silly thing to do, but the compiler SHOULD
- * complain if getprotobyname_r() is implemented on some system and
- * we're not using it. For sure these signatures are different than
- * any usable implementation.
- */
-
-#if defined(ANDROID)
-/* Android's Bionic libc system includes prototypes for these in netdb.h,
- * but doesn't actually include implementations. It uses the 5-arg form,
- * so these functions end up not matching the prototype. So just rename
- * them if not found.
- */
-#define getprotobyname_r _pr_getprotobyname_r
-#define getprotobynumber_r _pr_getprotobynumber_r
-#endif
-
-static struct protoent *getprotobyname_r(const char* name)
-{
- return getprotobyname(name);
-} /* getprotobyname_r */
-
-static struct protoent *getprotobynumber_r(PRInt32 number)
-{
- return getprotobynumber(number);
-} /* getprotobynumber_r */
-
-#endif /* !defined(_PR_HAVE_GETPROTO_R) */
-
-PR_IMPLEMENT(PRStatus) PR_GetProtoByName(
- const char* name, char* buffer, PRInt32 buflen, PRProtoEnt* result)
-{
- PRStatus rv = PR_SUCCESS;
-#if defined(_PR_HAVE_GETPROTO_R)
- struct protoent* res = (struct protoent*)result;
-#endif
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
-#if defined(_PR_HAVE_GETPROTO_R_INT)
- {
- /*
- ** The protoent_data has a pointer as the first field.
- ** That implies the buffer better be aligned, and char*
- ** doesn't promise much.
- */
- PRUptrdiff aligned = (PRUptrdiff)buffer;
- if (0 != (aligned & (sizeof(struct protoent_data*) - 1)))
- {
- aligned += sizeof(struct protoent_data*) - 1;
- aligned &= ~(sizeof(struct protoent_data*) - 1);
- buflen -= (aligned - (PRUptrdiff)buffer);
- buffer = (char*)aligned;
- }
- }
-#endif /* defined(_PR_HAVE_GETPROTO_R_INT) */
-
- if (PR_NETDB_BUF_SIZE > buflen)
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
-
-#if defined(_PR_HAVE_GETPROTO_R_POINTER)
- if (NULL == getprotobyname_r(name, res, buffer, buflen))
- {
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, _MD_ERRNO());
- return PR_FAILURE;
- }
-#elif defined(_PR_HAVE_GETPROTO_R_INT)
- /*
- ** The buffer needs to be zero'd, and it should be
- ** at least the size of a struct protoent_data.
- */
- memset(buffer, 0, buflen);
- if (-1 == getprotobyname_r(name, res, (struct protoent_data*)buffer))
- {
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, _MD_ERRNO());
- return PR_FAILURE;
- }
-#elif defined(_PR_HAVE_5_ARG_GETPROTO_R)
- /* The 5th argument for getprotobyname_r() cannot be NULL */
- if (-1 == getprotobyname_r(name, res, buffer, buflen, &res))
- {
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, _MD_ERRNO());
- return PR_FAILURE;
- }
-#else /* do it the hard way */
- {
- struct protoent *staticBuf;
- PR_Lock(_getproto_lock);
- staticBuf = getprotobyname_r(name);
- if (NULL == staticBuf)
- {
- rv = PR_FAILURE;
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, _MD_ERRNO());
- }
- else
- {
-#if defined(SYMBIAN)
- char* aliases[2];
- AssignAliases(staticBuf, aliases);
-#endif
- rv = CopyProtoent(staticBuf, buffer, buflen, result);
- if (PR_FAILURE == rv)
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
- }
- PR_Unlock(_getproto_lock);
- }
-#endif /* all that */
- return rv;
-}
-
-PR_IMPLEMENT(PRStatus) PR_GetProtoByNumber(
- PRInt32 number, char* buffer, PRInt32 buflen, PRProtoEnt* result)
-{
- PRStatus rv = PR_SUCCESS;
-#if defined(_PR_HAVE_GETPROTO_R)
- struct protoent* res = (struct protoent*)result;
-#endif
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
-#if defined(_PR_HAVE_GETPROTO_R_INT)
- {
- /*
- ** The protoent_data has a pointer as the first field.
- ** That implies the buffer better be aligned, and char*
- ** doesn't promise much.
- */
- PRUptrdiff aligned = (PRUptrdiff)buffer;
- if (0 != (aligned & (sizeof(struct protoent_data*) - 1)))
- {
- aligned += sizeof(struct protoent_data*) - 1;
- aligned &= ~(sizeof(struct protoent_data*) - 1);
- buflen -= (aligned - (PRUptrdiff)buffer);
- buffer = (char*)aligned;
- }
- }
-#endif /* defined(_PR_HAVE_GETPROTO_R_INT) */
-
- if (PR_NETDB_BUF_SIZE > buflen)
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
-
-#if defined(_PR_HAVE_GETPROTO_R_POINTER)
- if (NULL == getprotobynumber_r(number, res, buffer, buflen))
- {
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, _MD_ERRNO());
- return PR_FAILURE;
- }
-
-#elif defined(_PR_HAVE_GETPROTO_R_INT)
- /*
- ** The buffer needs to be zero'd for these OS's.
- */
- memset(buffer, 0, buflen);
- if (-1 == getprotobynumber_r(number, res, (struct protoent_data*)buffer))
- {
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, _MD_ERRNO());
- return PR_FAILURE;
- }
-#elif defined(_PR_HAVE_5_ARG_GETPROTO_R)
- /* The 5th argument for getprotobynumber_r() cannot be NULL */
- if (-1 == getprotobynumber_r(number, res, buffer, buflen, &res))
- {
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, _MD_ERRNO());
- return PR_FAILURE;
- }
-#else /* do it the hard way */
- {
- struct protoent *staticBuf;
- PR_Lock(_getproto_lock);
- staticBuf = getprotobynumber_r(number);
- if (NULL == staticBuf)
- {
- rv = PR_FAILURE;
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, _MD_ERRNO());
- }
- else
- {
-#if defined(SYMBIAN)
- char* aliases[2];
- AssignAliases(staticBuf, aliases);
-#endif
- rv = CopyProtoent(staticBuf, buffer, buflen, result);
- if (PR_FAILURE == rv)
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
- }
- PR_Unlock(_getproto_lock);
- }
-#endif /* all that crap */
- return rv;
-
-}
-
-PRUintn _PR_NetAddrSize(const PRNetAddr* addr)
-{
- PRUintn addrsize;
-
- /*
- * RFC 2553 added a new field (sin6_scope_id) to
- * struct sockaddr_in6. PRNetAddr's ipv6 member has a
- * scope_id field to match the new field. In order to
- * work with older implementations supporting RFC 2133,
- * we take the size of struct sockaddr_in6 instead of
- * addr->ipv6.
- */
- if (AF_INET == addr->raw.family)
- addrsize = sizeof(addr->inet);
- else if (PR_AF_INET6 == addr->raw.family)
-#if defined(_PR_INET6)
- addrsize = sizeof(struct sockaddr_in6);
-#else
- addrsize = sizeof(addr->ipv6);
-#endif
-#if defined(XP_UNIX) || defined(XP_OS2)
- else if (AF_UNIX == addr->raw.family)
- addrsize = sizeof(addr->local);
-#endif
- else addrsize = 0;
-
- return addrsize;
-} /* _PR_NetAddrSize */
-
-PR_IMPLEMENT(PRIntn) PR_EnumerateHostEnt(
- PRIntn enumIndex, const PRHostEnt *hostEnt, PRUint16 port, PRNetAddr *address)
-{
- void *addr = hostEnt->h_addr_list[enumIndex++];
- memset(address, 0, sizeof(PRNetAddr));
- if (NULL == addr) enumIndex = 0;
- else
- {
- address->raw.family = hostEnt->h_addrtype;
- if (PR_AF_INET6 == hostEnt->h_addrtype)
- {
- address->ipv6.port = htons(port);
- address->ipv6.flowinfo = 0;
- address->ipv6.scope_id = 0;
- memcpy(&address->ipv6.ip, addr, hostEnt->h_length);
- }
- else
- {
- PR_ASSERT(AF_INET == hostEnt->h_addrtype);
- address->inet.port = htons(port);
- memcpy(&address->inet.ip, addr, hostEnt->h_length);
- }
- }
- return enumIndex;
-} /* PR_EnumerateHostEnt */
-
-PR_IMPLEMENT(PRStatus) PR_InitializeNetAddr(
- PRNetAddrValue val, PRUint16 port, PRNetAddr *addr)
-{
- PRStatus rv = PR_SUCCESS;
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (val != PR_IpAddrNull) memset(addr, 0, sizeof(addr->inet));
- addr->inet.family = AF_INET;
- addr->inet.port = htons(port);
- switch (val)
- {
- case PR_IpAddrNull:
- break; /* don't overwrite the address */
- case PR_IpAddrAny:
- addr->inet.ip = htonl(INADDR_ANY);
- break;
- case PR_IpAddrLoopback:
- addr->inet.ip = htonl(INADDR_LOOPBACK);
- break;
- default:
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- rv = PR_FAILURE;
- }
- return rv;
-} /* PR_InitializeNetAddr */
-
-PR_IMPLEMENT(PRStatus) PR_SetNetAddr(
- PRNetAddrValue val, PRUint16 af, PRUint16 port, PRNetAddr *addr)
-{
- PRStatus rv = PR_SUCCESS;
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (af == PR_AF_INET6)
- {
- if (val != PR_IpAddrNull) memset(addr, 0, sizeof(addr->ipv6));
- addr->ipv6.family = af;
- addr->ipv6.port = htons(port);
- addr->ipv6.flowinfo = 0;
- addr->ipv6.scope_id = 0;
- switch (val)
- {
- case PR_IpAddrNull:
- break; /* don't overwrite the address */
- case PR_IpAddrAny:
- addr->ipv6.ip = _pr_in6addr_any;
- break;
- case PR_IpAddrLoopback:
- addr->ipv6.ip = _pr_in6addr_loopback;
- break;
- default:
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- rv = PR_FAILURE;
- }
- }
- else
- {
- if (val != PR_IpAddrNull) memset(addr, 0, sizeof(addr->inet));
- addr->inet.family = af;
- addr->inet.port = htons(port);
- switch (val)
- {
- case PR_IpAddrNull:
- break; /* don't overwrite the address */
- case PR_IpAddrAny:
- addr->inet.ip = htonl(INADDR_ANY);
- break;
- case PR_IpAddrLoopback:
- addr->inet.ip = htonl(INADDR_LOOPBACK);
- break;
- default:
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- rv = PR_FAILURE;
- }
- }
- return rv;
-} /* PR_SetNetAddr */
-
-PR_IMPLEMENT(PRBool)
-PR_IsNetAddrType(const PRNetAddr *addr, PRNetAddrValue val)
-{
- if (addr->raw.family == PR_AF_INET6) {
- if (val == PR_IpAddrAny) {
- if (_PR_IN6_IS_ADDR_UNSPECIFIED((PRIPv6Addr *)&addr->ipv6.ip)) {
- return PR_TRUE;
- } else if (_PR_IN6_IS_ADDR_V4MAPPED((PRIPv6Addr *)&addr->ipv6.ip)
- && _PR_IN6_V4MAPPED_TO_IPADDR((PRIPv6Addr *)&addr->ipv6.ip)
- == htonl(INADDR_ANY)) {
- return PR_TRUE;
- }
- } else if (val == PR_IpAddrLoopback) {
- if (_PR_IN6_IS_ADDR_LOOPBACK((PRIPv6Addr *)&addr->ipv6.ip)) {
- return PR_TRUE;
- } else if (_PR_IN6_IS_ADDR_V4MAPPED((PRIPv6Addr *)&addr->ipv6.ip)
- && _PR_IN6_V4MAPPED_TO_IPADDR((PRIPv6Addr *)&addr->ipv6.ip)
- == htonl(INADDR_LOOPBACK)) {
- return PR_TRUE;
- }
- } else if (val == PR_IpAddrV4Mapped
- && _PR_IN6_IS_ADDR_V4MAPPED((PRIPv6Addr *)&addr->ipv6.ip)) {
- return PR_TRUE;
- }
- } else {
- if (addr->raw.family == AF_INET) {
- if (val == PR_IpAddrAny && addr->inet.ip == htonl(INADDR_ANY)) {
- return PR_TRUE;
- } else if (val == PR_IpAddrLoopback
- && addr->inet.ip == htonl(INADDR_LOOPBACK)) {
- return PR_TRUE;
- }
- }
- }
- return PR_FALSE;
-}
-
-extern int pr_inet_aton(const char *cp, PRUint32 *addr);
-
-#define XX 127
-static const unsigned char index_hex[256] = {
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,XX,XX, XX,XX,XX,XX,
- XX,10,11,12, 13,14,15,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,10,11,12, 13,14,15,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
- XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX,
-};
-
-/*
- * StringToV6Addr() returns 1 if the conversion succeeds,
- * or 0 if the input is not a valid IPv6 address string.
- * (Same as inet_pton(AF_INET6, string, addr).)
- */
-static int StringToV6Addr(const char *string, PRIPv6Addr *addr)
-{
- const unsigned char *s = (const unsigned char *)string;
- int section = 0; /* index of the current section (a 16-bit
- * piece of the address */
- int double_colon = -1; /* index of the section after the first
- * 16-bit group of zeros represented by
- * the double colon */
- unsigned int val;
- int len;
-
- /* Handle initial (double) colon */
- if (*s == ':') {
- if (s[1] != ':') return 0;
- s += 2;
- addr->pr_s6_addr16[0] = 0;
- section = double_colon = 1;
- }
-
- while (*s) {
- if (section == 8) return 0; /* too long */
- if (*s == ':') {
- if (double_colon != -1) return 0; /* two double colons */
- addr->pr_s6_addr16[section++] = 0;
- double_colon = section;
- s++;
- continue;
- }
- for (len = val = 0; len < 4 && index_hex[*s] != XX; len++) {
- val = (val << 4) + index_hex[*s++];
- }
- if (*s == '.') {
- if (len == 0) return 0; /* nothing between : and . */
- break;
- }
- if (*s == ':') {
- s++;
- if (!*s) return 0; /* cannot end with single colon */
- } else if (*s) {
- return 0; /* bad character */
- }
- addr->pr_s6_addr16[section++] = htons((unsigned short)val);
- }
-
- if (*s == '.') {
- /* Have a trailing v4 format address */
- if (section > 6) return 0; /* not enough room */
-
- /*
- * The number before the '.' is decimal, but we parsed it
- * as hex. That means it is in BCD. Check it for validity
- * and convert it to binary.
- */
- if (val > 0x0255 || (val & 0xf0) > 0x90 || (val & 0xf) > 9) return 0;
- val = (val >> 8) * 100 + ((val >> 4) & 0xf) * 10 + (val & 0xf);
- addr->pr_s6_addr[2 * section] = val;
-
- s++;
- val = index_hex[*s++];
- if (val > 9) return 0;
- while (*s >= '0' && *s <= '9') {
- val = val * 10 + *s++ - '0';
- if (val > 255) return 0;
- }
- if (*s != '.') return 0; /* must have exactly 4 decimal numbers */
- addr->pr_s6_addr[2 * section + 1] = val;
- section++;
-
- s++;
- val = index_hex[*s++];
- if (val > 9) return 0;
- while (*s >= '0' && *s <= '9') {
- val = val * 10 + *s++ - '0';
- if (val > 255) return 0;
- }
- if (*s != '.') return 0; /* must have exactly 4 decimal numbers */
- addr->pr_s6_addr[2 * section] = val;
-
- s++;
- val = index_hex[*s++];
- if (val > 9) return 0;
- while (*s >= '0' && *s <= '9') {
- val = val * 10 + *s++ - '0';
- if (val > 255) return 0;
- }
- if (*s) return 0; /* must have exactly 4 decimal numbers */
- addr->pr_s6_addr[2 * section + 1] = val;
- section++;
- }
-
- if (double_colon != -1) {
- /* Stretch the double colon */
- int tosection;
- int ncopy = section - double_colon;
- for (tosection = 7; ncopy--; tosection--) {
- addr->pr_s6_addr16[tosection] =
- addr->pr_s6_addr16[double_colon + ncopy];
- }
- while (tosection >= double_colon) {
- addr->pr_s6_addr16[tosection--] = 0;
- }
- } else if (section != 8) {
- return 0; /* too short */
- }
- return 1;
-}
-#undef XX
-
-#ifndef _PR_HAVE_INET_NTOP
-static const char *basis_hex = "0123456789abcdef";
-
-/*
- * V6AddrToString() returns a pointer to the buffer containing
- * the text string if the conversion succeeds, and NULL otherwise.
- * (Same as inet_ntop(AF_INET6, addr, buf, size), except that errno
- * is not set on failure.)
- */
-static const char *V6AddrToString(
- const PRIPv6Addr *addr, char *buf, PRUint32 size)
-{
-#define STUFF(c) do { \
- if (!size--) return NULL; \
- *buf++ = (c); \
-} while (0)
-
- int double_colon = -1; /* index of the first 16-bit
- * group of zeros represented
- * by the double colon */
- int double_colon_length = 1; /* use double colon only if
- * there are two or more 16-bit
- * groups of zeros */
- int zero_length;
- int section;
- unsigned int val;
- const char *bufcopy = buf;
-
- /* Scan to find the placement of the double colon */
- for (section = 0; section < 8; section++) {
- if (addr->pr_s6_addr16[section] == 0) {
- zero_length = 1;
- section++;
- while (section < 8 && addr->pr_s6_addr16[section] == 0) {
- zero_length++;
- section++;
- }
- /* Select the longest sequence of zeros */
- if (zero_length > double_colon_length) {
- double_colon = section - zero_length;
- double_colon_length = zero_length;
- }
- }
- }
-
- /* Now start converting to a string */
- section = 0;
-
- if (double_colon == 0) {
- if (double_colon_length == 6 ||
- (double_colon_length == 5 && addr->pr_s6_addr16[5] == 0xffff)) {
- /* ipv4 format address */
- STUFF(':');
- STUFF(':');
- if (double_colon_length == 5) {
- STUFF('f');
- STUFF('f');
- STUFF('f');
- STUFF('f');
- STUFF(':');
- }
- if (addr->pr_s6_addr[12] > 99) STUFF(addr->pr_s6_addr[12]/100 + '0');
- if (addr->pr_s6_addr[12] > 9) STUFF((addr->pr_s6_addr[12]%100)/10 + '0');
- STUFF(addr->pr_s6_addr[12]%10 + '0');
- STUFF('.');
- if (addr->pr_s6_addr[13] > 99) STUFF(addr->pr_s6_addr[13]/100 + '0');
- if (addr->pr_s6_addr[13] > 9) STUFF((addr->pr_s6_addr[13]%100)/10 + '0');
- STUFF(addr->pr_s6_addr[13]%10 + '0');
- STUFF('.');
- if (addr->pr_s6_addr[14] > 99) STUFF(addr->pr_s6_addr[14]/100 + '0');
- if (addr->pr_s6_addr[14] > 9) STUFF((addr->pr_s6_addr[14]%100)/10 + '0');
- STUFF(addr->pr_s6_addr[14]%10 + '0');
- STUFF('.');
- if (addr->pr_s6_addr[15] > 99) STUFF(addr->pr_s6_addr[15]/100 + '0');
- if (addr->pr_s6_addr[15] > 9) STUFF((addr->pr_s6_addr[15]%100)/10 + '0');
- STUFF(addr->pr_s6_addr[15]%10 + '0');
- STUFF('\0');
- return bufcopy;
- }
- }
-
- while (section < 8) {
- if (section == double_colon) {
- STUFF(':');
- STUFF(':');
- section += double_colon_length;
- continue;
- }
- val = ntohs(addr->pr_s6_addr16[section]);
- if (val > 0xfff) {
- STUFF(basis_hex[val >> 12]);
- }
- if (val > 0xff) {
- STUFF(basis_hex[(val >> 8) & 0xf]);
- }
- if (val > 0xf) {
- STUFF(basis_hex[(val >> 4) & 0xf]);
- }
- STUFF(basis_hex[val & 0xf]);
- section++;
- if (section < 8 && section != double_colon) STUFF(':');
- }
- STUFF('\0');
- return bufcopy;
-#undef STUFF
-}
-#endif /* !_PR_HAVE_INET_NTOP */
-
-/*
- * Convert an IPv4 addr to an (IPv4-mapped) IPv6 addr
- */
-PR_IMPLEMENT(void) PR_ConvertIPv4AddrToIPv6(PRUint32 v4addr, PRIPv6Addr *v6addr)
-{
- PRUint8 *dstp;
- dstp = v6addr->pr_s6_addr;
- memset(dstp, 0, 10);
- memset(dstp + 10, 0xff, 2);
- memcpy(dstp + 12,(char *) &v4addr, 4);
-}
-
-PR_IMPLEMENT(PRUint16) PR_ntohs(PRUint16 n) { return ntohs(n); }
-PR_IMPLEMENT(PRUint32) PR_ntohl(PRUint32 n) { return ntohl(n); }
-PR_IMPLEMENT(PRUint16) PR_htons(PRUint16 n) { return htons(n); }
-PR_IMPLEMENT(PRUint32) PR_htonl(PRUint32 n) { return htonl(n); }
-PR_IMPLEMENT(PRUint64) PR_ntohll(PRUint64 n)
-{
-#ifdef IS_BIG_ENDIAN
- return n;
-#else
- PRUint64 tmp;
- PRUint32 hi, lo;
- LL_L2UI(lo, n);
- LL_SHR(tmp, n, 32);
- LL_L2UI(hi, tmp);
- hi = PR_ntohl(hi);
- lo = PR_ntohl(lo);
- LL_UI2L(n, lo);
- LL_SHL(n, n, 32);
- LL_UI2L(tmp, hi);
- LL_ADD(n, n, tmp);
- return n;
-#endif
-} /* ntohll */
-
-PR_IMPLEMENT(PRUint64) PR_htonll(PRUint64 n)
-{
-#ifdef IS_BIG_ENDIAN
- return n;
-#else
- PRUint64 tmp;
- PRUint32 hi, lo;
- LL_L2UI(lo, n);
- LL_SHR(tmp, n, 32);
- LL_L2UI(hi, tmp);
- hi = htonl(hi);
- lo = htonl(lo);
- LL_UI2L(n, lo);
- LL_SHL(n, n, 32);
- LL_UI2L(tmp, hi);
- LL_ADD(n, n, tmp);
- return n;
-#endif
-} /* htonll */
-
-
-/*
- * Implementation of PR_GetAddrInfoByName and friends
- *
- * Compile-time options:
- *
- * _PR_HAVE_GETADDRINFO Define this macro if the target system provides
- * getaddrinfo. With this defined, NSPR will require
- * getaddrinfo at run time. If this if not defined,
- * then NSPR will attempt to dynamically resolve
- * getaddrinfo, falling back to PR_GetHostByName if
- * getaddrinfo does not exist on the target system.
- *
- * Since getaddrinfo is a relatively new system call on many systems,
- * we are forced to dynamically resolve it at run time in most cases.
- * The exception includes any system (such as Mac OS X) that is known to
- * provide getaddrinfo in all versions that NSPR cares to support.
- */
-
-#if defined(_PR_HAVE_GETADDRINFO)
-
-#if defined(_PR_INET6)
-
-typedef struct addrinfo PRADDRINFO;
-#define GETADDRINFO getaddrinfo
-#define FREEADDRINFO freeaddrinfo
-#define GETNAMEINFO getnameinfo
-
-#elif defined(_PR_INET6_PROBE)
-
-typedef struct addrinfo PRADDRINFO;
-
-/* getaddrinfo/freeaddrinfo/getnameinfo prototypes */
-#if defined(WIN32)
-#define FUNC_MODIFIER __stdcall
-#else
-#define FUNC_MODIFIER
-#endif
-typedef int (FUNC_MODIFIER * FN_GETADDRINFO)
- (const char *nodename,
- const char *servname,
- const PRADDRINFO *hints,
- PRADDRINFO **res);
-typedef int (FUNC_MODIFIER * FN_FREEADDRINFO)
- (PRADDRINFO *ai);
-typedef int (FUNC_MODIFIER * FN_GETNAMEINFO)
- (const struct sockaddr *addr, int addrlen,
- char *host, int hostlen,
- char *serv, int servlen, int flags);
-
-/* global state */
-static FN_GETADDRINFO _pr_getaddrinfo = NULL;
-static FN_FREEADDRINFO _pr_freeaddrinfo = NULL;
-static FN_GETNAMEINFO _pr_getnameinfo = NULL;
-
-#define GETADDRINFO_SYMBOL "getaddrinfo"
-#define FREEADDRINFO_SYMBOL "freeaddrinfo"
-#define GETNAMEINFO_SYMBOL "getnameinfo"
-
-PRStatus
-_pr_find_getaddrinfo(void)
-{
- PRLibrary *lib;
-#ifdef WIN32
- /*
- * On windows, we need to search ws2_32.dll or wship6.dll
- * (Microsoft IPv6 Technology Preview for Windows 2000) for
- * getaddrinfo and freeaddrinfo. These libraries might not
- * be loaded yet.
- */
- const char *libname[] = { "ws2_32.dll", "wship6.dll" };
- int i;
-
- for (i = 0; i < sizeof(libname)/sizeof(libname[0]); i++) {
- lib = PR_LoadLibrary(libname[i]);
- if (!lib) {
- continue;
- }
- _pr_getaddrinfo = (FN_GETADDRINFO)
- PR_FindFunctionSymbol(lib, GETADDRINFO_SYMBOL);
- if (!_pr_getaddrinfo) {
- PR_UnloadLibrary(lib);
- continue;
- }
- _pr_freeaddrinfo = (FN_FREEADDRINFO)
- PR_FindFunctionSymbol(lib, FREEADDRINFO_SYMBOL);
- _pr_getnameinfo = (FN_GETNAMEINFO)
- PR_FindFunctionSymbol(lib, GETNAMEINFO_SYMBOL);
- if (!_pr_freeaddrinfo || !_pr_getnameinfo) {
- PR_UnloadLibrary(lib);
- continue;
- }
- /* Keep the library loaded. */
- return PR_SUCCESS;
- }
- return PR_FAILURE;
-#else
- /*
- * Resolve getaddrinfo by searching all loaded libraries. Then
- * search library containing getaddrinfo for freeaddrinfo.
- */
- _pr_getaddrinfo = (FN_GETADDRINFO)
- PR_FindFunctionSymbolAndLibrary(GETADDRINFO_SYMBOL, &lib);
- if (!_pr_getaddrinfo) {
- return PR_FAILURE;
- }
- _pr_freeaddrinfo = (FN_FREEADDRINFO)
- PR_FindFunctionSymbol(lib, FREEADDRINFO_SYMBOL);
- _pr_getnameinfo = (FN_GETNAMEINFO)
- PR_FindFunctionSymbol(lib, GETNAMEINFO_SYMBOL);
- PR_UnloadLibrary(lib);
- if (!_pr_freeaddrinfo || !_pr_getnameinfo) {
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-#endif
-}
-
-#define GETADDRINFO (*_pr_getaddrinfo)
-#define FREEADDRINFO (*_pr_freeaddrinfo)
-#define GETNAMEINFO (*_pr_getnameinfo)
-
-#endif /* _PR_INET6 */
-
-#endif /* _PR_HAVE_GETADDRINFO */
-
-#if !defined(_PR_HAVE_GETADDRINFO) || defined(_PR_INET6_PROBE)
-/*
- * If getaddrinfo does not exist, then we will fall back on
- * PR_GetHostByName, which requires that we allocate a buffer for the
- * PRHostEnt data structure and its members.
- */
-typedef struct PRAddrInfoFB {
- char buf[PR_NETDB_BUF_SIZE];
- PRHostEnt hostent;
- PRBool has_cname;
-} PRAddrInfoFB;
-
-static PRAddrInfo *
-pr_GetAddrInfoByNameFB(const char *hostname,
- PRUint16 af,
- PRIntn flags)
-{
- PRStatus rv;
- PRAddrInfoFB *ai;
- /* fallback on PR_GetHostByName */
- ai = PR_NEW(PRAddrInfoFB);
- if (!ai) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
- rv = PR_GetHostByName(hostname, ai->buf, sizeof ai->buf, &ai->hostent);
- if (rv == PR_FAILURE) {
- PR_Free(ai);
- return NULL;
- }
- ai->has_cname = !(flags & PR_AI_NOCANONNAME);
-
- return (PRAddrInfo *) ai;
-}
-#endif /* !_PR_HAVE_GETADDRINFO || _PR_INET6_PROBE */
-
-PR_IMPLEMENT(PRAddrInfo *) PR_GetAddrInfoByName(const char *hostname,
- PRUint16 af,
- PRIntn flags)
-{
- /* restrict input to supported values */
- if ((af != PR_AF_INET && af != PR_AF_UNSPEC) ||
- (flags & ~ PR_AI_NOCANONNAME) != PR_AI_ADDRCONFIG) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return NULL;
- }
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
-#if !defined(_PR_HAVE_GETADDRINFO)
- return pr_GetAddrInfoByNameFB(hostname, af, flags);
-#else
-#if defined(_PR_INET6_PROBE)
- if (!_pr_ipv6_is_present()) {
- return pr_GetAddrInfoByNameFB(hostname, af, flags);
- }
-#endif
- {
- PRADDRINFO *res, hints;
- int rv;
-
- /*
- * we assume a RFC 2553 compliant getaddrinfo. this may at some
- * point need to be customized as platforms begin to adopt the
- * RFC 3493.
- */
-
- memset(&hints, 0, sizeof(hints));
- if (!(flags & PR_AI_NOCANONNAME))
- hints.ai_flags |= AI_CANONNAME;
-#ifdef AI_ADDRCONFIG
- /*
- * Propagate AI_ADDRCONFIG to the GETADDRINFO call if PR_AI_ADDRCONFIG
- * is set.
- *
- * Need a workaround for loopback host addresses:
- * The problem is that in glibc and Windows, AI_ADDRCONFIG applies the
- * existence of an outgoing network interface to IP addresses of the
- * loopback interface, due to a strict interpretation of the
- * specification. For example, if a computer does not have any
- * outgoing IPv6 network interface, but its loopback network interface
- * supports IPv6, a getaddrinfo call on "localhost" with AI_ADDRCONFIG
- * won't return the IPv6 loopback address "::1", because getaddrinfo
- * thinks the computer cannot connect to any IPv6 destination,
- * ignoring the remote vs. local/loopback distinction.
- */
- if ((flags & PR_AI_ADDRCONFIG) &&
- strcmp(hostname, "localhost") != 0 &&
- strcmp(hostname, "localhost.localdomain") != 0 &&
- strcmp(hostname, "localhost6") != 0 &&
- strcmp(hostname, "localhost6.localdomain6") != 0) {
- hints.ai_flags |= AI_ADDRCONFIG;
- }
-#endif
- hints.ai_family = (af == PR_AF_INET) ? AF_INET : AF_UNSPEC;
-
- /*
- * it is important to select a socket type in the hints, otherwise we
- * will get back repetitive entries: one for each socket type. since
- * we do not expose ai_socktype through our API, it is okay to do this
- * here. the application may still choose to create a socket of some
- * other type.
- */
- hints.ai_socktype = SOCK_STREAM;
-
- rv = GETADDRINFO(hostname, NULL, &hints, &res);
-#ifdef AI_ADDRCONFIG
- if (rv == EAI_BADFLAGS && (hints.ai_flags & AI_ADDRCONFIG)) {
- hints.ai_flags &= ~AI_ADDRCONFIG;
- rv = GETADDRINFO(hostname, NULL, &hints, &res);
- }
-#endif
- if (rv == 0)
- return (PRAddrInfo *) res;
-
- PR_SetError(PR_DIRECTORY_LOOKUP_ERROR, rv);
- }
- return NULL;
-#endif
-}
-
-PR_IMPLEMENT(void) PR_FreeAddrInfo(PRAddrInfo *ai)
-{
-#if defined(_PR_HAVE_GETADDRINFO)
-#if defined(_PR_INET6_PROBE)
- if (!_pr_ipv6_is_present())
- PR_Free((PRAddrInfoFB *) ai);
- else
-#endif
- FREEADDRINFO((PRADDRINFO *) ai);
-#else
- PR_Free((PRAddrInfoFB *) ai);
-#endif
-}
-
-PR_IMPLEMENT(void *) PR_EnumerateAddrInfo(void *iterPtr,
- const PRAddrInfo *base,
- PRUint16 port,
- PRNetAddr *result)
-{
-#if defined(_PR_HAVE_GETADDRINFO)
- PRADDRINFO *ai;
-#if defined(_PR_INET6_PROBE)
- if (!_pr_ipv6_is_present()) {
- /* using PRAddrInfoFB */
- PRIntn iter = (PRIntn)(PRPtrdiff) iterPtr;
- iter = PR_EnumerateHostEnt(iter, &((PRAddrInfoFB *) base)->hostent, port, result);
- if (iter < 0)
- iter = 0;
- return (void *)(PRPtrdiff) iter;
- }
-#endif
-
- if (iterPtr)
- ai = ((PRADDRINFO *) iterPtr)->ai_next;
- else
- ai = (PRADDRINFO *) base;
-
- while (ai && ai->ai_addrlen > sizeof(PRNetAddr))
- ai = ai->ai_next;
-
- if (ai) {
- /* copy sockaddr to PRNetAddr */
- memcpy(result, ai->ai_addr, ai->ai_addrlen);
- result->raw.family = ai->ai_addr->sa_family;
-#ifdef _PR_INET6
- if (AF_INET6 == result->raw.family)
- result->raw.family = PR_AF_INET6;
-#endif
- if (ai->ai_addrlen < sizeof(PRNetAddr))
- memset(((char*)result)+ai->ai_addrlen, 0, sizeof(PRNetAddr) - ai->ai_addrlen);
-
- if (result->raw.family == PR_AF_INET)
- result->inet.port = htons(port);
- else
- result->ipv6.port = htons(port);
- }
-
- return ai;
-#else
- /* using PRAddrInfoFB */
- PRIntn iter = (PRIntn) iterPtr;
- iter = PR_EnumerateHostEnt(iter, &((PRAddrInfoFB *) base)->hostent, port, result);
- if (iter < 0)
- iter = 0;
- return (void *) iter;
-#endif
-}
-
-PR_IMPLEMENT(const char *) PR_GetCanonNameFromAddrInfo(const PRAddrInfo *ai)
-{
-#if defined(_PR_HAVE_GETADDRINFO)
-#if defined(_PR_INET6_PROBE)
- if (!_pr_ipv6_is_present()) {
- const PRAddrInfoFB *fb = (const PRAddrInfoFB *) ai;
- return fb->has_cname ? fb->hostent.h_name : NULL;
- }
-#endif
- return ((const PRADDRINFO *) ai)->ai_canonname;
-#else
- const PRAddrInfoFB *fb = (const PRAddrInfoFB *) ai;
- return fb->has_cname ? fb->hostent.h_name : NULL;
-#endif
-}
-
-#if defined(_PR_HAVE_GETADDRINFO)
-static PRStatus pr_StringToNetAddrGAI(const char *string, PRNetAddr *addr)
-{
- PRADDRINFO *res, hints;
- int rv; /* 0 for success, or the error code EAI_xxx */
- PRNetAddr laddr;
- PRStatus status = PR_SUCCESS;
-
- memset(&hints, 0, sizeof(hints));
- hints.ai_flags = AI_NUMERICHOST;
- hints.ai_family = AF_UNSPEC;
- hints.ai_socktype = SOCK_STREAM;
-
- rv = GETADDRINFO(string, NULL, &hints, &res);
- if (rv != 0)
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, rv);
- return PR_FAILURE;
- }
-
- /* pick up the first addr */
- memcpy(&laddr, res->ai_addr, res->ai_addrlen);
- if (AF_INET6 == res->ai_addr->sa_family)
- {
- addr->ipv6.family = PR_AF_INET6;
- addr->ipv6.ip = laddr.ipv6.ip;
- addr->ipv6.scope_id = laddr.ipv6.scope_id;
- }
- else if (AF_INET == res->ai_addr->sa_family)
- {
- addr->inet.family = PR_AF_INET;
- addr->inet.ip = laddr.inet.ip;
- }
- else
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- status = PR_FAILURE;
- }
-
- FREEADDRINFO(res);
- return status;
-}
-#endif /* _PR_HAVE_GETADDRINFO */
-
-static PRStatus pr_StringToNetAddrFB(const char *string, PRNetAddr *addr)
-{
- PRIntn rv;
-
- rv = pr_inet_aton(string, &addr->inet.ip);
- if (1 == rv)
- {
- addr->raw.family = AF_INET;
- return PR_SUCCESS;
- }
-
- PR_ASSERT(0 == rv);
- /* clean up after the failed call */
- memset(&addr->inet.ip, 0, sizeof(addr->inet.ip));
-
- rv = StringToV6Addr(string, &addr->ipv6.ip);
- if (1 == rv)
- {
- addr->raw.family = PR_AF_INET6;
- return PR_SUCCESS;
- }
-
- PR_ASSERT(0 == rv);
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
-}
-
-PR_IMPLEMENT(PRStatus) PR_StringToNetAddr(const char *string, PRNetAddr *addr)
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (!addr || !string || !*string)
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
-
-#if !defined(_PR_HAVE_GETADDRINFO)
- return pr_StringToNetAddrFB(string, addr);
-#else
- /*
- * getaddrinfo with AI_NUMERICHOST is much slower than pr_inet_aton on some
- * platforms, such as Mac OS X (bug 404399), Linux glibc 2.10 (bug 344809),
- * and most likely others. So we only use it to convert literal IP addresses
- * that contain IPv6 scope IDs, which pr_inet_aton cannot convert.
- */
- if (!strchr(string, '%'))
- return pr_StringToNetAddrFB(string, addr);
-
-#if defined(_PR_INET6_PROBE)
- if (!_pr_ipv6_is_present())
- return pr_StringToNetAddrFB(string, addr);
-#endif
-
- return pr_StringToNetAddrGAI(string, addr);
-#endif
-}
-
-#if defined(_PR_HAVE_GETADDRINFO)
-static PRStatus pr_NetAddrToStringGNI(
- const PRNetAddr *addr, char *string, PRUint32 size)
-{
- int addrlen;
- const PRNetAddr *addrp = addr;
-#if defined(_PR_HAVE_SOCKADDR_LEN) || defined(_PR_INET6)
- PRUint16 md_af = addr->raw.family;
- PRNetAddr addrcopy;
-#endif
- int rv; /* 0 for success, or the error code EAI_xxx */
-
-#ifdef _PR_INET6
- if (addr->raw.family == PR_AF_INET6)
- {
- md_af = AF_INET6;
-#ifndef _PR_HAVE_SOCKADDR_LEN
- addrcopy = *addr;
- addrcopy.raw.family = md_af;
- addrp = &addrcopy;
-#endif
- }
-#endif
-
- addrlen = PR_NETADDR_SIZE(addr);
-#ifdef _PR_HAVE_SOCKADDR_LEN
- addrcopy = *addr;
- ((struct sockaddr*)&addrcopy)->sa_len = addrlen;
- ((struct sockaddr*)&addrcopy)->sa_family = md_af;
- addrp = &addrcopy;
-#endif
- rv = GETNAMEINFO((const struct sockaddr *)addrp, addrlen,
- string, size, NULL, 0, NI_NUMERICHOST);
- if (rv != 0)
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, rv);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-#endif /* _PR_HAVE_GETADDRINFO */
-
-#if !defined(_PR_HAVE_GETADDRINFO) || defined(_PR_INET6_PROBE)
-static PRStatus pr_NetAddrToStringFB(
- const PRNetAddr *addr, char *string, PRUint32 size)
-{
- if (PR_AF_INET6 == addr->raw.family)
- {
-#if defined(_PR_HAVE_INET_NTOP)
- if (NULL == inet_ntop(AF_INET6, &addr->ipv6.ip, string, size))
-#else
- if (NULL == V6AddrToString(&addr->ipv6.ip, string, size))
-#endif
- {
- /* the size of the result buffer is inadequate */
- PR_SetError(PR_BUFFER_OVERFLOW_ERROR, 0);
- return PR_FAILURE;
- }
- }
- else
- {
- if (size < 16) goto failed;
- if (AF_INET != addr->raw.family) goto failed;
- else
- {
- unsigned char *byte = (unsigned char*)&addr->inet.ip;
- PR_snprintf(string, size, "%u.%u.%u.%u",
- byte[0], byte[1], byte[2], byte[3]);
- }
- }
-
- return PR_SUCCESS;
-
-failed:
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
-
-} /* pr_NetAddrToStringFB */
-#endif /* !_PR_HAVE_GETADDRINFO || _PR_INET6_PROBE */
-
-PR_IMPLEMENT(PRStatus) PR_NetAddrToString(
- const PRNetAddr *addr, char *string, PRUint32 size)
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
-#if !defined(_PR_HAVE_GETADDRINFO)
- return pr_NetAddrToStringFB(addr, string, size);
-#else
-#if defined(_PR_INET6_PROBE)
- if (!_pr_ipv6_is_present())
- return pr_NetAddrToStringFB(addr, string, size);
-#endif
- return pr_NetAddrToStringGNI(addr, string, size);
-#endif
-} /* PR_NetAddrToString */
diff --git a/nspr/pr/src/misc/prolock.c b/nspr/pr/src/misc/prolock.c
deleted file mode 100644
index 38b7787..0000000
--- a/nspr/pr/src/misc/prolock.c
+++ /dev/null
@@ -1,56 +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/. */
-
-/*
-** prolock.c -- NSPR Ordered Lock
-**
-** Implement the API defined in prolock.h
-**
-*/
-#include "prolock.h"
-#include "prlog.h"
-#include "prerror.h"
-
-PR_IMPLEMENT(PROrderedLock *)
- PR_CreateOrderedLock(
- PRInt32 order,
- const char *name
-)
-{
- PR_NOT_REACHED("Not implemented"); /* Not implemented yet */
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return NULL;
-} /* end PR_CreateOrderedLock() */
-
-
-PR_IMPLEMENT(void)
- PR_DestroyOrderedLock(
- PROrderedLock *lock
-)
-{
- PR_NOT_REACHED("Not implemented"); /* Not implemented yet */
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
-} /* end PR_DestroyOrderedLock() */
-
-
-PR_IMPLEMENT(void)
- PR_LockOrderedLock(
- PROrderedLock *lock
-)
-{
- PR_NOT_REACHED("Not implemented"); /* Not implemented yet */
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
-} /* end PR_LockOrderedLock() */
-
-
-PR_IMPLEMENT(PRStatus)
- PR_UnlockOrderedLock(
- PROrderedLock *lock
-)
-{
- PR_NOT_REACHED("Not implemented"); /* Not implemented yet */
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-} /* end PR_UnlockOrderedLock() */
diff --git a/nspr/pr/src/misc/prrng.c b/nspr/pr/src/misc/prrng.c
deleted file mode 100644
index b5c38f8..0000000
--- a/nspr/pr/src/misc/prrng.c
+++ /dev/null
@@ -1,44 +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/. */
-
-#include "primpl.h"
-
-/*
- * We were not including <string.h> in optimized builds. On AIX this
- * caused libnspr4.so to export memcpy and some binaries linked with
- * libnspr4.so resolved their memcpy references with libnspr4.so. To
- * be backward compatible with old libnspr4.so binaries, we do not
- * include <string.h> in optimized builds for AIX. (bug 200561)
- */
-#if !(defined(AIX) && !defined(DEBUG))
-#include <string.h>
-#endif
-
-PRSize _pr_CopyLowBits(
- void *dst,
- PRSize dstlen,
- void *src,
- PRSize srclen )
-{
- if (srclen <= dstlen) {
- memcpy(dst, src, srclen);
- return srclen;
- }
-#if defined IS_BIG_ENDIAN
- memcpy(dst, (char*)src + (srclen - dstlen), dstlen);
-#else
- memcpy(dst, src, dstlen);
-#endif
- return dstlen;
-}
-
-PR_IMPLEMENT(PRSize) PR_GetRandomNoise(
- void *buf,
- PRSize size
-)
-{
- return( _PR_MD_GET_RANDOM_NOISE( buf, size ));
-} /* end PR_GetRandomNoise() */
-/* end prrng.c */
diff --git a/nspr/pr/src/misc/prsystem.c b/nspr/pr/src/misc/prsystem.c
deleted file mode 100644
index eba85fb..0000000
--- a/nspr/pr/src/misc/prsystem.c
+++ /dev/null
@@ -1,357 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* 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 "primpl.h"
-#include "prsystem.h"
-#include "prprf.h"
-#include "prlong.h"
-
-#if defined(BEOS)
-#include <kernel/OS.h>
-#endif
-
-#if defined(OS2)
-#define INCL_DOS
-#define INCL_DOSMISC
-#include <os2.h>
-/* define the required constant if it is not already defined in the headers */
-#ifndef QSV_NUMPROCESSORS
-#define QSV_NUMPROCESSORS 26
-#endif
-#endif
-
-/* BSD-derived systems use sysctl() to get the number of processors */
-#if defined(BSDI) || defined(FREEBSD) || defined(NETBSD) \
- || defined(OPENBSD) || defined(DRAGONFLY) || defined(DARWIN)
-#define _PR_HAVE_SYSCTL
-#include <sys/param.h>
-#include <sys/sysctl.h>
-#endif
-
-#if defined(DARWIN)
-#include <mach/mach_init.h>
-#include <mach/mach_host.h>
-#include <mach/mach_port.h>
-#endif
-
-#if defined(HPUX)
-#include <sys/mpctl.h>
-#include <sys/pstat.h>
-#endif
-
-#if defined(XP_UNIX)
-#include <unistd.h>
-#include <sys/utsname.h>
-#endif
-
-#if defined(LINUX)
-#include <string.h>
-#include <ctype.h>
-#define MAX_LINE 512
-#endif
-
-#if defined(AIX)
-#include <cf.h>
-#include <sys/cfgodm.h>
-#endif
-
-PR_IMPLEMENT(char) PR_GetDirectorySeparator(void)
-{
- return PR_DIRECTORY_SEPARATOR;
-} /* PR_GetDirectorySeparator */
-
-/*
-** OBSOLETE -- the function name is misspelled.
-*/
-PR_IMPLEMENT(char) PR_GetDirectorySepartor(void)
-{
-#if defined(DEBUG)
- static PRBool warn = PR_TRUE;
- if (warn) {
- warn = _PR_Obsolete("PR_GetDirectorySepartor()",
- "PR_GetDirectorySeparator()");
- }
-#endif
- return PR_GetDirectorySeparator();
-} /* PR_GetDirectorySepartor */
-
-PR_IMPLEMENT(char) PR_GetPathSeparator(void)
-{
- return PR_PATH_SEPARATOR;
-} /* PR_GetPathSeparator */
-
-PR_IMPLEMENT(PRStatus) PR_GetSystemInfo(PRSysInfo cmd, char *buf, PRUint32 buflen)
-{
- PRUintn len = 0;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- switch(cmd)
- {
- case PR_SI_HOSTNAME:
- case PR_SI_HOSTNAME_UNTRUNCATED:
- if (PR_FAILURE == _PR_MD_GETHOSTNAME(buf, (PRUintn)buflen))
- return PR_FAILURE;
-
- if (cmd == PR_SI_HOSTNAME_UNTRUNCATED)
- break;
- /*
- * On some platforms a system does not have a hostname and
- * its IP address is returned instead. The following code
- * should be skipped on those platforms.
- */
-#ifndef _PR_GET_HOST_ADDR_AS_NAME
- /* Return the unqualified hostname */
- while (buf[len] && (len < buflen)) {
- if (buf[len] == '.') {
- buf[len] = '\0';
- break;
- }
- len += 1;
- }
-#endif
- break;
-
- case PR_SI_SYSNAME:
- /* Return the operating system name */
-#if defined(XP_UNIX) || defined(WIN32)
- if (PR_FAILURE == _PR_MD_GETSYSINFO(cmd, buf, (PRUintn)buflen))
- return PR_FAILURE;
-#else
- (void)PR_snprintf(buf, buflen, _PR_SI_SYSNAME);
-#endif
- break;
-
- case PR_SI_RELEASE:
- /* Return the version of the operating system */
-#if defined(XP_UNIX) || defined(WIN32)
- if (PR_FAILURE == _PR_MD_GETSYSINFO(cmd, buf, (PRUintn)buflen))
- return PR_FAILURE;
-#endif
-#if defined(XP_OS2)
- {
- ULONG os2ver[2] = {0};
- DosQuerySysInfo(QSV_VERSION_MINOR, QSV_VERSION_REVISION,
- &os2ver, sizeof(os2ver));
- /* Formatting for normal usage (2.11, 3.0, 4.0, 4.5); officially,
- Warp 4 is version 2.40.00, WSeB 2.45.00 */
- if (os2ver[0] < 30)
- (void)PR_snprintf(buf, buflen, "%s%lu",
- "2.", os2ver[0]);
- else if (os2ver[0] < 45)
- (void)PR_snprintf(buf, buflen, "%lu%s%lu",
- os2ver[0]/10, ".", os2ver[1]);
- else
- (void)PR_snprintf(buf, buflen, "%.1f",
- os2ver[0]/10.0);
- }
-#endif /* OS2 */
- break;
-
- case PR_SI_ARCHITECTURE:
- /* Return the architecture of the machine (ie. x86, mips, alpha, ...)*/
- (void)PR_snprintf(buf, buflen, _PR_SI_ARCHITECTURE);
- break;
- default:
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-/*
-** PR_GetNumberOfProcessors()
-**
-** Implementation notes:
-** Every platform does it a bit different.
-** numCpus is the returned value.
-** for each platform's "if defined" section
-** declare your local variable
-** do your thing, assign to numCpus
-** order of the if defined()s may be important,
-** especially for unix variants. Do platform
-** specific implementations before XP_UNIX.
-**
-*/
-PR_IMPLEMENT(PRInt32) PR_GetNumberOfProcessors( void )
-{
- PRInt32 numCpus;
-#if defined(WIN32)
- SYSTEM_INFO info;
-
- GetSystemInfo( &info );
- numCpus = info.dwNumberOfProcessors;
-#elif defined(BEOS)
- system_info sysInfo;
-
- get_system_info(&sysInfo);
- numCpus = sysInfo.cpu_count;
-#elif defined(OS2)
- DosQuerySysInfo( QSV_NUMPROCESSORS, QSV_NUMPROCESSORS, &numCpus, sizeof(numCpus));
-#elif defined(_PR_HAVE_SYSCTL)
- int mib[2];
- int rc;
- size_t len = sizeof(numCpus);
-
- mib[0] = CTL_HW;
- mib[1] = HW_NCPU;
- rc = sysctl( mib, 2, &numCpus, &len, NULL, 0 );
- if ( -1 == rc ) {
- numCpus = -1; /* set to -1 for return value on error */
- _PR_MD_MAP_DEFAULT_ERROR( _MD_ERRNO() );
- }
-#elif defined(HPUX)
- numCpus = mpctl( MPC_GETNUMSPUS, 0, 0 );
- if ( numCpus < 1 ) {
- numCpus = -1; /* set to -1 for return value on error */
- _PR_MD_MAP_DEFAULT_ERROR( _MD_ERRNO() );
- }
-#elif defined(IRIX)
- numCpus = sysconf( _SC_NPROC_ONLN );
-#elif defined(RISCOS) || defined(SYMBIAN)
- numCpus = 1;
-#elif defined(LINUX)
- /* for the benefit of devices with advanced power-saving, that
- actually hotplug their cpus in heavy load, try to figure out
- the real number of CPUs */
- char buf[MAX_LINE];
- FILE *fin;
- const char *cpu_present = "/sys/devices/system/cpu/present";
- size_t strsize;
- numCpus = 0;
- fin = fopen(cpu_present, "r");
- if (fin != NULL) {
- if (fgets(buf, MAX_LINE, fin) != NULL) {
- /* check that the format is what we expect */
- if (buf[0] == '0') {
- strsize = strlen(buf);
- if (strsize == 1) {
- /* single core */
- numCpus = 1;
- } else if (strsize >= 3 && strsize <= 5) {
- /* should be of the form 0-999 */
- /* parse the part after the 0-, note count is 0-based */
- if (buf[1] == '-' && isdigit(buf[2])) {
- numCpus = 1 + atoi(buf + 2);
- }
- }
- }
- }
- fclose(fin);
- }
- /* if that fails, fall back to more standard methods */
- if (!numCpus) {
- numCpus = sysconf( _SC_NPROCESSORS_CONF );
- }
-#elif defined(XP_UNIX)
- numCpus = sysconf( _SC_NPROCESSORS_CONF );
-#else
-#error "An implementation is required"
-#endif
- return(numCpus);
-} /* end PR_GetNumberOfProcessors() */
-
-/*
-** PR_GetPhysicalMemorySize()
-**
-** Implementation notes:
-** Every platform does it a bit different.
-** bytes is the returned value.
-** for each platform's "if defined" section
-** declare your local variable
-** do your thing, assign to bytes.
-**
-*/
-PR_IMPLEMENT(PRUint64) PR_GetPhysicalMemorySize(void)
-{
- PRUint64 bytes = 0;
-
-#if defined(LINUX) || defined(SOLARIS)
-
- long pageSize = sysconf(_SC_PAGESIZE);
- long pageCount = sysconf(_SC_PHYS_PAGES);
- if (pageSize >= 0 && pageCount >= 0)
- bytes = (PRUint64) pageSize * pageCount;
-
-#elif defined(NETBSD) || defined(OPENBSD) \
- || defined(FREEBSD) || defined(DRAGONFLY)
-
- int mib[2];
- int rc;
-#ifdef HW_PHYSMEM64
- uint64_t memSize;
-#else
- unsigned long memSize;
-#endif
- size_t len = sizeof(memSize);
-
- mib[0] = CTL_HW;
-#ifdef HW_PHYSMEM64
- mib[1] = HW_PHYSMEM64;
-#else
- mib[1] = HW_PHYSMEM;
-#endif
- rc = sysctl(mib, 2, &memSize, &len, NULL, 0);
- if (-1 != rc) {
- bytes = memSize;
- }
-
-#elif defined(HPUX)
-
- struct pst_static info;
- int result = pstat_getstatic(&info, sizeof(info), 1, 0);
- if (result == 1)
- bytes = (PRUint64) info.physical_memory * info.page_size;
-
-#elif defined(DARWIN)
-
- mach_port_t mach_host = mach_host_self();
- struct host_basic_info hInfo;
- mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
-
- int result = host_info(mach_host,
- HOST_BASIC_INFO,
- (host_info_t) &hInfo,
- &count);
- mach_port_deallocate(mach_task_self(), mach_host);
- if (result == KERN_SUCCESS)
- bytes = hInfo.max_mem;
-
-#elif defined(WIN32)
-
- MEMORYSTATUSEX memStat;
- memStat.dwLength = sizeof(memStat);
- if (GlobalMemoryStatusEx(&memStat))
- bytes = memStat.ullTotalPhys;
-
-#elif defined(OS2)
-
- ULONG ulPhysMem;
- DosQuerySysInfo(QSV_TOTPHYSMEM,
- QSV_TOTPHYSMEM,
- &ulPhysMem,
- sizeof(ulPhysMem));
- bytes = ulPhysMem;
-
-#elif defined(AIX)
-
- if (odm_initialize() == 0) {
- int how_many;
- struct CuAt *obj = getattr("sys0", "realmem", 0, &how_many);
- if (obj != NULL) {
- bytes = (PRUint64) atoi(obj->value) * 1024;
- free(obj);
- }
- odm_terminate();
- }
-
-#else
-
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
-
-#endif
-
- return bytes;
-} /* end PR_GetPhysicalMemorySize() */
diff --git a/nspr/pr/src/misc/prthinfo.c b/nspr/pr/src/misc/prthinfo.c
deleted file mode 100644
index 2477899..0000000
--- a/nspr/pr/src/misc/prthinfo.c
+++ /dev/null
@@ -1,206 +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/. */
-
-#include "prlog.h"
-#include "prthread.h"
-#include "private/pprthred.h"
-#include "primpl.h"
-
-PR_IMPLEMENT(PRWord *)
-PR_GetGCRegisters(PRThread *t, int isCurrent, int *np)
-{
- return _MD_HomeGCRegisters(t, isCurrent, np);
-}
-
-PR_IMPLEMENT(PRStatus)
-PR_ThreadScanStackPointers(PRThread* t,
- PRScanStackFun scanFun, void* scanClosure)
-{
- PRThread* current = PR_GetCurrentThread();
- PRWord *sp, *esp, *p0;
- int n;
- void **ptd;
- PRStatus status;
- PRUint32 index;
- int stack_end;
-
- /*
- ** Store the thread's registers in the thread structure so the GC
- ** can scan them. Then scan them.
- */
- p0 = _MD_HomeGCRegisters(t, t == current, &n);
- status = scanFun(t, (void**)p0, n, scanClosure);
- if (status != PR_SUCCESS)
- return status;
-
- /* Scan the C stack for pointers into the GC heap */
-#if defined(XP_PC) && defined(WIN16)
- /*
- ** Under WIN16, the stack of the current thread is always mapped into
- ** the "task stack" (at SS:xxxx). So, if t is the current thread, scan
- ** the "task stack". Otherwise, scan the "cached stack" of the inactive
- ** thread...
- */
- if (t == current) {
- sp = (PRWord*) &stack_end;
- esp = (PRWord*) _pr_top_of_task_stack;
-
- PR_ASSERT(sp <= esp);
- } else {
- sp = (PRWord*) PR_GetSP(t);
- esp = (PRWord*) t->stack->stackTop;
-
- PR_ASSERT((t->stack->stackSize == 0) ||
- ((sp > (PRWord*)t->stack->stackBottom) &&
- (sp <= (PRWord*)t->stack->stackTop)));
- }
-#else /* ! WIN16 */
-#ifdef HAVE_STACK_GROWING_UP
- if (t == current) {
- esp = (PRWord*) &stack_end;
- } else {
- esp = (PRWord*) PR_GetSP(t);
- }
- sp = (PRWord*) t->stack->stackTop;
- if (t->stack->stackSize) {
- PR_ASSERT((esp > (PRWord*)t->stack->stackTop) &&
- (esp < (PRWord*)t->stack->stackBottom));
- }
-#else /* ! HAVE_STACK_GROWING_UP */
- if (t == current) {
- sp = (PRWord*) &stack_end;
- } else {
- sp = (PRWord*) PR_GetSP(t);
- }
- esp = (PRWord*) t->stack->stackTop;
- if (t->stack->stackSize) {
- PR_ASSERT((sp > (PRWord*)t->stack->stackBottom) &&
- (sp < (PRWord*)t->stack->stackTop));
- }
-#endif /* ! HAVE_STACK_GROWING_UP */
-#endif /* ! WIN16 */
-
-#if defined(WIN16)
- {
- prword_t scan;
- prword_t limit;
-
- scan = (prword_t) sp;
- limit = (prword_t) esp;
- while (scan < limit) {
- prword_t *test;
-
- test = *((prword_t **)scan);
- status = scanFun(t, (void**)&test, 1, scanClosure);
- if (status != PR_SUCCESS)
- return status;
- scan += sizeof(char);
- }
- }
-#else
- if (sp < esp) {
- status = scanFun(t, (void**)sp, esp - sp, scanClosure);
- if (status != PR_SUCCESS)
- return status;
- }
-#endif
-
- /*
- ** Mark all of the per-thread-data items attached to this thread
- **
- ** The execution environment better be accounted for otherwise it
- ** will be collected
- */
- status = scanFun(t, (void**)&t->environment, 1, scanClosure);
- if (status != PR_SUCCESS)
- return status;
-
- /* if thread is not allocated on stack, this is redundant. */
- ptd = t->privateData;
- for (index = 0; index < t->tpdLength; index++, ptd++) {
- status = scanFun(t, (void**)ptd, 1, scanClosure);
- if (status != PR_SUCCESS)
- return status;
- }
-
- return PR_SUCCESS;
-}
-
-/* transducer for PR_EnumerateThreads */
-typedef struct PRScanStackData {
- PRScanStackFun scanFun;
- void* scanClosure;
-} PRScanStackData;
-
-static PRStatus PR_CALLBACK
-pr_ScanStack(PRThread* t, int i, void* arg)
-{
- PRScanStackData* data = (PRScanStackData*)arg;
- return PR_ThreadScanStackPointers(t, data->scanFun, data->scanClosure);
-}
-
-PR_IMPLEMENT(PRStatus)
-PR_ScanStackPointers(PRScanStackFun scanFun, void* scanClosure)
-{
- PRScanStackData data;
- data.scanFun = scanFun;
- data.scanClosure = scanClosure;
- return PR_EnumerateThreads(pr_ScanStack, &data);
-}
-
-PR_IMPLEMENT(PRUword)
-PR_GetStackSpaceLeft(PRThread* t)
-{
- PRThread *current = PR_GetCurrentThread();
- PRWord *sp, *esp;
- int stack_end;
-
-#if defined(WIN16)
- /*
- ** Under WIN16, the stack of the current thread is always mapped into
- ** the "task stack" (at SS:xxxx). So, if t is the current thread, scan
- ** the "task stack". Otherwise, scan the "cached stack" of the inactive
- ** thread...
- */
- if (t == current) {
- sp = (PRWord*) &stack_end;
- esp = (PRWord*) _pr_top_of_task_stack;
-
- PR_ASSERT(sp <= esp);
- } else {
- sp = (PRWord*) PR_GetSP(t);
- esp = (PRWord*) t->stack->stackTop;
-
- PR_ASSERT((t->stack->stackSize == 0) ||
- ((sp > (PRWord*)t->stack->stackBottom) &&
- (sp <= (PRWord*)t->stack->stackTop)));
- }
-#else /* ! WIN16 */
-#ifdef HAVE_STACK_GROWING_UP
- if (t == current) {
- esp = (PRWord*) &stack_end;
- } else {
- esp = (PRWord*) PR_GetSP(t);
- }
- sp = (PRWord*) t->stack->stackTop;
- if (t->stack->stackSize) {
- PR_ASSERT((esp > (PRWord*)t->stack->stackTop) &&
- (esp < (PRWord*)t->stack->stackBottom));
- }
-#else /* ! HAVE_STACK_GROWING_UP */
- if (t == current) {
- sp = (PRWord*) &stack_end;
- } else {
- sp = (PRWord*) PR_GetSP(t);
- }
- esp = (PRWord*) t->stack->stackTop;
- if (t->stack->stackSize) {
- PR_ASSERT((sp > (PRWord*)t->stack->stackBottom) &&
- (sp < (PRWord*)t->stack->stackTop));
- }
-#endif /* ! HAVE_STACK_GROWING_UP */
-#endif /* ! WIN16 */
- return (PRUword)t->stack->stackSize - ((PRWord)esp - (PRWord)sp);
-}
diff --git a/nspr/pr/src/misc/prtime.c b/nspr/pr/src/misc/prtime.c
deleted file mode 100644
index 6735805..0000000
--- a/nspr/pr/src/misc/prtime.c
+++ /dev/null
@@ -1,2012 +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/. */
-
-/*
- * prtime.c --
- *
- * NSPR date and time functions
- *
- */
-
-#include "prinit.h"
-#include "prtime.h"
-#include "prlock.h"
-#include "prprf.h"
-#include "prlog.h"
-
-#include <string.h>
-#include <ctype.h>
-#include <errno.h> /* for EINVAL */
-#include <time.h>
-
-/*
- * The COUNT_LEAPS macro counts the number of leap years passed by
- * till the start of the given year Y. At the start of the year 4
- * A.D. the number of leap years passed by is 0, while at the start of
- * the year 5 A.D. this count is 1. The number of years divisible by
- * 100 but not divisible by 400 (the non-leap years) is deducted from
- * the count to get the correct number of leap years.
- *
- * The COUNT_DAYS macro counts the number of days since 01/01/01 till the
- * start of the given year Y. The number of days at the start of the year
- * 1 is 0 while the number of days at the start of the year 2 is 365
- * (which is ((2)-1) * 365) and so on. The reference point is 01/01/01
- * midnight 00:00:00.
- */
-
-#define COUNT_LEAPS(Y) ( ((Y)-1)/4 - ((Y)-1)/100 + ((Y)-1)/400 )
-#define COUNT_DAYS(Y) ( ((Y)-1)*365 + COUNT_LEAPS(Y) )
-#define DAYS_BETWEEN_YEARS(A, B) (COUNT_DAYS(B) - COUNT_DAYS(A))
-
-/*
- * Static variables used by functions in this file
- */
-
-/*
- * The following array contains the day of year for the last day of
- * each month, where index 1 is January, and day 0 is January 1.
- */
-
-static const int lastDayOfMonth[2][13] = {
- {-1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364},
- {-1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}
-};
-
-/*
- * The number of days in a month
- */
-
-static const PRInt8 nDays[2][12] = {
- {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
- {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
-};
-
-/*
- * Declarations for internal functions defined later in this file.
- */
-
-static void ComputeGMT(PRTime time, PRExplodedTime *gmt);
-static int IsLeapYear(PRInt16 year);
-static void ApplySecOffset(PRExplodedTime *time, PRInt32 secOffset);
-
-/*
- *------------------------------------------------------------------------
- *
- * ComputeGMT --
- *
- * Caveats:
- * - we ignore leap seconds
- *
- *------------------------------------------------------------------------
- */
-
-static void
-ComputeGMT(PRTime time, PRExplodedTime *gmt)
-{
- PRInt32 tmp, rem;
- PRInt32 numDays;
- PRInt64 numDays64, rem64;
- int isLeap;
- PRInt64 sec;
- PRInt64 usec;
- PRInt64 usecPerSec;
- PRInt64 secPerDay;
-
- /*
- * We first do the usec, sec, min, hour thing so that we do not
- * have to do LL arithmetic.
- */
-
- LL_I2L(usecPerSec, 1000000L);
- LL_DIV(sec, time, usecPerSec);
- LL_MOD(usec, time, usecPerSec);
- LL_L2I(gmt->tm_usec, usec);
- /* Correct for weird mod semantics so the remainder is always positive */
- if (gmt->tm_usec < 0) {
- PRInt64 one;
-
- LL_I2L(one, 1L);
- LL_SUB(sec, sec, one);
- gmt->tm_usec += 1000000L;
- }
-
- LL_I2L(secPerDay, 86400L);
- LL_DIV(numDays64, sec, secPerDay);
- LL_MOD(rem64, sec, secPerDay);
- /* We are sure both of these numbers can fit into PRInt32 */
- LL_L2I(numDays, numDays64);
- LL_L2I(rem, rem64);
- if (rem < 0) {
- numDays--;
- rem += 86400L;
- }
-
- /* Compute day of week. Epoch started on a Thursday. */
-
- gmt->tm_wday = (numDays + 4) % 7;
- if (gmt->tm_wday < 0) {
- gmt->tm_wday += 7;
- }
-
- /* Compute the time of day. */
-
- gmt->tm_hour = rem / 3600;
- rem %= 3600;
- gmt->tm_min = rem / 60;
- gmt->tm_sec = rem % 60;
-
- /*
- * Compute the year by finding the 400 year period, then working
- * down from there.
- *
- * Since numDays is originally the number of days since January 1, 1970,
- * we must change it to be the number of days from January 1, 0001.
- */
-
- numDays += 719162; /* 719162 = days from year 1 up to 1970 */
- tmp = numDays / 146097; /* 146097 = days in 400 years */
- rem = numDays % 146097;
- gmt->tm_year = tmp * 400 + 1;
-
- /* Compute the 100 year period. */
-
- tmp = rem / 36524; /* 36524 = days in 100 years */
- rem %= 36524;
- if (tmp == 4) { /* the 400th year is a leap year */
- tmp = 3;
- rem = 36524;
- }
- gmt->tm_year += tmp * 100;
-
- /* Compute the 4 year period. */
-
- tmp = rem / 1461; /* 1461 = days in 4 years */
- rem %= 1461;
- gmt->tm_year += tmp * 4;
-
- /* Compute which year in the 4. */
-
- tmp = rem / 365;
- rem %= 365;
- if (tmp == 4) { /* the 4th year is a leap year */
- tmp = 3;
- rem = 365;
- }
-
- gmt->tm_year += tmp;
- gmt->tm_yday = rem;
- isLeap = IsLeapYear(gmt->tm_year);
-
- /* Compute the month and day of month. */
-
- for (tmp = 1; lastDayOfMonth[isLeap][tmp] < gmt->tm_yday; tmp++) {
- }
- gmt->tm_month = --tmp;
- gmt->tm_mday = gmt->tm_yday - lastDayOfMonth[isLeap][tmp];
-
- gmt->tm_params.tp_gmt_offset = 0;
- gmt->tm_params.tp_dst_offset = 0;
-}
-
-
-/*
- *------------------------------------------------------------------------
- *
- * PR_ExplodeTime --
- *
- * Cf. struct tm *gmtime(const time_t *tp) and
- * struct tm *localtime(const time_t *tp)
- *
- *------------------------------------------------------------------------
- */
-
-PR_IMPLEMENT(void)
-PR_ExplodeTime(
- PRTime usecs,
- PRTimeParamFn params,
- PRExplodedTime *exploded)
-{
- ComputeGMT(usecs, exploded);
- exploded->tm_params = params(exploded);
- ApplySecOffset(exploded, exploded->tm_params.tp_gmt_offset
- + exploded->tm_params.tp_dst_offset);
-}
-
-
-/*
- *------------------------------------------------------------------------
- *
- * PR_ImplodeTime --
- *
- * Cf. time_t mktime(struct tm *tp)
- * Note that 1 year has < 2^25 seconds. So an PRInt32 is large enough.
- *
- *------------------------------------------------------------------------
- */
-PR_IMPLEMENT(PRTime)
-PR_ImplodeTime(const PRExplodedTime *exploded)
-{
- PRExplodedTime copy;
- PRTime retVal;
- PRInt64 secPerDay, usecPerSec;
- PRInt64 temp;
- PRInt64 numSecs64;
- PRInt32 numDays;
- PRInt32 numSecs;
-
- /* Normalize first. Do this on our copy */
- copy = *exploded;
- PR_NormalizeTime(©, PR_GMTParameters);
-
- numDays = DAYS_BETWEEN_YEARS(1970, copy.tm_year);
-
- numSecs = copy.tm_yday * 86400 + copy.tm_hour * 3600
- + copy.tm_min * 60 + copy.tm_sec;
-
- LL_I2L(temp, numDays);
- LL_I2L(secPerDay, 86400);
- LL_MUL(temp, temp, secPerDay);
- LL_I2L(numSecs64, numSecs);
- LL_ADD(numSecs64, numSecs64, temp);
-
- /* apply the GMT and DST offsets */
- LL_I2L(temp, copy.tm_params.tp_gmt_offset);
- LL_SUB(numSecs64, numSecs64, temp);
- LL_I2L(temp, copy.tm_params.tp_dst_offset);
- LL_SUB(numSecs64, numSecs64, temp);
-
- LL_I2L(usecPerSec, 1000000L);
- LL_MUL(temp, numSecs64, usecPerSec);
- LL_I2L(retVal, copy.tm_usec);
- LL_ADD(retVal, retVal, temp);
-
- return retVal;
-}
-
-/*
- *-------------------------------------------------------------------------
- *
- * IsLeapYear --
- *
- * Returns 1 if the year is a leap year, 0 otherwise.
- *
- *-------------------------------------------------------------------------
- */
-
-static int IsLeapYear(PRInt16 year)
-{
- if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
- return 1;
- else
- return 0;
-}
-
-/*
- * 'secOffset' should be less than 86400 (i.e., a day).
- * 'time' should point to a normalized PRExplodedTime.
- */
-
-static void
-ApplySecOffset(PRExplodedTime *time, PRInt32 secOffset)
-{
- time->tm_sec += secOffset;
-
- /* Note that in this implementation we do not count leap seconds */
- if (time->tm_sec < 0 || time->tm_sec >= 60) {
- time->tm_min += time->tm_sec / 60;
- time->tm_sec %= 60;
- if (time->tm_sec < 0) {
- time->tm_sec += 60;
- time->tm_min--;
- }
- }
-
- if (time->tm_min < 0 || time->tm_min >= 60) {
- time->tm_hour += time->tm_min / 60;
- time->tm_min %= 60;
- if (time->tm_min < 0) {
- time->tm_min += 60;
- time->tm_hour--;
- }
- }
-
- if (time->tm_hour < 0) {
- /* Decrement mday, yday, and wday */
- time->tm_hour += 24;
- time->tm_mday--;
- time->tm_yday--;
- if (time->tm_mday < 1) {
- time->tm_month--;
- if (time->tm_month < 0) {
- time->tm_month = 11;
- time->tm_year--;
- if (IsLeapYear(time->tm_year))
- time->tm_yday = 365;
- else
- time->tm_yday = 364;
- }
- time->tm_mday = nDays[IsLeapYear(time->tm_year)][time->tm_month];
- }
- time->tm_wday--;
- if (time->tm_wday < 0)
- time->tm_wday = 6;
- } else if (time->tm_hour > 23) {
- /* Increment mday, yday, and wday */
- time->tm_hour -= 24;
- time->tm_mday++;
- time->tm_yday++;
- if (time->tm_mday >
- nDays[IsLeapYear(time->tm_year)][time->tm_month]) {
- time->tm_mday = 1;
- time->tm_month++;
- if (time->tm_month > 11) {
- time->tm_month = 0;
- time->tm_year++;
- time->tm_yday = 0;
- }
- }
- time->tm_wday++;
- if (time->tm_wday > 6)
- time->tm_wday = 0;
- }
-}
-
-PR_IMPLEMENT(void)
-PR_NormalizeTime(PRExplodedTime *time, PRTimeParamFn params)
-{
- int daysInMonth;
- PRInt32 numDays;
-
- /* Get back to GMT */
- time->tm_sec -= time->tm_params.tp_gmt_offset
- + time->tm_params.tp_dst_offset;
- time->tm_params.tp_gmt_offset = 0;
- time->tm_params.tp_dst_offset = 0;
-
- /* Now normalize GMT */
-
- if (time->tm_usec < 0 || time->tm_usec >= 1000000) {
- time->tm_sec += time->tm_usec / 1000000;
- time->tm_usec %= 1000000;
- if (time->tm_usec < 0) {
- time->tm_usec += 1000000;
- time->tm_sec--;
- }
- }
-
- /* Note that we do not count leap seconds in this implementation */
- if (time->tm_sec < 0 || time->tm_sec >= 60) {
- time->tm_min += time->tm_sec / 60;
- time->tm_sec %= 60;
- if (time->tm_sec < 0) {
- time->tm_sec += 60;
- time->tm_min--;
- }
- }
-
- if (time->tm_min < 0 || time->tm_min >= 60) {
- time->tm_hour += time->tm_min / 60;
- time->tm_min %= 60;
- if (time->tm_min < 0) {
- time->tm_min += 60;
- time->tm_hour--;
- }
- }
-
- if (time->tm_hour < 0 || time->tm_hour >= 24) {
- time->tm_mday += time->tm_hour / 24;
- time->tm_hour %= 24;
- if (time->tm_hour < 0) {
- time->tm_hour += 24;
- time->tm_mday--;
- }
- }
-
- /* Normalize month and year before mday */
- if (time->tm_month < 0 || time->tm_month >= 12) {
- time->tm_year += time->tm_month / 12;
- time->tm_month %= 12;
- if (time->tm_month < 0) {
- time->tm_month += 12;
- time->tm_year--;
- }
- }
-
- /* Now that month and year are in proper range, normalize mday */
-
- if (time->tm_mday < 1) {
- /* mday too small */
- do {
- /* the previous month */
- time->tm_month--;
- if (time->tm_month < 0) {
- time->tm_month = 11;
- time->tm_year--;
- }
- time->tm_mday += nDays[IsLeapYear(time->tm_year)][time->tm_month];
- } while (time->tm_mday < 1);
- } else {
- daysInMonth = nDays[IsLeapYear(time->tm_year)][time->tm_month];
- while (time->tm_mday > daysInMonth) {
- /* mday too large */
- time->tm_mday -= daysInMonth;
- time->tm_month++;
- if (time->tm_month > 11) {
- time->tm_month = 0;
- time->tm_year++;
- }
- daysInMonth = nDays[IsLeapYear(time->tm_year)][time->tm_month];
- }
- }
-
- /* Recompute yday and wday */
- time->tm_yday = time->tm_mday +
- lastDayOfMonth[IsLeapYear(time->tm_year)][time->tm_month];
-
- numDays = DAYS_BETWEEN_YEARS(1970, time->tm_year) + time->tm_yday;
- time->tm_wday = (numDays + 4) % 7;
- if (time->tm_wday < 0) {
- time->tm_wday += 7;
- }
-
- /* Recompute time parameters */
-
- time->tm_params = params(time);
-
- ApplySecOffset(time, time->tm_params.tp_gmt_offset
- + time->tm_params.tp_dst_offset);
-}
-
-
-/*
- *-------------------------------------------------------------------------
- *
- * PR_LocalTimeParameters --
- *
- * returns the time parameters for the local time zone
- *
- * The following uses localtime() from the standard C library.
- * (time.h) This is our fallback implementation. Unix, PC, and BeOS
- * use this version. A platform may have its own machine-dependent
- * implementation of this function.
- *
- *-------------------------------------------------------------------------
- */
-
-#if defined(HAVE_INT_LOCALTIME_R)
-
-/*
- * In this case we could define the macro as
- * #define MT_safe_localtime(timer, result) \
- * (localtime_r(timer, result) == 0 ? result : NULL)
- * I chose to compare the return value of localtime_r with -1 so
- * that I can catch the cases where localtime_r returns a pointer
- * to struct tm. The macro definition above would not be able to
- * detect such mistakes because it is legal to compare a pointer
- * with 0.
- */
-
-#define MT_safe_localtime(timer, result) \
- (localtime_r(timer, result) == -1 ? NULL: result)
-
-#elif defined(HAVE_POINTER_LOCALTIME_R)
-
-#define MT_safe_localtime localtime_r
-
-#else
-
-#define HAVE_LOCALTIME_MONITOR 1 /* We use 'monitor' to serialize our calls
- * to localtime(). */
-static PRLock *monitor = NULL;
-
-static struct tm *MT_safe_localtime(const time_t *clock, struct tm *result)
-{
- struct tm *tmPtr;
- int needLock = PR_Initialized(); /* We need to use a lock to protect
- * against NSPR threads only when the
- * NSPR thread system is activated. */
-
- if (needLock) PR_Lock(monitor);
-
- /*
- * Microsoft (all flavors) localtime() returns a NULL pointer if 'clock'
- * represents a time before midnight January 1, 1970. In
- * that case, we also return a NULL pointer and the struct tm
- * object pointed to by 'result' is not modified.
- *
- * Watcom C/C++ 11.0 localtime() treats time_t as unsigned long
- * hence, does not recognize negative values of clock as pre-1/1/70.
- * We have to manually check (WIN16 only) for negative value of
- * clock and return NULL.
- *
- * With negative values of clock, OS/2 returns the struct tm for
- * clock plus ULONG_MAX. So we also have to check for the invalid
- * structs returned for timezones west of Greenwich when clock == 0.
- */
-
- tmPtr = localtime(clock);
-
-#if defined(WIN16) || defined(XP_OS2)
- if ( (PRInt32) *clock < 0 ||
- ( (PRInt32) *clock == 0 && tmPtr->tm_year != 70))
- result = NULL;
- else
- *result = *tmPtr;
-#else
- if (tmPtr) {
- *result = *tmPtr;
- } else {
- result = NULL;
- }
-#endif /* WIN16 */
-
- if (needLock) PR_Unlock(monitor);
-
- return result;
-}
-
-#endif /* definition of MT_safe_localtime() */
-
-void _PR_InitTime(void)
-{
-#ifdef HAVE_LOCALTIME_MONITOR
- monitor = PR_NewLock();
-#endif
-#ifdef WINCE
- _MD_InitTime();
-#endif
-}
-
-void _PR_CleanupTime(void)
-{
-#ifdef HAVE_LOCALTIME_MONITOR
- if (monitor) {
- PR_DestroyLock(monitor);
- monitor = NULL;
- }
-#endif
-#ifdef WINCE
- _MD_CleanupTime();
-#endif
-}
-
-#if defined(XP_UNIX) || defined(XP_PC) || defined(XP_BEOS)
-
-PR_IMPLEMENT(PRTimeParameters)
-PR_LocalTimeParameters(const PRExplodedTime *gmt)
-{
-
- PRTimeParameters retVal;
- struct tm localTime;
- time_t secs;
- PRTime secs64;
- PRInt64 usecPerSec;
- PRInt64 usecPerSec_1;
- PRInt64 maxInt32;
- PRInt64 minInt32;
- PRInt32 dayOffset;
- PRInt32 offset2Jan1970;
- PRInt32 offsetNew;
- int isdst2Jan1970;
-
- /*
- * Calculate the GMT offset. First, figure out what is
- * 00:00:00 Jan. 2, 1970 GMT (which is exactly a day, or 86400
- * seconds, since the epoch) in local time. Then we calculate
- * the difference between local time and GMT in seconds:
- * gmt_offset = local_time - GMT
- *
- * Caveat: the validity of this calculation depends on two
- * assumptions:
- * 1. Daylight saving time was not in effect on Jan. 2, 1970.
- * 2. The time zone of the geographic location has not changed
- * since Jan. 2, 1970.
- */
-
- secs = 86400L;
- (void) MT_safe_localtime(&secs, &localTime);
-
- /* GMT is 00:00:00, 2nd of Jan. */
-
- offset2Jan1970 = (PRInt32)localTime.tm_sec
- + 60L * (PRInt32)localTime.tm_min
- + 3600L * (PRInt32)localTime.tm_hour
- + 86400L * (PRInt32)((PRInt32)localTime.tm_mday - 2L);
-
- isdst2Jan1970 = localTime.tm_isdst;
-
- /*
- * Now compute DST offset. We calculate the overall offset
- * of local time from GMT, similar to above. The overall
- * offset has two components: gmt offset and dst offset.
- * We subtract gmt offset from the overall offset to get
- * the dst offset.
- * overall_offset = local_time - GMT
- * overall_offset = gmt_offset + dst_offset
- * ==> dst_offset = local_time - GMT - gmt_offset
- */
-
- secs64 = PR_ImplodeTime(gmt); /* This is still in microseconds */
- LL_I2L(usecPerSec, PR_USEC_PER_SEC);
- LL_I2L(usecPerSec_1, PR_USEC_PER_SEC - 1);
- /* Convert to seconds, truncating down (3.1 -> 3 and -3.1 -> -4) */
- if (LL_GE_ZERO(secs64)) {
- LL_DIV(secs64, secs64, usecPerSec);
- } else {
- LL_NEG(secs64, secs64);
- LL_ADD(secs64, secs64, usecPerSec_1);
- LL_DIV(secs64, secs64, usecPerSec);
- LL_NEG(secs64, secs64);
- }
- LL_I2L(maxInt32, PR_INT32_MAX);
- LL_I2L(minInt32, PR_INT32_MIN);
- if (LL_CMP(secs64, >, maxInt32) || LL_CMP(secs64, <, minInt32)) {
- /* secs64 is too large or too small for time_t (32-bit integer) */
- retVal.tp_gmt_offset = offset2Jan1970;
- retVal.tp_dst_offset = 0;
- return retVal;
- }
- LL_L2I(secs, secs64);
-
- /*
- * On Windows, localtime() (and our MT_safe_localtime() too)
- * returns a NULL pointer for time before midnight January 1,
- * 1970 GMT. In that case, we just use the GMT offset for
- * Jan 2, 1970 and assume that DST was not in effect.
- */
-
- if (MT_safe_localtime(&secs, &localTime) == NULL) {
- retVal.tp_gmt_offset = offset2Jan1970;
- retVal.tp_dst_offset = 0;
- return retVal;
- }
-
- /*
- * dayOffset is the offset between local time and GMT in
- * the day component, which can only be -1, 0, or 1. We
- * use the day of the week to compute dayOffset.
- */
-
- dayOffset = (PRInt32) localTime.tm_wday - gmt->tm_wday;
-
- /*
- * Need to adjust for wrapping around of day of the week from
- * 6 back to 0.
- */
-
- if (dayOffset == -6) {
- /* Local time is Sunday (0) and GMT is Saturday (6) */
- dayOffset = 1;
- } else if (dayOffset == 6) {
- /* Local time is Saturday (6) and GMT is Sunday (0) */
- dayOffset = -1;
- }
-
- offsetNew = (PRInt32)localTime.tm_sec - gmt->tm_sec
- + 60L * ((PRInt32)localTime.tm_min - gmt->tm_min)
- + 3600L * ((PRInt32)localTime.tm_hour - gmt->tm_hour)
- + 86400L * (PRInt32)dayOffset;
-
- if (localTime.tm_isdst <= 0) {
- /* DST is not in effect */
- retVal.tp_gmt_offset = offsetNew;
- retVal.tp_dst_offset = 0;
- } else {
- /* DST is in effect */
- if (isdst2Jan1970 <=0) {
- /*
- * DST was not in effect back in 2 Jan. 1970.
- * Use the offset back then as the GMT offset,
- * assuming the time zone has not changed since then.
- */
- retVal.tp_gmt_offset = offset2Jan1970;
- retVal.tp_dst_offset = offsetNew - offset2Jan1970;
- } else {
- /*
- * DST was also in effect back in 2 Jan. 1970.
- * Then our clever trick (or rather, ugly hack) fails.
- * We will just assume DST offset is an hour.
- */
- retVal.tp_gmt_offset = offsetNew - 3600;
- retVal.tp_dst_offset = 3600;
- }
- }
-
- return retVal;
-}
-
-#endif /* defined(XP_UNIX) || defined(XP_PC) || defined(XP_BEOS) */
-
-/*
- *------------------------------------------------------------------------
- *
- * PR_USPacificTimeParameters --
- *
- * The time parameters function for the US Pacific Time Zone.
- *
- *------------------------------------------------------------------------
- */
-
-/*
- * Returns the mday of the first sunday of the month, where
- * mday and wday are for a given day in the month.
- * mdays start with 1 (e.g. 1..31).
- * wdays start with 0 and are in the range 0..6. 0 = Sunday.
- */
-#define firstSunday(mday, wday) (((mday - wday + 7 - 1) % 7) + 1)
-
-/*
- * Returns the mday for the N'th Sunday of the month, where
- * mday and wday are for a given day in the month.
- * mdays start with 1 (e.g. 1..31).
- * wdays start with 0 and are in the range 0..6. 0 = Sunday.
- * N has the following values: 0 = first, 1 = second (etc), -1 = last.
- * ndays is the number of days in that month, the same value as the
- * mday of the last day of the month.
- */
-static PRInt32
-NthSunday(PRInt32 mday, PRInt32 wday, PRInt32 N, PRInt32 ndays)
-{
- PRInt32 firstSun = firstSunday(mday, wday);
-
- if (N < 0)
- N = (ndays - firstSun) / 7;
- return firstSun + (7 * N);
-}
-
-typedef struct DSTParams {
- PRInt8 dst_start_month; /* 0 = January */
- PRInt8 dst_start_Nth_Sunday; /* N as defined above */
- PRInt8 dst_start_month_ndays; /* ndays as defined above */
- PRInt8 dst_end_month; /* 0 = January */
- PRInt8 dst_end_Nth_Sunday; /* N as defined above */
- PRInt8 dst_end_month_ndays; /* ndays as defined above */
-} DSTParams;
-
-static const DSTParams dstParams[2] = {
- /* year < 2007: First April Sunday - Last October Sunday */
- { 3, 0, 30, 9, -1, 31 },
- /* year >= 2007: Second March Sunday - First November Sunday */
- { 2, 1, 31, 10, 0, 30 }
-};
-
-PR_IMPLEMENT(PRTimeParameters)
-PR_USPacificTimeParameters(const PRExplodedTime *gmt)
-{
- const DSTParams *dst;
- PRTimeParameters retVal;
- PRExplodedTime st;
-
- /*
- * Based on geographic location and GMT, figure out offset of
- * standard time from GMT. In this example implementation, we
- * assume the local time zone is US Pacific Time.
- */
-
- retVal.tp_gmt_offset = -8L * 3600L;
-
- /*
- * Make a copy of GMT. Note that the tm_params field of this copy
- * is ignored.
- */
-
- st.tm_usec = gmt->tm_usec;
- st.tm_sec = gmt->tm_sec;
- st.tm_min = gmt->tm_min;
- st.tm_hour = gmt->tm_hour;
- st.tm_mday = gmt->tm_mday;
- st.tm_month = gmt->tm_month;
- st.tm_year = gmt->tm_year;
- st.tm_wday = gmt->tm_wday;
- st.tm_yday = gmt->tm_yday;
-
- /* Apply the offset to GMT to obtain the local standard time */
- ApplySecOffset(&st, retVal.tp_gmt_offset);
-
- if (st.tm_year < 2007) { /* first April Sunday - Last October Sunday */
- dst = &dstParams[0];
- } else { /* Second March Sunday - First November Sunday */
- dst = &dstParams[1];
- }
-
- /*
- * Apply the rules on standard time or GMT to obtain daylight saving
- * time offset. In this implementation, we use the US DST rule.
- */
- if (st.tm_month < dst->dst_start_month) {
- retVal.tp_dst_offset = 0L;
- } else if (st.tm_month == dst->dst_start_month) {
- int NthSun = NthSunday(st.tm_mday, st.tm_wday,
- dst->dst_start_Nth_Sunday,
- dst->dst_start_month_ndays);
- if (st.tm_mday < NthSun) { /* Before starting Sunday */
- retVal.tp_dst_offset = 0L;
- } else if (st.tm_mday == NthSun) { /* Starting Sunday */
- /* 01:59:59 PST -> 03:00:00 PDT */
- if (st.tm_hour < 2) {
- retVal.tp_dst_offset = 0L;
- } else {
- retVal.tp_dst_offset = 3600L;
- }
- } else { /* After starting Sunday */
- retVal.tp_dst_offset = 3600L;
- }
- } else if (st.tm_month < dst->dst_end_month) {
- retVal.tp_dst_offset = 3600L;
- } else if (st.tm_month == dst->dst_end_month) {
- int NthSun = NthSunday(st.tm_mday, st.tm_wday,
- dst->dst_end_Nth_Sunday,
- dst->dst_end_month_ndays);
- if (st.tm_mday < NthSun) { /* Before ending Sunday */
- retVal.tp_dst_offset = 3600L;
- } else if (st.tm_mday == NthSun) { /* Ending Sunday */
- /* 01:59:59 PDT -> 01:00:00 PST */
- if (st.tm_hour < 1) {
- retVal.tp_dst_offset = 3600L;
- } else {
- retVal.tp_dst_offset = 0L;
- }
- } else { /* After ending Sunday */
- retVal.tp_dst_offset = 0L;
- }
- } else {
- retVal.tp_dst_offset = 0L;
- }
- return retVal;
-}
-
-/*
- *------------------------------------------------------------------------
- *
- * PR_GMTParameters --
- *
- * Returns the PRTimeParameters for Greenwich Mean Time.
- * Trivially, both the tp_gmt_offset and tp_dst_offset fields are 0.
- *
- *------------------------------------------------------------------------
- */
-
-PR_IMPLEMENT(PRTimeParameters)
-PR_GMTParameters(const PRExplodedTime *gmt)
-{
- PRTimeParameters retVal = { 0, 0 };
- return retVal;
-}
-
-/*
- * The following code implements PR_ParseTimeString(). It is based on
- * ns/lib/xp/xp_time.c, revision 1.25, by Jamie Zawinski <[email protected]>.
- */
-
-/*
- * We only recognize the abbreviations of a small subset of time zones
- * in North America, Europe, and Japan.
- *
- * PST/PDT: Pacific Standard/Daylight Time
- * MST/MDT: Mountain Standard/Daylight Time
- * CST/CDT: Central Standard/Daylight Time
- * EST/EDT: Eastern Standard/Daylight Time
- * AST: Atlantic Standard Time
- * NST: Newfoundland Standard Time
- * GMT: Greenwich Mean Time
- * BST: British Summer Time
- * MET: Middle Europe Time
- * EET: Eastern Europe Time
- * JST: Japan Standard Time
- */
-
-typedef enum
-{
- TT_UNKNOWN,
-
- TT_SUN, TT_MON, TT_TUE, TT_WED, TT_THU, TT_FRI, TT_SAT,
-
- TT_JAN, TT_FEB, TT_MAR, TT_APR, TT_MAY, TT_JUN,
- TT_JUL, TT_AUG, TT_SEP, TT_OCT, TT_NOV, TT_DEC,
-
- TT_PST, TT_PDT, TT_MST, TT_MDT, TT_CST, TT_CDT, TT_EST, TT_EDT,
- TT_AST, TT_NST, TT_GMT, TT_BST, TT_MET, TT_EET, TT_JST
-} TIME_TOKEN;
-
-/*
- * This parses a time/date string into a PRTime
- * (microseconds after "1-Jan-1970 00:00:00 GMT").
- * It returns PR_SUCCESS on success, and PR_FAILURE
- * if the time/date string can't be parsed.
- *
- * Many formats are handled, including:
- *
- * 14 Apr 89 03:20:12
- * 14 Apr 89 03:20 GMT
- * Fri, 17 Mar 89 4:01:33
- * Fri, 17 Mar 89 4:01 GMT
- * Mon Jan 16 16:12 PDT 1989
- * Mon Jan 16 16:12 +0130 1989
- * 6 May 1992 16:41-JST (Wednesday)
- * 22-AUG-1993 10:59:12.82
- * 22-AUG-1993 10:59pm
- * 22-AUG-1993 12:59am
- * 22-AUG-1993 12:59 PM
- * Friday, August 04, 1995 3:54 PM
- * 06/21/95 04:24:34 PM
- * 20/06/95 21:07
- * 95-06-08 19:32:48 EDT
- *
- * If the input string doesn't contain a description of the timezone,
- * we consult the `default_to_gmt' to decide whether the string should
- * be interpreted relative to the local time zone (PR_FALSE) or GMT (PR_TRUE).
- * The correct value for this argument depends on what standard specified
- * the time string which you are parsing.
- */
-
-PR_IMPLEMENT(PRStatus)
-PR_ParseTimeStringToExplodedTime(
- const char *string,
- PRBool default_to_gmt,
- PRExplodedTime *result)
-{
- TIME_TOKEN dotw = TT_UNKNOWN;
- TIME_TOKEN month = TT_UNKNOWN;
- TIME_TOKEN zone = TT_UNKNOWN;
- int zone_offset = -1;
- int dst_offset = 0;
- int date = -1;
- PRInt32 year = -1;
- int hour = -1;
- int min = -1;
- int sec = -1;
-
- const char *rest = string;
-
- int iterations = 0;
-
- PR_ASSERT(string && result);
- if (!string || !result) return PR_FAILURE;
-
- while (*rest)
- {
-
- if (iterations++ > 1000)
- {
- return PR_FAILURE;
- }
-
- switch (*rest)
- {
- case 'a': case 'A':
- if (month == TT_UNKNOWN &&
- (rest[1] == 'p' || rest[1] == 'P') &&
- (rest[2] == 'r' || rest[2] == 'R'))
- month = TT_APR;
- else if (zone == TT_UNKNOWN &&
- (rest[1] == 's' || rest[1] == 'S') &&
- (rest[2] == 't' || rest[2] == 'T'))
- zone = TT_AST;
- else if (month == TT_UNKNOWN &&
- (rest[1] == 'u' || rest[1] == 'U') &&
- (rest[2] == 'g' || rest[2] == 'G'))
- month = TT_AUG;
- break;
- case 'b': case 'B':
- if (zone == TT_UNKNOWN &&
- (rest[1] == 's' || rest[1] == 'S') &&
- (rest[2] == 't' || rest[2] == 'T'))
- zone = TT_BST;
- break;
- case 'c': case 'C':
- if (zone == TT_UNKNOWN &&
- (rest[1] == 'd' || rest[1] == 'D') &&
- (rest[2] == 't' || rest[2] == 'T'))
- zone = TT_CDT;
- else if (zone == TT_UNKNOWN &&
- (rest[1] == 's' || rest[1] == 'S') &&
- (rest[2] == 't' || rest[2] == 'T'))
- zone = TT_CST;
- break;
- case 'd': case 'D':
- if (month == TT_UNKNOWN &&
- (rest[1] == 'e' || rest[1] == 'E') &&
- (rest[2] == 'c' || rest[2] == 'C'))
- month = TT_DEC;
- break;
- case 'e': case 'E':
- if (zone == TT_UNKNOWN &&
- (rest[1] == 'd' || rest[1] == 'D') &&
- (rest[2] == 't' || rest[2] == 'T'))
- zone = TT_EDT;
- else if (zone == TT_UNKNOWN &&
- (rest[1] == 'e' || rest[1] == 'E') &&
- (rest[2] == 't' || rest[2] == 'T'))
- zone = TT_EET;
- else if (zone == TT_UNKNOWN &&
- (rest[1] == 's' || rest[1] == 'S') &&
- (rest[2] == 't' || rest[2] == 'T'))
- zone = TT_EST;
- break;
- case 'f': case 'F':
- if (month == TT_UNKNOWN &&
- (rest[1] == 'e' || rest[1] == 'E') &&
- (rest[2] == 'b' || rest[2] == 'B'))
- month = TT_FEB;
- else if (dotw == TT_UNKNOWN &&
- (rest[1] == 'r' || rest[1] == 'R') &&
- (rest[2] == 'i' || rest[2] == 'I'))
- dotw = TT_FRI;
- break;
- case 'g': case 'G':
- if (zone == TT_UNKNOWN &&
- (rest[1] == 'm' || rest[1] == 'M') &&
- (rest[2] == 't' || rest[2] == 'T'))
- zone = TT_GMT;
- break;
- case 'j': case 'J':
- if (month == TT_UNKNOWN &&
- (rest[1] == 'a' || rest[1] == 'A') &&
- (rest[2] == 'n' || rest[2] == 'N'))
- month = TT_JAN;
- else if (zone == TT_UNKNOWN &&
- (rest[1] == 's' || rest[1] == 'S') &&
- (rest[2] == 't' || rest[2] == 'T'))
- zone = TT_JST;
- else if (month == TT_UNKNOWN &&
- (rest[1] == 'u' || rest[1] == 'U') &&
- (rest[2] == 'l' || rest[2] == 'L'))
- month = TT_JUL;
- else if (month == TT_UNKNOWN &&
- (rest[1] == 'u' || rest[1] == 'U') &&
- (rest[2] == 'n' || rest[2] == 'N'))
- month = TT_JUN;
- break;
- case 'm': case 'M':
- if (month == TT_UNKNOWN &&
- (rest[1] == 'a' || rest[1] == 'A') &&
- (rest[2] == 'r' || rest[2] == 'R'))
- month = TT_MAR;
- else if (month == TT_UNKNOWN &&
- (rest[1] == 'a' || rest[1] == 'A') &&
- (rest[2] == 'y' || rest[2] == 'Y'))
- month = TT_MAY;
- else if (zone == TT_UNKNOWN &&
- (rest[1] == 'd' || rest[1] == 'D') &&
- (rest[2] == 't' || rest[2] == 'T'))
- zone = TT_MDT;
- else if (zone == TT_UNKNOWN &&
- (rest[1] == 'e' || rest[1] == 'E') &&
- (rest[2] == 't' || rest[2] == 'T'))
- zone = TT_MET;
- else if (dotw == TT_UNKNOWN &&
- (rest[1] == 'o' || rest[1] == 'O') &&
- (rest[2] == 'n' || rest[2] == 'N'))
- dotw = TT_MON;
- else if (zone == TT_UNKNOWN &&
- (rest[1] == 's' || rest[1] == 'S') &&
- (rest[2] == 't' || rest[2] == 'T'))
- zone = TT_MST;
- break;
- case 'n': case 'N':
- if (month == TT_UNKNOWN &&
- (rest[1] == 'o' || rest[1] == 'O') &&
- (rest[2] == 'v' || rest[2] == 'V'))
- month = TT_NOV;
- else if (zone == TT_UNKNOWN &&
- (rest[1] == 's' || rest[1] == 'S') &&
- (rest[2] == 't' || rest[2] == 'T'))
- zone = TT_NST;
- break;
- case 'o': case 'O':
- if (month == TT_UNKNOWN &&
- (rest[1] == 'c' || rest[1] == 'C') &&
- (rest[2] == 't' || rest[2] == 'T'))
- month = TT_OCT;
- break;
- case 'p': case 'P':
- if (zone == TT_UNKNOWN &&
- (rest[1] == 'd' || rest[1] == 'D') &&
- (rest[2] == 't' || rest[2] == 'T'))
- zone = TT_PDT;
- else if (zone == TT_UNKNOWN &&
- (rest[1] == 's' || rest[1] == 'S') &&
- (rest[2] == 't' || rest[2] == 'T'))
- zone = TT_PST;
- break;
- case 's': case 'S':
- if (dotw == TT_UNKNOWN &&
- (rest[1] == 'a' || rest[1] == 'A') &&
- (rest[2] == 't' || rest[2] == 'T'))
- dotw = TT_SAT;
- else if (month == TT_UNKNOWN &&
- (rest[1] == 'e' || rest[1] == 'E') &&
- (rest[2] == 'p' || rest[2] == 'P'))
- month = TT_SEP;
- else if (dotw == TT_UNKNOWN &&
- (rest[1] == 'u' || rest[1] == 'U') &&
- (rest[2] == 'n' || rest[2] == 'N'))
- dotw = TT_SUN;
- break;
- case 't': case 'T':
- if (dotw == TT_UNKNOWN &&
- (rest[1] == 'h' || rest[1] == 'H') &&
- (rest[2] == 'u' || rest[2] == 'U'))
- dotw = TT_THU;
- else if (dotw == TT_UNKNOWN &&
- (rest[1] == 'u' || rest[1] == 'U') &&
- (rest[2] == 'e' || rest[2] == 'E'))
- dotw = TT_TUE;
- break;
- case 'u': case 'U':
- if (zone == TT_UNKNOWN &&
- (rest[1] == 't' || rest[1] == 'T') &&
- !(rest[2] >= 'A' && rest[2] <= 'Z') &&
- !(rest[2] >= 'a' && rest[2] <= 'z'))
- /* UT is the same as GMT but UTx is not. */
- zone = TT_GMT;
- break;
- case 'w': case 'W':
- if (dotw == TT_UNKNOWN &&
- (rest[1] == 'e' || rest[1] == 'E') &&
- (rest[2] == 'd' || rest[2] == 'D'))
- dotw = TT_WED;
- break;
-
- case '+': case '-':
- {
- const char *end;
- int sign;
- if (zone_offset != -1)
- {
- /* already got one... */
- rest++;
- break;
- }
- if (zone != TT_UNKNOWN && zone != TT_GMT)
- {
- /* GMT+0300 is legal, but PST+0300 is not. */
- rest++;
- break;
- }
-
- sign = ((*rest == '+') ? 1 : -1);
- rest++; /* move over sign */
- end = rest;
- while (*end >= '0' && *end <= '9')
- end++;
- if (rest == end) /* no digits here */
- break;
-
- if ((end - rest) == 4)
- /* offset in HHMM */
- zone_offset = (((((rest[0]-'0')*10) + (rest[1]-'0')) * 60) +
- (((rest[2]-'0')*10) + (rest[3]-'0')));
- else if ((end - rest) == 2)
- /* offset in hours */
- zone_offset = (((rest[0]-'0')*10) + (rest[1]-'0')) * 60;
- else if ((end - rest) == 1)
- /* offset in hours */
- zone_offset = (rest[0]-'0') * 60;
- else
- /* 3 or >4 */
- break;
-
- zone_offset *= sign;
- zone = TT_GMT;
- break;
- }
-
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- {
- int tmp_hour = -1;
- int tmp_min = -1;
- int tmp_sec = -1;
- const char *end = rest + 1;
- while (*end >= '0' && *end <= '9')
- end++;
-
- /* end is now the first character after a range of digits. */
-
- if (*end == ':')
- {
- if (hour >= 0 && min >= 0) /* already got it */
- break;
-
- /* We have seen "[0-9]+:", so this is probably HH:MM[:SS] */
- if ((end - rest) > 2)
- /* it is [0-9][0-9][0-9]+: */
- break;
- else if ((end - rest) == 2)
- tmp_hour = ((rest[0]-'0')*10 +
- (rest[1]-'0'));
- else
- tmp_hour = (rest[0]-'0');
-
- /* move over the colon, and parse minutes */
-
- rest = ++end;
- while (*end >= '0' && *end <= '9')
- end++;
-
- if (end == rest)
- /* no digits after first colon? */
- break;
- else if ((end - rest) > 2)
- /* it is [0-9][0-9][0-9]+: */
- break;
- else if ((end - rest) == 2)
- tmp_min = ((rest[0]-'0')*10 +
- (rest[1]-'0'));
- else
- tmp_min = (rest[0]-'0');
-
- /* now go for seconds */
- rest = end;
- if (*rest == ':')
- rest++;
- end = rest;
- while (*end >= '0' && *end <= '9')
- end++;
-
- if (end == rest)
- /* no digits after second colon - that's ok. */
- ;
- else if ((end - rest) > 2)
- /* it is [0-9][0-9][0-9]+: */
- break;
- else if ((end - rest) == 2)
- tmp_sec = ((rest[0]-'0')*10 +
- (rest[1]-'0'));
- else
- tmp_sec = (rest[0]-'0');
-
- /* If we made it here, we've parsed hour and min,
- and possibly sec, so it worked as a unit. */
-
- /* skip over whitespace and see if there's an AM or PM
- directly following the time.
- */
- if (tmp_hour <= 12)
- {
- const char *s = end;
- while (*s && (*s == ' ' || *s == '\t'))
- s++;
- if ((s[0] == 'p' || s[0] == 'P') &&
- (s[1] == 'm' || s[1] == 'M'))
- /* 10:05pm == 22:05, and 12:05pm == 12:05 */
- tmp_hour = (tmp_hour == 12 ? 12 : tmp_hour + 12);
- else if (tmp_hour == 12 &&
- (s[0] == 'a' || s[0] == 'A') &&
- (s[1] == 'm' || s[1] == 'M'))
- /* 12:05am == 00:05 */
- tmp_hour = 0;
- }
-
- hour = tmp_hour;
- min = tmp_min;
- sec = tmp_sec;
- rest = end;
- break;
- }
- else if ((*end == '/' || *end == '-') &&
- end[1] >= '0' && end[1] <= '9')
- {
- /* Perhaps this is 6/16/95, 16/6/95, 6-16-95, or 16-6-95
- or even 95-06-05...
- #### But it doesn't handle 1995-06-22.
- */
- int n1, n2, n3;
- const char *s;
-
- if (month != TT_UNKNOWN)
- /* if we saw a month name, this can't be. */
- break;
-
- s = rest;
-
- n1 = (*s++ - '0'); /* first 1 or 2 digits */
- if (*s >= '0' && *s <= '9')
- n1 = n1*10 + (*s++ - '0');
-
- if (*s != '/' && *s != '-') /* slash */
- break;
- s++;
-
- if (*s < '0' || *s > '9') /* second 1 or 2 digits */
- break;
- n2 = (*s++ - '0');
- if (*s >= '0' && *s <= '9')
- n2 = n2*10 + (*s++ - '0');
-
- if (*s != '/' && *s != '-') /* slash */
- break;
- s++;
-
- if (*s < '0' || *s > '9') /* third 1, 2, 4, or 5 digits */
- break;
- n3 = (*s++ - '0');
- if (*s >= '0' && *s <= '9')
- n3 = n3*10 + (*s++ - '0');
-
- if (*s >= '0' && *s <= '9') /* optional digits 3, 4, and 5 */
- {
- n3 = n3*10 + (*s++ - '0');
- if (*s < '0' || *s > '9')
- break;
- n3 = n3*10 + (*s++ - '0');
- if (*s >= '0' && *s <= '9')
- n3 = n3*10 + (*s++ - '0');
- }
-
- if ((*s >= '0' && *s <= '9') || /* followed by non-alphanum */
- (*s >= 'A' && *s <= 'Z') ||
- (*s >= 'a' && *s <= 'z'))
- break;
-
- /* Ok, we parsed three 1-2 digit numbers, with / or -
- between them. Now decide what the hell they are
- (DD/MM/YY or MM/DD/YY or YY/MM/DD.)
- */
-
- if (n1 > 31 || n1 == 0) /* must be YY/MM/DD */
- {
- if (n2 > 12) break;
- if (n3 > 31) break;
- year = n1;
- if (year < 70)
- year += 2000;
- else if (year < 100)
- year += 1900;
- month = (TIME_TOKEN)(n2 + ((int)TT_JAN) - 1);
- date = n3;
- rest = s;
- break;
- }
-
- if (n1 > 12 && n2 > 12) /* illegal */
- {
- rest = s;
- break;
- }
-
- if (n3 < 70)
- n3 += 2000;
- else if (n3 < 100)
- n3 += 1900;
-
- if (n1 > 12) /* must be DD/MM/YY */
- {
- date = n1;
- month = (TIME_TOKEN)(n2 + ((int)TT_JAN) - 1);
- year = n3;
- }
- else /* assume MM/DD/YY */
- {
- /* #### In the ambiguous case, should we consult the
- locale to find out the local default? */
- month = (TIME_TOKEN)(n1 + ((int)TT_JAN) - 1);
- date = n2;
- year = n3;
- }
- rest = s;
- }
- else if ((*end >= 'A' && *end <= 'Z') ||
- (*end >= 'a' && *end <= 'z'))
- /* Digits followed by non-punctuation - what's that? */
- ;
- else if ((end - rest) == 5) /* five digits is a year */
- year = (year < 0
- ? ((rest[0]-'0')*10000L +
- (rest[1]-'0')*1000L +
- (rest[2]-'0')*100L +
- (rest[3]-'0')*10L +
- (rest[4]-'0'))
- : year);
- else if ((end - rest) == 4) /* four digits is a year */
- year = (year < 0
- ? ((rest[0]-'0')*1000L +
- (rest[1]-'0')*100L +
- (rest[2]-'0')*10L +
- (rest[3]-'0'))
- : year);
- else if ((end - rest) == 2) /* two digits - date or year */
- {
- int n = ((rest[0]-'0')*10 +
- (rest[1]-'0'));
- /* If we don't have a date (day of the month) and we see a number
- less than 32, then assume that is the date.
-
- Otherwise, if we have a date and not a year, assume this is the
- year. If it is less than 70, then assume it refers to the 21st
- century. If it is two digits (>= 70), assume it refers to this
- century. Otherwise, assume it refers to an unambiguous year.
-
- The world will surely end soon.
- */
- if (date < 0 && n < 32)
- date = n;
- else if (year < 0)
- {
- if (n < 70)
- year = 2000 + n;
- else if (n < 100)
- year = 1900 + n;
- else
- year = n;
- }
- /* else what the hell is this. */
- }
- else if ((end - rest) == 1) /* one digit - date */
- date = (date < 0 ? (rest[0]-'0') : date);
- /* else, three or more than five digits - what's that? */
-
- break;
- }
- }
-
- /* Skip to the end of this token, whether we parsed it or not.
- Tokens are delimited by whitespace, or ,;-/
- But explicitly not :+-.
- */
- while (*rest &&
- *rest != ' ' && *rest != '\t' &&
- *rest != ',' && *rest != ';' &&
- *rest != '-' && *rest != '+' &&
- *rest != '/' &&
- *rest != '(' && *rest != ')' && *rest != '[' && *rest != ']')
- rest++;
- /* skip over uninteresting chars. */
- SKIP_MORE:
- while (*rest &&
- (*rest == ' ' || *rest == '\t' ||
- *rest == ',' || *rest == ';' || *rest == '/' ||
- *rest == '(' || *rest == ')' || *rest == '[' || *rest == ']'))
- rest++;
-
- /* "-" is ignored at the beginning of a token if we have not yet
- parsed a year (e.g., the second "-" in "30-AUG-1966"), or if
- the character after the dash is not a digit. */
- if (*rest == '-' && ((rest > string &&
- isalpha((unsigned char)rest[-1]) && year < 0) ||
- rest[1] < '0' || rest[1] > '9'))
- {
- rest++;
- goto SKIP_MORE;
- }
-
- }
-
- if (zone != TT_UNKNOWN && zone_offset == -1)
- {
- switch (zone)
- {
- case TT_PST: zone_offset = -8 * 60; break;
- case TT_PDT: zone_offset = -8 * 60; dst_offset = 1 * 60; break;
- case TT_MST: zone_offset = -7 * 60; break;
- case TT_MDT: zone_offset = -7 * 60; dst_offset = 1 * 60; break;
- case TT_CST: zone_offset = -6 * 60; break;
- case TT_CDT: zone_offset = -6 * 60; dst_offset = 1 * 60; break;
- case TT_EST: zone_offset = -5 * 60; break;
- case TT_EDT: zone_offset = -5 * 60; dst_offset = 1 * 60; break;
- case TT_AST: zone_offset = -4 * 60; break;
- case TT_NST: zone_offset = -3 * 60 - 30; break;
- case TT_GMT: zone_offset = 0 * 60; break;
- case TT_BST: zone_offset = 0 * 60; dst_offset = 1 * 60; break;
- case TT_MET: zone_offset = 1 * 60; break;
- case TT_EET: zone_offset = 2 * 60; break;
- case TT_JST: zone_offset = 9 * 60; break;
- default:
- PR_ASSERT (0);
- break;
- }
- }
-
- /* If we didn't find a year, month, or day-of-the-month, we can't
- possibly parse this, and in fact, mktime() will do something random
- (I'm seeing it return "Tue Feb 5 06:28:16 2036", which is no doubt
- a numerologically significant date... */
- if (month == TT_UNKNOWN || date == -1 || year == -1 || year > PR_INT16_MAX)
- return PR_FAILURE;
-
- memset(result, 0, sizeof(*result));
- if (sec != -1)
- result->tm_sec = sec;
- if (min != -1)
- result->tm_min = min;
- if (hour != -1)
- result->tm_hour = hour;
- if (date != -1)
- result->tm_mday = date;
- if (month != TT_UNKNOWN)
- result->tm_month = (((int)month) - ((int)TT_JAN));
- if (year != -1)
- result->tm_year = year;
- if (dotw != TT_UNKNOWN)
- result->tm_wday = (((int)dotw) - ((int)TT_SUN));
- /*
- * Mainly to compute wday and yday, but normalized time is also required
- * by the check below that works around a Visual C++ 2005 mktime problem.
- */
- PR_NormalizeTime(result, PR_GMTParameters);
- /* The remaining work is to set the gmt and dst offsets in tm_params. */
-
- if (zone == TT_UNKNOWN && default_to_gmt)
- {
- /* No zone was specified, so pretend the zone was GMT. */
- zone = TT_GMT;
- zone_offset = 0;
- }
-
- if (zone_offset == -1)
- {
- /* no zone was specified, and we're to assume that everything
- is local. */
- struct tm localTime;
- time_t secs;
-
- PR_ASSERT(result->tm_month > -1 &&
- result->tm_mday > 0 &&
- result->tm_hour > -1 &&
- result->tm_min > -1 &&
- result->tm_sec > -1);
-
- /*
- * To obtain time_t from a tm structure representing the local
- * time, we call mktime(). However, we need to see if we are
- * on 1-Jan-1970 or before. If we are, we can't call mktime()
- * because mktime() will crash on win16. In that case, we
- * calculate zone_offset based on the zone offset at
- * 00:00:00, 2 Jan 1970 GMT, and subtract zone_offset from the
- * date we are parsing to transform the date to GMT. We also
- * do so if mktime() returns (time_t) -1 (time out of range).
- */
-
- /* month, day, hours, mins and secs are always non-negative
- so we dont need to worry about them. */
- if(result->tm_year >= 1970)
- {
- PRInt64 usec_per_sec;
-
- localTime.tm_sec = result->tm_sec;
- localTime.tm_min = result->tm_min;
- localTime.tm_hour = result->tm_hour;
- localTime.tm_mday = result->tm_mday;
- localTime.tm_mon = result->tm_month;
- localTime.tm_year = result->tm_year - 1900;
- /* Set this to -1 to tell mktime "I don't care". If you set
- it to 0 or 1, you are making assertions about whether the
- date you are handing it is in daylight savings mode or not;
- and if you're wrong, it will "fix" it for you. */
- localTime.tm_isdst = -1;
-
-#if _MSC_VER == 1400 /* 1400 = Visual C++ 2005 (8.0) */
- /*
- * mktime will return (time_t) -1 if the input is a date
- * after 23:59:59, December 31, 3000, US Pacific Time (not
- * UTC as documented):
- * http://msdn.microsoft.com/en-us/library/d1y53h2a(VS.80).aspx
- * But if the year is 3001, mktime also invokes the invalid
- * parameter handler, causing the application to crash. This
- * problem has been reported in
- * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=266036.
- * We avoid this crash by not calling mktime if the date is
- * out of range. To use a simple test that works in any time
- * zone, we consider year 3000 out of range as well. (See
- * bug 480740.)
- */
- if (result->tm_year >= 3000) {
- /* Emulate what mktime would have done. */
- errno = EINVAL;
- secs = (time_t) -1;
- } else {
- secs = mktime(&localTime);
- }
-#else
- secs = mktime(&localTime);
-#endif
- if (secs != (time_t) -1)
- {
- PRTime usecs64;
- LL_I2L(usecs64, secs);
- LL_I2L(usec_per_sec, PR_USEC_PER_SEC);
- LL_MUL(usecs64, usecs64, usec_per_sec);
- PR_ExplodeTime(usecs64, PR_LocalTimeParameters, result);
- return PR_SUCCESS;
- }
- }
-
- /* So mktime() can't handle this case. We assume the
- zone_offset for the date we are parsing is the same as
- the zone offset on 00:00:00 2 Jan 1970 GMT. */
- secs = 86400;
- (void) MT_safe_localtime(&secs, &localTime);
- zone_offset = localTime.tm_min
- + 60 * localTime.tm_hour
- + 1440 * (localTime.tm_mday - 2);
- }
-
- result->tm_params.tp_gmt_offset = zone_offset * 60;
- result->tm_params.tp_dst_offset = dst_offset * 60;
-
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus)
-PR_ParseTimeString(
- const char *string,
- PRBool default_to_gmt,
- PRTime *result)
-{
- PRExplodedTime tm;
- PRStatus rv;
-
- rv = PR_ParseTimeStringToExplodedTime(string,
- default_to_gmt,
- &tm);
- if (rv != PR_SUCCESS)
- return rv;
-
- *result = PR_ImplodeTime(&tm);
-
- return PR_SUCCESS;
-}
-
-/*
- *******************************************************************
- *******************************************************************
- **
- ** OLD COMPATIBILITY FUNCTIONS
- **
- *******************************************************************
- *******************************************************************
- */
-
-
-/*
- *-----------------------------------------------------------------------
- *
- * PR_FormatTime --
- *
- * Format a time value into a buffer. Same semantics as strftime().
- *
- *-----------------------------------------------------------------------
- */
-
-PR_IMPLEMENT(PRUint32)
-PR_FormatTime(char *buf, int buflen, const char *fmt,
- const PRExplodedTime *time)
-{
- size_t rv;
- struct tm a;
- struct tm *ap;
-
- if (time) {
- ap = &a;
- a.tm_sec = time->tm_sec;
- a.tm_min = time->tm_min;
- a.tm_hour = time->tm_hour;
- a.tm_mday = time->tm_mday;
- a.tm_mon = time->tm_month;
- a.tm_wday = time->tm_wday;
- a.tm_year = time->tm_year - 1900;
- a.tm_yday = time->tm_yday;
- a.tm_isdst = time->tm_params.tp_dst_offset ? 1 : 0;
-
- /*
- * On some platforms, for example SunOS 4, struct tm has two
- * additional fields: tm_zone and tm_gmtoff.
- */
-
-#if (__GLIBC__ >= 2) || defined(XP_BEOS) \
- || defined(NETBSD) || defined(OPENBSD) || defined(FREEBSD) \
- || defined(DARWIN) || defined(SYMBIAN) || defined(ANDROID)
- a.tm_zone = NULL;
- a.tm_gmtoff = time->tm_params.tp_gmt_offset +
- time->tm_params.tp_dst_offset;
-#endif
- } else {
- ap = NULL;
- }
-
- rv = strftime(buf, buflen, fmt, ap);
- if (!rv && buf && buflen > 0) {
- /*
- * When strftime fails, the contents of buf are indeterminate.
- * Some callers don't check the return value from this function,
- * so store an empty string in buf in case they try to print it.
- */
- buf[0] = '\0';
- }
- return rv;
-}
-
-
-/*
- * The following string arrays and macros are used by PR_FormatTimeUSEnglish().
- */
-
-static const char* abbrevDays[] =
-{
- "Sun","Mon","Tue","Wed","Thu","Fri","Sat"
-};
-
-static const char* days[] =
-{
- "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"
-};
-
-static const char* abbrevMonths[] =
-{
- "Jan", "Feb", "Mar", "Apr", "May", "Jun",
- "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
-};
-
-static const char* months[] =
-{
- "January", "February", "March", "April", "May", "June",
- "July", "August", "September", "October", "November", "December"
-};
-
-
-/*
- * Add a single character to the given buffer, incrementing the buffer pointer
- * and decrementing the buffer size. Return 0 on error.
- */
-#define ADDCHAR( buf, bufSize, ch ) \
-do \
-{ \
- if( bufSize < 1 ) \
- { \
- *(--buf) = '\0'; \
- return 0; \
- } \
- *buf++ = ch; \
- bufSize--; \
-} \
-while(0)
-
-
-/*
- * Add a string to the given buffer, incrementing the buffer pointer
- * and decrementing the buffer size appropriately. Return 0 on error.
- */
-#define ADDSTR( buf, bufSize, str ) \
-do \
-{ \
- PRUint32 strSize = strlen( str ); \
- if( strSize > bufSize ) \
- { \
- if( bufSize==0 ) \
- *(--buf) = '\0'; \
- else \
- *buf = '\0'; \
- return 0; \
- } \
- memcpy(buf, str, strSize); \
- buf += strSize; \
- bufSize -= strSize; \
-} \
-while(0)
-
-/* Needed by PR_FormatTimeUSEnglish() */
-static unsigned int pr_WeekOfYear(const PRExplodedTime* time,
- unsigned int firstDayOfWeek);
-
-
-/***********************************************************************************
- *
- * Description:
- * This is a dumbed down version of strftime that will format the date in US
- * English regardless of the setting of the global locale. This functionality is
- * needed to write things like MIME headers which must always be in US English.
- *
- **********************************************************************************/
-
-PR_IMPLEMENT(PRUint32)
-PR_FormatTimeUSEnglish( char* buf, PRUint32 bufSize,
- const char* format, const PRExplodedTime* time )
-{
- char* bufPtr = buf;
- const char* fmtPtr;
- char tmpBuf[ 40 ];
- const int tmpBufSize = sizeof( tmpBuf );
-
-
- for( fmtPtr=format; *fmtPtr != '\0'; fmtPtr++ )
- {
- if( *fmtPtr != '%' )
- {
- ADDCHAR( bufPtr, bufSize, *fmtPtr );
- }
- else
- {
- switch( *(++fmtPtr) )
- {
- case '%':
- /* escaped '%' character */
- ADDCHAR( bufPtr, bufSize, '%' );
- break;
-
- case 'a':
- /* abbreviated weekday name */
- ADDSTR( bufPtr, bufSize, abbrevDays[ time->tm_wday ] );
- break;
-
- case 'A':
- /* full weekday name */
- ADDSTR( bufPtr, bufSize, days[ time->tm_wday ] );
- break;
-
- case 'b':
- /* abbreviated month name */
- ADDSTR( bufPtr, bufSize, abbrevMonths[ time->tm_month ] );
- break;
-
- case 'B':
- /* full month name */
- ADDSTR(bufPtr, bufSize, months[ time->tm_month ] );
- break;
-
- case 'c':
- /* Date and time. */
- PR_FormatTimeUSEnglish( tmpBuf, tmpBufSize, "%a %b %d %H:%M:%S %Y", time );
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- case 'd':
- /* day of month ( 01 - 31 ) */
- PR_snprintf(tmpBuf,tmpBufSize,"%.2ld",time->tm_mday );
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- case 'H':
- /* hour ( 00 - 23 ) */
- PR_snprintf(tmpBuf,tmpBufSize,"%.2ld",time->tm_hour );
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- case 'I':
- /* hour ( 01 - 12 ) */
- PR_snprintf(tmpBuf,tmpBufSize,"%.2ld",
- (time->tm_hour%12) ? time->tm_hour%12 : (PRInt32) 12 );
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- case 'j':
- /* day number of year ( 001 - 366 ) */
- PR_snprintf(tmpBuf,tmpBufSize,"%.3d",time->tm_yday + 1);
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- case 'm':
- /* month number ( 01 - 12 ) */
- PR_snprintf(tmpBuf,tmpBufSize,"%.2ld",time->tm_month+1);
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- case 'M':
- /* minute ( 00 - 59 ) */
- PR_snprintf(tmpBuf,tmpBufSize,"%.2ld",time->tm_min );
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- case 'p':
- /* locale's equivalent of either AM or PM */
- ADDSTR( bufPtr, bufSize, (time->tm_hour<12)?"AM":"PM" );
- break;
-
- case 'S':
- /* seconds ( 00 - 61 ), allows for leap seconds */
- PR_snprintf(tmpBuf,tmpBufSize,"%.2ld",time->tm_sec );
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- case 'U':
- /* week number of year ( 00 - 53 ), Sunday is the first day of week 1 */
- PR_snprintf(tmpBuf,tmpBufSize,"%.2d", pr_WeekOfYear( time, 0 ) );
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- case 'w':
- /* weekday number ( 0 - 6 ), Sunday = 0 */
- PR_snprintf(tmpBuf,tmpBufSize,"%d",time->tm_wday );
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- case 'W':
- /* Week number of year ( 00 - 53 ), Monday is the first day of week 1 */
- PR_snprintf(tmpBuf,tmpBufSize,"%.2d", pr_WeekOfYear( time, 1 ) );
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- case 'x':
- /* Date representation */
- PR_FormatTimeUSEnglish( tmpBuf, tmpBufSize, "%m/%d/%y", time );
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- case 'X':
- /* Time representation. */
- PR_FormatTimeUSEnglish( tmpBuf, tmpBufSize, "%H:%M:%S", time );
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- case 'y':
- /* year within century ( 00 - 99 ) */
- PR_snprintf(tmpBuf,tmpBufSize,"%.2d",time->tm_year % 100 );
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- case 'Y':
- /* year as ccyy ( for example 1986 ) */
- PR_snprintf(tmpBuf,tmpBufSize,"%.4d",time->tm_year );
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- case 'Z':
- /* Time zone name or no characters if no time zone exists.
- * Since time zone name is supposed to be independant of locale, we
- * defer to PR_FormatTime() for this option.
- */
- PR_FormatTime( tmpBuf, tmpBufSize, "%Z", time );
- ADDSTR( bufPtr, bufSize, tmpBuf );
- break;
-
- default:
- /* Unknown format. Simply copy format into output buffer. */
- ADDCHAR( bufPtr, bufSize, '%' );
- ADDCHAR( bufPtr, bufSize, *fmtPtr );
- break;
-
- }
- }
- }
-
- ADDCHAR( bufPtr, bufSize, '\0' );
- return (PRUint32)(bufPtr - buf - 1);
-}
-
-
-
-/***********************************************************************************
- *
- * Description:
- * Returns the week number of the year (0-53) for the given time. firstDayOfWeek
- * is the day on which the week is considered to start (0=Sun, 1=Mon, ...).
- * Week 1 starts the first time firstDayOfWeek occurs in the year. In other words,
- * a partial week at the start of the year is considered week 0.
- *
- **********************************************************************************/
-
-static unsigned int
-pr_WeekOfYear(const PRExplodedTime* time, unsigned int firstDayOfWeek)
-{
- int dayOfWeek;
- int dayOfYear;
-
- /* Get the day of the year for the given time then adjust it to represent the
- * first day of the week containing the given time.
- */
- dayOfWeek = time->tm_wday - firstDayOfWeek;
- if (dayOfWeek < 0)
- dayOfWeek += 7;
-
- dayOfYear = time->tm_yday - dayOfWeek;
-
-
- if( dayOfYear <= 0 )
- {
- /* If dayOfYear is <= 0, it is in the first partial week of the year. */
- return 0;
- }
- else
- {
- /* Count the number of full weeks ( dayOfYear / 7 ) then add a week if there
- * are any days left over ( dayOfYear % 7 ). Because we are only counting to
- * the first day of the week containing the given time, rather than to the
- * actual day representing the given time, any days in week 0 will be "absorbed"
- * as extra days in the given week.
- */
- return (dayOfYear / 7) + ( (dayOfYear % 7) == 0 ? 0 : 1 );
- }
-}
-
diff --git a/nspr/pr/src/misc/prtpool.c b/nspr/pr/src/misc/prtpool.c
deleted file mode 100644
index 0671cc1..0000000
--- a/nspr/pr/src/misc/prtpool.c
+++ /dev/null
@@ -1,1187 +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/. */
-
-#include "nspr.h"
-
-/*
- * Thread pools
- * Thread pools create and manage threads to provide support for
- * scheduling jobs onto one or more threads.
- *
- */
-#ifdef OPT_WINNT
-#include <windows.h>
-#endif
-
-/*
- * worker thread
- */
-typedef struct wthread {
- PRCList links;
- PRThread *thread;
-} wthread;
-
-/*
- * queue of timer jobs
- */
-typedef struct timer_jobq {
- PRCList list;
- PRLock *lock;
- PRCondVar *cv;
- PRInt32 cnt;
- PRCList wthreads;
-} timer_jobq;
-
-/*
- * queue of jobs
- */
-typedef struct tp_jobq {
- PRCList list;
- PRInt32 cnt;
- PRLock *lock;
- PRCondVar *cv;
- PRCList wthreads;
-#ifdef OPT_WINNT
- HANDLE nt_completion_port;
-#endif
-} tp_jobq;
-
-/*
- * queue of IO jobs
- */
-typedef struct io_jobq {
- PRCList list;
- PRPollDesc *pollfds;
- PRInt32 npollfds;
- PRJob **polljobs;
- PRLock *lock;
- PRInt32 cnt;
- PRFileDesc *notify_fd;
- PRCList wthreads;
-} io_jobq;
-
-/*
- * Threadpool
- */
-struct PRThreadPool {
- PRInt32 init_threads;
- PRInt32 max_threads;
- PRInt32 current_threads;
- PRInt32 idle_threads;
- PRUint32 stacksize;
- tp_jobq jobq;
- io_jobq ioq;
- timer_jobq timerq;
- PRLock *join_lock; /* used with jobp->join_cv */
- PRCondVar *shutdown_cv;
- PRBool shutdown;
-};
-
-typedef enum io_op_type
- { JOB_IO_READ, JOB_IO_WRITE, JOB_IO_CONNECT, JOB_IO_ACCEPT } io_op_type;
-
-#ifdef OPT_WINNT
-typedef struct NT_notifier {
- OVERLAPPED overlapped; /* must be first */
- PRJob *jobp;
-} NT_notifier;
-#endif
-
-struct PRJob {
- PRCList links; /* for linking jobs */
- PRBool on_ioq; /* job on ioq */
- PRBool on_timerq; /* job on timerq */
- PRJobFn job_func;
- void *job_arg;
- PRCondVar *join_cv;
- PRBool join_wait; /* == PR_TRUE, when waiting to join */
- PRCondVar *cancel_cv; /* for cancelling IO jobs */
- PRBool cancel_io; /* for cancelling IO jobs */
- PRThreadPool *tpool; /* back pointer to thread pool */
- PRJobIoDesc *iod;
- io_op_type io_op;
- PRInt16 io_poll_flags;
- PRNetAddr *netaddr;
- PRIntervalTime timeout; /* relative value */
- PRIntervalTime absolute;
-#ifdef OPT_WINNT
- NT_notifier nt_notifier;
-#endif
-};
-
-#define JOB_LINKS_PTR(_qp) \
- ((PRJob *) ((char *) (_qp) - offsetof(PRJob, links)))
-
-#define WTHREAD_LINKS_PTR(_qp) \
- ((wthread *) ((char *) (_qp) - offsetof(wthread, links)))
-
-#define JOINABLE_JOB(_jobp) (NULL != (_jobp)->join_cv)
-
-#define JOIN_NOTIFY(_jobp) \
- PR_BEGIN_MACRO \
- PR_Lock(_jobp->tpool->join_lock); \
- _jobp->join_wait = PR_FALSE; \
- PR_NotifyCondVar(_jobp->join_cv); \
- PR_Unlock(_jobp->tpool->join_lock); \
- PR_END_MACRO
-
-#define CANCEL_IO_JOB(jobp) \
- PR_BEGIN_MACRO \
- jobp->cancel_io = PR_FALSE; \
- jobp->on_ioq = PR_FALSE; \
- PR_REMOVE_AND_INIT_LINK(&jobp->links); \
- tp->ioq.cnt--; \
- PR_NotifyCondVar(jobp->cancel_cv); \
- PR_END_MACRO
-
-static void delete_job(PRJob *jobp);
-static PRThreadPool * alloc_threadpool(void);
-static PRJob * alloc_job(PRBool joinable, PRThreadPool *tp);
-static void notify_ioq(PRThreadPool *tp);
-static void notify_timerq(PRThreadPool *tp);
-
-/*
- * locks are acquired in the following order
- *
- * tp->ioq.lock,tp->timerq.lock
- * |
- * V
- * tp->jobq->lock
- */
-
-/*
- * worker thread function
- */
-static void wstart(void *arg)
-{
-PRThreadPool *tp = (PRThreadPool *) arg;
-PRCList *head;
-
- /*
- * execute jobs until shutdown
- */
- while (!tp->shutdown) {
- PRJob *jobp;
-#ifdef OPT_WINNT
- BOOL rv;
- DWORD unused, shutdown;
- LPOVERLAPPED olp;
-
- PR_Lock(tp->jobq.lock);
- tp->idle_threads++;
- PR_Unlock(tp->jobq.lock);
- rv = GetQueuedCompletionStatus(tp->jobq.nt_completion_port,
- &unused, &shutdown, &olp, INFINITE);
-
- PR_ASSERT(rv);
- if (shutdown)
- break;
- jobp = ((NT_notifier *) olp)->jobp;
- PR_Lock(tp->jobq.lock);
- tp->idle_threads--;
- tp->jobq.cnt--;
- PR_Unlock(tp->jobq.lock);
-#else
-
- PR_Lock(tp->jobq.lock);
- while (PR_CLIST_IS_EMPTY(&tp->jobq.list) && (!tp->shutdown)) {
- tp->idle_threads++;
- PR_WaitCondVar(tp->jobq.cv, PR_INTERVAL_NO_TIMEOUT);
- tp->idle_threads--;
- }
- if (tp->shutdown) {
- PR_Unlock(tp->jobq.lock);
- break;
- }
- head = PR_LIST_HEAD(&tp->jobq.list);
- /*
- * remove job from queue
- */
- PR_REMOVE_AND_INIT_LINK(head);
- tp->jobq.cnt--;
- jobp = JOB_LINKS_PTR(head);
- PR_Unlock(tp->jobq.lock);
-#endif
-
- jobp->job_func(jobp->job_arg);
- if (!JOINABLE_JOB(jobp)) {
- delete_job(jobp);
- } else {
- JOIN_NOTIFY(jobp);
- }
- }
- PR_Lock(tp->jobq.lock);
- tp->current_threads--;
- PR_Unlock(tp->jobq.lock);
-}
-
-/*
- * add a job to the work queue
- */
-static void
-add_to_jobq(PRThreadPool *tp, PRJob *jobp)
-{
- /*
- * add to jobq
- */
-#ifdef OPT_WINNT
- PR_Lock(tp->jobq.lock);
- tp->jobq.cnt++;
- PR_Unlock(tp->jobq.lock);
- /*
- * notify worker thread(s)
- */
- PostQueuedCompletionStatus(tp->jobq.nt_completion_port, 0,
- FALSE, &jobp->nt_notifier.overlapped);
-#else
- PR_Lock(tp->jobq.lock);
- PR_APPEND_LINK(&jobp->links,&tp->jobq.list);
- tp->jobq.cnt++;
- if ((tp->idle_threads < tp->jobq.cnt) &&
- (tp->current_threads < tp->max_threads)) {
- wthread *wthrp;
- /*
- * increment thread count and unlock the jobq lock
- */
- tp->current_threads++;
- PR_Unlock(tp->jobq.lock);
- /* create new worker thread */
- wthrp = PR_NEWZAP(wthread);
- if (wthrp) {
- wthrp->thread = PR_CreateThread(PR_USER_THREAD, wstart,
- tp, PR_PRIORITY_NORMAL,
- PR_GLOBAL_THREAD,PR_JOINABLE_THREAD,tp->stacksize);
- if (NULL == wthrp->thread) {
- PR_DELETE(wthrp); /* this sets wthrp to NULL */
- }
- }
- PR_Lock(tp->jobq.lock);
- if (NULL == wthrp) {
- tp->current_threads--;
- } else {
- PR_APPEND_LINK(&wthrp->links, &tp->jobq.wthreads);
- }
- }
- /*
- * wakeup a worker thread
- */
- PR_NotifyCondVar(tp->jobq.cv);
- PR_Unlock(tp->jobq.lock);
-#endif
-}
-
-/*
- * io worker thread function
- */
-static void io_wstart(void *arg)
-{
-PRThreadPool *tp = (PRThreadPool *) arg;
-int pollfd_cnt, pollfds_used;
-int rv;
-PRCList *qp, *nextqp;
-PRPollDesc *pollfds = NULL;
-PRJob **polljobs = NULL;
-int poll_timeout;
-PRIntervalTime now;
-
- /*
- * scan io_jobq
- * construct poll list
- * call PR_Poll
- * for all fds, for which poll returns true, move the job to
- * jobq and wakeup worker thread.
- */
- while (!tp->shutdown) {
- PRJob *jobp;
-
- pollfd_cnt = tp->ioq.cnt + 10;
- if (pollfd_cnt > tp->ioq.npollfds) {
-
- /*
- * re-allocate pollfd array if the current one is not large
- * enough
- */
- if (NULL != tp->ioq.pollfds)
- PR_Free(tp->ioq.pollfds);
- tp->ioq.pollfds = (PRPollDesc *) PR_Malloc(pollfd_cnt *
- (sizeof(PRPollDesc) + sizeof(PRJob *)));
- PR_ASSERT(NULL != tp->ioq.pollfds);
- /*
- * array of pollfds
- */
- pollfds = tp->ioq.pollfds;
- tp->ioq.polljobs = (PRJob **) (&tp->ioq.pollfds[pollfd_cnt]);
- /*
- * parallel array of jobs
- */
- polljobs = tp->ioq.polljobs;
- tp->ioq.npollfds = pollfd_cnt;
- }
-
- pollfds_used = 0;
- /*
- * add the notify fd; used for unblocking io thread(s)
- */
- pollfds[pollfds_used].fd = tp->ioq.notify_fd;
- pollfds[pollfds_used].in_flags = PR_POLL_READ;
- pollfds[pollfds_used].out_flags = 0;
- polljobs[pollfds_used] = NULL;
- pollfds_used++;
- /*
- * fill in the pollfd array
- */
- PR_Lock(tp->ioq.lock);
- for (qp = tp->ioq.list.next; qp != &tp->ioq.list; qp = nextqp) {
- nextqp = qp->next;
- jobp = JOB_LINKS_PTR(qp);
- if (jobp->cancel_io) {
- CANCEL_IO_JOB(jobp);
- continue;
- }
- if (pollfds_used == (pollfd_cnt))
- break;
- pollfds[pollfds_used].fd = jobp->iod->socket;
- pollfds[pollfds_used].in_flags = jobp->io_poll_flags;
- pollfds[pollfds_used].out_flags = 0;
- polljobs[pollfds_used] = jobp;
-
- pollfds_used++;
- }
- if (!PR_CLIST_IS_EMPTY(&tp->ioq.list)) {
- qp = tp->ioq.list.next;
- jobp = JOB_LINKS_PTR(qp);
- if (PR_INTERVAL_NO_TIMEOUT == jobp->timeout)
- poll_timeout = PR_INTERVAL_NO_TIMEOUT;
- else if (PR_INTERVAL_NO_WAIT == jobp->timeout)
- poll_timeout = PR_INTERVAL_NO_WAIT;
- else {
- poll_timeout = jobp->absolute - PR_IntervalNow();
- if (poll_timeout <= 0) /* already timed out */
- poll_timeout = PR_INTERVAL_NO_WAIT;
- }
- } else {
- poll_timeout = PR_INTERVAL_NO_TIMEOUT;
- }
- PR_Unlock(tp->ioq.lock);
-
- /*
- * XXXX
- * should retry if more jobs have been added to the queue?
- *
- */
- PR_ASSERT(pollfds_used <= pollfd_cnt);
- rv = PR_Poll(tp->ioq.pollfds, pollfds_used, poll_timeout);
-
- if (tp->shutdown) {
- break;
- }
-
- if (rv > 0) {
- /*
- * at least one io event is set
- */
- PRStatus rval_status;
- PRInt32 index;
-
- PR_ASSERT(pollfds[0].fd == tp->ioq.notify_fd);
- /*
- * reset the pollable event, if notified
- */
- if (pollfds[0].out_flags & PR_POLL_READ) {
- rval_status = PR_WaitForPollableEvent(tp->ioq.notify_fd);
- PR_ASSERT(PR_SUCCESS == rval_status);
- }
-
- for(index = 1; index < (pollfds_used); index++) {
- PRInt16 events = pollfds[index].in_flags;
- PRInt16 revents = pollfds[index].out_flags;
- jobp = polljobs[index];
-
- if ((revents & PR_POLL_NVAL) || /* busted in all cases */
- (revents & PR_POLL_ERR) ||
- ((events & PR_POLL_WRITE) &&
- (revents & PR_POLL_HUP))) { /* write op & hup */
- PR_Lock(tp->ioq.lock);
- if (jobp->cancel_io) {
- CANCEL_IO_JOB(jobp);
- PR_Unlock(tp->ioq.lock);
- continue;
- }
- PR_REMOVE_AND_INIT_LINK(&jobp->links);
- tp->ioq.cnt--;
- jobp->on_ioq = PR_FALSE;
- PR_Unlock(tp->ioq.lock);
-
- /* set error */
- if (PR_POLL_NVAL & revents)
- jobp->iod->error = PR_BAD_DESCRIPTOR_ERROR;
- else if (PR_POLL_HUP & revents)
- jobp->iod->error = PR_CONNECT_RESET_ERROR;
- else
- jobp->iod->error = PR_IO_ERROR;
-
- /*
- * add to jobq
- */
- add_to_jobq(tp, jobp);
- } else if (revents) {
- /*
- * add to jobq
- */
- PR_Lock(tp->ioq.lock);
- if (jobp->cancel_io) {
- CANCEL_IO_JOB(jobp);
- PR_Unlock(tp->ioq.lock);
- continue;
- }
- PR_REMOVE_AND_INIT_LINK(&jobp->links);
- tp->ioq.cnt--;
- jobp->on_ioq = PR_FALSE;
- PR_Unlock(tp->ioq.lock);
-
- if (jobp->io_op == JOB_IO_CONNECT) {
- if (PR_GetConnectStatus(&pollfds[index]) == PR_SUCCESS)
- jobp->iod->error = 0;
- else
- jobp->iod->error = PR_GetError();
- } else
- jobp->iod->error = 0;
-
- add_to_jobq(tp, jobp);
- }
- }
- }
- /*
- * timeout processing
- */
- now = PR_IntervalNow();
- PR_Lock(tp->ioq.lock);
- for (qp = tp->ioq.list.next; qp != &tp->ioq.list; qp = nextqp) {
- nextqp = qp->next;
- jobp = JOB_LINKS_PTR(qp);
- if (jobp->cancel_io) {
- CANCEL_IO_JOB(jobp);
- continue;
- }
- if (PR_INTERVAL_NO_TIMEOUT == jobp->timeout)
- break;
- if ((PR_INTERVAL_NO_WAIT != jobp->timeout) &&
- ((PRInt32)(jobp->absolute - now) > 0))
- break;
- PR_REMOVE_AND_INIT_LINK(&jobp->links);
- tp->ioq.cnt--;
- jobp->on_ioq = PR_FALSE;
- jobp->iod->error = PR_IO_TIMEOUT_ERROR;
- add_to_jobq(tp, jobp);
- }
- PR_Unlock(tp->ioq.lock);
- }
-}
-
-/*
- * timer worker thread function
- */
-static void timer_wstart(void *arg)
-{
-PRThreadPool *tp = (PRThreadPool *) arg;
-PRCList *qp;
-PRIntervalTime timeout;
-PRIntervalTime now;
-
- /*
- * call PR_WaitCondVar with minimum value of all timeouts
- */
- while (!tp->shutdown) {
- PRJob *jobp;
-
- PR_Lock(tp->timerq.lock);
- if (PR_CLIST_IS_EMPTY(&tp->timerq.list)) {
- timeout = PR_INTERVAL_NO_TIMEOUT;
- } else {
- PRCList *qp;
-
- qp = tp->timerq.list.next;
- jobp = JOB_LINKS_PTR(qp);
-
- timeout = jobp->absolute - PR_IntervalNow();
- if (timeout <= 0)
- timeout = PR_INTERVAL_NO_WAIT; /* already timed out */
- }
- if (PR_INTERVAL_NO_WAIT != timeout)
- PR_WaitCondVar(tp->timerq.cv, timeout);
- if (tp->shutdown) {
- PR_Unlock(tp->timerq.lock);
- break;
- }
- /*
- * move expired-timer jobs to jobq
- */
- now = PR_IntervalNow();
- while (!PR_CLIST_IS_EMPTY(&tp->timerq.list)) {
- qp = tp->timerq.list.next;
- jobp = JOB_LINKS_PTR(qp);
-
- if ((PRInt32)(jobp->absolute - now) > 0) {
- break;
- }
- /*
- * job timed out
- */
- PR_REMOVE_AND_INIT_LINK(&jobp->links);
- tp->timerq.cnt--;
- jobp->on_timerq = PR_FALSE;
- add_to_jobq(tp, jobp);
- }
- PR_Unlock(tp->timerq.lock);
- }
-}
-
-static void
-delete_threadpool(PRThreadPool *tp)
-{
- if (NULL != tp) {
- if (NULL != tp->shutdown_cv)
- PR_DestroyCondVar(tp->shutdown_cv);
- if (NULL != tp->jobq.cv)
- PR_DestroyCondVar(tp->jobq.cv);
- if (NULL != tp->jobq.lock)
- PR_DestroyLock(tp->jobq.lock);
- if (NULL != tp->join_lock)
- PR_DestroyLock(tp->join_lock);
-#ifdef OPT_WINNT
- if (NULL != tp->jobq.nt_completion_port)
- CloseHandle(tp->jobq.nt_completion_port);
-#endif
- /* Timer queue */
- if (NULL != tp->timerq.cv)
- PR_DestroyCondVar(tp->timerq.cv);
- if (NULL != tp->timerq.lock)
- PR_DestroyLock(tp->timerq.lock);
-
- if (NULL != tp->ioq.lock)
- PR_DestroyLock(tp->ioq.lock);
- if (NULL != tp->ioq.pollfds)
- PR_Free(tp->ioq.pollfds);
- if (NULL != tp->ioq.notify_fd)
- PR_DestroyPollableEvent(tp->ioq.notify_fd);
- PR_Free(tp);
- }
- return;
-}
-
-static PRThreadPool *
-alloc_threadpool(void)
-{
-PRThreadPool *tp;
-
- tp = (PRThreadPool *) PR_CALLOC(sizeof(*tp));
- if (NULL == tp)
- goto failed;
- tp->jobq.lock = PR_NewLock();
- if (NULL == tp->jobq.lock)
- goto failed;
- tp->jobq.cv = PR_NewCondVar(tp->jobq.lock);
- if (NULL == tp->jobq.cv)
- goto failed;
- tp->join_lock = PR_NewLock();
- if (NULL == tp->join_lock)
- goto failed;
-#ifdef OPT_WINNT
- tp->jobq.nt_completion_port = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
- NULL, 0, 0);
- if (NULL == tp->jobq.nt_completion_port)
- goto failed;
-#endif
-
- tp->ioq.lock = PR_NewLock();
- if (NULL == tp->ioq.lock)
- goto failed;
-
- /* Timer queue */
-
- tp->timerq.lock = PR_NewLock();
- if (NULL == tp->timerq.lock)
- goto failed;
- tp->timerq.cv = PR_NewCondVar(tp->timerq.lock);
- if (NULL == tp->timerq.cv)
- goto failed;
-
- tp->shutdown_cv = PR_NewCondVar(tp->jobq.lock);
- if (NULL == tp->shutdown_cv)
- goto failed;
- tp->ioq.notify_fd = PR_NewPollableEvent();
- if (NULL == tp->ioq.notify_fd)
- goto failed;
- return tp;
-failed:
- delete_threadpool(tp);
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
-}
-
-/* Create thread pool */
-PR_IMPLEMENT(PRThreadPool *)
-PR_CreateThreadPool(PRInt32 initial_threads, PRInt32 max_threads,
- PRUint32 stacksize)
-{
-PRThreadPool *tp;
-PRThread *thr;
-int i;
-wthread *wthrp;
-
- tp = alloc_threadpool();
- if (NULL == tp)
- return NULL;
-
- tp->init_threads = initial_threads;
- tp->max_threads = max_threads;
- tp->stacksize = stacksize;
- PR_INIT_CLIST(&tp->jobq.list);
- PR_INIT_CLIST(&tp->ioq.list);
- PR_INIT_CLIST(&tp->timerq.list);
- PR_INIT_CLIST(&tp->jobq.wthreads);
- PR_INIT_CLIST(&tp->ioq.wthreads);
- PR_INIT_CLIST(&tp->timerq.wthreads);
- tp->shutdown = PR_FALSE;
-
- PR_Lock(tp->jobq.lock);
- for(i=0; i < initial_threads; ++i) {
-
- thr = PR_CreateThread(PR_USER_THREAD, wstart,
- tp, PR_PRIORITY_NORMAL,
- PR_GLOBAL_THREAD, PR_JOINABLE_THREAD,stacksize);
- PR_ASSERT(thr);
- wthrp = PR_NEWZAP(wthread);
- PR_ASSERT(wthrp);
- wthrp->thread = thr;
- PR_APPEND_LINK(&wthrp->links, &tp->jobq.wthreads);
- }
- tp->current_threads = initial_threads;
-
- thr = PR_CreateThread(PR_USER_THREAD, io_wstart,
- tp, PR_PRIORITY_NORMAL,
- PR_GLOBAL_THREAD,PR_JOINABLE_THREAD,stacksize);
- PR_ASSERT(thr);
- wthrp = PR_NEWZAP(wthread);
- PR_ASSERT(wthrp);
- wthrp->thread = thr;
- PR_APPEND_LINK(&wthrp->links, &tp->ioq.wthreads);
-
- thr = PR_CreateThread(PR_USER_THREAD, timer_wstart,
- tp, PR_PRIORITY_NORMAL,
- PR_GLOBAL_THREAD,PR_JOINABLE_THREAD,stacksize);
- PR_ASSERT(thr);
- wthrp = PR_NEWZAP(wthread);
- PR_ASSERT(wthrp);
- wthrp->thread = thr;
- PR_APPEND_LINK(&wthrp->links, &tp->timerq.wthreads);
-
- PR_Unlock(tp->jobq.lock);
- return tp;
-}
-
-static void
-delete_job(PRJob *jobp)
-{
- if (NULL != jobp) {
- if (NULL != jobp->join_cv) {
- PR_DestroyCondVar(jobp->join_cv);
- jobp->join_cv = NULL;
- }
- if (NULL != jobp->cancel_cv) {
- PR_DestroyCondVar(jobp->cancel_cv);
- jobp->cancel_cv = NULL;
- }
- PR_DELETE(jobp);
- }
-}
-
-static PRJob *
-alloc_job(PRBool joinable, PRThreadPool *tp)
-{
- PRJob *jobp;
-
- jobp = PR_NEWZAP(PRJob);
- if (NULL == jobp)
- goto failed;
- if (joinable) {
- jobp->join_cv = PR_NewCondVar(tp->join_lock);
- jobp->join_wait = PR_TRUE;
- if (NULL == jobp->join_cv)
- goto failed;
- } else {
- jobp->join_cv = NULL;
- }
-#ifdef OPT_WINNT
- jobp->nt_notifier.jobp = jobp;
-#endif
- return jobp;
-failed:
- delete_job(jobp);
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
-}
-
-/* queue a job */
-PR_IMPLEMENT(PRJob *)
-PR_QueueJob(PRThreadPool *tpool, PRJobFn fn, void *arg, PRBool joinable)
-{
- PRJob *jobp;
-
- jobp = alloc_job(joinable, tpool);
- if (NULL == jobp)
- return NULL;
-
- jobp->job_func = fn;
- jobp->job_arg = arg;
- jobp->tpool = tpool;
-
- add_to_jobq(tpool, jobp);
- return jobp;
-}
-
-/* queue a job, when a socket is readable or writeable */
-static PRJob *
-queue_io_job(PRThreadPool *tpool, PRJobIoDesc *iod, PRJobFn fn, void * arg,
- PRBool joinable, io_op_type op)
-{
- PRJob *jobp;
- PRIntervalTime now;
-
- jobp = alloc_job(joinable, tpool);
- if (NULL == jobp) {
- return NULL;
- }
-
- /*
- * Add a new job to io_jobq
- * wakeup io worker thread
- */
-
- jobp->job_func = fn;
- jobp->job_arg = arg;
- jobp->tpool = tpool;
- jobp->iod = iod;
- if (JOB_IO_READ == op) {
- jobp->io_op = JOB_IO_READ;
- jobp->io_poll_flags = PR_POLL_READ;
- } else if (JOB_IO_WRITE == op) {
- jobp->io_op = JOB_IO_WRITE;
- jobp->io_poll_flags = PR_POLL_WRITE;
- } else if (JOB_IO_ACCEPT == op) {
- jobp->io_op = JOB_IO_ACCEPT;
- jobp->io_poll_flags = PR_POLL_READ;
- } else if (JOB_IO_CONNECT == op) {
- jobp->io_op = JOB_IO_CONNECT;
- jobp->io_poll_flags = PR_POLL_WRITE|PR_POLL_EXCEPT;
- } else {
- delete_job(jobp);
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return NULL;
- }
-
- jobp->timeout = iod->timeout;
- if ((PR_INTERVAL_NO_TIMEOUT == iod->timeout) ||
- (PR_INTERVAL_NO_WAIT == iod->timeout)) {
- jobp->absolute = iod->timeout;
- } else {
- now = PR_IntervalNow();
- jobp->absolute = now + iod->timeout;
- }
-
-
- PR_Lock(tpool->ioq.lock);
-
- if (PR_CLIST_IS_EMPTY(&tpool->ioq.list) ||
- (PR_INTERVAL_NO_TIMEOUT == iod->timeout)) {
- PR_APPEND_LINK(&jobp->links,&tpool->ioq.list);
- } else if (PR_INTERVAL_NO_WAIT == iod->timeout) {
- PR_INSERT_LINK(&jobp->links,&tpool->ioq.list);
- } else {
- PRCList *qp;
- PRJob *tmp_jobp;
- /*
- * insert into the timeout-sorted ioq
- */
- for (qp = tpool->ioq.list.prev; qp != &tpool->ioq.list;
- qp = qp->prev) {
- tmp_jobp = JOB_LINKS_PTR(qp);
- if ((PRInt32)(jobp->absolute - tmp_jobp->absolute) >= 0) {
- break;
- }
- }
- PR_INSERT_AFTER(&jobp->links,qp);
- }
-
- jobp->on_ioq = PR_TRUE;
- tpool->ioq.cnt++;
- /*
- * notify io worker thread(s)
- */
- PR_Unlock(tpool->ioq.lock);
- notify_ioq(tpool);
- return jobp;
-}
-
-/* queue a job, when a socket is readable */
-PR_IMPLEMENT(PRJob *)
-PR_QueueJob_Read(PRThreadPool *tpool, PRJobIoDesc *iod, PRJobFn fn, void * arg,
- PRBool joinable)
-{
- return (queue_io_job(tpool, iod, fn, arg, joinable, JOB_IO_READ));
-}
-
-/* queue a job, when a socket is writeable */
-PR_IMPLEMENT(PRJob *)
-PR_QueueJob_Write(PRThreadPool *tpool, PRJobIoDesc *iod, PRJobFn fn,void * arg,
- PRBool joinable)
-{
- return (queue_io_job(tpool, iod, fn, arg, joinable, JOB_IO_WRITE));
-}
-
-
-/* queue a job, when a socket has a pending connection */
-PR_IMPLEMENT(PRJob *)
-PR_QueueJob_Accept(PRThreadPool *tpool, PRJobIoDesc *iod, PRJobFn fn,
- void * arg, PRBool joinable)
-{
- return (queue_io_job(tpool, iod, fn, arg, joinable, JOB_IO_ACCEPT));
-}
-
-/* queue a job, when a socket can be connected */
-PR_IMPLEMENT(PRJob *)
-PR_QueueJob_Connect(PRThreadPool *tpool, PRJobIoDesc *iod,
- const PRNetAddr *addr, PRJobFn fn, void * arg, PRBool joinable)
-{
- PRStatus rv;
- PRErrorCode err;
-
- rv = PR_Connect(iod->socket, addr, PR_INTERVAL_NO_WAIT);
- if ((rv == PR_FAILURE) && ((err = PR_GetError()) == PR_IN_PROGRESS_ERROR)){
- /* connection pending */
- return(queue_io_job(tpool, iod, fn, arg, joinable, JOB_IO_CONNECT));
- } else {
- /*
- * connection succeeded or failed; add to jobq right away
- */
- if (rv == PR_FAILURE)
- iod->error = err;
- else
- iod->error = 0;
- return(PR_QueueJob(tpool, fn, arg, joinable));
- }
-}
-
-/* queue a job, when a timer expires */
-PR_IMPLEMENT(PRJob *)
-PR_QueueJob_Timer(PRThreadPool *tpool, PRIntervalTime timeout,
- PRJobFn fn, void * arg, PRBool joinable)
-{
- PRIntervalTime now;
- PRJob *jobp;
-
- if (PR_INTERVAL_NO_TIMEOUT == timeout) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return NULL;
- }
- if (PR_INTERVAL_NO_WAIT == timeout) {
- /*
- * no waiting; add to jobq right away
- */
- return(PR_QueueJob(tpool, fn, arg, joinable));
- }
- jobp = alloc_job(joinable, tpool);
- if (NULL == jobp) {
- return NULL;
- }
-
- /*
- * Add a new job to timer_jobq
- * wakeup timer worker thread
- */
-
- jobp->job_func = fn;
- jobp->job_arg = arg;
- jobp->tpool = tpool;
- jobp->timeout = timeout;
-
- now = PR_IntervalNow();
- jobp->absolute = now + timeout;
-
-
- PR_Lock(tpool->timerq.lock);
- jobp->on_timerq = PR_TRUE;
- if (PR_CLIST_IS_EMPTY(&tpool->timerq.list))
- PR_APPEND_LINK(&jobp->links,&tpool->timerq.list);
- else {
- PRCList *qp;
- PRJob *tmp_jobp;
- /*
- * insert into the sorted timer jobq
- */
- for (qp = tpool->timerq.list.prev; qp != &tpool->timerq.list;
- qp = qp->prev) {
- tmp_jobp = JOB_LINKS_PTR(qp);
- if ((PRInt32)(jobp->absolute - tmp_jobp->absolute) >= 0) {
- break;
- }
- }
- PR_INSERT_AFTER(&jobp->links,qp);
- }
- tpool->timerq.cnt++;
- /*
- * notify timer worker thread(s)
- */
- notify_timerq(tpool);
- PR_Unlock(tpool->timerq.lock);
- return jobp;
-}
-
-static void
-notify_timerq(PRThreadPool *tp)
-{
- /*
- * wakeup the timer thread(s)
- */
- PR_NotifyCondVar(tp->timerq.cv);
-}
-
-static void
-notify_ioq(PRThreadPool *tp)
-{
-PRStatus rval_status;
-
- /*
- * wakeup the io thread(s)
- */
- rval_status = PR_SetPollableEvent(tp->ioq.notify_fd);
- PR_ASSERT(PR_SUCCESS == rval_status);
-}
-
-/*
- * cancel a job
- *
- * XXXX: is this needed? likely to be removed
- */
-PR_IMPLEMENT(PRStatus)
-PR_CancelJob(PRJob *jobp) {
-
- PRStatus rval = PR_FAILURE;
- PRThreadPool *tp;
-
- if (jobp->on_timerq) {
- /*
- * now, check again while holding the timerq lock
- */
- tp = jobp->tpool;
- PR_Lock(tp->timerq.lock);
- if (jobp->on_timerq) {
- jobp->on_timerq = PR_FALSE;
- PR_REMOVE_AND_INIT_LINK(&jobp->links);
- tp->timerq.cnt--;
- PR_Unlock(tp->timerq.lock);
- if (!JOINABLE_JOB(jobp)) {
- delete_job(jobp);
- } else {
- JOIN_NOTIFY(jobp);
- }
- rval = PR_SUCCESS;
- } else
- PR_Unlock(tp->timerq.lock);
- } else if (jobp->on_ioq) {
- /*
- * now, check again while holding the ioq lock
- */
- tp = jobp->tpool;
- PR_Lock(tp->ioq.lock);
- if (jobp->on_ioq) {
- jobp->cancel_cv = PR_NewCondVar(tp->ioq.lock);
- if (NULL == jobp->cancel_cv) {
- PR_Unlock(tp->ioq.lock);
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
- return PR_FAILURE;
- }
- /*
- * mark job 'cancelled' and notify io thread(s)
- * XXXX:
- * this assumes there is only one io thread; when there
- * are multiple threads, the io thread processing this job
- * must be notified.
- */
- jobp->cancel_io = PR_TRUE;
- PR_Unlock(tp->ioq.lock); /* release, reacquire ioq lock */
- notify_ioq(tp);
- PR_Lock(tp->ioq.lock);
- while (jobp->cancel_io)
- PR_WaitCondVar(jobp->cancel_cv, PR_INTERVAL_NO_TIMEOUT);
- PR_Unlock(tp->ioq.lock);
- PR_ASSERT(!jobp->on_ioq);
- if (!JOINABLE_JOB(jobp)) {
- delete_job(jobp);
- } else {
- JOIN_NOTIFY(jobp);
- }
- rval = PR_SUCCESS;
- } else
- PR_Unlock(tp->ioq.lock);
- }
- if (PR_FAILURE == rval)
- PR_SetError(PR_INVALID_STATE_ERROR, 0);
- return rval;
-}
-
-/* join a job, wait until completion */
-PR_IMPLEMENT(PRStatus)
-PR_JoinJob(PRJob *jobp)
-{
- if (!JOINABLE_JOB(jobp)) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
- PR_Lock(jobp->tpool->join_lock);
- while(jobp->join_wait)
- PR_WaitCondVar(jobp->join_cv, PR_INTERVAL_NO_TIMEOUT);
- PR_Unlock(jobp->tpool->join_lock);
- delete_job(jobp);
- return PR_SUCCESS;
-}
-
-/* shutdown threadpool */
-PR_IMPLEMENT(PRStatus)
-PR_ShutdownThreadPool(PRThreadPool *tpool)
-{
-PRStatus rval = PR_SUCCESS;
-
- PR_Lock(tpool->jobq.lock);
- tpool->shutdown = PR_TRUE;
- PR_NotifyAllCondVar(tpool->shutdown_cv);
- PR_Unlock(tpool->jobq.lock);
-
- return rval;
-}
-
-/*
- * join thread pool
- * wait for termination of worker threads
- * reclaim threadpool resources
- */
-PR_IMPLEMENT(PRStatus)
-PR_JoinThreadPool(PRThreadPool *tpool)
-{
-PRStatus rval = PR_SUCCESS;
-PRCList *head;
-PRStatus rval_status;
-
- PR_Lock(tpool->jobq.lock);
- while (!tpool->shutdown)
- PR_WaitCondVar(tpool->shutdown_cv, PR_INTERVAL_NO_TIMEOUT);
-
- /*
- * wakeup worker threads
- */
-#ifdef OPT_WINNT
- /*
- * post shutdown notification for all threads
- */
- {
- int i;
- for(i=0; i < tpool->current_threads; i++) {
- PostQueuedCompletionStatus(tpool->jobq.nt_completion_port, 0,
- TRUE, NULL);
- }
- }
-#else
- PR_NotifyAllCondVar(tpool->jobq.cv);
-#endif
-
- /*
- * wakeup io thread(s)
- */
- notify_ioq(tpool);
-
- /*
- * wakeup timer thread(s)
- */
- PR_Lock(tpool->timerq.lock);
- notify_timerq(tpool);
- PR_Unlock(tpool->timerq.lock);
-
- while (!PR_CLIST_IS_EMPTY(&tpool->jobq.wthreads)) {
- wthread *wthrp;
-
- head = PR_LIST_HEAD(&tpool->jobq.wthreads);
- PR_REMOVE_AND_INIT_LINK(head);
- PR_Unlock(tpool->jobq.lock);
- wthrp = WTHREAD_LINKS_PTR(head);
- rval_status = PR_JoinThread(wthrp->thread);
- PR_ASSERT(PR_SUCCESS == rval_status);
- PR_DELETE(wthrp);
- PR_Lock(tpool->jobq.lock);
- }
- PR_Unlock(tpool->jobq.lock);
- while (!PR_CLIST_IS_EMPTY(&tpool->ioq.wthreads)) {
- wthread *wthrp;
-
- head = PR_LIST_HEAD(&tpool->ioq.wthreads);
- PR_REMOVE_AND_INIT_LINK(head);
- wthrp = WTHREAD_LINKS_PTR(head);
- rval_status = PR_JoinThread(wthrp->thread);
- PR_ASSERT(PR_SUCCESS == rval_status);
- PR_DELETE(wthrp);
- }
-
- while (!PR_CLIST_IS_EMPTY(&tpool->timerq.wthreads)) {
- wthread *wthrp;
-
- head = PR_LIST_HEAD(&tpool->timerq.wthreads);
- PR_REMOVE_AND_INIT_LINK(head);
- wthrp = WTHREAD_LINKS_PTR(head);
- rval_status = PR_JoinThread(wthrp->thread);
- PR_ASSERT(PR_SUCCESS == rval_status);
- PR_DELETE(wthrp);
- }
-
- /*
- * Delete queued jobs
- */
- while (!PR_CLIST_IS_EMPTY(&tpool->jobq.list)) {
- PRJob *jobp;
-
- head = PR_LIST_HEAD(&tpool->jobq.list);
- PR_REMOVE_AND_INIT_LINK(head);
- jobp = JOB_LINKS_PTR(head);
- tpool->jobq.cnt--;
- delete_job(jobp);
- }
-
- /* delete io jobs */
- while (!PR_CLIST_IS_EMPTY(&tpool->ioq.list)) {
- PRJob *jobp;
-
- head = PR_LIST_HEAD(&tpool->ioq.list);
- PR_REMOVE_AND_INIT_LINK(head);
- tpool->ioq.cnt--;
- jobp = JOB_LINKS_PTR(head);
- delete_job(jobp);
- }
-
- /* delete timer jobs */
- while (!PR_CLIST_IS_EMPTY(&tpool->timerq.list)) {
- PRJob *jobp;
-
- head = PR_LIST_HEAD(&tpool->timerq.list);
- PR_REMOVE_AND_INIT_LINK(head);
- tpool->timerq.cnt--;
- jobp = JOB_LINKS_PTR(head);
- delete_job(jobp);
- }
-
- PR_ASSERT(0 == tpool->jobq.cnt);
- PR_ASSERT(0 == tpool->ioq.cnt);
- PR_ASSERT(0 == tpool->timerq.cnt);
-
- delete_threadpool(tpool);
- return rval;
-}
diff --git a/nspr/pr/src/misc/prtrace.c b/nspr/pr/src/misc/prtrace.c
deleted file mode 100644
index 058f700..0000000
--- a/nspr/pr/src/misc/prtrace.c
+++ /dev/null
@@ -1,882 +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/. */
-
-/*
-** prtrace.c -- NSPR Trace Instrumentation
-**
-** Implement the API defined in prtrace.h
-**
-**
-**
-*/
-
-#include <string.h>
-#include "primpl.h"
-
-
-#define DEFAULT_TRACE_BUFSIZE ( 1024 * 1024 )
-#define DEFAULT_BUFFER_SEGMENTS 2
-
-/*
-** Enumerate states in a RName structure
-*/
-typedef enum TraceState
-{
- Running = 1,
- Suspended = 2
-} TraceState;
-
-/*
-** Define QName structure
-*/
-typedef struct QName
-{
- PRCList link;
- PRCList rNameList;
- char name[PRTRACE_NAME_MAX+1];
-} QName;
-
-/*
-** Define RName structure
-*/
-typedef struct RName
-{
- PRCList link;
- PRLock *lock;
- QName *qName;
- TraceState state;
- char name[PRTRACE_NAME_MAX+1];
- char desc[PRTRACE_DESC_MAX+1];
-} RName;
-
-
-/*
-** The Trace Facility database
-**
-*/
-static PRLogModuleInfo *lm;
-
-static PRLock *traceLock; /* Facility Lock */
-static PRCList qNameList; /* anchor to all QName structures */
-static TraceState traceState = Running;
-
-/*
-** in-memory trace buffer controls
-*/
-static PRTraceEntry *tBuf; /* pointer to buffer */
-static PRInt32 bufSize; /* size of buffer, in bytes, rounded up to sizeof(PRTraceEntry) */
-static volatile PRInt32 next; /* index to next PRTraceEntry */
-static PRInt32 last; /* index of highest numbered trace entry */
-
-/*
-** Real-time buffer capture controls
-*/
-static PRInt32 fetchLastSeen = 0;
-static PRBool fetchLostData = PR_FALSE;
-
-/*
-** Buffer write-to-file controls
-*/
-static PRLock *logLock; /* Sync lock */
-static PRCondVar *logCVar; /* Sync Condidtion Variable */
-/*
-** Inter-thread state communication.
-** Controling thread writes to logOrder under protection of logCVar
-** the logging thread reads logOrder and sets logState on Notify.
-**
-** logSegments, logCount, logLostData must be read and written under
-** protection of logLock, logCVar.
-**
-*/
-static enum LogState
-{
- LogNotRunning, /* Initial state */
- LogReset, /* Causes logger to re-calc controls */
- LogActive, /* Logging in progress, set only by log thread */
- LogSuspend, /* Suspend Logging */
- LogResume, /* Resume Logging => LogActive */
- LogStop /* Stop the log thread */
-} logOrder, logState, localState; /* controlling state variables */
-static PRInt32 logSegments; /* Number of buffer segments */
-static PRInt32 logEntries; /* number of Trace Entries in the buffer */
-static PRInt32 logEntriesPerSegment; /* number of PRTraceEntries per buffer segment */
-static PRInt32 logSegSize; /* size of buffer segment */
-static PRInt32 logCount; /* number of segments pending output */
-static PRInt32 logLostData; /* number of lost log buffer segments */
-
-/*
-** end Trace Database
-**
-*/
-
-/*
-** _PR_InitializeTrace() -- Initialize the trace facility
-*/
-static void NewTraceBuffer( PRInt32 size )
-{
- /*
- ** calculate the size of the buffer
- ** round down so that each segment has the same number of
- ** trace entries
- */
- logSegments = DEFAULT_BUFFER_SEGMENTS;
- logEntries = size / sizeof(PRTraceEntry);
- logEntriesPerSegment = logEntries / logSegments;
- logEntries = logSegments * logEntriesPerSegment;
- bufSize = logEntries * sizeof(PRTraceEntry);
- logSegSize = logEntriesPerSegment * sizeof(PRTraceEntry);
- PR_ASSERT( bufSize != 0);
- PR_LOG( lm, PR_LOG_ERROR,
- ("NewTraceBuffer: logSegments: %ld, logEntries: %ld, logEntriesPerSegment: %ld, logSegSize: %ld",
- logSegments, logEntries, logEntriesPerSegment, logSegSize ));
-
-
- tBuf = PR_Malloc( bufSize );
- if ( tBuf == NULL )
- {
- PR_LOG( lm, PR_LOG_ERROR,
- ("PRTrace: Failed to get trace buffer"));
- PR_ASSERT( 0 );
- }
- else
- {
- PR_LOG( lm, PR_LOG_NOTICE,
- ("PRTrace: Got trace buffer of size: %ld, at %p", bufSize, tBuf));
- }
-
- next = 0;
- last = logEntries -1;
- logCount = 0;
- logLostData = PR_TRUE; /* not really on first call */
- logOrder = LogReset;
-
-} /* end NewTraceBuffer() */
-
-/*
-** _PR_InitializeTrace() -- Initialize the trace facility
-*/
-static void _PR_InitializeTrace( void )
-{
- /* The lock pointer better be null on this call */
- PR_ASSERT( traceLock == NULL );
-
- traceLock = PR_NewLock();
- PR_ASSERT( traceLock != NULL );
-
- PR_Lock( traceLock );
-
- PR_INIT_CLIST( &qNameList );
-
- lm = PR_NewLogModule("trace");
-
- bufSize = DEFAULT_TRACE_BUFSIZE;
- NewTraceBuffer( bufSize );
-
- /* Initialize logging controls */
- logLock = PR_NewLock();
- logCVar = PR_NewCondVar( logLock );
-
- PR_Unlock( traceLock );
- return;
-} /* end _PR_InitializeTrace() */
-
-/*
-** Create a Trace Handle
-*/
-PR_IMPLEMENT(PRTraceHandle)
- PR_CreateTrace(
- const char *qName, /* QName for this trace handle */
- const char *rName, /* RName for this trace handle */
- const char *description /* description for this trace handle */
-)
-{
- QName *qnp;
- RName *rnp;
- PRBool matchQname = PR_FALSE;
-
- /* Self initialize, if necessary */
- if ( traceLock == NULL )
- _PR_InitializeTrace();
-
- /* Validate input arguments */
- PR_ASSERT( strlen(qName) <= PRTRACE_NAME_MAX );
- PR_ASSERT( strlen(rName) <= PRTRACE_NAME_MAX );
- PR_ASSERT( strlen(description) <= PRTRACE_DESC_MAX );
-
- PR_LOG( lm, PR_LOG_DEBUG,
- ("PRTRACE: CreateTrace: Qname: %s, RName: %s", qName, rName));
-
- /* Lock the Facility */
- PR_Lock( traceLock );
-
- /* Do we already have a matching QName? */
- if (!PR_CLIST_IS_EMPTY( &qNameList ))
- {
- qnp = (QName *) PR_LIST_HEAD( &qNameList );
- do {
- if ( strcmp(qnp->name, qName) == 0)
- {
- matchQname = PR_TRUE;
- break;
- }
- qnp = (QName *)PR_NEXT_LINK( &qnp->link );
- } while( qnp != (QName *)&qNameList );
- }
- /*
- ** If we did not find a matching QName,
- ** allocate one and initialize it.
- ** link it onto the qNameList.
- **
- */
- if ( matchQname != PR_TRUE )
- {
- qnp = PR_NEWZAP( QName );
- PR_ASSERT( qnp != NULL );
- PR_INIT_CLIST( &qnp->link );
- PR_INIT_CLIST( &qnp->rNameList );
- strcpy( qnp->name, qName );
- PR_APPEND_LINK( &qnp->link, &qNameList );
- }
-
- /* Do we already have a matching RName? */
- if (!PR_CLIST_IS_EMPTY( &qnp->rNameList ))
- {
- rnp = (RName *) PR_LIST_HEAD( &qnp->rNameList );
- do {
- /*
- ** No duplicate RNames are allowed within a QName
- **
- */
- PR_ASSERT( strcmp(rnp->name, rName));
- rnp = (RName *)PR_NEXT_LINK( &rnp->link );
- } while( rnp != (RName *)&qnp->rNameList );
- }
-
- /* Get a new RName structure; initialize its members */
- rnp = PR_NEWZAP( RName );
- PR_ASSERT( rnp != NULL );
- PR_INIT_CLIST( &rnp->link );
- strcpy( rnp->name, rName );
- strcpy( rnp->desc, description );
- rnp->lock = PR_NewLock();
- rnp->state = Running;
- if ( rnp->lock == NULL )
- {
- PR_ASSERT(0);
- }
-
- PR_APPEND_LINK( &rnp->link, &qnp->rNameList ); /* add RName to QName's rnList */
- rnp->qName = qnp; /* point the RName to the QName */
-
- /* Unlock the Facility */
- PR_Unlock( traceLock );
- PR_LOG( lm, PR_LOG_DEBUG, ("PRTrace: Create: QName: %s %p, RName: %s %p\n\t",
- qName, qnp, rName, rnp ));
-
- return((PRTraceHandle)rnp);
-} /* end PR_CreateTrace() */
-
-/*
-**
-*/
-PR_IMPLEMENT(void)
- PR_DestroyTrace(
- PRTraceHandle handle /* Handle to be destroyed */
-)
-{
- RName *rnp = (RName *)handle;
- QName *qnp = rnp->qName;
-
- PR_LOG( lm, PR_LOG_DEBUG, ("PRTrace: Deleting: QName: %s, RName: %s",
- qnp->name, rnp->name));
-
- /* Lock the Facility */
- PR_Lock( traceLock );
-
- /*
- ** Remove RName from the list of RNames in QName
- ** and free RName
- */
- PR_LOG( lm, PR_LOG_DEBUG, ("PRTrace: Deleting RName: %s, %p",
- rnp->name, rnp));
- PR_REMOVE_LINK( &rnp->link );
- PR_Free( rnp->lock );
- PR_DELETE( rnp );
-
- /*
- ** If this is the last RName within QName
- ** remove QName from the qNameList and free it
- */
- if ( PR_CLIST_IS_EMPTY( &qnp->rNameList ) )
- {
- PR_LOG( lm, PR_LOG_DEBUG, ("PRTrace: Deleting unused QName: %s, %p",
- qnp->name, qnp));
- PR_REMOVE_LINK( &qnp->link );
- PR_DELETE( qnp );
- }
-
- /* Unlock the Facility */
- PR_Unlock( traceLock );
- return;
-} /* end PR_DestroyTrace() */
-
-/*
-** Create a TraceEntry in the trace buffer
-*/
-PR_IMPLEMENT(void)
- PR_Trace(
- PRTraceHandle handle, /* use this trace handle */
- PRUint32 userData0, /* User supplied data word 0 */
- PRUint32 userData1, /* User supplied data word 1 */
- PRUint32 userData2, /* User supplied data word 2 */
- PRUint32 userData3, /* User supplied data word 3 */
- PRUint32 userData4, /* User supplied data word 4 */
- PRUint32 userData5, /* User supplied data word 5 */
- PRUint32 userData6, /* User supplied data word 6 */
- PRUint32 userData7 /* User supplied data word 7 */
-)
-{
- PRTraceEntry *tep;
- PRInt32 mark;
-
- if ( (traceState == Suspended )
- || ( ((RName *)handle)->state == Suspended ))
- return;
-
- /*
- ** Get the next trace entry slot w/ minimum delay
- */
- PR_Lock( traceLock );
-
- tep = &tBuf[next++];
- if ( next > last )
- next = 0;
- if ( fetchLostData == PR_FALSE && next == fetchLastSeen )
- fetchLostData = PR_TRUE;
-
- mark = next;
-
- PR_Unlock( traceLock );
-
- /*
- ** We have a trace entry. Fill it in.
- */
- tep->thread = PR_GetCurrentThread();
- tep->handle = handle;
- tep->time = PR_Now();
- tep->userData[0] = userData0;
- tep->userData[1] = userData1;
- tep->userData[2] = userData2;
- tep->userData[3] = userData3;
- tep->userData[4] = userData4;
- tep->userData[5] = userData5;
- tep->userData[6] = userData6;
- tep->userData[7] = userData7;
-
- /* When buffer segment is full, signal trace log thread to run */
- if (( mark % logEntriesPerSegment) == 0 )
- {
- PR_Lock( logLock );
- logCount++;
- PR_NotifyCondVar( logCVar );
- PR_Unlock( logLock );
- /*
- ** Gh0D! This is awful!
- ** Anyway, to minimize lost trace data segments,
- ** I inserted the PR_Sleep(0) to cause a context switch
- ** so that the log thread could run.
- ** I know, it perturbs the universe and may cause
- ** funny things to happen in the optimized builds.
- ** Take it out, lose data; leave it in risk Heisenberg.
- */
- /* PR_Sleep(0); */
- }
-
- return;
-} /* end PR_Trace() */
-
-/*
-**
-*/
-PR_IMPLEMENT(void)
- PR_SetTraceOption(
- PRTraceOption command, /* One of the enumerated values */
- void *value /* command value or NULL */
-)
-{
- RName * rnp;
-
- switch ( command )
- {
- case PRTraceBufSize :
- PR_Lock( traceLock );
- PR_Free( tBuf );
- bufSize = *(PRInt32 *)value;
- NewTraceBuffer( bufSize );
- PR_Unlock( traceLock );
- PR_LOG( lm, PR_LOG_DEBUG,
- ("PRSetTraceOption: PRTraceBufSize: %ld", bufSize));
- break;
-
- case PRTraceEnable :
- rnp = *(RName **)value;
- rnp->state = Running;
- PR_LOG( lm, PR_LOG_DEBUG,
- ("PRSetTraceOption: PRTraceEnable: %p", rnp));
- break;
-
- case PRTraceDisable :
- rnp = *(RName **)value;
- rnp->state = Suspended;
- PR_LOG( lm, PR_LOG_DEBUG,
- ("PRSetTraceOption: PRTraceDisable: %p", rnp));
- break;
-
- case PRTraceSuspend :
- traceState = Suspended;
- PR_LOG( lm, PR_LOG_DEBUG,
- ("PRSetTraceOption: PRTraceSuspend"));
- break;
-
- case PRTraceResume :
- traceState = Running;
- PR_LOG( lm, PR_LOG_DEBUG,
- ("PRSetTraceOption: PRTraceResume"));
- break;
-
- case PRTraceSuspendRecording :
- PR_Lock( logLock );
- logOrder = LogSuspend;
- PR_NotifyCondVar( logCVar );
- PR_Unlock( logLock );
- PR_LOG( lm, PR_LOG_DEBUG,
- ("PRSetTraceOption: PRTraceSuspendRecording"));
- break;
-
- case PRTraceResumeRecording :
- PR_LOG( lm, PR_LOG_DEBUG,
- ("PRSetTraceOption: PRTraceResumeRecording"));
- if ( logState != LogSuspend )
- break;
- PR_Lock( logLock );
- logOrder = LogResume;
- PR_NotifyCondVar( logCVar );
- PR_Unlock( logLock );
- break;
-
- case PRTraceStopRecording :
- PR_Lock( logLock );
- logOrder = LogStop;
- PR_NotifyCondVar( logCVar );
- PR_Unlock( logLock );
- PR_LOG( lm, PR_LOG_DEBUG,
- ("PRSetTraceOption: PRTraceStopRecording"));
- break;
-
- case PRTraceLockHandles :
- PR_LOG( lm, PR_LOG_DEBUG,
- ("PRSetTraceOption: PRTraceLockTraceHandles"));
- PR_Lock( traceLock );
- break;
-
- case PRTraceUnLockHandles :
- PR_LOG( lm, PR_LOG_DEBUG,
- ("PRSetTraceOption: PRTraceUnLockHandles"));
- PR_Unlock( traceLock );
- break;
-
- default:
- PR_LOG( lm, PR_LOG_ERROR,
- ("PRSetTraceOption: Invalid command %ld", command ));
- PR_ASSERT( 0 );
- break;
- } /* end switch() */
- return;
-} /* end PR_SetTraceOption() */
-
-/*
-**
-*/
-PR_IMPLEMENT(void)
- PR_GetTraceOption(
- PRTraceOption command, /* One of the enumerated values */
- void *value /* command value or NULL */
-)
-{
- switch ( command )
- {
- case PRTraceBufSize :
- *((PRInt32 *)value) = bufSize;
- PR_LOG( lm, PR_LOG_DEBUG,
- ("PRGetTraceOption: PRTraceBufSize: %ld", bufSize ));
- break;
-
- default:
- PR_LOG( lm, PR_LOG_ERROR,
- ("PRGetTraceOption: Invalid command %ld", command ));
- PR_ASSERT( 0 );
- break;
- } /* end switch() */
- return;
-} /* end PR_GetTraceOption() */
-
-/*
-**
-*/
-PR_IMPLEMENT(PRTraceHandle)
- PR_GetTraceHandleFromName(
- const char *qName, /* QName search argument */
- const char *rName /* RName search argument */
-)
-{
- const char *qn, *rn, *desc;
- PRTraceHandle qh, rh = NULL;
- RName *rnp = NULL;
-
- PR_LOG( lm, PR_LOG_DEBUG, ("PRTrace: GetTraceHandleFromName:\n\t"
- "QName: %s, RName: %s", qName, rName ));
-
- qh = PR_FindNextTraceQname( NULL );
- while (qh != NULL)
- {
- rh = PR_FindNextTraceRname( NULL, qh );
- while ( rh != NULL )
- {
- PR_GetTraceNameFromHandle( rh, &qn, &rn, &desc );
- if ( (strcmp( qName, qn ) == 0)
- && (strcmp( rName, rn ) == 0 ))
- {
- rnp = (RName *)rh;
- goto foundIt;
- }
- rh = PR_FindNextTraceRname( rh, qh );
- }
- qh = PR_FindNextTraceQname( NULL );
- }
-
-foundIt:
- PR_LOG( lm, PR_LOG_DEBUG, ("PR_Counter: GetConterHandleFromName: %p", rnp ));
- return(rh);
-} /* end PR_GetTraceHandleFromName() */
-
-/*
-**
-*/
-PR_IMPLEMENT(void)
- PR_GetTraceNameFromHandle(
- PRTraceHandle handle, /* handle as search argument */
- const char **qName, /* pointer to associated QName */
- const char **rName, /* pointer to associated RName */
- const char **description /* pointer to associated description */
-)
-{
- RName *rnp = (RName *)handle;
- QName *qnp = rnp->qName;
-
- *qName = qnp->name;
- *rName = rnp->name;
- *description = rnp->desc;
-
- PR_LOG( lm, PR_LOG_DEBUG, ("PRTrace: GetConterNameFromHandle: "
- "QNp: %p, RNp: %p,\n\tQName: %s, RName: %s, Desc: %s",
- qnp, rnp, qnp->name, rnp->name, rnp->desc ));
-
- return;
-} /* end PR_GetTraceNameFromHandle() */
-
-/*
-**
-*/
-PR_IMPLEMENT(PRTraceHandle)
- PR_FindNextTraceQname(
- PRTraceHandle handle
-)
-{
- QName *qnp = (QName *)handle;
-
- if ( PR_CLIST_IS_EMPTY( &qNameList ))
- qnp = NULL;
- else if ( qnp == NULL )
- qnp = (QName *)PR_LIST_HEAD( &qNameList );
- else if ( PR_NEXT_LINK( &qnp->link ) == &qNameList )
- qnp = NULL;
- else
- qnp = (QName *)PR_NEXT_LINK( &qnp->link );
-
- PR_LOG( lm, PR_LOG_DEBUG, ("PRTrace: FindNextQname: Handle: %p, Returns: %p",
- handle, qnp ));
-
- return((PRTraceHandle)qnp);
-} /* end PR_FindNextTraceQname() */
-
-/*
-**
-*/
-PR_IMPLEMENT(PRTraceHandle)
- PR_FindNextTraceRname(
- PRTraceHandle rhandle,
- PRTraceHandle qhandle
-)
-{
- RName *rnp = (RName *)rhandle;
- QName *qnp = (QName *)qhandle;
-
-
- if ( PR_CLIST_IS_EMPTY( &qnp->rNameList ))
- rnp = NULL;
- else if ( rnp == NULL )
- rnp = (RName *)PR_LIST_HEAD( &qnp->rNameList );
- else if ( PR_NEXT_LINK( &rnp->link ) == &qnp->rNameList )
- rnp = NULL;
- else
- rnp = (RName *)PR_NEXT_LINK( &rnp->link );
-
- PR_LOG( lm, PR_LOG_DEBUG, ("PRTrace: FindNextRname: Rhandle: %p, QHandle: %p, Returns: %p",
- rhandle, qhandle, rnp ));
-
- return((PRTraceHandle)rnp);
-} /* end PR_FindNextTraceRname() */
-
-/*
-**
-*/
-static PRFileDesc * InitializeRecording( void )
-{
- char *logFileName;
- PRFileDesc *logFile;
-
- /* Self initialize, if necessary */
- if ( traceLock == NULL )
- _PR_InitializeTrace();
-
- PR_LOG( lm, PR_LOG_DEBUG,
- ("PR_RecordTraceEntries: begins"));
-
- logLostData = 0; /* reset at entry */
- logState = LogReset;
-
- /* Get the filename for the logfile from the environment */
- logFileName = PR_GetEnvSecure( "NSPR_TRACE_LOG" );
- if ( logFileName == NULL )
- {
- PR_LOG( lm, PR_LOG_ERROR,
- ("RecordTraceEntries: Environment variable not defined. Exiting"));
- return NULL;
- }
-
- /* Open the logfile */
- logFile = PR_Open( logFileName, PR_WRONLY | PR_CREATE_FILE, 0666 );
- if ( logFile == NULL )
- {
- PR_LOG( lm, PR_LOG_ERROR,
- ("RecordTraceEntries: Cannot open %s as trace log file. OS error: %ld",
- logFileName, PR_GetOSError()));
- return NULL;
- }
- return logFile;
-} /* end InitializeRecording() */
-
-/*
-**
-*/
-static void ProcessOrders( void )
-{
- switch ( logOrder )
- {
- case LogReset :
- logOrder = logState = localState;
- PR_LOG( lm, PR_LOG_DEBUG,
- ("RecordTraceEntries: LogReset"));
- break;
-
- case LogSuspend :
- localState = logOrder = logState = LogSuspend;
- PR_LOG( lm, PR_LOG_DEBUG,
- ("RecordTraceEntries: LogSuspend"));
- break;
-
- case LogResume :
- localState = logOrder = logState = LogActive;
- PR_LOG( lm, PR_LOG_DEBUG,
- ("RecordTraceEntries: LogResume"));
- break;
-
- case LogStop :
- logOrder = logState = LogStop;
- PR_LOG( lm, PR_LOG_DEBUG,
- ("RecordTraceEntries: LogStop"));
- break;
-
- default :
- PR_LOG( lm, PR_LOG_ERROR,
- ("RecordTraceEntries: Invalid logOrder: %ld", logOrder ));
- PR_ASSERT( 0 );
- break;
- } /* end switch() */
- return ;
-} /* end ProcessOrders() */
-
-/*
-**
-*/
-static void WriteTraceSegment( PRFileDesc *logFile, void *buf, PRInt32 amount )
-{
- PRInt32 rc;
-
-
- PR_LOG( lm, PR_LOG_ERROR,
- ("WriteTraceSegment: Buffer: %p, Amount: %ld", buf, amount));
- rc = PR_Write( logFile, buf , amount );
- if ( rc == -1 )
- PR_LOG( lm, PR_LOG_ERROR,
- ("RecordTraceEntries: PR_Write() failed. Error: %ld", PR_GetError() ));
- else if ( rc != amount )
- PR_LOG( lm, PR_LOG_ERROR,
- ("RecordTraceEntries: PR_Write() Tried to write: %ld, Wrote: %ld", amount, rc));
- else
- PR_LOG( lm, PR_LOG_DEBUG,
- ("RecordTraceEntries: PR_Write(): Buffer: %p, bytes: %ld", buf, amount));
-
- return;
-} /* end WriteTraceSegment() */
-
-/*
-**
-*/
-PR_IMPLEMENT(void)
- PR_RecordTraceEntries(
- void
-)
-{
- PRFileDesc *logFile;
- PRInt32 lostSegments;
- PRInt32 currentSegment = 0;
- void *buf;
- PRBool doWrite;
-
- logFile = InitializeRecording();
- if ( logFile == NULL )
- {
- PR_LOG( lm, PR_LOG_DEBUG,
- ("PR_RecordTraceEntries: Failed to initialize"));
- return;
- }
-
- /* Do this until told to stop */
- while ( logState != LogStop )
- {
-
- PR_Lock( logLock );
-
- while ( (logCount == 0) && ( logOrder == logState ) )
- PR_WaitCondVar( logCVar, PR_INTERVAL_NO_TIMEOUT );
-
- /* Handle state transitions */
- if ( logOrder != logState )
- ProcessOrders();
-
- /* recalculate local controls */
- if ( logCount )
- {
- lostSegments = logCount - logSegments;
- if ( lostSegments > 0 )
- {
- logLostData += ( logCount - logSegments );
- logCount = (logCount % logSegments);
- currentSegment = logCount;
- PR_LOG( lm, PR_LOG_DEBUG,
- ("PR_RecordTraceEntries: LostData segments: %ld", logLostData));
- }
- else
- {
- logCount--;
- }
-
- buf = tBuf + ( logEntriesPerSegment * currentSegment );
- if (++currentSegment >= logSegments )
- currentSegment = 0;
- doWrite = PR_TRUE;
- }
- else
- doWrite = PR_FALSE;
-
- PR_Unlock( logLock );
-
- if ( doWrite == PR_TRUE )
- {
- if ( localState != LogSuspend )
- WriteTraceSegment( logFile, buf, logSegSize );
- else
- PR_LOG( lm, PR_LOG_DEBUG,
- ("RecordTraceEntries: PR_Write(): is suspended" ));
- }
-
- } /* end while(logState...) */
-
- PR_Close( logFile );
- PR_LOG( lm, PR_LOG_DEBUG,
- ("RecordTraceEntries: exiting"));
- return;
-} /* end PR_RecordTraceEntries() */
-
-/*
-**
-*/
-PR_IMPLEMENT(PRIntn)
- PR_GetTraceEntries(
- PRTraceEntry *buffer, /* where to write output */
- PRInt32 count, /* number to get */
- PRInt32 *found /* number you got */
-)
-{
- PRInt32 rc;
- PRInt32 copied = 0;
-
- PR_Lock( traceLock );
-
- /*
- ** Depending on where the LastSeen and Next indices are,
- ** copy the trace buffer in one or two pieces.
- */
- PR_LOG( lm, PR_LOG_ERROR,
- ("PR_GetTraceEntries: Next: %ld, LastSeen: %ld", next, fetchLastSeen));
-
- if ( fetchLastSeen <= next )
- {
- while (( count-- > 0 ) && (fetchLastSeen < next ))
- {
- *(buffer + copied++) = *(tBuf + fetchLastSeen++);
- }
- PR_LOG( lm, PR_LOG_ERROR,
- ("PR_GetTraceEntries: Copied: %ld, LastSeen: %ld", copied, fetchLastSeen));
- }
- else /* copy in 2 parts */
- {
- while ( count-- > 0 && fetchLastSeen <= last )
- {
- *(buffer + copied++) = *(tBuf + fetchLastSeen++);
- }
- fetchLastSeen = 0;
-
- PR_LOG( lm, PR_LOG_ERROR,
- ("PR_GetTraceEntries: Copied: %ld, LastSeen: %ld", copied, fetchLastSeen));
-
- while ( count-- > 0 && fetchLastSeen < next )
- {
- *(buffer + copied++) = *(tBuf + fetchLastSeen++);
- }
- PR_LOG( lm, PR_LOG_ERROR,
- ("PR_GetTraceEntries: Copied: %ld, LastSeen: %ld", copied, fetchLastSeen));
- }
-
- *found = copied;
- rc = ( fetchLostData == PR_TRUE )? 1 : 0;
- fetchLostData = PR_FALSE;
-
- PR_Unlock( traceLock );
- return rc;
-} /* end PR_GetTraceEntries() */
-
-/* end prtrace.c */
diff --git a/nspr/pr/src/pthreads/ptio.c b/nspr/pr/src/pthreads/ptio.c
deleted file mode 100644
index e4fe519..0000000
--- a/nspr/pr/src/pthreads/ptio.c
+++ /dev/null
@@ -1,5012 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* 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/. */
-
-/*
-** File: ptio.c
-** Descritpion: Implemenation of I/O methods for pthreads
-*/
-
-#if defined(_PR_PTHREADS)
-
-#if defined(_PR_POLL_WITH_SELECT)
-#if !(defined(HPUX) && defined(_USE_BIG_FDS))
-/* set fd limit for select(), before including system header files */
-#define FD_SETSIZE (16 * 1024)
-#endif
-#endif
-
-#include <pthread.h>
-#include <string.h> /* for memset() */
-#include <sys/types.h>
-#include <dirent.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/uio.h>
-#include <sys/file.h>
-#include <sys/ioctl.h>
-#if defined(DARWIN)
-#include <sys/utsname.h> /* for uname */
-#endif
-#if defined(SOLARIS) || defined(UNIXWARE)
-#include <sys/filio.h> /* to pick up FIONREAD */
-#endif
-#ifdef _PR_POLL_AVAILABLE
-#include <poll.h>
-#endif
-#ifdef AIX
-/* To pick up sysconf() */
-#include <unistd.h>
-#include <dlfcn.h> /* for dlopen */
-#else
-/* To pick up getrlimit() etc. */
-#include <sys/time.h>
-#include <sys/resource.h>
-#endif
-
-#ifdef SOLARIS
-/*
- * Define HAVE_SENDFILEV if the system has the sendfilev() system call.
- * Code built this way won't run on a system without sendfilev().
- * We can define HAVE_SENDFILEV by default when the minimum release
- * of Solaris that NSPR supports has sendfilev().
- */
-#ifdef HAVE_SENDFILEV
-
-#include <sys/sendfile.h>
-
-#define SOLARIS_SENDFILEV(a, b, c, d) sendfilev((a), (b), (c), (d))
-
-#else
-
-#include <dlfcn.h> /* for dlopen */
-
-/*
- * Match the definitions in <sys/sendfile.h>.
- */
-typedef struct sendfilevec {
- int sfv_fd; /* input fd */
- uint_t sfv_flag; /* flags */
- off_t sfv_off; /* offset to start reading from */
- size_t sfv_len; /* amount of data */
-} sendfilevec_t;
-
-#define SFV_FD_SELF (-2)
-
-/*
- * extern ssize_t sendfilev(int, const struct sendfilevec *, int, size_t *);
- */
-static ssize_t (*pt_solaris_sendfilev_fptr)() = NULL;
-
-#define SOLARIS_SENDFILEV(a, b, c, d) \
- (*pt_solaris_sendfilev_fptr)((a), (b), (c), (d))
-
-#endif /* HAVE_SENDFILEV */
-#endif /* SOLARIS */
-
-/*
- * The send_file() system call is available in AIX 4.3.2 or later.
- * If this file is compiled on an older AIX system, it attempts to
- * look up the send_file symbol at run time to determine whether
- * we can use the faster PR_SendFile/PR_TransmitFile implementation based on
- * send_file(). On AIX 4.3.2 or later, we can safely skip this
- * runtime function dispatching and just use the send_file based
- * implementation.
- */
-#ifdef AIX
-#ifdef SF_CLOSE
-#define HAVE_SEND_FILE
-#endif
-
-#ifdef HAVE_SEND_FILE
-
-#define AIX_SEND_FILE(a, b, c) send_file(a, b, c)
-
-#else /* HAVE_SEND_FILE */
-
-/*
- * The following definitions match those in <sys/socket.h>
- * on AIX 4.3.2.
- */
-
-/*
- * Structure for the send_file() system call
- */
-struct sf_parms {
- /* --------- header parms ---------- */
- void *header_data; /* Input/Output. Points to header buf */
- uint_t header_length; /* Input/Output. Length of the header */
- /* --------- file parms ------------ */
- int file_descriptor; /* Input. File descriptor of the file */
- unsigned long long file_size; /* Output. Size of the file */
- unsigned long long file_offset; /* Input/Output. Starting offset */
- long long file_bytes; /* Input/Output. no. of bytes to send */
- /* --------- trailer parms --------- */
- void *trailer_data; /* Input/Output. Points to trailer buf */
- uint_t trailer_length; /* Input/Output. Length of the trailer */
- /* --------- return info ----------- */
- unsigned long long bytes_sent; /* Output. no. of bytes sent */
-};
-
-/*
- * Flags for the send_file() system call
- */
-#define SF_CLOSE 0x00000001 /* close the socket after completion */
-#define SF_REUSE 0x00000002 /* reuse socket. not supported */
-#define SF_DONT_CACHE 0x00000004 /* don't apply network buffer cache */
-#define SF_SYNC_CACHE 0x00000008 /* sync/update network buffer cache */
-
-/*
- * prototype: size_t send_file(int *, struct sf_parms *, uint_t);
- */
-static ssize_t (*pt_aix_sendfile_fptr)() = NULL;
-
-#define AIX_SEND_FILE(a, b, c) (*pt_aix_sendfile_fptr)(a, b, c)
-
-#endif /* HAVE_SEND_FILE */
-#endif /* AIX */
-
-#ifdef LINUX
-#include <sys/sendfile.h>
-#endif
-
-#include "primpl.h"
-
-#ifdef HAVE_NETINET_TCP_H
-#include <netinet/tcp.h> /* TCP_NODELAY, TCP_MAXSEG */
-#endif
-
-#ifdef LINUX
-/* TCP_CORK is not defined in <netinet/tcp.h> on Red Hat Linux 6.0 */
-#ifndef TCP_CORK
-#define TCP_CORK 3
-#endif
-#endif
-
-#ifdef _PR_IPV6_V6ONLY_PROBE
-static PRBool _pr_ipv6_v6only_on_by_default;
-#endif
-
-#if (defined(HPUX) && !defined(HPUX10_30) && !defined(HPUX11))
-#define _PRSelectFdSetArg_t int *
-#elif defined(AIX4_1)
-#define _PRSelectFdSetArg_t void *
-#elif defined(IRIX) || (defined(AIX) && !defined(AIX4_1)) \
- || defined(OSF1) || defined(SOLARIS) \
- || defined(HPUX10_30) || defined(HPUX11) \
- || defined(LINUX) || defined(__GNU__) || defined(__GLIBC__) \
- || defined(FREEBSD) || defined(NETBSD) || defined(OPENBSD) \
- || defined(BSDI) || defined(NTO) || defined(DARWIN) \
- || defined(UNIXWARE) || defined(RISCOS) || defined(SYMBIAN)
-#define _PRSelectFdSetArg_t fd_set *
-#else
-#error "Cannot determine architecture"
-#endif
-
-#if defined(SOLARIS)
-#ifndef PROTO_SDP
-/* on solaris, SDP is a new type of protocol */
-#define PROTO_SDP 257
-#endif
-#define _PR_HAVE_SDP
-#elif defined(LINUX)
-#ifndef AF_INET_SDP
-/* on linux, SDP is a new type of address family */
-#define AF_INET_SDP 27
-#endif
-#define _PR_HAVE_SDP
-#endif /* LINUX */
-
-static PRFileDesc *pt_SetMethods(
- PRIntn osfd, PRDescType type, PRBool isAcceptedSocket, PRBool imported);
-
-static PRLock *_pr_flock_lock; /* For PR_LockFile() etc. */
-static PRCondVar *_pr_flock_cv; /* For PR_LockFile() etc. */
-static PRLock *_pr_rename_lock; /* For PR_Rename() */
-
-/**************************************************************************/
-
-/* These two functions are only used in assertions. */
-#if defined(DEBUG)
-
-PRBool IsValidNetAddr(const PRNetAddr *addr)
-{
- if ((addr != NULL)
- && (addr->raw.family != AF_UNIX)
- && (addr->raw.family != PR_AF_INET6)
- && (addr->raw.family != AF_INET)) {
- return PR_FALSE;
- }
- return PR_TRUE;
-}
-
-static PRBool IsValidNetAddrLen(const PRNetAddr *addr, PRInt32 addr_len)
-{
- /*
- * The definition of the length of a Unix domain socket address
- * is not uniform, so we don't check it.
- */
- if ((addr != NULL)
- && (addr->raw.family != AF_UNIX)
- && (PR_NETADDR_SIZE(addr) != addr_len)) {
-#if defined(LINUX) && __GLIBC__ == 2 && __GLIBC_MINOR__ == 1
- /*
- * In glibc 2.1, struct sockaddr_in6 is 24 bytes. In glibc 2.2
- * and in the 2.4 kernel, struct sockaddr_in6 has the scope_id
- * field and is 28 bytes. It is possible for socket functions
- * to return an addr_len greater than sizeof(struct sockaddr_in6).
- * We need to allow that. (Bugzilla bug #77264)
- */
- if ((PR_AF_INET6 == addr->raw.family)
- && (sizeof(addr->ipv6) == addr_len)) {
- return PR_TRUE;
- }
-#endif
- return PR_FALSE;
- }
- return PR_TRUE;
-}
-
-#endif /* DEBUG */
-
-/*****************************************************************************/
-/************************* I/O Continuation machinery ************************/
-/*****************************************************************************/
-
-/*
- * The polling interval defines the maximum amount of time that a thread
- * might hang up before an interrupt is noticed.
- */
-#define PT_DEFAULT_POLL_MSEC 5000
-#if defined(_PR_POLL_WITH_SELECT)
-#define PT_DEFAULT_SELECT_SEC (PT_DEFAULT_POLL_MSEC/PR_MSEC_PER_SEC)
-#define PT_DEFAULT_SELECT_USEC \
- ((PT_DEFAULT_POLL_MSEC % PR_MSEC_PER_SEC) * PR_USEC_PER_MSEC)
-#endif
-
-/*
- * pt_SockLen is the type for the length of a socket address
- * structure, used in the address length argument to bind,
- * connect, accept, getsockname, getpeername, etc. Posix.1g
- * defines this type as socklen_t. It is size_t or int on
- * most current systems.
- */
-#if defined(HAVE_SOCKLEN_T) \
- || (defined(__GLIBC__) && __GLIBC__ >= 2)
-typedef socklen_t pt_SockLen;
-#elif (defined(AIX) && !defined(AIX4_1))
-typedef PRSize pt_SockLen;
-#else
-typedef PRIntn pt_SockLen;
-#endif
-
-typedef struct pt_Continuation pt_Continuation;
-typedef PRBool (*ContinuationFn)(pt_Continuation *op, PRInt16 revents);
-
-typedef enum pr_ContuationStatus
-{
- pt_continuation_pending,
- pt_continuation_done
-} pr_ContuationStatus;
-
-struct pt_Continuation
-{
- /* The building of the continuation operation */
- ContinuationFn function; /* what function to continue */
- union { PRIntn osfd; } arg1; /* #1 - the op's fd */
- union { void* buffer; } arg2; /* #2 - primary transfer buffer */
- union {
- PRSize amount; /* #3 - size of 'buffer', or */
- pt_SockLen *addr_len; /* - length of address */
-#ifdef HPUX11
- /*
- * For sendfile()
- */
- struct file_spec {
- off_t offset; /* offset in file to send */
- size_t nbytes; /* length of file data to send */
- size_t st_size; /* file size */
- } file_spec;
-#endif
- } arg3;
- union { PRIntn flags; } arg4; /* #4 - read/write flags */
- union { PRNetAddr *addr; } arg5; /* #5 - send/recv address */
-
-#ifdef HPUX11
- /*
- * For sendfile()
- */
- int filedesc; /* descriptor of file to send */
- int nbytes_to_send; /* size of header and file */
-#endif /* HPUX11 */
-
-#ifdef SOLARIS
- /*
- * For sendfilev()
- */
- int nbytes_to_send; /* size of header and file */
-#endif /* SOLARIS */
-
-#ifdef LINUX
- /*
- * For sendfile()
- */
- int in_fd; /* descriptor of file to send */
- off_t offset;
- size_t count;
-#endif /* LINUX */
-
- PRIntervalTime timeout; /* client (relative) timeout */
-
- PRInt16 event; /* flags for poll()'s events */
-
- /*
- ** The representation and notification of the results of the operation.
- ** These function can either return an int return code or a pointer to
- ** some object.
- */
- union { PRSize code; void *object; } result;
-
- PRIntn syserrno; /* in case it failed, why (errno) */
- pr_ContuationStatus status; /* the status of the operation */
-};
-
-#if defined(DEBUG)
-
-PTDebug pt_debug; /* this is shared between several modules */
-
-PR_IMPLEMENT(void) PT_FPrintStats(PRFileDesc *debug_out, const char *msg)
-{
- PTDebug stats;
- char buffer[100];
- PRExplodedTime tod;
- PRInt64 elapsed, aMil;
- stats = pt_debug; /* a copy */
- PR_ExplodeTime(stats.timeStarted, PR_LocalTimeParameters, &tod);
- (void)PR_FormatTime(buffer, sizeof(buffer), "%T", &tod);
-
- LL_SUB(elapsed, PR_Now(), stats.timeStarted);
- LL_I2L(aMil, 1000000);
- LL_DIV(elapsed, elapsed, aMil);
-
- if (NULL != msg) PR_fprintf(debug_out, "%s", msg);
- PR_fprintf(
- debug_out, "\tstarted: %s[%lld]\n", buffer, elapsed);
- PR_fprintf(
- debug_out, "\tlocks [created: %u, destroyed: %u]\n",
- stats.locks_created, stats.locks_destroyed);
- PR_fprintf(
- debug_out, "\tlocks [acquired: %u, released: %u]\n",
- stats.locks_acquired, stats.locks_released);
- PR_fprintf(
- debug_out, "\tcvars [created: %u, destroyed: %u]\n",
- stats.cvars_created, stats.cvars_destroyed);
- PR_fprintf(
- debug_out, "\tcvars [notified: %u, delayed_delete: %u]\n",
- stats.cvars_notified, stats.delayed_cv_deletes);
-} /* PT_FPrintStats */
-
-#else
-
-PR_IMPLEMENT(void) PT_FPrintStats(PRFileDesc *debug_out, const char *msg)
-{
- /* do nothing */
-} /* PT_FPrintStats */
-
-#endif /* DEBUG */
-
-#if defined(_PR_POLL_WITH_SELECT)
-/*
- * OSF1 and HPUX report the POLLHUP event for a socket when the
- * shutdown(SHUT_WR) operation is called for the remote end, even though
- * the socket is still writeable. Use select(), instead of poll(), to
- * workaround this problem.
- */
-static void pt_poll_now_with_select(pt_Continuation *op)
-{
- PRInt32 msecs;
- fd_set rd, wr, *rdp, *wrp;
- struct timeval tv;
- PRIntervalTime epoch, now, elapsed, remaining;
- PRBool wait_for_remaining;
- PRThread *self = PR_GetCurrentThread();
-
- PR_ASSERT(PR_INTERVAL_NO_WAIT != op->timeout);
- PR_ASSERT(op->arg1.osfd < FD_SETSIZE);
-
- switch (op->timeout) {
- case PR_INTERVAL_NO_TIMEOUT:
- tv.tv_sec = PT_DEFAULT_SELECT_SEC;
- tv.tv_usec = PT_DEFAULT_SELECT_USEC;
- do
- {
- PRIntn rv;
-
- if (op->event & POLLIN) {
- FD_ZERO(&rd);
- FD_SET(op->arg1.osfd, &rd);
- rdp = &rd;
- } else
- rdp = NULL;
- if (op->event & POLLOUT) {
- FD_ZERO(&wr);
- FD_SET(op->arg1.osfd, &wr);
- wrp = ≀
- } else
- wrp = NULL;
-
- rv = select(op->arg1.osfd + 1, rdp, wrp, NULL, &tv);
-
- if (_PT_THREAD_INTERRUPTED(self))
- {
- self->state &= ~PT_THREAD_ABORTED;
- op->result.code = -1;
- op->syserrno = EINTR;
- op->status = pt_continuation_done;
- return;
- }
-
- if ((-1 == rv) && ((errno == EINTR) || (errno == EAGAIN)))
- continue; /* go around the loop again */
-
- if (rv > 0)
- {
- PRInt16 revents = 0;
-
- if ((op->event & POLLIN) && FD_ISSET(op->arg1.osfd, &rd))
- revents |= POLLIN;
- if ((op->event & POLLOUT) && FD_ISSET(op->arg1.osfd, &wr))
- revents |= POLLOUT;
-
- if (op->function(op, revents))
- op->status = pt_continuation_done;
- } else if (rv == -1) {
- op->result.code = -1;
- op->syserrno = errno;
- op->status = pt_continuation_done;
- }
- /* else, select timed out */
- } while (pt_continuation_done != op->status);
- break;
- default:
- now = epoch = PR_IntervalNow();
- remaining = op->timeout;
- do
- {
- PRIntn rv;
-
- if (op->event & POLLIN) {
- FD_ZERO(&rd);
- FD_SET(op->arg1.osfd, &rd);
- rdp = &rd;
- } else
- rdp = NULL;
- if (op->event & POLLOUT) {
- FD_ZERO(&wr);
- FD_SET(op->arg1.osfd, &wr);
- wrp = ≀
- } else
- wrp = NULL;
-
- wait_for_remaining = PR_TRUE;
- msecs = (PRInt32)PR_IntervalToMilliseconds(remaining);
- if (msecs > PT_DEFAULT_POLL_MSEC) {
- wait_for_remaining = PR_FALSE;
- msecs = PT_DEFAULT_POLL_MSEC;
- }
- tv.tv_sec = msecs/PR_MSEC_PER_SEC;
- tv.tv_usec = (msecs % PR_MSEC_PER_SEC) * PR_USEC_PER_MSEC;
- rv = select(op->arg1.osfd + 1, rdp, wrp, NULL, &tv);
-
- if (_PT_THREAD_INTERRUPTED(self))
- {
- self->state &= ~PT_THREAD_ABORTED;
- op->result.code = -1;
- op->syserrno = EINTR;
- op->status = pt_continuation_done;
- return;
- }
-
- if (rv > 0) {
- PRInt16 revents = 0;
-
- if ((op->event & POLLIN) && FD_ISSET(op->arg1.osfd, &rd))
- revents |= POLLIN;
- if ((op->event & POLLOUT) && FD_ISSET(op->arg1.osfd, &wr))
- revents |= POLLOUT;
-
- if (op->function(op, revents))
- op->status = pt_continuation_done;
-
- } else if ((rv == 0) ||
- ((errno == EINTR) || (errno == EAGAIN))) {
- if (rv == 0) { /* select timed out */
- if (wait_for_remaining)
- now += remaining;
- else
- now += PR_MillisecondsToInterval(msecs);
- } else
- now = PR_IntervalNow();
- elapsed = (PRIntervalTime) (now - epoch);
- if (elapsed >= op->timeout) {
- op->result.code = -1;
- op->syserrno = ETIMEDOUT;
- op->status = pt_continuation_done;
- } else
- remaining = op->timeout - elapsed;
- } else {
- op->result.code = -1;
- op->syserrno = errno;
- op->status = pt_continuation_done;
- }
- } while (pt_continuation_done != op->status);
- break;
- }
-
-} /* pt_poll_now_with_select */
-
-#endif /* _PR_POLL_WITH_SELECT */
-
-static void pt_poll_now(pt_Continuation *op)
-{
- PRInt32 msecs;
- PRIntervalTime epoch, now, elapsed, remaining;
- PRBool wait_for_remaining;
- PRThread *self = PR_GetCurrentThread();
-
- PR_ASSERT(PR_INTERVAL_NO_WAIT != op->timeout);
-#if defined (_PR_POLL_WITH_SELECT)
- /*
- * If the fd is small enough call the select-based poll operation
- */
- if (op->arg1.osfd < FD_SETSIZE) {
- pt_poll_now_with_select(op);
- return;
- }
-#endif
-
- switch (op->timeout) {
- case PR_INTERVAL_NO_TIMEOUT:
- msecs = PT_DEFAULT_POLL_MSEC;
- do
- {
- PRIntn rv;
- struct pollfd tmp_pfd;
-
- tmp_pfd.revents = 0;
- tmp_pfd.fd = op->arg1.osfd;
- tmp_pfd.events = op->event;
-
- rv = poll(&tmp_pfd, 1, msecs);
-
- if (_PT_THREAD_INTERRUPTED(self))
- {
- self->state &= ~PT_THREAD_ABORTED;
- op->result.code = -1;
- op->syserrno = EINTR;
- op->status = pt_continuation_done;
- return;
- }
-
- if ((-1 == rv) && ((errno == EINTR) || (errno == EAGAIN)))
- continue; /* go around the loop again */
-
- if (rv > 0)
- {
- PRInt16 events = tmp_pfd.events;
- PRInt16 revents = tmp_pfd.revents;
-
- if ((revents & POLLNVAL) /* busted in all cases */
- || ((events & POLLOUT) && (revents & POLLHUP)))
- /* write op & hup */
- {
- op->result.code = -1;
- if (POLLNVAL & revents) op->syserrno = EBADF;
- else if (POLLHUP & revents) op->syserrno = EPIPE;
- op->status = pt_continuation_done;
- } else {
- if (op->function(op, revents))
- op->status = pt_continuation_done;
- }
- } else if (rv == -1) {
- op->result.code = -1;
- op->syserrno = errno;
- op->status = pt_continuation_done;
- }
- /* else, poll timed out */
- } while (pt_continuation_done != op->status);
- break;
- default:
- now = epoch = PR_IntervalNow();
- remaining = op->timeout;
- do
- {
- PRIntn rv;
- struct pollfd tmp_pfd;
-
- tmp_pfd.revents = 0;
- tmp_pfd.fd = op->arg1.osfd;
- tmp_pfd.events = op->event;
-
- wait_for_remaining = PR_TRUE;
- msecs = (PRInt32)PR_IntervalToMilliseconds(remaining);
- if (msecs > PT_DEFAULT_POLL_MSEC)
- {
- wait_for_remaining = PR_FALSE;
- msecs = PT_DEFAULT_POLL_MSEC;
- }
- rv = poll(&tmp_pfd, 1, msecs);
-
- if (_PT_THREAD_INTERRUPTED(self))
- {
- self->state &= ~PT_THREAD_ABORTED;
- op->result.code = -1;
- op->syserrno = EINTR;
- op->status = pt_continuation_done;
- return;
- }
-
- if (rv > 0)
- {
- PRInt16 events = tmp_pfd.events;
- PRInt16 revents = tmp_pfd.revents;
-
- if ((revents & POLLNVAL) /* busted in all cases */
- || ((events & POLLOUT) && (revents & POLLHUP)))
- /* write op & hup */
- {
- op->result.code = -1;
- if (POLLNVAL & revents) op->syserrno = EBADF;
- else if (POLLHUP & revents) op->syserrno = EPIPE;
- op->status = pt_continuation_done;
- } else {
- if (op->function(op, revents))
- {
- op->status = pt_continuation_done;
- }
- }
- } else if ((rv == 0) ||
- ((errno == EINTR) || (errno == EAGAIN))) {
- if (rv == 0) /* poll timed out */
- {
- if (wait_for_remaining)
- now += remaining;
- else
- now += PR_MillisecondsToInterval(msecs);
- }
- else
- now = PR_IntervalNow();
- elapsed = (PRIntervalTime) (now - epoch);
- if (elapsed >= op->timeout) {
- op->result.code = -1;
- op->syserrno = ETIMEDOUT;
- op->status = pt_continuation_done;
- } else
- remaining = op->timeout - elapsed;
- } else {
- op->result.code = -1;
- op->syserrno = errno;
- op->status = pt_continuation_done;
- }
- } while (pt_continuation_done != op->status);
- break;
- }
-
-} /* pt_poll_now */
-
-static PRIntn pt_Continue(pt_Continuation *op)
-{
- op->status = pt_continuation_pending; /* set default value */
- /*
- * let each thread call poll directly
- */
- pt_poll_now(op);
- PR_ASSERT(pt_continuation_done == op->status);
- return op->result.code;
-} /* pt_Continue */
-
-/*****************************************************************************/
-/*********************** specific continuation functions *********************/
-/*****************************************************************************/
-static PRBool pt_connect_cont(pt_Continuation *op, PRInt16 revents)
-{
- op->syserrno = _MD_unix_get_nonblocking_connect_error(op->arg1.osfd);
- if (op->syserrno != 0) {
- op->result.code = -1;
- } else {
- op->result.code = 0;
- }
- return PR_TRUE; /* this one is cooked */
-} /* pt_connect_cont */
-
-static PRBool pt_accept_cont(pt_Continuation *op, PRInt16 revents)
-{
- op->syserrno = 0;
- op->result.code = accept(
- op->arg1.osfd, op->arg2.buffer, op->arg3.addr_len);
- if (-1 == op->result.code)
- {
- op->syserrno = errno;
- if (EWOULDBLOCK == errno || EAGAIN == errno || ECONNABORTED == errno)
- return PR_FALSE; /* do nothing - this one ain't finished */
- }
- return PR_TRUE;
-} /* pt_accept_cont */
-
-static PRBool pt_read_cont(pt_Continuation *op, PRInt16 revents)
-{
- /*
- * Any number of bytes will complete the operation. It need
- * not (and probably will not) satisfy the request. The only
- * error we continue is EWOULDBLOCK|EAGAIN.
- */
- op->result.code = read(
- op->arg1.osfd, op->arg2.buffer, op->arg3.amount);
- op->syserrno = errno;
- return ((-1 == op->result.code) &&
- (EWOULDBLOCK == op->syserrno || EAGAIN == op->syserrno)) ?
- PR_FALSE : PR_TRUE;
-} /* pt_read_cont */
-
-static PRBool pt_recv_cont(pt_Continuation *op, PRInt16 revents)
-{
- /*
- * Any number of bytes will complete the operation. It need
- * not (and probably will not) satisfy the request. The only
- * error we continue is EWOULDBLOCK|EAGAIN.
- */
-#if defined(SOLARIS)
- if (0 == op->arg4.flags)
- op->result.code = read(
- op->arg1.osfd, op->arg2.buffer, op->arg3.amount);
- else
- op->result.code = recv(
- op->arg1.osfd, op->arg2.buffer, op->arg3.amount, op->arg4.flags);
-#else
- op->result.code = recv(
- op->arg1.osfd, op->arg2.buffer, op->arg3.amount, op->arg4.flags);
-#endif
- op->syserrno = errno;
- return ((-1 == op->result.code) &&
- (EWOULDBLOCK == op->syserrno || EAGAIN == op->syserrno)) ?
- PR_FALSE : PR_TRUE;
-} /* pt_recv_cont */
-
-static PRBool pt_send_cont(pt_Continuation *op, PRInt16 revents)
-{
- PRIntn bytes;
-#if defined(SOLARIS)
- PRInt32 tmp_amount = op->arg3.amount;
-#endif
- /*
- * We want to write the entire amount out, no matter how many
- * tries it takes. Keep advancing the buffer and the decrementing
- * the amount until the amount goes away. Return the total bytes
- * (which should be the original amount) when finished (or an
- * error).
- */
-#if defined(SOLARIS)
-retry:
- bytes = write(op->arg1.osfd, op->arg2.buffer, tmp_amount);
-#else
- bytes = send(
- op->arg1.osfd, op->arg2.buffer, op->arg3.amount, op->arg4.flags);
-#endif
- op->syserrno = errno;
-
-#if defined(SOLARIS)
- /*
- * The write system call has been reported to return the ERANGE error
- * on occasion. Try to write in smaller chunks to workaround this bug.
- */
- if ((bytes == -1) && (op->syserrno == ERANGE))
- {
- if (tmp_amount > 1)
- {
- tmp_amount = tmp_amount/2; /* half the bytes */
- goto retry;
- }
- }
-#endif
-
- if (bytes >= 0) /* this is progress */
- {
- char *bp = (char*)op->arg2.buffer;
- bp += bytes; /* adjust the buffer pointer */
- op->arg2.buffer = bp;
- op->result.code += bytes; /* accumulate the number sent */
- op->arg3.amount -= bytes; /* and reduce the required count */
- return (0 == op->arg3.amount) ? PR_TRUE : PR_FALSE;
- }
- else if ((EWOULDBLOCK != op->syserrno) && (EAGAIN != op->syserrno))
- {
- op->result.code = -1;
- return PR_TRUE;
- }
- else return PR_FALSE;
-} /* pt_send_cont */
-
-static PRBool pt_write_cont(pt_Continuation *op, PRInt16 revents)
-{
- PRIntn bytes;
- /*
- * We want to write the entire amount out, no matter how many
- * tries it takes. Keep advancing the buffer and the decrementing
- * the amount until the amount goes away. Return the total bytes
- * (which should be the original amount) when finished (or an
- * error).
- */
- bytes = write(op->arg1.osfd, op->arg2.buffer, op->arg3.amount);
- op->syserrno = errno;
- if (bytes >= 0) /* this is progress */
- {
- char *bp = (char*)op->arg2.buffer;
- bp += bytes; /* adjust the buffer pointer */
- op->arg2.buffer = bp;
- op->result.code += bytes; /* accumulate the number sent */
- op->arg3.amount -= bytes; /* and reduce the required count */
- return (0 == op->arg3.amount) ? PR_TRUE : PR_FALSE;
- }
- else if ((EWOULDBLOCK != op->syserrno) && (EAGAIN != op->syserrno))
- {
- op->result.code = -1;
- return PR_TRUE;
- }
- else return PR_FALSE;
-} /* pt_write_cont */
-
-static PRBool pt_writev_cont(pt_Continuation *op, PRInt16 revents)
-{
- PRIntn bytes;
- struct iovec *iov = (struct iovec*)op->arg2.buffer;
- /*
- * Same rules as write, but continuing seems to be a bit more
- * complicated. As the number of bytes sent grows, we have to
- * redefine the vector we're pointing at. We might have to
- * modify an individual vector parms or we might have to eliminate
- * a pair altogether.
- */
- bytes = writev(op->arg1.osfd, iov, op->arg3.amount);
- op->syserrno = errno;
- if (bytes >= 0) /* this is progress */
- {
- PRIntn iov_index;
- op->result.code += bytes; /* accumulate the number sent */
- for (iov_index = 0; iov_index < op->arg3.amount; ++iov_index)
- {
- /* how much progress did we make in the i/o vector? */
- if (bytes < iov[iov_index].iov_len)
- {
- /* this element's not done yet */
- char **bp = (char**)&(iov[iov_index].iov_base);
- iov[iov_index].iov_len -= bytes; /* there's that much left */
- *bp += bytes; /* starting there */
- break; /* go off and do that */
- }
- bytes -= iov[iov_index].iov_len; /* that element's consumed */
- }
- op->arg2.buffer = &iov[iov_index]; /* new start of array */
- op->arg3.amount -= iov_index; /* and array length */
- return (0 == op->arg3.amount) ? PR_TRUE : PR_FALSE;
- }
- else if ((EWOULDBLOCK != op->syserrno) && (EAGAIN != op->syserrno))
- {
- op->result.code = -1;
- return PR_TRUE;
- }
- else return PR_FALSE;
-} /* pt_writev_cont */
-
-static PRBool pt_sendto_cont(pt_Continuation *op, PRInt16 revents)
-{
- PRIntn bytes = sendto(
- op->arg1.osfd, op->arg2.buffer, op->arg3.amount, op->arg4.flags,
- (struct sockaddr*)op->arg5.addr, PR_NETADDR_SIZE(op->arg5.addr));
- op->syserrno = errno;
- if (bytes >= 0) /* this is progress */
- {
- char *bp = (char*)op->arg2.buffer;
- bp += bytes; /* adjust the buffer pointer */
- op->arg2.buffer = bp;
- op->result.code += bytes; /* accumulate the number sent */
- op->arg3.amount -= bytes; /* and reduce the required count */
- return (0 == op->arg3.amount) ? PR_TRUE : PR_FALSE;
- }
- else if ((EWOULDBLOCK != op->syserrno) && (EAGAIN != op->syserrno))
- {
- op->result.code = -1;
- return PR_TRUE;
- }
- else return PR_FALSE;
-} /* pt_sendto_cont */
-
-static PRBool pt_recvfrom_cont(pt_Continuation *op, PRInt16 revents)
-{
- pt_SockLen addr_len = sizeof(PRNetAddr);
- op->result.code = recvfrom(
- op->arg1.osfd, op->arg2.buffer, op->arg3.amount,
- op->arg4.flags, (struct sockaddr*)op->arg5.addr, &addr_len);
- op->syserrno = errno;
- return ((-1 == op->result.code) &&
- (EWOULDBLOCK == op->syserrno || EAGAIN == op->syserrno)) ?
- PR_FALSE : PR_TRUE;
-} /* pt_recvfrom_cont */
-
-#ifdef AIX
-static PRBool pt_aix_sendfile_cont(pt_Continuation *op, PRInt16 revents)
-{
- struct sf_parms *sf_struct = (struct sf_parms *) op->arg2.buffer;
- ssize_t rv;
- unsigned long long saved_file_offset;
- long long saved_file_bytes;
-
- saved_file_offset = sf_struct->file_offset;
- saved_file_bytes = sf_struct->file_bytes;
- sf_struct->bytes_sent = 0;
-
- if ((sf_struct->file_bytes > 0) && (sf_struct->file_size > 0))
- PR_ASSERT((sf_struct->file_bytes + sf_struct->file_offset) <=
- sf_struct->file_size);
- rv = AIX_SEND_FILE(&op->arg1.osfd, sf_struct, op->arg4.flags);
- op->syserrno = errno;
-
- if (rv != -1) {
- op->result.code += sf_struct->bytes_sent;
- /*
- * A bug in AIX 4.3.2 prevents the 'file_bytes' field from
- * being updated. So, 'file_bytes' is maintained by NSPR to
- * avoid conflict when this bug is fixed in AIX, in the future.
- */
- if (saved_file_bytes != -1)
- saved_file_bytes -= (sf_struct->file_offset - saved_file_offset);
- sf_struct->file_bytes = saved_file_bytes;
- } else if (op->syserrno != EWOULDBLOCK && op->syserrno != EAGAIN) {
- op->result.code = -1;
- } else {
- return PR_FALSE;
- }
-
- if (rv == 1) { /* more data to send */
- return PR_FALSE;
- }
-
- return PR_TRUE;
-}
-#endif /* AIX */
-
-#ifdef HPUX11
-static PRBool pt_hpux_sendfile_cont(pt_Continuation *op, PRInt16 revents)
-{
- struct iovec *hdtrl = (struct iovec *) op->arg2.buffer;
- int count;
-
- count = sendfile(op->arg1.osfd, op->filedesc, op->arg3.file_spec.offset,
- op->arg3.file_spec.nbytes, hdtrl, op->arg4.flags);
- PR_ASSERT(count <= op->nbytes_to_send);
- op->syserrno = errno;
-
- if (count != -1) {
- op->result.code += count;
- } else if (op->syserrno != EWOULDBLOCK && op->syserrno != EAGAIN) {
- op->result.code = -1;
- } else {
- return PR_FALSE;
- }
- if (count != -1 && count < op->nbytes_to_send) {
- if (count < hdtrl[0].iov_len) {
- /* header not sent */
-
- hdtrl[0].iov_base = ((char *) hdtrl[0].iov_base) + count;
- hdtrl[0].iov_len -= count;
-
- } else if (count < (hdtrl[0].iov_len + op->arg3.file_spec.nbytes)) {
- /* header sent, file not sent */
- PRUint32 file_nbytes_sent = count - hdtrl[0].iov_len;
-
- hdtrl[0].iov_base = NULL;
- hdtrl[0].iov_len = 0;
-
- op->arg3.file_spec.offset += file_nbytes_sent;
- op->arg3.file_spec.nbytes -= file_nbytes_sent;
- } else if (count < (hdtrl[0].iov_len + op->arg3.file_spec.nbytes +
- hdtrl[1].iov_len)) {
- PRUint32 trailer_nbytes_sent = count - (hdtrl[0].iov_len +
- op->arg3.file_spec.nbytes);
-
- /* header sent, file sent, trailer not sent */
-
- hdtrl[0].iov_base = NULL;
- hdtrl[0].iov_len = 0;
- /*
- * set file offset and len so that no more file data is
- * sent
- */
- op->arg3.file_spec.offset = op->arg3.file_spec.st_size;
- op->arg3.file_spec.nbytes = 0;
-
- hdtrl[1].iov_base =((char *) hdtrl[1].iov_base)+ trailer_nbytes_sent;
- hdtrl[1].iov_len -= trailer_nbytes_sent;
- }
- op->nbytes_to_send -= count;
- return PR_FALSE;
- }
-
- return PR_TRUE;
-}
-#endif /* HPUX11 */
-
-#ifdef SOLARIS
-static PRBool pt_solaris_sendfile_cont(pt_Continuation *op, PRInt16 revents)
-{
- struct sendfilevec *vec = (struct sendfilevec *) op->arg2.buffer;
- size_t xferred;
- ssize_t count;
-
- count = SOLARIS_SENDFILEV(op->arg1.osfd, vec, op->arg3.amount, &xferred);
- op->syserrno = errno;
- PR_ASSERT((count == -1) || (count == xferred));
-
- if (count == -1) {
- if (op->syserrno != EWOULDBLOCK && op->syserrno != EAGAIN
- && op->syserrno != EINTR) {
- op->result.code = -1;
- return PR_TRUE;
- }
- count = xferred;
- } else if (count == 0) {
- /*
- * We are now at EOF. The file was truncated. Solaris sendfile is
- * supposed to return 0 and no error in this case, though some versions
- * may return -1 and EINVAL .
- */
- op->result.code = -1;
- op->syserrno = 0; /* will be treated as EOF */
- return PR_TRUE;
- }
- PR_ASSERT(count <= op->nbytes_to_send);
-
- op->result.code += count;
- if (count < op->nbytes_to_send) {
- op->nbytes_to_send -= count;
-
- while (count >= vec->sfv_len) {
- count -= vec->sfv_len;
- vec++;
- op->arg3.amount--;
- }
- PR_ASSERT(op->arg3.amount > 0);
-
- vec->sfv_off += count;
- vec->sfv_len -= count;
- PR_ASSERT(vec->sfv_len > 0);
- op->arg2.buffer = vec;
-
- return PR_FALSE;
- }
-
- return PR_TRUE;
-}
-#endif /* SOLARIS */
-
-#ifdef LINUX
-static PRBool pt_linux_sendfile_cont(pt_Continuation *op, PRInt16 revents)
-{
- ssize_t rv;
- off_t oldoffset;
-
- oldoffset = op->offset;
- rv = sendfile(op->arg1.osfd, op->in_fd, &op->offset, op->count);
- op->syserrno = errno;
-
- if (rv == -1) {
- if (op->syserrno != EWOULDBLOCK && op->syserrno != EAGAIN) {
- op->result.code = -1;
- return PR_TRUE;
- }
- rv = 0;
- }
- PR_ASSERT(rv == op->offset - oldoffset);
- op->result.code += rv;
- if (rv < op->count) {
- op->count -= rv;
- return PR_FALSE;
- }
- return PR_TRUE;
-}
-#endif /* LINUX */
-
-void _PR_InitIO(void)
-{
-#if defined(DEBUG)
- memset(&pt_debug, 0, sizeof(PTDebug));
- pt_debug.timeStarted = PR_Now();
-#endif
-
- _pr_flock_lock = PR_NewLock();
- PR_ASSERT(NULL != _pr_flock_lock);
- _pr_flock_cv = PR_NewCondVar(_pr_flock_lock);
- PR_ASSERT(NULL != _pr_flock_cv);
- _pr_rename_lock = PR_NewLock();
- PR_ASSERT(NULL != _pr_rename_lock);
-
- _PR_InitFdCache(); /* do that */
-
- _pr_stdin = pt_SetMethods(0, PR_DESC_FILE, PR_FALSE, PR_TRUE);
- _pr_stdout = pt_SetMethods(1, PR_DESC_FILE, PR_FALSE, PR_TRUE);
- _pr_stderr = pt_SetMethods(2, PR_DESC_FILE, PR_FALSE, PR_TRUE);
- PR_ASSERT(_pr_stdin && _pr_stdout && _pr_stderr);
-
-#ifdef _PR_IPV6_V6ONLY_PROBE
- /* In Mac OS X v10.3 Panther Beta the IPV6_V6ONLY socket option
- * is turned on by default, contrary to what RFC 3493, Section
- * 5.3 says. So we have to turn it off. Find out whether we
- * are running on such a system.
- */
- {
- int osfd;
- osfd = socket(AF_INET6, SOCK_STREAM, 0);
- if (osfd != -1) {
- int on;
- socklen_t optlen = sizeof(on);
- if (getsockopt(osfd, IPPROTO_IPV6, IPV6_V6ONLY,
- &on, &optlen) == 0) {
- _pr_ipv6_v6only_on_by_default = on;
- }
- close(osfd);
- }
- }
-#endif
-} /* _PR_InitIO */
-
-void _PR_CleanupIO(void)
-{
- _PR_Putfd(_pr_stdin);
- _pr_stdin = NULL;
- _PR_Putfd(_pr_stdout);
- _pr_stdout = NULL;
- _PR_Putfd(_pr_stderr);
- _pr_stderr = NULL;
-
- _PR_CleanupFdCache();
-
- if (_pr_flock_cv)
- {
- PR_DestroyCondVar(_pr_flock_cv);
- _pr_flock_cv = NULL;
- }
- if (_pr_flock_lock)
- {
- PR_DestroyLock(_pr_flock_lock);
- _pr_flock_lock = NULL;
- }
- if (_pr_rename_lock)
- {
- PR_DestroyLock(_pr_rename_lock);
- _pr_rename_lock = NULL;
- }
-} /* _PR_CleanupIO */
-
-PR_IMPLEMENT(PRFileDesc*) PR_GetSpecialFD(PRSpecialFD osfd)
-{
- PRFileDesc *result = NULL;
- PR_ASSERT(osfd >= PR_StandardInput && osfd <= PR_StandardError);
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- switch (osfd)
- {
- case PR_StandardInput: result = _pr_stdin; break;
- case PR_StandardOutput: result = _pr_stdout; break;
- case PR_StandardError: result = _pr_stderr; break;
- default:
- (void)PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- }
- return result;
-} /* PR_GetSpecialFD */
-
-/*****************************************************************************/
-/***************************** I/O private methods ***************************/
-/*****************************************************************************/
-
-static PRBool pt_TestAbort(void)
-{
- PRThread *me = PR_GetCurrentThread();
- if(_PT_THREAD_INTERRUPTED(me))
- {
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- me->state &= ~PT_THREAD_ABORTED;
- return PR_TRUE;
- }
- return PR_FALSE;
-} /* pt_TestAbort */
-
-static void pt_MapError(void (*mapper)(PRIntn), PRIntn syserrno)
-{
- switch (syserrno)
- {
- case EINTR:
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0); break;
- case ETIMEDOUT:
- PR_SetError(PR_IO_TIMEOUT_ERROR, 0); break;
- default:
- mapper(syserrno);
- }
-} /* pt_MapError */
-
-static PRStatus pt_Close(PRFileDesc *fd)
-{
- if ((NULL == fd) || (NULL == fd->secret)
- || ((_PR_FILEDESC_OPEN != fd->secret->state)
- && (_PR_FILEDESC_CLOSED != fd->secret->state)))
- {
- PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
- return PR_FAILURE;
- }
- if (pt_TestAbort()) return PR_FAILURE;
-
- if (_PR_FILEDESC_OPEN == fd->secret->state)
- {
- if (-1 == close(fd->secret->md.osfd))
- {
-#ifdef OSF1
- /*
- * Bug 86941: On Tru64 UNIX V5.0A and V5.1, the close()
- * system call, when called to close a TCP socket, may
- * return -1 with errno set to EINVAL but the system call
- * does close the socket successfully. An application
- * may safely ignore the EINVAL error. This bug is fixed
- * on Tru64 UNIX V5.1A and later. The defect tracking
- * number is QAR 81431.
- */
- if (PR_DESC_SOCKET_TCP != fd->methods->file_type
- || EINVAL != errno)
- {
- pt_MapError(_PR_MD_MAP_CLOSE_ERROR, errno);
- return PR_FAILURE;
- }
-#else
- pt_MapError(_PR_MD_MAP_CLOSE_ERROR, errno);
- return PR_FAILURE;
-#endif
- }
- fd->secret->state = _PR_FILEDESC_CLOSED;
- }
- _PR_Putfd(fd);
- return PR_SUCCESS;
-} /* pt_Close */
-
-static PRInt32 pt_Read(PRFileDesc *fd, void *buf, PRInt32 amount)
-{
- PRInt32 syserrno, bytes = -1;
-
- if (pt_TestAbort()) return bytes;
-
- bytes = read(fd->secret->md.osfd, buf, amount);
- syserrno = errno;
-
- if ((bytes == -1) && (syserrno == EWOULDBLOCK || syserrno == EAGAIN)
- && (!fd->secret->nonblocking))
- {
- pt_Continuation op;
- op.arg1.osfd = fd->secret->md.osfd;
- op.arg2.buffer = buf;
- op.arg3.amount = amount;
- op.timeout = PR_INTERVAL_NO_TIMEOUT;
- op.function = pt_read_cont;
- op.event = POLLIN | POLLPRI;
- bytes = pt_Continue(&op);
- syserrno = op.syserrno;
- }
- if (bytes < 0)
- pt_MapError(_PR_MD_MAP_READ_ERROR, syserrno);
- return bytes;
-} /* pt_Read */
-
-static PRInt32 pt_Write(PRFileDesc *fd, const void *buf, PRInt32 amount)
-{
- PRInt32 syserrno, bytes = -1;
- PRBool fNeedContinue = PR_FALSE;
-
- if (pt_TestAbort()) return bytes;
-
- bytes = write(fd->secret->md.osfd, buf, amount);
- syserrno = errno;
-
- if ( (bytes >= 0) && (bytes < amount) && (!fd->secret->nonblocking) )
- {
- buf = (char *) buf + bytes;
- amount -= bytes;
- fNeedContinue = PR_TRUE;
- }
- if ( (bytes == -1) && (syserrno == EWOULDBLOCK || syserrno == EAGAIN)
- && (!fd->secret->nonblocking) )
- {
- bytes = 0;
- fNeedContinue = PR_TRUE;
- }
-
- if (fNeedContinue == PR_TRUE)
- {
- pt_Continuation op;
- op.arg1.osfd = fd->secret->md.osfd;
- op.arg2.buffer = (void*)buf;
- op.arg3.amount = amount;
- op.timeout = PR_INTERVAL_NO_TIMEOUT;
- op.result.code = bytes; /* initialize the number sent */
- op.function = pt_write_cont;
- op.event = POLLOUT | POLLPRI;
- bytes = pt_Continue(&op);
- syserrno = op.syserrno;
- }
- if (bytes == -1)
- pt_MapError(_PR_MD_MAP_WRITE_ERROR, syserrno);
- return bytes;
-} /* pt_Write */
-
-static PRInt32 pt_Writev(
- PRFileDesc *fd, const PRIOVec *iov, PRInt32 iov_len, PRIntervalTime timeout)
-{
- PRIntn iov_index;
- PRBool fNeedContinue = PR_FALSE;
- PRInt32 syserrno, bytes, rv = -1;
- struct iovec osiov_local[PR_MAX_IOVECTOR_SIZE], *osiov;
- int osiov_len;
-
- if (pt_TestAbort()) return rv;
-
- /* Ensured by PR_Writev */
- PR_ASSERT(iov_len <= PR_MAX_IOVECTOR_SIZE);
-
- /*
- * We can't pass iov to writev because PRIOVec and struct iovec
- * may not be binary compatible. Make osiov a copy of iov and
- * pass osiov to writev. We can modify osiov if we need to
- * continue the operation.
- */
- osiov = osiov_local;
- osiov_len = iov_len;
- for (iov_index = 0; iov_index < osiov_len; iov_index++)
- {
- osiov[iov_index].iov_base = iov[iov_index].iov_base;
- osiov[iov_index].iov_len = iov[iov_index].iov_len;
- }
-
- rv = bytes = writev(fd->secret->md.osfd, osiov, osiov_len);
- syserrno = errno;
-
- if (!fd->secret->nonblocking)
- {
- if (bytes >= 0)
- {
- /*
- * If we moved some bytes, how does that implicate the
- * i/o vector list? In other words, exactly where are
- * we within that array? What are the parameters for
- * resumption? Maybe we're done!
- */
- for ( ;osiov_len > 0; osiov++, osiov_len--)
- {
- if (bytes < osiov->iov_len)
- {
- /* this one's not done yet */
- osiov->iov_base = (char*)osiov->iov_base + bytes;
- osiov->iov_len -= bytes;
- break; /* go off and do that */
- }
- bytes -= osiov->iov_len; /* this one's done cooked */
- }
- PR_ASSERT(osiov_len > 0 || bytes == 0);
- if (osiov_len > 0)
- {
- if (PR_INTERVAL_NO_WAIT == timeout)
- {
- rv = -1;
- syserrno = ETIMEDOUT;
- }
- else fNeedContinue = PR_TRUE;
- }
- }
- else if (syserrno == EWOULDBLOCK || syserrno == EAGAIN)
- {
- if (PR_INTERVAL_NO_WAIT == timeout) syserrno = ETIMEDOUT;
- else
- {
- rv = 0;
- fNeedContinue = PR_TRUE;
- }
- }
- }
-
- if (fNeedContinue == PR_TRUE)
- {
- pt_Continuation op;
-
- op.arg1.osfd = fd->secret->md.osfd;
- op.arg2.buffer = (void*)osiov;
- op.arg3.amount = osiov_len;
- op.timeout = timeout;
- op.result.code = rv;
- op.function = pt_writev_cont;
- op.event = POLLOUT | POLLPRI;
- rv = pt_Continue(&op);
- syserrno = op.syserrno;
- }
- if (rv == -1) pt_MapError(_PR_MD_MAP_WRITEV_ERROR, syserrno);
- return rv;
-} /* pt_Writev */
-
-static PRInt32 pt_Seek(PRFileDesc *fd, PRInt32 offset, PRSeekWhence whence)
-{
- return _PR_MD_LSEEK(fd, offset, whence);
-} /* pt_Seek */
-
-static PRInt64 pt_Seek64(PRFileDesc *fd, PRInt64 offset, PRSeekWhence whence)
-{
- return _PR_MD_LSEEK64(fd, offset, whence);
-} /* pt_Seek64 */
-
-static PRInt32 pt_Available_f(PRFileDesc *fd)
-{
- PRInt32 result, cur, end;
-
- cur = _PR_MD_LSEEK(fd, 0, PR_SEEK_CUR);
-
- if (cur >= 0)
- end = _PR_MD_LSEEK(fd, 0, PR_SEEK_END);
-
- if ((cur < 0) || (end < 0)) {
- return -1;
- }
-
- result = end - cur;
- _PR_MD_LSEEK(fd, cur, PR_SEEK_SET);
-
- return result;
-} /* pt_Available_f */
-
-static PRInt64 pt_Available64_f(PRFileDesc *fd)
-{
- PRInt64 result, cur, end;
- PRInt64 minus_one;
-
- LL_I2L(minus_one, -1);
- cur = _PR_MD_LSEEK64(fd, LL_ZERO, PR_SEEK_CUR);
-
- if (LL_GE_ZERO(cur))
- end = _PR_MD_LSEEK64(fd, LL_ZERO, PR_SEEK_END);
-
- if (!LL_GE_ZERO(cur) || !LL_GE_ZERO(end)) return minus_one;
-
- LL_SUB(result, end, cur);
- (void)_PR_MD_LSEEK64(fd, cur, PR_SEEK_SET);
-
- return result;
-} /* pt_Available64_f */
-
-static PRInt32 pt_Available_s(PRFileDesc *fd)
-{
- PRInt32 rv, bytes = -1;
- if (pt_TestAbort()) return bytes;
-
- rv = ioctl(fd->secret->md.osfd, FIONREAD, &bytes);
-
- if (rv == -1)
- pt_MapError(_PR_MD_MAP_SOCKETAVAILABLE_ERROR, errno);
- return bytes;
-} /* pt_Available_s */
-
-static PRInt64 pt_Available64_s(PRFileDesc *fd)
-{
- PRInt64 rv;
- LL_I2L(rv, pt_Available_s(fd));
- return rv;
-} /* pt_Available64_s */
-
-static PRStatus pt_FileInfo(PRFileDesc *fd, PRFileInfo *info)
-{
- PRInt32 rv = _PR_MD_GETOPENFILEINFO(fd, info);
- return (-1 == rv) ? PR_FAILURE : PR_SUCCESS;
-} /* pt_FileInfo */
-
-static PRStatus pt_FileInfo64(PRFileDesc *fd, PRFileInfo64 *info)
-{
- PRInt32 rv = _PR_MD_GETOPENFILEINFO64(fd, info);
- return (-1 == rv) ? PR_FAILURE : PR_SUCCESS;
-} /* pt_FileInfo64 */
-
-static PRStatus pt_Synch(PRFileDesc *fd)
-{
- return (NULL == fd) ? PR_FAILURE : PR_SUCCESS;
-} /* pt_Synch */
-
-static PRStatus pt_Fsync(PRFileDesc *fd)
-{
- PRIntn rv = -1;
- if (pt_TestAbort()) return PR_FAILURE;
-
- rv = fsync(fd->secret->md.osfd);
- if (rv < 0) {
- pt_MapError(_PR_MD_MAP_FSYNC_ERROR, errno);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-} /* pt_Fsync */
-
-static PRStatus pt_Connect(
- PRFileDesc *fd, const PRNetAddr *addr, PRIntervalTime timeout)
-{
- PRIntn rv = -1, syserrno;
- pt_SockLen addr_len;
- const PRNetAddr *addrp = addr;
-#if defined(_PR_HAVE_SOCKADDR_LEN) || defined(_PR_INET6)
- PRUint16 md_af = addr->raw.family;
- PRNetAddr addrCopy;
-#endif
-
- if (pt_TestAbort()) return PR_FAILURE;
-
- PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
- addr_len = PR_NETADDR_SIZE(addr);
-#if defined(_PR_INET6)
- if (addr->raw.family == PR_AF_INET6) {
- md_af = AF_INET6;
-#ifndef _PR_HAVE_SOCKADDR_LEN
- addrCopy = *addr;
- addrCopy.raw.family = AF_INET6;
- addrp = &addrCopy;
-#endif
- }
-#endif
-
-#ifdef _PR_HAVE_SOCKADDR_LEN
- addrCopy = *addr;
- ((struct sockaddr*)&addrCopy)->sa_len = addr_len;
- ((struct sockaddr*)&addrCopy)->sa_family = md_af;
- addrp = &addrCopy;
-#endif
- rv = connect(fd->secret->md.osfd, (struct sockaddr*)addrp, addr_len);
- syserrno = errno;
- if ((-1 == rv) && (EINPROGRESS == syserrno) && (!fd->secret->nonblocking))
- {
- if (PR_INTERVAL_NO_WAIT == timeout) syserrno = ETIMEDOUT;
- else
- {
- pt_Continuation op;
- op.arg1.osfd = fd->secret->md.osfd;
- op.arg2.buffer = (void*)addrp;
- op.arg3.amount = addr_len;
- op.timeout = timeout;
- op.function = pt_connect_cont;
- op.event = POLLOUT | POLLPRI;
- rv = pt_Continue(&op);
- syserrno = op.syserrno;
- }
- }
- if (-1 == rv) {
- pt_MapError(_PR_MD_MAP_CONNECT_ERROR, syserrno);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-} /* pt_Connect */
-
-static PRStatus pt_ConnectContinue(
- PRFileDesc *fd, PRInt16 out_flags)
-{
- int err;
- PRInt32 osfd;
-
- if (out_flags & PR_POLL_NVAL)
- {
- PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
- return PR_FAILURE;
- }
- if ((out_flags & (PR_POLL_WRITE | PR_POLL_EXCEPT | PR_POLL_ERR
- | PR_POLL_HUP)) == 0)
- {
- PR_ASSERT(out_flags == 0);
- PR_SetError(PR_IN_PROGRESS_ERROR, 0);
- return PR_FAILURE;
- }
-
- osfd = fd->secret->md.osfd;
-
- err = _MD_unix_get_nonblocking_connect_error(osfd);
- if (err != 0)
- {
- _PR_MD_MAP_CONNECT_ERROR(err);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-} /* pt_ConnectContinue */
-
-PR_IMPLEMENT(PRStatus) PR_GetConnectStatus(const PRPollDesc *pd)
-{
- /* Find the NSPR layer and invoke its connectcontinue method */
- PRFileDesc *bottom = PR_GetIdentitiesLayer(pd->fd, PR_NSPR_IO_LAYER);
-
- if (NULL == bottom)
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
- return pt_ConnectContinue(bottom, pd->out_flags);
-} /* PR_GetConnectStatus */
-
-static PRFileDesc* pt_Accept(
- PRFileDesc *fd, PRNetAddr *addr, PRIntervalTime timeout)
-{
- PRFileDesc *newfd = NULL;
- PRIntn syserrno, osfd = -1;
- pt_SockLen addr_len = sizeof(PRNetAddr);
-#ifdef SYMBIAN
- PRNetAddr dummy_addr;
-#endif
-
- if (pt_TestAbort()) return newfd;
-
-#ifdef SYMBIAN
- /* On Symbian OS, accept crashes if addr is NULL. */
- if (!addr)
- addr = &dummy_addr;
-#endif
-
-#ifdef _PR_STRICT_ADDR_LEN
- if (addr)
- {
- /*
- * Set addr->raw.family just so that we can use the
- * PR_NETADDR_SIZE macro.
- */
- addr->raw.family = fd->secret->af;
- addr_len = PR_NETADDR_SIZE(addr);
- }
-#endif
-
- osfd = accept(fd->secret->md.osfd, (struct sockaddr*)addr, &addr_len);
- syserrno = errno;
-
- if (osfd == -1)
- {
- if (fd->secret->nonblocking) goto failed;
-
- if (EWOULDBLOCK != syserrno && EAGAIN != syserrno
- && ECONNABORTED != syserrno)
- goto failed;
- else
- {
- if (PR_INTERVAL_NO_WAIT == timeout) syserrno = ETIMEDOUT;
- else
- {
- pt_Continuation op;
- op.arg1.osfd = fd->secret->md.osfd;
- op.arg2.buffer = addr;
- op.arg3.addr_len = &addr_len;
- op.timeout = timeout;
- op.function = pt_accept_cont;
- op.event = POLLIN | POLLPRI;
- osfd = pt_Continue(&op);
- syserrno = op.syserrno;
- }
- if (osfd < 0) goto failed;
- }
- }
-#ifdef _PR_HAVE_SOCKADDR_LEN
- /* ignore the sa_len field of struct sockaddr */
- if (addr)
- {
- addr->raw.family = ((struct sockaddr*)addr)->sa_family;
- }
-#endif /* _PR_HAVE_SOCKADDR_LEN */
-#ifdef _PR_INET6
- if (addr && (AF_INET6 == addr->raw.family))
- addr->raw.family = PR_AF_INET6;
-#endif
- newfd = pt_SetMethods(osfd, PR_DESC_SOCKET_TCP, PR_TRUE, PR_FALSE);
- if (newfd == NULL) close(osfd); /* $$$ whoops! this doesn't work $$$ */
- else
- {
- PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
- PR_ASSERT(IsValidNetAddrLen(addr, addr_len) == PR_TRUE);
-#ifdef LINUX
- /*
- * On Linux, experiments showed that the accepted sockets
- * inherit the TCP_NODELAY socket option of the listening
- * socket.
- */
- newfd->secret->md.tcp_nodelay = fd->secret->md.tcp_nodelay;
-#endif
- }
- return newfd;
-
-failed:
- pt_MapError(_PR_MD_MAP_ACCEPT_ERROR, syserrno);
- return NULL;
-} /* pt_Accept */
-
-static PRStatus pt_Bind(PRFileDesc *fd, const PRNetAddr *addr)
-{
- PRIntn rv;
- pt_SockLen addr_len;
- const PRNetAddr *addrp = addr;
-#if defined(_PR_HAVE_SOCKADDR_LEN) || defined(_PR_INET6)
- PRUint16 md_af = addr->raw.family;
- PRNetAddr addrCopy;
-#endif
-
- if (pt_TestAbort()) return PR_FAILURE;
-
- PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
- if (addr->raw.family == AF_UNIX)
- {
- /* Disallow relative pathnames */
- if (addr->local.path[0] != '/')
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
- }
-
-#if defined(_PR_INET6)
- if (addr->raw.family == PR_AF_INET6) {
- md_af = AF_INET6;
-#ifndef _PR_HAVE_SOCKADDR_LEN
- addrCopy = *addr;
- addrCopy.raw.family = AF_INET6;
- addrp = &addrCopy;
-#endif
- }
-#endif
-
- addr_len = PR_NETADDR_SIZE(addr);
-#ifdef _PR_HAVE_SOCKADDR_LEN
- addrCopy = *addr;
- ((struct sockaddr*)&addrCopy)->sa_len = addr_len;
- ((struct sockaddr*)&addrCopy)->sa_family = md_af;
- addrp = &addrCopy;
-#endif
- rv = bind(fd->secret->md.osfd, (struct sockaddr*)addrp, addr_len);
-
- if (rv == -1) {
- pt_MapError(_PR_MD_MAP_BIND_ERROR, errno);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-} /* pt_Bind */
-
-static PRStatus pt_Listen(PRFileDesc *fd, PRIntn backlog)
-{
- PRIntn rv;
-
- if (pt_TestAbort()) return PR_FAILURE;
-
- rv = listen(fd->secret->md.osfd, backlog);
- if (rv == -1) {
- pt_MapError(_PR_MD_MAP_LISTEN_ERROR, errno);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-} /* pt_Listen */
-
-static PRStatus pt_Shutdown(PRFileDesc *fd, PRIntn how)
-{
- PRIntn rv = -1;
- if (pt_TestAbort()) return PR_FAILURE;
-
- rv = shutdown(fd->secret->md.osfd, how);
-
- if (rv == -1) {
- pt_MapError(_PR_MD_MAP_SHUTDOWN_ERROR, errno);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-} /* pt_Shutdown */
-
-static PRInt16 pt_Poll(PRFileDesc *fd, PRInt16 in_flags, PRInt16 *out_flags)
-{
- *out_flags = 0;
- return in_flags;
-} /* pt_Poll */
-
-static PRInt32 pt_Recv(
- PRFileDesc *fd, void *buf, PRInt32 amount,
- PRIntn flags, PRIntervalTime timeout)
-{
- PRInt32 syserrno, bytes = -1;
- PRIntn osflags;
-
- if (0 == flags)
- osflags = 0;
- else if (PR_MSG_PEEK == flags)
- {
-#ifdef SYMBIAN
- /* MSG_PEEK doesn't work as expected. */
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return bytes;
-#else
- osflags = MSG_PEEK;
-#endif
- }
- else
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return bytes;
- }
-
- if (pt_TestAbort()) return bytes;
-
- /* recv() is a much slower call on pre-2.6 Solaris than read(). */
-#if defined(SOLARIS)
- if (0 == osflags)
- bytes = read(fd->secret->md.osfd, buf, amount);
- else
- bytes = recv(fd->secret->md.osfd, buf, amount, osflags);
-#else
- bytes = recv(fd->secret->md.osfd, buf, amount, osflags);
-#endif
- syserrno = errno;
-
- if ((bytes == -1) && (syserrno == EWOULDBLOCK || syserrno == EAGAIN)
- && (!fd->secret->nonblocking))
- {
- if (PR_INTERVAL_NO_WAIT == timeout) syserrno = ETIMEDOUT;
- else
- {
- pt_Continuation op;
- op.arg1.osfd = fd->secret->md.osfd;
- op.arg2.buffer = buf;
- op.arg3.amount = amount;
- op.arg4.flags = osflags;
- op.timeout = timeout;
- op.function = pt_recv_cont;
- op.event = POLLIN | POLLPRI;
- bytes = pt_Continue(&op);
- syserrno = op.syserrno;
- }
- }
- if (bytes < 0)
- pt_MapError(_PR_MD_MAP_RECV_ERROR, syserrno);
- return bytes;
-} /* pt_Recv */
-
-static PRInt32 pt_SocketRead(PRFileDesc *fd, void *buf, PRInt32 amount)
-{
- return pt_Recv(fd, buf, amount, 0, PR_INTERVAL_NO_TIMEOUT);
-} /* pt_SocketRead */
-
-static PRInt32 pt_Send(
- PRFileDesc *fd, const void *buf, PRInt32 amount,
- PRIntn flags, PRIntervalTime timeout)
-{
- PRInt32 syserrno, bytes = -1;
- PRBool fNeedContinue = PR_FALSE;
-#if defined(SOLARIS)
- PRInt32 tmp_amount = amount;
-#endif
-
- /*
- * Under HP-UX DCE threads, pthread.h includes dce/cma_ux.h,
- * which has the following:
- * # define send cma_send
- * extern int cma_send (int , void *, int, int );
- * So we need to cast away the 'const' of argument #2 for send().
- */
-#if defined (HPUX) && defined(_PR_DCETHREADS)
-#define PT_SENDBUF_CAST (void *)
-#else
-#define PT_SENDBUF_CAST
-#endif
-
- if (pt_TestAbort()) return bytes;
-
- /*
- * On pre-2.6 Solaris, send() is much slower than write().
- * On 2.6 and beyond, with in-kernel sockets, send() and
- * write() are fairly equivalent in performance.
- */
-#if defined(SOLARIS)
- PR_ASSERT(0 == flags);
-retry:
- bytes = write(fd->secret->md.osfd, PT_SENDBUF_CAST buf, tmp_amount);
-#else
- bytes = send(fd->secret->md.osfd, PT_SENDBUF_CAST buf, amount, flags);
-#endif
- syserrno = errno;
-
-#if defined(SOLARIS)
- /*
- * The write system call has been reported to return the ERANGE error
- * on occasion. Try to write in smaller chunks to workaround this bug.
- */
- if ((bytes == -1) && (syserrno == ERANGE))
- {
- if (tmp_amount > 1)
- {
- tmp_amount = tmp_amount/2; /* half the bytes */
- goto retry;
- }
- }
-#endif
-
- if ( (bytes >= 0) && (bytes < amount) && (!fd->secret->nonblocking) )
- {
- if (PR_INTERVAL_NO_WAIT == timeout)
- {
- bytes = -1;
- syserrno = ETIMEDOUT;
- }
- else
- {
- buf = (char *) buf + bytes;
- amount -= bytes;
- fNeedContinue = PR_TRUE;
- }
- }
- if ( (bytes == -1) && (syserrno == EWOULDBLOCK || syserrno == EAGAIN)
- && (!fd->secret->nonblocking) )
- {
- if (PR_INTERVAL_NO_WAIT == timeout) syserrno = ETIMEDOUT;
- else
- {
- bytes = 0;
- fNeedContinue = PR_TRUE;
- }
- }
-
- if (fNeedContinue == PR_TRUE)
- {
- pt_Continuation op;
- op.arg1.osfd = fd->secret->md.osfd;
- op.arg2.buffer = (void*)buf;
- op.arg3.amount = amount;
- op.arg4.flags = flags;
- op.timeout = timeout;
- op.result.code = bytes; /* initialize the number sent */
- op.function = pt_send_cont;
- op.event = POLLOUT | POLLPRI;
- bytes = pt_Continue(&op);
- syserrno = op.syserrno;
- }
- if (bytes == -1)
- pt_MapError(_PR_MD_MAP_SEND_ERROR, syserrno);
- return bytes;
-} /* pt_Send */
-
-static PRInt32 pt_SocketWrite(PRFileDesc *fd, const void *buf, PRInt32 amount)
-{
- return pt_Send(fd, buf, amount, 0, PR_INTERVAL_NO_TIMEOUT);
-} /* pt_SocketWrite */
-
-static PRInt32 pt_SendTo(
- PRFileDesc *fd, const void *buf,
- PRInt32 amount, PRIntn flags, const PRNetAddr *addr,
- PRIntervalTime timeout)
-{
- PRInt32 syserrno, bytes = -1;
- PRBool fNeedContinue = PR_FALSE;
- pt_SockLen addr_len;
- const PRNetAddr *addrp = addr;
-#if defined(_PR_HAVE_SOCKADDR_LEN) || defined(_PR_INET6)
- PRUint16 md_af = addr->raw.family;
- PRNetAddr addrCopy;
-#endif
-
- if (pt_TestAbort()) return bytes;
-
- PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
-#if defined(_PR_INET6)
- if (addr->raw.family == PR_AF_INET6) {
- md_af = AF_INET6;
-#ifndef _PR_HAVE_SOCKADDR_LEN
- addrCopy = *addr;
- addrCopy.raw.family = AF_INET6;
- addrp = &addrCopy;
-#endif
- }
-#endif
-
- addr_len = PR_NETADDR_SIZE(addr);
-#ifdef _PR_HAVE_SOCKADDR_LEN
- addrCopy = *addr;
- ((struct sockaddr*)&addrCopy)->sa_len = addr_len;
- ((struct sockaddr*)&addrCopy)->sa_family = md_af;
- addrp = &addrCopy;
-#endif
- bytes = sendto(
- fd->secret->md.osfd, buf, amount, flags,
- (struct sockaddr*)addrp, addr_len);
- syserrno = errno;
- if ( (bytes == -1) && (syserrno == EWOULDBLOCK || syserrno == EAGAIN)
- && (!fd->secret->nonblocking) )
- {
- if (PR_INTERVAL_NO_WAIT == timeout) syserrno = ETIMEDOUT;
- else fNeedContinue = PR_TRUE;
- }
- if (fNeedContinue == PR_TRUE)
- {
- pt_Continuation op;
- op.arg1.osfd = fd->secret->md.osfd;
- op.arg2.buffer = (void*)buf;
- op.arg3.amount = amount;
- op.arg4.flags = flags;
- op.arg5.addr = (PRNetAddr*)addrp;
- op.timeout = timeout;
- op.result.code = 0; /* initialize the number sent */
- op.function = pt_sendto_cont;
- op.event = POLLOUT | POLLPRI;
- bytes = pt_Continue(&op);
- syserrno = op.syserrno;
- }
- if (bytes < 0)
- pt_MapError(_PR_MD_MAP_SENDTO_ERROR, syserrno);
- return bytes;
-} /* pt_SendTo */
-
-static PRInt32 pt_RecvFrom(PRFileDesc *fd, void *buf, PRInt32 amount,
- PRIntn flags, PRNetAddr *addr, PRIntervalTime timeout)
-{
- PRBool fNeedContinue = PR_FALSE;
- PRInt32 syserrno, bytes = -1;
- pt_SockLen addr_len = sizeof(PRNetAddr);
-
- if (pt_TestAbort()) return bytes;
-
- bytes = recvfrom(
- fd->secret->md.osfd, buf, amount, flags,
- (struct sockaddr*)addr, &addr_len);
- syserrno = errno;
-
- if ( (bytes == -1) && (syserrno == EWOULDBLOCK || syserrno == EAGAIN)
- && (!fd->secret->nonblocking) )
- {
- if (PR_INTERVAL_NO_WAIT == timeout) syserrno = ETIMEDOUT;
- else fNeedContinue = PR_TRUE;
- }
-
- if (fNeedContinue == PR_TRUE)
- {
- pt_Continuation op;
- op.arg1.osfd = fd->secret->md.osfd;
- op.arg2.buffer = buf;
- op.arg3.amount = amount;
- op.arg4.flags = flags;
- op.arg5.addr = addr;
- op.timeout = timeout;
- op.function = pt_recvfrom_cont;
- op.event = POLLIN | POLLPRI;
- bytes = pt_Continue(&op);
- syserrno = op.syserrno;
- }
- if (bytes >= 0)
- {
-#ifdef _PR_HAVE_SOCKADDR_LEN
- /* ignore the sa_len field of struct sockaddr */
- if (addr)
- {
- addr->raw.family = ((struct sockaddr*)addr)->sa_family;
- }
-#endif /* _PR_HAVE_SOCKADDR_LEN */
-#ifdef _PR_INET6
- if (addr && (AF_INET6 == addr->raw.family))
- addr->raw.family = PR_AF_INET6;
-#endif
- }
- else
- pt_MapError(_PR_MD_MAP_RECVFROM_ERROR, syserrno);
- return bytes;
-} /* pt_RecvFrom */
-
-#ifdef AIX
-#ifndef HAVE_SEND_FILE
-static pthread_once_t pt_aix_sendfile_once_block = PTHREAD_ONCE_INIT;
-
-static void pt_aix_sendfile_init_routine(void)
-{
- void *handle = dlopen(NULL, RTLD_NOW | RTLD_GLOBAL);
- pt_aix_sendfile_fptr = (ssize_t (*)()) dlsym(handle, "send_file");
- dlclose(handle);
-}
-
-/*
- * pt_AIXDispatchSendFile
- */
-static PRInt32 pt_AIXDispatchSendFile(PRFileDesc *sd, PRSendFileData *sfd,
- PRTransmitFileFlags flags, PRIntervalTime timeout)
-{
- int rv;
-
- rv = pthread_once(&pt_aix_sendfile_once_block,
- pt_aix_sendfile_init_routine);
- PR_ASSERT(0 == rv);
- if (pt_aix_sendfile_fptr) {
- return pt_AIXSendFile(sd, sfd, flags, timeout);
- } else {
- return PR_EmulateSendFile(sd, sfd, flags, timeout);
- }
-}
-#endif /* !HAVE_SEND_FILE */
-
-
-/*
- * pt_AIXSendFile
- *
- * Send file sfd->fd across socket sd. If specified, header and trailer
- * buffers are sent before and after the file, respectively.
- *
- * PR_TRANSMITFILE_CLOSE_SOCKET flag - close socket after sending file
- *
- * return number of bytes sent or -1 on error
- *
- * This implementation takes advantage of the send_file() system
- * call available in AIX 4.3.2.
- */
-
-static PRInt32 pt_AIXSendFile(PRFileDesc *sd, PRSendFileData *sfd,
- PRTransmitFileFlags flags, PRIntervalTime timeout)
-{
- struct sf_parms sf_struct;
- uint_t send_flags;
- ssize_t rv;
- int syserrno;
- PRInt32 count;
- unsigned long long saved_file_offset;
- long long saved_file_bytes;
-
- sf_struct.header_data = (void *) sfd->header; /* cast away the 'const' */
- sf_struct.header_length = sfd->hlen;
- sf_struct.file_descriptor = sfd->fd->secret->md.osfd;
- sf_struct.file_size = 0;
- sf_struct.file_offset = sfd->file_offset;
- if (sfd->file_nbytes == 0)
- sf_struct.file_bytes = -1;
- else
- sf_struct.file_bytes = sfd->file_nbytes;
- sf_struct.trailer_data = (void *) sfd->trailer;
- sf_struct.trailer_length = sfd->tlen;
- sf_struct.bytes_sent = 0;
-
- saved_file_offset = sf_struct.file_offset;
- saved_file_bytes = sf_struct.file_bytes;
-
- send_flags = 0; /* flags processed at the end */
-
- /* The first argument to send_file() is int*. */
- PR_ASSERT(sizeof(int) == sizeof(sd->secret->md.osfd));
- do {
- rv = AIX_SEND_FILE(&sd->secret->md.osfd, &sf_struct, send_flags);
- } while (rv == -1 && (syserrno = errno) == EINTR);
-
- if (rv == -1) {
- if (syserrno == EAGAIN || syserrno == EWOULDBLOCK) {
- count = 0; /* Not a real error. Need to continue. */
- } else {
- count = -1;
- }
- } else {
- count = sf_struct.bytes_sent;
- /*
- * A bug in AIX 4.3.2 prevents the 'file_bytes' field from
- * being updated. So, 'file_bytes' is maintained by NSPR to
- * avoid conflict when this bug is fixed in AIX, in the future.
- */
- if (saved_file_bytes != -1)
- saved_file_bytes -= (sf_struct.file_offset - saved_file_offset);
- sf_struct.file_bytes = saved_file_bytes;
- }
-
- if ((rv == 1) || ((rv == -1) && (count == 0))) {
- pt_Continuation op;
-
- op.arg1.osfd = sd->secret->md.osfd;
- op.arg2.buffer = &sf_struct;
- op.arg4.flags = send_flags;
- op.result.code = count;
- op.timeout = timeout;
- op.function = pt_aix_sendfile_cont;
- op.event = POLLOUT | POLLPRI;
- count = pt_Continue(&op);
- syserrno = op.syserrno;
- }
-
- if (count == -1) {
- pt_MapError(_MD_aix_map_sendfile_error, syserrno);
- return -1;
- }
- if (flags & PR_TRANSMITFILE_CLOSE_SOCKET) {
- PR_Close(sd);
- }
- PR_ASSERT(count == (sfd->hlen + sfd->tlen +
- ((sfd->file_nbytes == 0) ?
- sf_struct.file_size - sfd->file_offset :
- sfd->file_nbytes)));
- return count;
-}
-#endif /* AIX */
-
-#ifdef HPUX11
-/*
- * pt_HPUXSendFile
- *
- * Send file sfd->fd across socket sd. If specified, header and trailer
- * buffers are sent before and after the file, respectively.
- *
- * PR_TRANSMITFILE_CLOSE_SOCKET flag - close socket after sending file
- *
- * return number of bytes sent or -1 on error
- *
- * This implementation takes advantage of the sendfile() system
- * call available in HP-UX B.11.00.
- */
-
-static PRInt32 pt_HPUXSendFile(PRFileDesc *sd, PRSendFileData *sfd,
- PRTransmitFileFlags flags, PRIntervalTime timeout)
-{
- struct stat statbuf;
- size_t nbytes_to_send, file_nbytes_to_send;
- struct iovec hdtrl[2]; /* optional header and trailer buffers */
- int send_flags;
- PRInt32 count;
- int syserrno;
-
- if (sfd->file_nbytes == 0) {
- /* Get file size */
- if (fstat(sfd->fd->secret->md.osfd, &statbuf) == -1) {
- _PR_MD_MAP_FSTAT_ERROR(errno);
- return -1;
- }
- file_nbytes_to_send = statbuf.st_size - sfd->file_offset;
- } else {
- file_nbytes_to_send = sfd->file_nbytes;
- }
- nbytes_to_send = sfd->hlen + sfd->tlen + file_nbytes_to_send;
-
- hdtrl[0].iov_base = (void *) sfd->header; /* cast away the 'const' */
- hdtrl[0].iov_len = sfd->hlen;
- hdtrl[1].iov_base = (void *) sfd->trailer;
- hdtrl[1].iov_len = sfd->tlen;
- /*
- * SF_DISCONNECT seems to close the socket even if sendfile()
- * only does a partial send on a nonblocking socket. This
- * would prevent the subsequent sendfile() calls on that socket
- * from working. So we don't use the SD_DISCONNECT flag.
- */
- send_flags = 0;
-
- do {
- count = sendfile(sd->secret->md.osfd, sfd->fd->secret->md.osfd,
- sfd->file_offset, file_nbytes_to_send, hdtrl, send_flags);
- } while (count == -1 && (syserrno = errno) == EINTR);
-
- if (count == -1 && (syserrno == EAGAIN || syserrno == EWOULDBLOCK)) {
- count = 0;
- }
- if (count != -1 && count < nbytes_to_send) {
- pt_Continuation op;
-
- if (count < sfd->hlen) {
- /* header not sent */
-
- hdtrl[0].iov_base = ((char *) sfd->header) + count;
- hdtrl[0].iov_len = sfd->hlen - count;
- op.arg3.file_spec.offset = sfd->file_offset;
- op.arg3.file_spec.nbytes = file_nbytes_to_send;
- } else if (count < (sfd->hlen + file_nbytes_to_send)) {
- /* header sent, file not sent */
-
- hdtrl[0].iov_base = NULL;
- hdtrl[0].iov_len = 0;
-
- op.arg3.file_spec.offset = sfd->file_offset + count - sfd->hlen;
- op.arg3.file_spec.nbytes = file_nbytes_to_send - (count - sfd->hlen);
- } else if (count < (sfd->hlen + file_nbytes_to_send + sfd->tlen)) {
- PRUint32 trailer_nbytes_sent;
-
- /* header sent, file sent, trailer not sent */
-
- hdtrl[0].iov_base = NULL;
- hdtrl[0].iov_len = 0;
- /*
- * set file offset and len so that no more file data is
- * sent
- */
- op.arg3.file_spec.offset = statbuf.st_size;
- op.arg3.file_spec.nbytes = 0;
-
- trailer_nbytes_sent = count - sfd->hlen - file_nbytes_to_send;
- hdtrl[1].iov_base = ((char *) sfd->trailer) + trailer_nbytes_sent;
- hdtrl[1].iov_len = sfd->tlen - trailer_nbytes_sent;
- }
-
- op.arg1.osfd = sd->secret->md.osfd;
- op.filedesc = sfd->fd->secret->md.osfd;
- op.arg2.buffer = hdtrl;
- op.arg3.file_spec.st_size = statbuf.st_size;
- op.arg4.flags = send_flags;
- op.nbytes_to_send = nbytes_to_send - count;
- op.result.code = count;
- op.timeout = timeout;
- op.function = pt_hpux_sendfile_cont;
- op.event = POLLOUT | POLLPRI;
- count = pt_Continue(&op);
- syserrno = op.syserrno;
- }
-
- if (count == -1) {
- pt_MapError(_MD_hpux_map_sendfile_error, syserrno);
- return -1;
- }
- if (flags & PR_TRANSMITFILE_CLOSE_SOCKET) {
- PR_Close(sd);
- }
- PR_ASSERT(count == nbytes_to_send);
- return count;
-}
-
-#endif /* HPUX11 */
-
-#ifdef SOLARIS
-
-/*
- * pt_SolarisSendFile
- *
- * Send file sfd->fd across socket sd. If specified, header and trailer
- * buffers are sent before and after the file, respectively.
- *
- * PR_TRANSMITFILE_CLOSE_SOCKET flag - close socket after sending file
- *
- * return number of bytes sent or -1 on error
- *
- * This implementation takes advantage of the sendfilev() system
- * call available in Solaris 8.
- */
-
-static PRInt32 pt_SolarisSendFile(PRFileDesc *sd, PRSendFileData *sfd,
- PRTransmitFileFlags flags, PRIntervalTime timeout)
-{
- struct stat statbuf;
- size_t nbytes_to_send, file_nbytes_to_send;
- struct sendfilevec sfv_struct[3];
- int sfvcnt = 0;
- size_t xferred;
- PRInt32 count;
- int syserrno;
-
- if (sfd->file_nbytes == 0) {
- /* Get file size */
- if (fstat(sfd->fd->secret->md.osfd, &statbuf) == -1) {
- _PR_MD_MAP_FSTAT_ERROR(errno);
- return -1;
- }
- file_nbytes_to_send = statbuf.st_size - sfd->file_offset;
- } else {
- file_nbytes_to_send = sfd->file_nbytes;
- }
-
- nbytes_to_send = sfd->hlen + sfd->tlen + file_nbytes_to_send;
-
- if (sfd->hlen != 0) {
- sfv_struct[sfvcnt].sfv_fd = SFV_FD_SELF;
- sfv_struct[sfvcnt].sfv_flag = 0;
- sfv_struct[sfvcnt].sfv_off = (off_t) sfd->header;
- sfv_struct[sfvcnt].sfv_len = sfd->hlen;
- sfvcnt++;
- }
-
- if (file_nbytes_to_send != 0) {
- sfv_struct[sfvcnt].sfv_fd = sfd->fd->secret->md.osfd;
- sfv_struct[sfvcnt].sfv_flag = 0;
- sfv_struct[sfvcnt].sfv_off = sfd->file_offset;
- sfv_struct[sfvcnt].sfv_len = file_nbytes_to_send;
- sfvcnt++;
- }
-
- if (sfd->tlen != 0) {
- sfv_struct[sfvcnt].sfv_fd = SFV_FD_SELF;
- sfv_struct[sfvcnt].sfv_flag = 0;
- sfv_struct[sfvcnt].sfv_off = (off_t) sfd->trailer;
- sfv_struct[sfvcnt].sfv_len = sfd->tlen;
- sfvcnt++;
- }
-
- if (0 == sfvcnt) {
- count = 0;
- goto done;
- }
-
- /*
- * Strictly speaking, we may have sent some bytes when the
- * sendfilev() is interrupted and we should retry it from an
- * updated offset. We are not doing that here.
- */
- count = SOLARIS_SENDFILEV(sd->secret->md.osfd, sfv_struct,
- sfvcnt, &xferred);
-
- PR_ASSERT((count == -1) || (count == xferred));
-
- if (count == -1) {
- syserrno = errno;
- if (syserrno == EINTR
- || syserrno == EAGAIN || syserrno == EWOULDBLOCK) {
- count = xferred;
- }
- } else if (count == 0) {
- /*
- * We are now at EOF. The file was truncated. Solaris sendfile is
- * supposed to return 0 and no error in this case, though some versions
- * may return -1 and EINVAL .
- */
- count = -1;
- syserrno = 0; /* will be treated as EOF */
- }
-
- if (count != -1 && count < nbytes_to_send) {
- pt_Continuation op;
- struct sendfilevec *vec = sfv_struct;
- PRInt32 rem = count;
-
- while (rem >= vec->sfv_len) {
- rem -= vec->sfv_len;
- vec++;
- sfvcnt--;
- }
- PR_ASSERT(sfvcnt > 0);
-
- vec->sfv_off += rem;
- vec->sfv_len -= rem;
- PR_ASSERT(vec->sfv_len > 0);
-
- op.arg1.osfd = sd->secret->md.osfd;
- op.arg2.buffer = vec;
- op.arg3.amount = sfvcnt;
- op.arg4.flags = 0;
- op.nbytes_to_send = nbytes_to_send - count;
- op.result.code = count;
- op.timeout = timeout;
- op.function = pt_solaris_sendfile_cont;
- op.event = POLLOUT | POLLPRI;
- count = pt_Continue(&op);
- syserrno = op.syserrno;
- }
-
-done:
- if (count == -1) {
- pt_MapError(_MD_solaris_map_sendfile_error, syserrno);
- return -1;
- }
- if (flags & PR_TRANSMITFILE_CLOSE_SOCKET) {
- PR_Close(sd);
- }
- PR_ASSERT(count == nbytes_to_send);
- return count;
-}
-
-#ifndef HAVE_SENDFILEV
-static pthread_once_t pt_solaris_sendfilev_once_block = PTHREAD_ONCE_INIT;
-
-static void pt_solaris_sendfilev_init_routine(void)
-{
- void *handle;
- PRBool close_it = PR_FALSE;
-
- /*
- * We do not want to unload libsendfile.so. This handle is leaked
- * intentionally.
- */
- handle = dlopen("libsendfile.so", RTLD_LAZY | RTLD_GLOBAL);
- PR_LOG(_pr_io_lm, PR_LOG_DEBUG,
- ("dlopen(libsendfile.so) returns %p", handle));
-
- if (NULL == handle) {
- /*
- * The dlopen(0, mode) call is to allow for the possibility that
- * sendfilev() may become part of a standard system library in a
- * future Solaris release.
- */
- handle = dlopen(0, RTLD_LAZY | RTLD_GLOBAL);
- PR_LOG(_pr_io_lm, PR_LOG_DEBUG,
- ("dlopen(0) returns %p", handle));
- close_it = PR_TRUE;
- }
- pt_solaris_sendfilev_fptr = (ssize_t (*)()) dlsym(handle, "sendfilev");
- PR_LOG(_pr_io_lm, PR_LOG_DEBUG,
- ("dlsym(sendfilev) returns %p", pt_solaris_sendfilev_fptr));
-
- if (close_it) {
- dlclose(handle);
- }
-}
-
-/*
- * pt_SolarisDispatchSendFile
- */
-static PRInt32 pt_SolarisDispatchSendFile(PRFileDesc *sd, PRSendFileData *sfd,
- PRTransmitFileFlags flags, PRIntervalTime timeout)
-{
- int rv;
-
- rv = pthread_once(&pt_solaris_sendfilev_once_block,
- pt_solaris_sendfilev_init_routine);
- PR_ASSERT(0 == rv);
- if (pt_solaris_sendfilev_fptr) {
- return pt_SolarisSendFile(sd, sfd, flags, timeout);
- } else {
- return PR_EmulateSendFile(sd, sfd, flags, timeout);
- }
-}
-#endif /* !HAVE_SENDFILEV */
-
-#endif /* SOLARIS */
-
-#ifdef LINUX
-/*
- * pt_LinuxSendFile
- *
- * Send file sfd->fd across socket sd. If specified, header and trailer
- * buffers are sent before and after the file, respectively.
- *
- * PR_TRANSMITFILE_CLOSE_SOCKET flag - close socket after sending file
- *
- * return number of bytes sent or -1 on error
- *
- * This implementation takes advantage of the sendfile() system
- * call available in Linux kernel 2.2 or higher.
- */
-
-static PRInt32 pt_LinuxSendFile(PRFileDesc *sd, PRSendFileData *sfd,
- PRTransmitFileFlags flags, PRIntervalTime timeout)
-{
- struct stat statbuf;
- size_t file_nbytes_to_send;
- PRInt32 count = 0;
- ssize_t rv;
- int syserrno;
- off_t offset;
- PRBool tcp_cork_enabled = PR_FALSE;
- int tcp_cork;
-
- if (sfd->file_nbytes == 0) {
- /* Get file size */
- if (fstat(sfd->fd->secret->md.osfd, &statbuf) == -1) {
- _PR_MD_MAP_FSTAT_ERROR(errno);
- return -1;
- }
- file_nbytes_to_send = statbuf.st_size - sfd->file_offset;
- } else {
- file_nbytes_to_send = sfd->file_nbytes;
- }
-
- if ((sfd->hlen != 0 || sfd->tlen != 0)
- && sd->secret->md.tcp_nodelay == 0) {
- tcp_cork = 1;
- if (setsockopt(sd->secret->md.osfd, SOL_TCP, TCP_CORK,
- &tcp_cork, sizeof tcp_cork) == 0) {
- tcp_cork_enabled = PR_TRUE;
- } else {
- syserrno = errno;
- if (syserrno != EINVAL) {
- _PR_MD_MAP_SETSOCKOPT_ERROR(syserrno);
- return -1;
- }
- /*
- * The most likely reason for the EINVAL error is that
- * TCP_NODELAY is set (with a function other than
- * PR_SetSocketOption). This is not fatal, so we keep
- * on going.
- */
- PR_LOG(_pr_io_lm, PR_LOG_WARNING,
- ("pt_LinuxSendFile: "
- "setsockopt(TCP_CORK) failed with EINVAL\n"));
- }
- }
-
- if (sfd->hlen != 0) {
- count = PR_Send(sd, sfd->header, sfd->hlen, 0, timeout);
- if (count == -1) {
- goto failed;
- }
- }
-
- if (file_nbytes_to_send != 0) {
- offset = sfd->file_offset;
- do {
- rv = sendfile(sd->secret->md.osfd, sfd->fd->secret->md.osfd,
- &offset, file_nbytes_to_send);
- } while (rv == -1 && (syserrno = errno) == EINTR);
- if (rv == -1) {
- if (syserrno != EAGAIN && syserrno != EWOULDBLOCK) {
- _MD_linux_map_sendfile_error(syserrno);
- count = -1;
- goto failed;
- }
- rv = 0;
- }
- PR_ASSERT(rv == offset - sfd->file_offset);
- count += rv;
-
- if (rv < file_nbytes_to_send) {
- pt_Continuation op;
-
- op.arg1.osfd = sd->secret->md.osfd;
- op.in_fd = sfd->fd->secret->md.osfd;
- op.offset = offset;
- op.count = file_nbytes_to_send - rv;
- op.result.code = count;
- op.timeout = timeout;
- op.function = pt_linux_sendfile_cont;
- op.event = POLLOUT | POLLPRI;
- count = pt_Continue(&op);
- syserrno = op.syserrno;
- if (count == -1) {
- pt_MapError(_MD_linux_map_sendfile_error, syserrno);
- goto failed;
- }
- }
- }
-
- if (sfd->tlen != 0) {
- rv = PR_Send(sd, sfd->trailer, sfd->tlen, 0, timeout);
- if (rv == -1) {
- count = -1;
- goto failed;
- }
- count += rv;
- }
-
-failed:
- if (tcp_cork_enabled) {
- tcp_cork = 0;
- if (setsockopt(sd->secret->md.osfd, SOL_TCP, TCP_CORK,
- &tcp_cork, sizeof tcp_cork) == -1 && count != -1) {
- _PR_MD_MAP_SETSOCKOPT_ERROR(errno);
- count = -1;
- }
- }
- if (count != -1) {
- if (flags & PR_TRANSMITFILE_CLOSE_SOCKET) {
- PR_Close(sd);
- }
- PR_ASSERT(count == sfd->hlen + sfd->tlen + file_nbytes_to_send);
- }
- return count;
-}
-#endif /* LINUX */
-
-#ifdef AIX
-extern int _pr_aix_send_file_use_disabled;
-#endif
-
-static PRInt32 pt_SendFile(
- PRFileDesc *sd, PRSendFileData *sfd,
- PRTransmitFileFlags flags, PRIntervalTime timeout)
-{
- if (pt_TestAbort()) return -1;
- /* The socket must be in blocking mode. */
- if (sd->secret->nonblocking)
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return -1;
- }
-#ifdef HPUX11
- return(pt_HPUXSendFile(sd, sfd, flags, timeout));
-#elif defined(AIX)
-#ifdef HAVE_SEND_FILE
- /*
- * A bug in AIX 4.3.2 results in corruption of data transferred by
- * send_file(); AIX patch PTF U463956 contains the fix. A user can
- * disable the use of send_file function in NSPR, when this patch is
- * not installed on the system, by setting the envionment variable
- * NSPR_AIX_SEND_FILE_USE_DISABLED to 1.
- */
- if (_pr_aix_send_file_use_disabled)
- return(PR_EmulateSendFile(sd, sfd, flags, timeout));
- else
- return(pt_AIXSendFile(sd, sfd, flags, timeout));
-#else
- return(PR_EmulateSendFile(sd, sfd, flags, timeout));
- /* return(pt_AIXDispatchSendFile(sd, sfd, flags, timeout));*/
-#endif /* HAVE_SEND_FILE */
-#elif defined(SOLARIS)
-#ifdef HAVE_SENDFILEV
- return(pt_SolarisSendFile(sd, sfd, flags, timeout));
-#else
- return(pt_SolarisDispatchSendFile(sd, sfd, flags, timeout));
-#endif /* HAVE_SENDFILEV */
-#elif defined(LINUX)
- return(pt_LinuxSendFile(sd, sfd, flags, timeout));
-#else
- return(PR_EmulateSendFile(sd, sfd, flags, timeout));
-#endif
-}
-
-static PRInt32 pt_TransmitFile(
- PRFileDesc *sd, PRFileDesc *fd, const void *headers,
- PRInt32 hlen, PRTransmitFileFlags flags, PRIntervalTime timeout)
-{
- PRSendFileData sfd;
-
- sfd.fd = fd;
- sfd.file_offset = 0;
- sfd.file_nbytes = 0;
- sfd.header = headers;
- sfd.hlen = hlen;
- sfd.trailer = NULL;
- sfd.tlen = 0;
-
- return(pt_SendFile(sd, &sfd, flags, timeout));
-} /* pt_TransmitFile */
-
-static PRInt32 pt_AcceptRead(
- PRFileDesc *sd, PRFileDesc **nd, PRNetAddr **raddr,
- void *buf, PRInt32 amount, PRIntervalTime timeout)
-{
- PRInt32 rv = -1;
-
- if (pt_TestAbort()) return rv;
- /* The socket must be in blocking mode. */
- if (sd->secret->nonblocking)
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return rv;
- }
-
- rv = PR_EmulateAcceptRead(sd, nd, raddr, buf, amount, timeout);
- return rv;
-} /* pt_AcceptRead */
-
-static PRStatus pt_GetSockName(PRFileDesc *fd, PRNetAddr *addr)
-{
- PRIntn rv = -1;
- pt_SockLen addr_len = sizeof(PRNetAddr);
-
- if (pt_TestAbort()) return PR_FAILURE;
-
- rv = getsockname(
- fd->secret->md.osfd, (struct sockaddr*)addr, &addr_len);
- if (rv == -1) {
- pt_MapError(_PR_MD_MAP_GETSOCKNAME_ERROR, errno);
- return PR_FAILURE;
- } else {
-#ifdef _PR_HAVE_SOCKADDR_LEN
- /* ignore the sa_len field of struct sockaddr */
- if (addr)
- {
- addr->raw.family = ((struct sockaddr*)addr)->sa_family;
- }
-#endif /* _PR_HAVE_SOCKADDR_LEN */
-#ifdef _PR_INET6
- if (AF_INET6 == addr->raw.family)
- addr->raw.family = PR_AF_INET6;
-#endif
- PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
- PR_ASSERT(IsValidNetAddrLen(addr, addr_len) == PR_TRUE);
- return PR_SUCCESS;
- }
-} /* pt_GetSockName */
-
-static PRStatus pt_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
-{
- PRIntn rv = -1;
- pt_SockLen addr_len = sizeof(PRNetAddr);
-
- if (pt_TestAbort()) return PR_FAILURE;
-
- rv = getpeername(
- fd->secret->md.osfd, (struct sockaddr*)addr, &addr_len);
-
- if (rv == -1) {
- pt_MapError(_PR_MD_MAP_GETPEERNAME_ERROR, errno);
- return PR_FAILURE;
- } else {
-#ifdef _PR_HAVE_SOCKADDR_LEN
- /* ignore the sa_len field of struct sockaddr */
- if (addr)
- {
- addr->raw.family = ((struct sockaddr*)addr)->sa_family;
- }
-#endif /* _PR_HAVE_SOCKADDR_LEN */
-#ifdef _PR_INET6
- if (AF_INET6 == addr->raw.family)
- addr->raw.family = PR_AF_INET6;
-#endif
- PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
- PR_ASSERT(IsValidNetAddrLen(addr, addr_len) == PR_TRUE);
- return PR_SUCCESS;
- }
-} /* pt_GetPeerName */
-
-static PRStatus pt_GetSocketOption(PRFileDesc *fd, PRSocketOptionData *data)
-{
- PRIntn rv;
- pt_SockLen length;
- PRInt32 level, name;
-
- /*
- * PR_SockOpt_Nonblocking is a special case that does not
- * translate to a getsockopt() call
- */
- if (PR_SockOpt_Nonblocking == data->option)
- {
- data->value.non_blocking = fd->secret->nonblocking;
- return PR_SUCCESS;
- }
-
- rv = _PR_MapOptionName(data->option, &level, &name);
- if (PR_SUCCESS == rv)
- {
- switch (data->option)
- {
- case PR_SockOpt_Linger:
- {
- struct linger linger;
- length = sizeof(linger);
- rv = getsockopt(
- fd->secret->md.osfd, level, name, (char *) &linger, &length);
- PR_ASSERT((-1 == rv) || (sizeof(linger) == length));
- data->value.linger.polarity =
- (linger.l_onoff) ? PR_TRUE : PR_FALSE;
- data->value.linger.linger =
- PR_SecondsToInterval(linger.l_linger);
- break;
- }
- case PR_SockOpt_Reuseaddr:
- case PR_SockOpt_Keepalive:
- case PR_SockOpt_NoDelay:
- case PR_SockOpt_Broadcast:
- case PR_SockOpt_Reuseport:
- {
- PRIntn value;
- length = sizeof(PRIntn);
- rv = getsockopt(
- fd->secret->md.osfd, level, name, (char*)&value, &length);
- PR_ASSERT((-1 == rv) || (sizeof(PRIntn) == length));
- data->value.reuse_addr = (0 == value) ? PR_FALSE : PR_TRUE;
- break;
- }
- case PR_SockOpt_McastLoopback:
- {
- PRUint8 xbool;
- length = sizeof(xbool);
- rv = getsockopt(
- fd->secret->md.osfd, level, name,
- (char*)&xbool, &length);
- PR_ASSERT((-1 == rv) || (sizeof(xbool) == length));
- data->value.mcast_loopback = (0 == xbool) ? PR_FALSE : PR_TRUE;
- break;
- }
- case PR_SockOpt_RecvBufferSize:
- case PR_SockOpt_SendBufferSize:
- case PR_SockOpt_MaxSegment:
- {
- PRIntn value;
- length = sizeof(PRIntn);
- rv = getsockopt(
- fd->secret->md.osfd, level, name, (char*)&value, &length);
- PR_ASSERT((-1 == rv) || (sizeof(PRIntn) == length));
- data->value.recv_buffer_size = value;
- break;
- }
- case PR_SockOpt_IpTimeToLive:
- case PR_SockOpt_IpTypeOfService:
- {
- length = sizeof(PRUintn);
- rv = getsockopt(
- fd->secret->md.osfd, level, name,
- (char*)&data->value.ip_ttl, &length);
- PR_ASSERT((-1 == rv) || (sizeof(PRIntn) == length));
- break;
- }
- case PR_SockOpt_McastTimeToLive:
- {
- PRUint8 ttl;
- length = sizeof(ttl);
- rv = getsockopt(
- fd->secret->md.osfd, level, name,
- (char*)&ttl, &length);
- PR_ASSERT((-1 == rv) || (sizeof(ttl) == length));
- data->value.mcast_ttl = ttl;
- break;
- }
- case PR_SockOpt_AddMember:
- case PR_SockOpt_DropMember:
- {
- struct ip_mreq mreq;
- length = sizeof(mreq);
- rv = getsockopt(
- fd->secret->md.osfd, level, name, (char*)&mreq, &length);
- PR_ASSERT((-1 == rv) || (sizeof(mreq) == length));
- data->value.add_member.mcaddr.inet.ip =
- mreq.imr_multiaddr.s_addr;
- data->value.add_member.ifaddr.inet.ip =
- mreq.imr_interface.s_addr;
- break;
- }
- case PR_SockOpt_McastInterface:
- {
- length = sizeof(data->value.mcast_if.inet.ip);
- rv = getsockopt(
- fd->secret->md.osfd, level, name,
- (char*)&data->value.mcast_if.inet.ip, &length);
- PR_ASSERT((-1 == rv)
- || (sizeof(data->value.mcast_if.inet.ip) == length));
- break;
- }
- default:
- PR_NOT_REACHED("Unknown socket option");
- break;
- }
- if (-1 == rv) _PR_MD_MAP_GETSOCKOPT_ERROR(errno);
- }
- return (-1 == rv) ? PR_FAILURE : PR_SUCCESS;
-} /* pt_GetSocketOption */
-
-static PRStatus pt_SetSocketOption(PRFileDesc *fd, const PRSocketOptionData *data)
-{
- PRIntn rv;
- PRInt32 level, name;
-
- /*
- * PR_SockOpt_Nonblocking is a special case that does not
- * translate to a setsockopt call.
- */
- if (PR_SockOpt_Nonblocking == data->option)
- {
- fd->secret->nonblocking = data->value.non_blocking;
- return PR_SUCCESS;
- }
-
- rv = _PR_MapOptionName(data->option, &level, &name);
- if (PR_SUCCESS == rv)
- {
- switch (data->option)
- {
- case PR_SockOpt_Linger:
- {
- struct linger linger;
- linger.l_onoff = data->value.linger.polarity;
- linger.l_linger = PR_IntervalToSeconds(data->value.linger.linger);
- rv = setsockopt(
- fd->secret->md.osfd, level, name, (char*)&linger, sizeof(linger));
- break;
- }
- case PR_SockOpt_Reuseaddr:
- case PR_SockOpt_Keepalive:
- case PR_SockOpt_NoDelay:
- case PR_SockOpt_Broadcast:
- case PR_SockOpt_Reuseport:
- {
- PRIntn value = (data->value.reuse_addr) ? 1 : 0;
- rv = setsockopt(
- fd->secret->md.osfd, level, name,
- (char*)&value, sizeof(PRIntn));
-#ifdef LINUX
- /* for pt_LinuxSendFile */
- if (name == TCP_NODELAY && rv == 0) {
- fd->secret->md.tcp_nodelay = value;
- }
-#endif
- break;
- }
- case PR_SockOpt_McastLoopback:
- {
- PRUint8 xbool = data->value.mcast_loopback ? 1 : 0;
- rv = setsockopt(
- fd->secret->md.osfd, level, name,
- (char*)&xbool, sizeof(xbool));
- break;
- }
- case PR_SockOpt_RecvBufferSize:
- case PR_SockOpt_SendBufferSize:
- case PR_SockOpt_MaxSegment:
- {
- PRIntn value = data->value.recv_buffer_size;
- rv = setsockopt(
- fd->secret->md.osfd, level, name,
- (char*)&value, sizeof(PRIntn));
- break;
- }
- case PR_SockOpt_IpTimeToLive:
- case PR_SockOpt_IpTypeOfService:
- {
- rv = setsockopt(
- fd->secret->md.osfd, level, name,
- (char*)&data->value.ip_ttl, sizeof(PRUintn));
- break;
- }
- case PR_SockOpt_McastTimeToLive:
- {
- PRUint8 ttl = data->value.mcast_ttl;
- rv = setsockopt(
- fd->secret->md.osfd, level, name,
- (char*)&ttl, sizeof(ttl));
- break;
- }
- case PR_SockOpt_AddMember:
- case PR_SockOpt_DropMember:
- {
- struct ip_mreq mreq;
- mreq.imr_multiaddr.s_addr =
- data->value.add_member.mcaddr.inet.ip;
- mreq.imr_interface.s_addr =
- data->value.add_member.ifaddr.inet.ip;
- rv = setsockopt(
- fd->secret->md.osfd, level, name,
- (char*)&mreq, sizeof(mreq));
- break;
- }
- case PR_SockOpt_McastInterface:
- {
- rv = setsockopt(
- fd->secret->md.osfd, level, name,
- (char*)&data->value.mcast_if.inet.ip,
- sizeof(data->value.mcast_if.inet.ip));
- break;
- }
- default:
- PR_NOT_REACHED("Unknown socket option");
- break;
- }
- if (-1 == rv) _PR_MD_MAP_SETSOCKOPT_ERROR(errno);
- }
- return (-1 == rv) ? PR_FAILURE : PR_SUCCESS;
-} /* pt_SetSocketOption */
-
-/*****************************************************************************/
-/****************************** I/O method objects ***************************/
-/*****************************************************************************/
-
-static PRIOMethods _pr_file_methods = {
- PR_DESC_FILE,
- pt_Close,
- pt_Read,
- pt_Write,
- pt_Available_f,
- pt_Available64_f,
- pt_Fsync,
- pt_Seek,
- pt_Seek64,
- pt_FileInfo,
- pt_FileInfo64,
- (PRWritevFN)_PR_InvalidInt,
- (PRConnectFN)_PR_InvalidStatus,
- (PRAcceptFN)_PR_InvalidDesc,
- (PRBindFN)_PR_InvalidStatus,
- (PRListenFN)_PR_InvalidStatus,
- (PRShutdownFN)_PR_InvalidStatus,
- (PRRecvFN)_PR_InvalidInt,
- (PRSendFN)_PR_InvalidInt,
- (PRRecvfromFN)_PR_InvalidInt,
- (PRSendtoFN)_PR_InvalidInt,
- pt_Poll,
- (PRAcceptreadFN)_PR_InvalidInt,
- (PRTransmitfileFN)_PR_InvalidInt,
- (PRGetsocknameFN)_PR_InvalidStatus,
- (PRGetpeernameFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRGetsocketoptionFN)_PR_InvalidStatus,
- (PRSetsocketoptionFN)_PR_InvalidStatus,
- (PRSendfileFN)_PR_InvalidInt,
- (PRConnectcontinueFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt
-};
-
-static PRIOMethods _pr_pipe_methods = {
- PR_DESC_PIPE,
- pt_Close,
- pt_Read,
- pt_Write,
- pt_Available_s,
- pt_Available64_s,
- pt_Synch,
- (PRSeekFN)_PR_InvalidInt,
- (PRSeek64FN)_PR_InvalidInt64,
- (PRFileInfoFN)_PR_InvalidStatus,
- (PRFileInfo64FN)_PR_InvalidStatus,
- (PRWritevFN)_PR_InvalidInt,
- (PRConnectFN)_PR_InvalidStatus,
- (PRAcceptFN)_PR_InvalidDesc,
- (PRBindFN)_PR_InvalidStatus,
- (PRListenFN)_PR_InvalidStatus,
- (PRShutdownFN)_PR_InvalidStatus,
- (PRRecvFN)_PR_InvalidInt,
- (PRSendFN)_PR_InvalidInt,
- (PRRecvfromFN)_PR_InvalidInt,
- (PRSendtoFN)_PR_InvalidInt,
- pt_Poll,
- (PRAcceptreadFN)_PR_InvalidInt,
- (PRTransmitfileFN)_PR_InvalidInt,
- (PRGetsocknameFN)_PR_InvalidStatus,
- (PRGetpeernameFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRGetsocketoptionFN)_PR_InvalidStatus,
- (PRSetsocketoptionFN)_PR_InvalidStatus,
- (PRSendfileFN)_PR_InvalidInt,
- (PRConnectcontinueFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt
-};
-
-static PRIOMethods _pr_tcp_methods = {
- PR_DESC_SOCKET_TCP,
- pt_Close,
- pt_SocketRead,
- pt_SocketWrite,
- pt_Available_s,
- pt_Available64_s,
- pt_Synch,
- (PRSeekFN)_PR_InvalidInt,
- (PRSeek64FN)_PR_InvalidInt64,
- (PRFileInfoFN)_PR_InvalidStatus,
- (PRFileInfo64FN)_PR_InvalidStatus,
- pt_Writev,
- pt_Connect,
- pt_Accept,
- pt_Bind,
- pt_Listen,
- pt_Shutdown,
- pt_Recv,
- pt_Send,
- (PRRecvfromFN)_PR_InvalidInt,
- (PRSendtoFN)_PR_InvalidInt,
- pt_Poll,
- pt_AcceptRead,
- pt_TransmitFile,
- pt_GetSockName,
- pt_GetPeerName,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- pt_GetSocketOption,
- pt_SetSocketOption,
- pt_SendFile,
- pt_ConnectContinue,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt
-};
-
-static PRIOMethods _pr_udp_methods = {
- PR_DESC_SOCKET_UDP,
- pt_Close,
- pt_SocketRead,
- pt_SocketWrite,
- pt_Available_s,
- pt_Available64_s,
- pt_Synch,
- (PRSeekFN)_PR_InvalidInt,
- (PRSeek64FN)_PR_InvalidInt64,
- (PRFileInfoFN)_PR_InvalidStatus,
- (PRFileInfo64FN)_PR_InvalidStatus,
- pt_Writev,
- pt_Connect,
- (PRAcceptFN)_PR_InvalidDesc,
- pt_Bind,
- pt_Listen,
- pt_Shutdown,
- pt_Recv,
- pt_Send,
- pt_RecvFrom,
- pt_SendTo,
- pt_Poll,
- (PRAcceptreadFN)_PR_InvalidInt,
- (PRTransmitfileFN)_PR_InvalidInt,
- pt_GetSockName,
- pt_GetPeerName,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- pt_GetSocketOption,
- pt_SetSocketOption,
- (PRSendfileFN)_PR_InvalidInt,
- (PRConnectcontinueFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt
-};
-
-static PRIOMethods _pr_socketpollfd_methods = {
- (PRDescType) 0,
- (PRCloseFN)_PR_InvalidStatus,
- (PRReadFN)_PR_InvalidInt,
- (PRWriteFN)_PR_InvalidInt,
- (PRAvailableFN)_PR_InvalidInt,
- (PRAvailable64FN)_PR_InvalidInt64,
- (PRFsyncFN)_PR_InvalidStatus,
- (PRSeekFN)_PR_InvalidInt,
- (PRSeek64FN)_PR_InvalidInt64,
- (PRFileInfoFN)_PR_InvalidStatus,
- (PRFileInfo64FN)_PR_InvalidStatus,
- (PRWritevFN)_PR_InvalidInt,
- (PRConnectFN)_PR_InvalidStatus,
- (PRAcceptFN)_PR_InvalidDesc,
- (PRBindFN)_PR_InvalidStatus,
- (PRListenFN)_PR_InvalidStatus,
- (PRShutdownFN)_PR_InvalidStatus,
- (PRRecvFN)_PR_InvalidInt,
- (PRSendFN)_PR_InvalidInt,
- (PRRecvfromFN)_PR_InvalidInt,
- (PRSendtoFN)_PR_InvalidInt,
- pt_Poll,
- (PRAcceptreadFN)_PR_InvalidInt,
- (PRTransmitfileFN)_PR_InvalidInt,
- (PRGetsocknameFN)_PR_InvalidStatus,
- (PRGetpeernameFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRGetsocketoptionFN)_PR_InvalidStatus,
- (PRSetsocketoptionFN)_PR_InvalidStatus,
- (PRSendfileFN)_PR_InvalidInt,
- (PRConnectcontinueFN)_PR_InvalidStatus,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt,
- (PRReservedFN)_PR_InvalidInt
-};
-
-#if defined(HPUX) || defined(OSF1) || defined(SOLARIS) || defined (IRIX) \
- || defined(LINUX) || defined(__GNU__) || defined(__GLIBC__) \
- || defined(AIX) || defined(FREEBSD) || defined(NETBSD) \
- || defined(OPENBSD) || defined(BSDI) || defined(NTO) \
- || defined(DARWIN) || defined(UNIXWARE) || defined(RISCOS) \
- || defined(SYMBIAN)
-#define _PR_FCNTL_FLAGS O_NONBLOCK
-#else
-#error "Can't determine architecture"
-#endif
-
-/*
- * Put a Unix file descriptor in non-blocking mode.
- */
-static void pt_MakeFdNonblock(PRIntn osfd)
-{
- PRIntn flags;
- flags = fcntl(osfd, F_GETFL, 0);
- flags |= _PR_FCNTL_FLAGS;
- (void)fcntl(osfd, F_SETFL, flags);
-}
-
-/*
- * Put a Unix socket fd in non-blocking mode that can
- * ideally be inherited by an accepted socket.
- *
- * Why doesn't pt_MakeFdNonblock do? This is to deal with
- * the special case of HP-UX. HP-UX has three kinds of
- * non-blocking modes for sockets: the fcntl() O_NONBLOCK
- * and O_NDELAY flags and ioctl() FIOSNBIO request. Only
- * the ioctl() FIOSNBIO form of non-blocking mode is
- * inherited by an accepted socket.
- *
- * Other platforms just use the generic pt_MakeFdNonblock
- * to put a socket in non-blocking mode.
- */
-#ifdef HPUX
-static void pt_MakeSocketNonblock(PRIntn osfd)
-{
- PRIntn one = 1;
- (void)ioctl(osfd, FIOSNBIO, &one);
-}
-#else
-#define pt_MakeSocketNonblock pt_MakeFdNonblock
-#endif
-
-static PRFileDesc *pt_SetMethods(
- PRIntn osfd, PRDescType type, PRBool isAcceptedSocket, PRBool imported)
-{
- PRFileDesc *fd = _PR_Getfd();
-
- if (fd == NULL) PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- else
- {
- fd->secret->md.osfd = osfd;
- fd->secret->state = _PR_FILEDESC_OPEN;
- if (imported) fd->secret->inheritable = _PR_TRI_UNKNOWN;
- else
- {
- /* By default, a Unix fd is not closed on exec. */
-#ifdef DEBUG
- PRIntn flags;
- flags = fcntl(osfd, F_GETFD, 0);
- PR_ASSERT(0 == flags);
-#endif
- fd->secret->inheritable = _PR_TRI_TRUE;
- }
- switch (type)
- {
- case PR_DESC_FILE:
- fd->methods = PR_GetFileMethods();
- break;
- case PR_DESC_SOCKET_TCP:
- fd->methods = PR_GetTCPMethods();
-#ifdef _PR_ACCEPT_INHERIT_NONBLOCK
- if (!isAcceptedSocket) pt_MakeSocketNonblock(osfd);
-#else
- pt_MakeSocketNonblock(osfd);
-#endif
- break;
- case PR_DESC_SOCKET_UDP:
- fd->methods = PR_GetUDPMethods();
- pt_MakeFdNonblock(osfd);
- break;
- case PR_DESC_PIPE:
- fd->methods = PR_GetPipeMethods();
- pt_MakeFdNonblock(osfd);
- break;
- default:
- break;
- }
- }
- return fd;
-} /* pt_SetMethods */
-
-PR_IMPLEMENT(const PRIOMethods*) PR_GetFileMethods(void)
-{
- return &_pr_file_methods;
-} /* PR_GetFileMethods */
-
-PR_IMPLEMENT(const PRIOMethods*) PR_GetPipeMethods(void)
-{
- return &_pr_pipe_methods;
-} /* PR_GetPipeMethods */
-
-PR_IMPLEMENT(const PRIOMethods*) PR_GetTCPMethods(void)
-{
- return &_pr_tcp_methods;
-} /* PR_GetTCPMethods */
-
-PR_IMPLEMENT(const PRIOMethods*) PR_GetUDPMethods(void)
-{
- return &_pr_udp_methods;
-} /* PR_GetUDPMethods */
-
-static const PRIOMethods* PR_GetSocketPollFdMethods(void)
-{
- return &_pr_socketpollfd_methods;
-} /* PR_GetSocketPollFdMethods */
-
-PR_IMPLEMENT(PRFileDesc*) PR_AllocFileDesc(
- PRInt32 osfd, const PRIOMethods *methods)
-{
- PRFileDesc *fd = _PR_Getfd();
-
- if (NULL == fd) goto failed;
-
- fd->methods = methods;
- fd->secret->md.osfd = osfd;
- /* Make fd non-blocking */
- if (osfd > 2)
- {
- /* Don't mess around with stdin, stdout or stderr */
- if (&_pr_tcp_methods == methods) pt_MakeSocketNonblock(osfd);
- else pt_MakeFdNonblock(osfd);
- }
- fd->secret->state = _PR_FILEDESC_OPEN;
- fd->secret->inheritable = _PR_TRI_UNKNOWN;
- return fd;
-
-failed:
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return fd;
-} /* PR_AllocFileDesc */
-
-#if !defined(_PR_INET6) || defined(_PR_INET6_PROBE)
-PR_EXTERN(PRStatus) _pr_push_ipv6toipv4_layer(PRFileDesc *fd);
-#if defined(_PR_INET6_PROBE)
-extern PRBool _pr_ipv6_is_present(void);
-PR_IMPLEMENT(PRBool) _pr_test_ipv6_socket()
-{
- int osfd;
-
-#if defined(DARWIN)
- /*
- * Disable IPv6 if Darwin version is less than 7.0.0 (OS X 10.3). IPv6 on
- * lesser versions is not ready for general use (see bug 222031).
- */
- {
- struct utsname u;
- if (uname(&u) != 0 || atoi(u.release) < 7)
- return PR_FALSE;
- }
-#endif
-
- /*
- * HP-UX only: HP-UX IPv6 Porting Guide (dated February 2001)
- * suggests that we call open("/dev/ip6", O_RDWR) to determine
- * whether IPv6 APIs and the IPv6 stack are on the system.
- * Our portable test below seems to work fine, so I am using it.
- */
- osfd = socket(AF_INET6, SOCK_STREAM, 0);
- if (osfd != -1) {
- close(osfd);
- return PR_TRUE;
- }
- return PR_FALSE;
-}
-#endif /* _PR_INET6_PROBE */
-#endif
-
-PR_IMPLEMENT(PRFileDesc*) PR_Socket(PRInt32 domain, PRInt32 type, PRInt32 proto)
-{
- PRIntn osfd;
- PRDescType ftype;
- PRFileDesc *fd = NULL;
-#if defined(_PR_INET6_PROBE) || !defined(_PR_INET6)
- PRInt32 tmp_domain = domain;
-#endif
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (pt_TestAbort()) return NULL;
-
- if (PF_INET != domain
- && PR_AF_INET6 != domain
-#if defined(_PR_HAVE_SDP)
- && PR_AF_INET_SDP != domain
-#if defined(SOLARIS)
- && PR_AF_INET6_SDP != domain
-#endif /* SOLARIS */
-#endif /* _PR_HAVE_SDP */
- && PF_UNIX != domain)
- {
- PR_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR, 0);
- return fd;
- }
- if (type == SOCK_STREAM) ftype = PR_DESC_SOCKET_TCP;
- else if (type == SOCK_DGRAM) ftype = PR_DESC_SOCKET_UDP;
- else
- {
- (void)PR_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR, 0);
- return fd;
- }
-#if defined(_PR_HAVE_SDP)
-#if defined(LINUX)
- if (PR_AF_INET_SDP == domain)
- domain = AF_INET_SDP;
-#elif defined(SOLARIS)
- if (PR_AF_INET_SDP == domain) {
- domain = AF_INET;
- proto = PROTO_SDP;
- } else if(PR_AF_INET6_SDP == domain) {
- domain = AF_INET6;
- proto = PROTO_SDP;
- }
-#endif /* SOLARIS */
-#endif /* _PR_HAVE_SDP */
-#if defined(_PR_INET6_PROBE)
- if (PR_AF_INET6 == domain)
- domain = _pr_ipv6_is_present() ? AF_INET6 : AF_INET;
-#elif defined(_PR_INET6)
- if (PR_AF_INET6 == domain)
- domain = AF_INET6;
-#else
- if (PR_AF_INET6 == domain)
- domain = AF_INET;
-#endif
-
- osfd = socket(domain, type, proto);
- if (osfd == -1) pt_MapError(_PR_MD_MAP_SOCKET_ERROR, errno);
- else
- {
-#ifdef _PR_IPV6_V6ONLY_PROBE
- if ((domain == AF_INET6) && _pr_ipv6_v6only_on_by_default)
- {
- int on = 0;
- (void)setsockopt(osfd, IPPROTO_IPV6, IPV6_V6ONLY,
- &on, sizeof(on));
- }
-#endif
- fd = pt_SetMethods(osfd, ftype, PR_FALSE, PR_FALSE);
- if (fd == NULL) close(osfd);
- }
-#ifdef _PR_NEED_SECRET_AF
- if (fd != NULL) fd->secret->af = domain;
-#endif
-#if defined(_PR_INET6_PROBE) || !defined(_PR_INET6)
- if (fd != NULL) {
- /*
- * For platforms with no support for IPv6
- * create layered socket for IPv4-mapped IPv6 addresses
- */
- if (PR_AF_INET6 == tmp_domain && PR_AF_INET == domain) {
- if (PR_FAILURE == _pr_push_ipv6toipv4_layer(fd)) {
- PR_Close(fd);
- fd = NULL;
- }
- }
- }
-#endif
- return fd;
-} /* PR_Socket */
-
-/*****************************************************************************/
-/****************************** I/O public methods ***************************/
-/*****************************************************************************/
-
-PR_IMPLEMENT(PRFileDesc*) PR_OpenFile(
- const char *name, PRIntn flags, PRIntn mode)
-{
- PRFileDesc *fd = NULL;
- PRIntn syserrno, osfd = -1, osflags = 0;;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (pt_TestAbort()) return NULL;
-
- if (flags & PR_RDONLY) osflags |= O_RDONLY;
- if (flags & PR_WRONLY) osflags |= O_WRONLY;
- if (flags & PR_RDWR) osflags |= O_RDWR;
- if (flags & PR_APPEND) osflags |= O_APPEND;
- if (flags & PR_TRUNCATE) osflags |= O_TRUNC;
- if (flags & PR_EXCL) osflags |= O_EXCL;
- if (flags & PR_SYNC)
- {
-#if defined(O_SYNC)
- osflags |= O_SYNC;
-#elif defined(O_FSYNC)
- osflags |= O_FSYNC;
-#else
-#error "Neither O_SYNC nor O_FSYNC is defined on this platform"
-#endif
- }
-
- /*
- ** We have to hold the lock across the creation in order to
- ** enforce the sematics of PR_Rename(). (see the latter for
- ** more details)
- */
- if (flags & PR_CREATE_FILE)
- {
- osflags |= O_CREAT;
- if (NULL !=_pr_rename_lock)
- PR_Lock(_pr_rename_lock);
- }
-
- osfd = _md_iovector._open64(name, osflags, mode);
- syserrno = errno;
-
- if ((flags & PR_CREATE_FILE) && (NULL !=_pr_rename_lock))
- PR_Unlock(_pr_rename_lock);
-
- if (osfd == -1)
- pt_MapError(_PR_MD_MAP_OPEN_ERROR, syserrno);
- else
- {
- fd = pt_SetMethods(osfd, PR_DESC_FILE, PR_FALSE, PR_FALSE);
- if (fd == NULL) close(osfd); /* $$$ whoops! this is bad $$$ */
- }
- return fd;
-} /* PR_OpenFile */
-
-PR_IMPLEMENT(PRFileDesc*) PR_Open(const char *name, PRIntn flags, PRIntn mode)
-{
- return PR_OpenFile(name, flags, mode);
-} /* PR_Open */
-
-PR_IMPLEMENT(PRStatus) PR_Delete(const char *name)
-{
- PRIntn rv = -1;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (pt_TestAbort()) return PR_FAILURE;
-
- rv = unlink(name);
-
- if (rv == -1) {
- pt_MapError(_PR_MD_MAP_UNLINK_ERROR, errno);
- return PR_FAILURE;
- } else
- return PR_SUCCESS;
-} /* PR_Delete */
-
-PR_IMPLEMENT(PRStatus) PR_Access(const char *name, PRAccessHow how)
-{
- PRIntn rv;
-
- if (pt_TestAbort()) return PR_FAILURE;
-
- switch (how)
- {
- case PR_ACCESS_READ_OK:
- rv = access(name, R_OK);
- break;
- case PR_ACCESS_WRITE_OK:
- rv = access(name, W_OK);
- break;
- case PR_ACCESS_EXISTS:
- default:
- rv = access(name, F_OK);
- }
- if (0 == rv) return PR_SUCCESS;
- pt_MapError(_PR_MD_MAP_ACCESS_ERROR, errno);
- return PR_FAILURE;
-
-} /* PR_Access */
-
-PR_IMPLEMENT(PRStatus) PR_GetFileInfo(const char *fn, PRFileInfo *info)
-{
- PRInt32 rv = _PR_MD_GETFILEINFO(fn, info);
- return (0 == rv) ? PR_SUCCESS : PR_FAILURE;
-} /* PR_GetFileInfo */
-
-PR_IMPLEMENT(PRStatus) PR_GetFileInfo64(const char *fn, PRFileInfo64 *info)
-{
- PRInt32 rv;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- rv = _PR_MD_GETFILEINFO64(fn, info);
- return (0 == rv) ? PR_SUCCESS : PR_FAILURE;
-} /* PR_GetFileInfo64 */
-
-PR_IMPLEMENT(PRStatus) PR_Rename(const char *from, const char *to)
-{
- PRIntn rv = -1;
-
- if (pt_TestAbort()) return PR_FAILURE;
-
- /*
- ** We have to acquire a lock here to stiffle anybody trying to create
- ** a new file at the same time. And we have to hold that lock while we
- ** test to see if the file exists and do the rename. The other place
- ** where the lock is held is in PR_Open() when possibly creating a
- ** new file.
- */
-
- PR_Lock(_pr_rename_lock);
- rv = access(to, F_OK);
- if (0 == rv)
- {
- PR_SetError(PR_FILE_EXISTS_ERROR, 0);
- rv = -1;
- }
- else
- {
- rv = rename(from, to);
- if (rv == -1)
- pt_MapError(_PR_MD_MAP_RENAME_ERROR, errno);
- }
- PR_Unlock(_pr_rename_lock);
- return (-1 == rv) ? PR_FAILURE : PR_SUCCESS;
-} /* PR_Rename */
-
-PR_IMPLEMENT(PRStatus) PR_CloseDir(PRDir *dir)
-{
- if (pt_TestAbort()) return PR_FAILURE;
-
- if (NULL != dir->md.d)
- {
- if (closedir(dir->md.d) == -1)
- {
- _PR_MD_MAP_CLOSEDIR_ERROR(errno);
- return PR_FAILURE;
- }
- dir->md.d = NULL;
- PR_DELETE(dir);
- }
- return PR_SUCCESS;
-} /* PR_CloseDir */
-
-PR_IMPLEMENT(PRStatus) PR_MakeDir(const char *name, PRIntn mode)
-{
- PRInt32 rv = -1;
-
- if (pt_TestAbort()) return PR_FAILURE;
-
- /*
- ** This lock is used to enforce rename semantics as described
- ** in PR_Rename.
- */
- if (NULL !=_pr_rename_lock)
- PR_Lock(_pr_rename_lock);
- rv = mkdir(name, mode);
- if (-1 == rv)
- pt_MapError(_PR_MD_MAP_MKDIR_ERROR, errno);
- if (NULL !=_pr_rename_lock)
- PR_Unlock(_pr_rename_lock);
-
- return (-1 == rv) ? PR_FAILURE : PR_SUCCESS;
-} /* PR_Makedir */
-
-PR_IMPLEMENT(PRStatus) PR_MkDir(const char *name, PRIntn mode)
-{
- return PR_MakeDir(name, mode);
-} /* PR_Mkdir */
-
-PR_IMPLEMENT(PRStatus) PR_RmDir(const char *name)
-{
- PRInt32 rv;
-
- if (pt_TestAbort()) return PR_FAILURE;
-
- rv = rmdir(name);
- if (0 == rv) {
- return PR_SUCCESS;
- } else {
- pt_MapError(_PR_MD_MAP_RMDIR_ERROR, errno);
- return PR_FAILURE;
- }
-} /* PR_Rmdir */
-
-
-PR_IMPLEMENT(PRDir*) PR_OpenDir(const char *name)
-{
- DIR *osdir;
- PRDir *dir = NULL;
-
- if (pt_TestAbort()) return dir;
-
- osdir = opendir(name);
- if (osdir == NULL)
- pt_MapError(_PR_MD_MAP_OPENDIR_ERROR, errno);
- else
- {
- dir = PR_NEWZAP(PRDir);
- if (dir)
- dir->md.d = osdir;
- else
- (void)closedir(osdir);
- }
- return dir;
-} /* PR_OpenDir */
-
-static PRInt32 _pr_poll_with_poll(
- PRPollDesc *pds, PRIntn npds, PRIntervalTime timeout)
-{
- PRInt32 ready = 0;
- /*
- * For restarting poll() if it is interrupted by a signal.
- * We use these variables to figure out how much time has
- * elapsed and how much of the timeout still remains.
- */
- PRIntervalTime start = 0, elapsed, remaining;
-
- if (pt_TestAbort()) return -1;
-
- if (0 == npds) PR_Sleep(timeout);
- else
- {
-#define STACK_POLL_DESC_COUNT 64
- struct pollfd stack_syspoll[STACK_POLL_DESC_COUNT];
- struct pollfd *syspoll;
- PRIntn index, msecs;
-
- if (npds <= STACK_POLL_DESC_COUNT)
- {
- syspoll = stack_syspoll;
- }
- else
- {
- PRThread *me = PR_GetCurrentThread();
- if (npds > me->syspoll_count)
- {
- PR_Free(me->syspoll_list);
- me->syspoll_list =
- (struct pollfd*)PR_MALLOC(npds * sizeof(struct pollfd));
- if (NULL == me->syspoll_list)
- {
- me->syspoll_count = 0;
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return -1;
- }
- me->syspoll_count = npds;
- }
- syspoll = me->syspoll_list;
- }
-
- for (index = 0; index < npds; ++index)
- {
- PRInt16 in_flags_read = 0, in_flags_write = 0;
- PRInt16 out_flags_read = 0, out_flags_write = 0;
-
- if ((NULL != pds[index].fd) && (0 != pds[index].in_flags))
- {
- if (pds[index].in_flags & PR_POLL_READ)
- {
- in_flags_read = (pds[index].fd->methods->poll)(
- pds[index].fd,
- pds[index].in_flags & ~PR_POLL_WRITE,
- &out_flags_read);
- }
- if (pds[index].in_flags & PR_POLL_WRITE)
- {
- in_flags_write = (pds[index].fd->methods->poll)(
- pds[index].fd,
- pds[index].in_flags & ~PR_POLL_READ,
- &out_flags_write);
- }
- if ((0 != (in_flags_read & out_flags_read))
- || (0 != (in_flags_write & out_flags_write)))
- {
- /* this one is ready right now */
- if (0 == ready)
- {
- /*
- * We will return without calling the system
- * poll function. So zero the out_flags
- * fields of all the poll descriptors before
- * this one.
- */
- int i;
- for (i = 0; i < index; i++)
- {
- pds[i].out_flags = 0;
- }
- }
- ready += 1;
- pds[index].out_flags = out_flags_read | out_flags_write;
- }
- else
- {
- /* now locate the NSPR layer at the bottom of the stack */
- PRFileDesc *bottom = PR_GetIdentitiesLayer(
- pds[index].fd, PR_NSPR_IO_LAYER);
- PR_ASSERT(NULL != bottom); /* what to do about that? */
- pds[index].out_flags = 0; /* pre-condition */
- if ((NULL != bottom)
- && (_PR_FILEDESC_OPEN == bottom->secret->state))
- {
- if (0 == ready)
- {
- syspoll[index].fd = bottom->secret->md.osfd;
- syspoll[index].events = 0;
- if (in_flags_read & PR_POLL_READ)
- {
- pds[index].out_flags |=
- _PR_POLL_READ_SYS_READ;
- syspoll[index].events |= POLLIN;
- }
- if (in_flags_read & PR_POLL_WRITE)
- {
- pds[index].out_flags |=
- _PR_POLL_READ_SYS_WRITE;
- syspoll[index].events |= POLLOUT;
- }
- if (in_flags_write & PR_POLL_READ)
- {
- pds[index].out_flags |=
- _PR_POLL_WRITE_SYS_READ;
- syspoll[index].events |= POLLIN;
- }
- if (in_flags_write & PR_POLL_WRITE)
- {
- pds[index].out_flags |=
- _PR_POLL_WRITE_SYS_WRITE;
- syspoll[index].events |= POLLOUT;
- }
- if (pds[index].in_flags & PR_POLL_EXCEPT)
- syspoll[index].events |= POLLPRI;
- }
- }
- else
- {
- if (0 == ready)
- {
- int i;
- for (i = 0; i < index; i++)
- {
- pds[i].out_flags = 0;
- }
- }
- ready += 1; /* this will cause an abrupt return */
- pds[index].out_flags = PR_POLL_NVAL; /* bogii */
- }
- }
- }
- else
- {
- /* make poll() ignore this entry */
- syspoll[index].fd = -1;
- syspoll[index].events = 0;
- pds[index].out_flags = 0;
- }
- }
- if (0 == ready)
- {
- switch (timeout)
- {
- case PR_INTERVAL_NO_WAIT: msecs = 0; break;
- case PR_INTERVAL_NO_TIMEOUT: msecs = -1; break;
- default:
- msecs = PR_IntervalToMilliseconds(timeout);
- start = PR_IntervalNow();
- }
-
-retry:
- ready = poll(syspoll, npds, msecs);
- if (-1 == ready)
- {
- PRIntn oserror = errno;
-
- if (EINTR == oserror)
- {
- if (timeout == PR_INTERVAL_NO_TIMEOUT)
- goto retry;
- else if (timeout == PR_INTERVAL_NO_WAIT)
- ready = 0; /* don't retry, just time out */
- else
- {
- elapsed = (PRIntervalTime) (PR_IntervalNow()
- - start);
- if (elapsed > timeout)
- ready = 0; /* timed out */
- else
- {
- remaining = timeout - elapsed;
- msecs = PR_IntervalToMilliseconds(remaining);
- goto retry;
- }
- }
- }
- else
- {
- _PR_MD_MAP_POLL_ERROR(oserror);
- }
- }
- else if (ready > 0)
- {
- for (index = 0; index < npds; ++index)
- {
- PRInt16 out_flags = 0;
- if ((NULL != pds[index].fd) && (0 != pds[index].in_flags))
- {
- if (0 != syspoll[index].revents)
- {
- if (syspoll[index].revents & POLLIN)
- {
- if (pds[index].out_flags
- & _PR_POLL_READ_SYS_READ)
- {
- out_flags |= PR_POLL_READ;
- }
- if (pds[index].out_flags
- & _PR_POLL_WRITE_SYS_READ)
- {
- out_flags |= PR_POLL_WRITE;
- }
- }
- if (syspoll[index].revents & POLLOUT)
- {
- if (pds[index].out_flags
- & _PR_POLL_READ_SYS_WRITE)
- {
- out_flags |= PR_POLL_READ;
- }
- if (pds[index].out_flags
- & _PR_POLL_WRITE_SYS_WRITE)
- {
- out_flags |= PR_POLL_WRITE;
- }
- }
- if (syspoll[index].revents & POLLPRI)
- out_flags |= PR_POLL_EXCEPT;
- if (syspoll[index].revents & POLLERR)
- out_flags |= PR_POLL_ERR;
- if (syspoll[index].revents & POLLNVAL)
- out_flags |= PR_POLL_NVAL;
- if (syspoll[index].revents & POLLHUP)
- out_flags |= PR_POLL_HUP;
- }
- }
- pds[index].out_flags = out_flags;
- }
- }
- }
- }
- return ready;
-
-} /* _pr_poll_with_poll */
-
-#if defined(_PR_POLL_WITH_SELECT)
-/*
- * OSF1 and HPUX report the POLLHUP event for a socket when the
- * shutdown(SHUT_WR) operation is called for the remote end, even though
- * the socket is still writeable. Use select(), instead of poll(), to
- * workaround this problem.
- */
-static PRInt32 _pr_poll_with_select(
- PRPollDesc *pds, PRIntn npds, PRIntervalTime timeout)
-{
- PRInt32 ready = 0;
- /*
- * For restarting select() if it is interrupted by a signal.
- * We use these variables to figure out how much time has
- * elapsed and how much of the timeout still remains.
- */
- PRIntervalTime start = 0, elapsed, remaining;
-
- if (pt_TestAbort()) return -1;
-
- if (0 == npds) PR_Sleep(timeout);
- else
- {
-#define STACK_POLL_DESC_COUNT 64
- int stack_selectfd[STACK_POLL_DESC_COUNT];
- int *selectfd;
- fd_set rd, wr, ex, *rdp = NULL, *wrp = NULL, *exp = NULL;
- struct timeval tv, *tvp;
- PRIntn index, msecs, maxfd = 0;
-
- if (npds <= STACK_POLL_DESC_COUNT)
- {
- selectfd = stack_selectfd;
- }
- else
- {
- PRThread *me = PR_GetCurrentThread();
- if (npds > me->selectfd_count)
- {
- PR_Free(me->selectfd_list);
- me->selectfd_list = (int *)PR_MALLOC(npds * sizeof(int));
- if (NULL == me->selectfd_list)
- {
- me->selectfd_count = 0;
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return -1;
- }
- me->selectfd_count = npds;
- }
- selectfd = me->selectfd_list;
- }
- FD_ZERO(&rd);
- FD_ZERO(&wr);
- FD_ZERO(&ex);
-
- for (index = 0; index < npds; ++index)
- {
- PRInt16 in_flags_read = 0, in_flags_write = 0;
- PRInt16 out_flags_read = 0, out_flags_write = 0;
-
- if ((NULL != pds[index].fd) && (0 != pds[index].in_flags))
- {
- if (pds[index].in_flags & PR_POLL_READ)
- {
- in_flags_read = (pds[index].fd->methods->poll)(
- pds[index].fd,
- pds[index].in_flags & ~PR_POLL_WRITE,
- &out_flags_read);
- }
- if (pds[index].in_flags & PR_POLL_WRITE)
- {
- in_flags_write = (pds[index].fd->methods->poll)(
- pds[index].fd,
- pds[index].in_flags & ~PR_POLL_READ,
- &out_flags_write);
- }
- if ((0 != (in_flags_read & out_flags_read))
- || (0 != (in_flags_write & out_flags_write)))
- {
- /* this one is ready right now */
- if (0 == ready)
- {
- /*
- * We will return without calling the system
- * poll function. So zero the out_flags
- * fields of all the poll descriptors before
- * this one.
- */
- int i;
- for (i = 0; i < index; i++)
- {
- pds[i].out_flags = 0;
- }
- }
- ready += 1;
- pds[index].out_flags = out_flags_read | out_flags_write;
- }
- else
- {
- /* now locate the NSPR layer at the bottom of the stack */
- PRFileDesc *bottom = PR_GetIdentitiesLayer(
- pds[index].fd, PR_NSPR_IO_LAYER);
- PR_ASSERT(NULL != bottom); /* what to do about that? */
- pds[index].out_flags = 0; /* pre-condition */
- if ((NULL != bottom)
- && (_PR_FILEDESC_OPEN == bottom->secret->state))
- {
- if (0 == ready)
- {
- PRBool add_to_rd = PR_FALSE;
- PRBool add_to_wr = PR_FALSE;
- PRBool add_to_ex = PR_FALSE;
-
- selectfd[index] = bottom->secret->md.osfd;
- if (in_flags_read & PR_POLL_READ)
- {
- pds[index].out_flags |=
- _PR_POLL_READ_SYS_READ;
- add_to_rd = PR_TRUE;
- }
- if (in_flags_read & PR_POLL_WRITE)
- {
- pds[index].out_flags |=
- _PR_POLL_READ_SYS_WRITE;
- add_to_wr = PR_TRUE;
- }
- if (in_flags_write & PR_POLL_READ)
- {
- pds[index].out_flags |=
- _PR_POLL_WRITE_SYS_READ;
- add_to_rd = PR_TRUE;
- }
- if (in_flags_write & PR_POLL_WRITE)
- {
- pds[index].out_flags |=
- _PR_POLL_WRITE_SYS_WRITE;
- add_to_wr = PR_TRUE;
- }
- if (pds[index].in_flags & PR_POLL_EXCEPT)
- {
- add_to_ex = PR_TRUE;
- }
- if ((selectfd[index] > maxfd) &&
- (add_to_rd || add_to_wr || add_to_ex))
- {
- maxfd = selectfd[index];
- /*
- * If maxfd is too large to be used with
- * select, fall back to calling poll.
- */
- if (maxfd >= FD_SETSIZE)
- break;
- }
- if (add_to_rd)
- {
- FD_SET(bottom->secret->md.osfd, &rd);
- rdp = &rd;
- }
- if (add_to_wr)
- {
- FD_SET(bottom->secret->md.osfd, &wr);
- wrp = ≀
- }
- if (add_to_ex)
- {
- FD_SET(bottom->secret->md.osfd, &ex);
- exp = &ex;
- }
- }
- }
- else
- {
- if (0 == ready)
- {
- int i;
- for (i = 0; i < index; i++)
- {
- pds[i].out_flags = 0;
- }
- }
- ready += 1; /* this will cause an abrupt return */
- pds[index].out_flags = PR_POLL_NVAL; /* bogii */
- }
- }
- }
- else
- {
- pds[index].out_flags = 0;
- }
- }
- if (0 == ready)
- {
- if (maxfd >= FD_SETSIZE)
- {
- /*
- * maxfd too large to be used with select, fall back to
- * calling poll
- */
- return(_pr_poll_with_poll(pds, npds, timeout));
- }
- switch (timeout)
- {
- case PR_INTERVAL_NO_WAIT:
- tv.tv_sec = 0;
- tv.tv_usec = 0;
- tvp = &tv;
- break;
- case PR_INTERVAL_NO_TIMEOUT:
- tvp = NULL;
- break;
- default:
- msecs = PR_IntervalToMilliseconds(timeout);
- tv.tv_sec = msecs/PR_MSEC_PER_SEC;
- tv.tv_usec = (msecs % PR_MSEC_PER_SEC) * PR_USEC_PER_MSEC;
- tvp = &tv;
- start = PR_IntervalNow();
- }
-
-retry:
- ready = select(maxfd + 1, rdp, wrp, exp, tvp);
- if (-1 == ready)
- {
- PRIntn oserror = errno;
-
- if ((EINTR == oserror) || (EAGAIN == oserror))
- {
- if (timeout == PR_INTERVAL_NO_TIMEOUT)
- goto retry;
- else if (timeout == PR_INTERVAL_NO_WAIT)
- ready = 0; /* don't retry, just time out */
- else
- {
- elapsed = (PRIntervalTime) (PR_IntervalNow()
- - start);
- if (elapsed > timeout)
- ready = 0; /* timed out */
- else
- {
- remaining = timeout - elapsed;
- msecs = PR_IntervalToMilliseconds(remaining);
- tv.tv_sec = msecs/PR_MSEC_PER_SEC;
- tv.tv_usec = (msecs % PR_MSEC_PER_SEC) *
- PR_USEC_PER_MSEC;
- goto retry;
- }
- }
- } else if (EBADF == oserror)
- {
- /* find all the bad fds */
- ready = 0;
- for (index = 0; index < npds; ++index)
- {
- pds[index].out_flags = 0;
- if ((NULL != pds[index].fd) &&
- (0 != pds[index].in_flags))
- {
- if (fcntl(selectfd[index], F_GETFL, 0) == -1)
- {
- pds[index].out_flags = PR_POLL_NVAL;
- ready++;
- }
- }
- }
- } else
- _PR_MD_MAP_SELECT_ERROR(oserror);
- }
- else if (ready > 0)
- {
- for (index = 0; index < npds; ++index)
- {
- PRInt16 out_flags = 0;
- if ((NULL != pds[index].fd) && (0 != pds[index].in_flags))
- {
- if (FD_ISSET(selectfd[index], &rd))
- {
- if (pds[index].out_flags
- & _PR_POLL_READ_SYS_READ)
- {
- out_flags |= PR_POLL_READ;
- }
- if (pds[index].out_flags
- & _PR_POLL_WRITE_SYS_READ)
- {
- out_flags |= PR_POLL_WRITE;
- }
- }
- if (FD_ISSET(selectfd[index], &wr))
- {
- if (pds[index].out_flags
- & _PR_POLL_READ_SYS_WRITE)
- {
- out_flags |= PR_POLL_READ;
- }
- if (pds[index].out_flags
- & _PR_POLL_WRITE_SYS_WRITE)
- {
- out_flags |= PR_POLL_WRITE;
- }
- }
- if (FD_ISSET(selectfd[index], &ex))
- out_flags |= PR_POLL_EXCEPT;
- }
- pds[index].out_flags = out_flags;
- }
- }
- }
- }
- return ready;
-
-} /* _pr_poll_with_select */
-#endif /* _PR_POLL_WITH_SELECT */
-
-PR_IMPLEMENT(PRInt32) PR_Poll(
- PRPollDesc *pds, PRIntn npds, PRIntervalTime timeout)
-{
-#if defined(_PR_POLL_WITH_SELECT)
- return(_pr_poll_with_select(pds, npds, timeout));
-#else
- return(_pr_poll_with_poll(pds, npds, timeout));
-#endif
-}
-
-PR_IMPLEMENT(PRDirEntry*) PR_ReadDir(PRDir *dir, PRDirFlags flags)
-{
- struct dirent *dp;
-
- if (pt_TestAbort()) return NULL;
-
- for (;;)
- {
- errno = 0;
- dp = readdir(dir->md.d);
- if (NULL == dp)
- {
- pt_MapError(_PR_MD_MAP_READDIR_ERROR, errno);
- return NULL;
- }
- if ((flags & PR_SKIP_DOT)
- && ('.' == dp->d_name[0])
- && (0 == dp->d_name[1])) continue;
- if ((flags & PR_SKIP_DOT_DOT)
- && ('.' == dp->d_name[0])
- && ('.' == dp->d_name[1])
- && (0 == dp->d_name[2])) continue;
- if ((flags & PR_SKIP_HIDDEN) && ('.' == dp->d_name[0]))
- continue;
- break;
- }
- dir->d.name = dp->d_name;
- return &dir->d;
-} /* PR_ReadDir */
-
-PR_IMPLEMENT(PRFileDesc*) PR_NewUDPSocket(void)
-{
- PRIntn domain = PF_INET;
-
- return PR_Socket(domain, SOCK_DGRAM, 0);
-} /* PR_NewUDPSocket */
-
-PR_IMPLEMENT(PRFileDesc*) PR_NewTCPSocket(void)
-{
- PRIntn domain = PF_INET;
-
- return PR_Socket(domain, SOCK_STREAM, 0);
-} /* PR_NewTCPSocket */
-
-PR_IMPLEMENT(PRFileDesc*) PR_OpenUDPSocket(PRIntn af)
-{
- return PR_Socket(af, SOCK_DGRAM, 0);
-} /* PR_NewUDPSocket */
-
-PR_IMPLEMENT(PRFileDesc*) PR_OpenTCPSocket(PRIntn af)
-{
- return PR_Socket(af, SOCK_STREAM, 0);
-} /* PR_NewTCPSocket */
-
-PR_IMPLEMENT(PRStatus) PR_NewTCPSocketPair(PRFileDesc *fds[2])
-{
-#ifdef SYMBIAN
- /*
- * For the platforms that don't have socketpair.
- *
- * Copied from prsocket.c, with the parameter f[] renamed fds[] and the
- * _PR_CONNECT_DOES_NOT_BIND code removed.
- */
- PRFileDesc *listenSock;
- PRNetAddr selfAddr, peerAddr;
- PRUint16 port;
-
- fds[0] = fds[1] = NULL;
- listenSock = PR_NewTCPSocket();
- if (listenSock == NULL) {
- goto failed;
- }
- PR_InitializeNetAddr(PR_IpAddrLoopback, 0, &selfAddr); /* BugZilla: 35408 */
- if (PR_Bind(listenSock, &selfAddr) == PR_FAILURE) {
- goto failed;
- }
- if (PR_GetSockName(listenSock, &selfAddr) == PR_FAILURE) {
- goto failed;
- }
- port = ntohs(selfAddr.inet.port);
- if (PR_Listen(listenSock, 5) == PR_FAILURE) {
- goto failed;
- }
- fds[0] = PR_NewTCPSocket();
- if (fds[0] == NULL) {
- goto failed;
- }
- PR_InitializeNetAddr(PR_IpAddrLoopback, port, &selfAddr);
-
- /*
- * Only a thread is used to do the connect and accept.
- * I am relying on the fact that PR_Connect returns
- * successfully as soon as the connect request is put
- * into the listen queue (but before PR_Accept is called).
- * This is the behavior of the BSD socket code. If
- * connect does not return until accept is called, we
- * will need to create another thread to call connect.
- */
- if (PR_Connect(fds[0], &selfAddr, PR_INTERVAL_NO_TIMEOUT)
- == PR_FAILURE) {
- goto failed;
- }
- /*
- * A malicious local process may connect to the listening
- * socket, so we need to verify that the accepted connection
- * is made from our own socket fds[0].
- */
- if (PR_GetSockName(fds[0], &selfAddr) == PR_FAILURE) {
- goto failed;
- }
- fds[1] = PR_Accept(listenSock, &peerAddr, PR_INTERVAL_NO_TIMEOUT);
- if (fds[1] == NULL) {
- goto failed;
- }
- if (peerAddr.inet.port != selfAddr.inet.port) {
- /* the connection we accepted is not from fds[0] */
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
- goto failed;
- }
- PR_Close(listenSock);
- return PR_SUCCESS;
-
-failed:
- if (listenSock) {
- PR_Close(listenSock);
- }
- if (fds[0]) {
- PR_Close(fds[0]);
- }
- if (fds[1]) {
- PR_Close(fds[1]);
- }
- return PR_FAILURE;
-#else
- PRInt32 osfd[2];
-
- if (pt_TestAbort()) return PR_FAILURE;
-
- if (socketpair(AF_UNIX, SOCK_STREAM, 0, osfd) == -1) {
- pt_MapError(_PR_MD_MAP_SOCKETPAIR_ERROR, errno);
- return PR_FAILURE;
- }
-
- fds[0] = pt_SetMethods(osfd[0], PR_DESC_SOCKET_TCP, PR_FALSE, PR_FALSE);
- if (fds[0] == NULL) {
- close(osfd[0]);
- close(osfd[1]);
- return PR_FAILURE;
- }
- fds[1] = pt_SetMethods(osfd[1], PR_DESC_SOCKET_TCP, PR_FALSE, PR_FALSE);
- if (fds[1] == NULL) {
- PR_Close(fds[0]);
- close(osfd[1]);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-#endif
-} /* PR_NewTCPSocketPair */
-
-PR_IMPLEMENT(PRStatus) PR_CreatePipe(
- PRFileDesc **readPipe,
- PRFileDesc **writePipe
-)
-{
- int pipefd[2];
-
- if (pt_TestAbort()) return PR_FAILURE;
-
- if (pipe(pipefd) == -1)
- {
- /* XXX map pipe error */
- PR_SetError(PR_UNKNOWN_ERROR, errno);
- return PR_FAILURE;
- }
- *readPipe = pt_SetMethods(pipefd[0], PR_DESC_PIPE, PR_FALSE, PR_FALSE);
- if (NULL == *readPipe)
- {
- close(pipefd[0]);
- close(pipefd[1]);
- return PR_FAILURE;
- }
- *writePipe = pt_SetMethods(pipefd[1], PR_DESC_PIPE, PR_FALSE, PR_FALSE);
- if (NULL == *writePipe)
- {
- PR_Close(*readPipe);
- close(pipefd[1]);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-/*
-** Set the inheritance attribute of a file descriptor.
-*/
-PR_IMPLEMENT(PRStatus) PR_SetFDInheritable(
- PRFileDesc *fd,
- PRBool inheritable)
-{
- /*
- * Only a non-layered, NSPR file descriptor can be inherited
- * by a child process.
- */
- if (fd->identity != PR_NSPR_IO_LAYER)
- {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
- if (fd->secret->inheritable != inheritable)
- {
- if (fcntl(fd->secret->md.osfd, F_SETFD,
- inheritable ? 0 : FD_CLOEXEC) == -1)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- return PR_FAILURE;
- }
- fd->secret->inheritable = (_PRTriStateBool) inheritable;
- }
- return PR_SUCCESS;
-}
-
-/*****************************************************************************/
-/***************************** I/O friends methods ***************************/
-/*****************************************************************************/
-
-PR_IMPLEMENT(PRFileDesc*) PR_ImportFile(PRInt32 osfd)
-{
- PRFileDesc *fd;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- fd = pt_SetMethods(osfd, PR_DESC_FILE, PR_FALSE, PR_TRUE);
- if (NULL == fd) close(osfd);
- return fd;
-} /* PR_ImportFile */
-
-PR_IMPLEMENT(PRFileDesc*) PR_ImportPipe(PRInt32 osfd)
-{
- PRFileDesc *fd;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- fd = pt_SetMethods(osfd, PR_DESC_PIPE, PR_FALSE, PR_TRUE);
- if (NULL == fd) close(osfd);
- return fd;
-} /* PR_ImportPipe */
-
-PR_IMPLEMENT(PRFileDesc*) PR_ImportTCPSocket(PRInt32 osfd)
-{
- PRFileDesc *fd;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- fd = pt_SetMethods(osfd, PR_DESC_SOCKET_TCP, PR_FALSE, PR_TRUE);
- if (NULL == fd) close(osfd);
-#ifdef _PR_NEED_SECRET_AF
- if (NULL != fd) fd->secret->af = PF_INET;
-#endif
- return fd;
-} /* PR_ImportTCPSocket */
-
-PR_IMPLEMENT(PRFileDesc*) PR_ImportUDPSocket(PRInt32 osfd)
-{
- PRFileDesc *fd;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
- fd = pt_SetMethods(osfd, PR_DESC_SOCKET_UDP, PR_FALSE, PR_TRUE);
- if (NULL == fd) close(osfd);
- return fd;
-} /* PR_ImportUDPSocket */
-
-PR_IMPLEMENT(PRFileDesc*) PR_CreateSocketPollFd(PRInt32 osfd)
-{
- PRFileDesc *fd;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- fd = _PR_Getfd();
-
- if (fd == NULL) PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- else
- {
- fd->secret->md.osfd = osfd;
- fd->secret->inheritable = _PR_TRI_FALSE;
- fd->secret->state = _PR_FILEDESC_OPEN;
- fd->methods = PR_GetSocketPollFdMethods();
- }
-
- return fd;
-} /* PR_CreateSocketPollFD */
-
-PR_IMPLEMENT(PRStatus) PR_DestroySocketPollFd(PRFileDesc *fd)
-{
- if (NULL == fd)
- {
- PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
- return PR_FAILURE;
- }
- fd->secret->state = _PR_FILEDESC_CLOSED;
- _PR_Putfd(fd);
- return PR_SUCCESS;
-} /* PR_DestroySocketPollFd */
-
-PR_IMPLEMENT(PRInt32) PR_FileDesc2NativeHandle(PRFileDesc *bottom)
-{
- PRInt32 osfd = -1;
- bottom = (NULL == bottom) ?
- NULL : PR_GetIdentitiesLayer(bottom, PR_NSPR_IO_LAYER);
- if (NULL == bottom) PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- else osfd = bottom->secret->md.osfd;
- return osfd;
-} /* PR_FileDesc2NativeHandle */
-
-PR_IMPLEMENT(void) PR_ChangeFileDescNativeHandle(PRFileDesc *fd,
- PRInt32 handle)
-{
- if (fd) fd->secret->md.osfd = handle;
-} /* PR_ChangeFileDescNativeHandle*/
-
-PR_IMPLEMENT(PRStatus) PR_LockFile(PRFileDesc *fd)
-{
- PRStatus status = PR_SUCCESS;
-
- if (pt_TestAbort()) return PR_FAILURE;
-
- PR_Lock(_pr_flock_lock);
- while (-1 == fd->secret->lockCount)
- PR_WaitCondVar(_pr_flock_cv, PR_INTERVAL_NO_TIMEOUT);
- if (0 == fd->secret->lockCount)
- {
- fd->secret->lockCount = -1;
- PR_Unlock(_pr_flock_lock);
- status = _PR_MD_LOCKFILE(fd->secret->md.osfd);
- PR_Lock(_pr_flock_lock);
- fd->secret->lockCount = (PR_SUCCESS == status) ? 1 : 0;
- PR_NotifyAllCondVar(_pr_flock_cv);
- }
- else
- {
- fd->secret->lockCount += 1;
- }
- PR_Unlock(_pr_flock_lock);
-
- return status;
-} /* PR_LockFile */
-
-PR_IMPLEMENT(PRStatus) PR_TLockFile(PRFileDesc *fd)
-{
- PRStatus status = PR_SUCCESS;
-
- if (pt_TestAbort()) return PR_FAILURE;
-
- PR_Lock(_pr_flock_lock);
- if (0 == fd->secret->lockCount)
- {
- status = _PR_MD_TLOCKFILE(fd->secret->md.osfd);
- if (PR_SUCCESS == status) fd->secret->lockCount = 1;
- }
- else fd->secret->lockCount += 1;
- PR_Unlock(_pr_flock_lock);
-
- return status;
-} /* PR_TLockFile */
-
-PR_IMPLEMENT(PRStatus) PR_UnlockFile(PRFileDesc *fd)
-{
- PRStatus status = PR_SUCCESS;
-
- if (pt_TestAbort()) return PR_FAILURE;
-
- PR_Lock(_pr_flock_lock);
- if (fd->secret->lockCount == 1)
- {
- status = _PR_MD_UNLOCKFILE(fd->secret->md.osfd);
- if (PR_SUCCESS == status) fd->secret->lockCount = 0;
- }
- else fd->secret->lockCount -= 1;
- PR_Unlock(_pr_flock_lock);
-
- return status;
-}
-
-/*
- * The next two entry points should not be in the API, but they are
- * defined here for historical (or hysterical) reasons.
- */
-
-PR_IMPLEMENT(PRInt32) PR_GetSysfdTableMax(void)
-{
-#if defined(AIX) || defined(SYMBIAN)
- return sysconf(_SC_OPEN_MAX);
-#else
- struct rlimit rlim;
-
- if ( getrlimit(RLIMIT_NOFILE, &rlim) < 0)
- return -1;
-
- return rlim.rlim_max;
-#endif
-}
-
-PR_IMPLEMENT(PRInt32) PR_SetSysfdTableSize(PRIntn table_size)
-{
-#if defined(AIX) || defined(SYMBIAN)
- return -1;
-#else
- struct rlimit rlim;
- PRInt32 tableMax = PR_GetSysfdTableMax();
-
- if (tableMax < 0) return -1;
- rlim.rlim_max = tableMax;
-
- /* Grow as much as we can; even if too big */
- if ( rlim.rlim_max < table_size )
- rlim.rlim_cur = rlim.rlim_max;
- else
- rlim.rlim_cur = table_size;
-
- if ( setrlimit(RLIMIT_NOFILE, &rlim) < 0)
- return -1;
-
- return rlim.rlim_cur;
-#endif
-}
-
-/*
- * PR_Stat is supported for backward compatibility; some existing Java
- * code uses it. New code should use PR_GetFileInfo.
- */
-
-#ifndef NO_NSPR_10_SUPPORT
-PR_IMPLEMENT(PRInt32) PR_Stat(const char *name, struct stat *buf)
-{
- static PRBool unwarned = PR_TRUE;
- if (unwarned) unwarned = _PR_Obsolete("PR_Stat", "PR_GetFileInfo");
-
- if (pt_TestAbort()) return -1;
-
- if (-1 == stat(name, buf)) {
- pt_MapError(_PR_MD_MAP_STAT_ERROR, errno);
- return -1;
- } else {
- return 0;
- }
-}
-#endif /* ! NO_NSPR_10_SUPPORT */
-
-
-PR_IMPLEMENT(void) PR_FD_ZERO(PR_fd_set *set)
-{
- static PRBool unwarned = PR_TRUE;
- if (unwarned) unwarned = _PR_Obsolete("PR_FD_ZERO (PR_Select)", "PR_Poll");
- memset(set, 0, sizeof(PR_fd_set));
-}
-
-PR_IMPLEMENT(void) PR_FD_SET(PRFileDesc *fh, PR_fd_set *set)
-{
- static PRBool unwarned = PR_TRUE;
- if (unwarned) unwarned = _PR_Obsolete("PR_FD_SET (PR_Select)", "PR_Poll");
- PR_ASSERT( set->hsize < PR_MAX_SELECT_DESC );
-
- set->harray[set->hsize++] = fh;
-}
-
-PR_IMPLEMENT(void) PR_FD_CLR(PRFileDesc *fh, PR_fd_set *set)
-{
- PRUint32 index, index2;
- static PRBool unwarned = PR_TRUE;
- if (unwarned) unwarned = _PR_Obsolete("PR_FD_CLR (PR_Select)", "PR_Poll");
-
- for (index = 0; index<set->hsize; index++)
- if (set->harray[index] == fh) {
- for (index2=index; index2 < (set->hsize-1); index2++) {
- set->harray[index2] = set->harray[index2+1];
- }
- set->hsize--;
- break;
- }
-}
-
-PR_IMPLEMENT(PRInt32) PR_FD_ISSET(PRFileDesc *fh, PR_fd_set *set)
-{
- PRUint32 index;
- static PRBool unwarned = PR_TRUE;
- if (unwarned) unwarned = _PR_Obsolete("PR_FD_ISSET (PR_Select)", "PR_Poll");
- for (index = 0; index<set->hsize; index++)
- if (set->harray[index] == fh) {
- return 1;
- }
- return 0;
-}
-
-PR_IMPLEMENT(void) PR_FD_NSET(PRInt32 fd, PR_fd_set *set)
-{
- static PRBool unwarned = PR_TRUE;
- if (unwarned) unwarned = _PR_Obsolete("PR_FD_NSET (PR_Select)", "PR_Poll");
- PR_ASSERT( set->nsize < PR_MAX_SELECT_DESC );
-
- set->narray[set->nsize++] = fd;
-}
-
-PR_IMPLEMENT(void) PR_FD_NCLR(PRInt32 fd, PR_fd_set *set)
-{
- PRUint32 index, index2;
- static PRBool unwarned = PR_TRUE;
- if (unwarned) unwarned = _PR_Obsolete("PR_FD_NCLR (PR_Select)", "PR_Poll");
-
- for (index = 0; index<set->nsize; index++)
- if (set->narray[index] == fd) {
- for (index2=index; index2 < (set->nsize-1); index2++) {
- set->narray[index2] = set->narray[index2+1];
- }
- set->nsize--;
- break;
- }
-}
-
-PR_IMPLEMENT(PRInt32) PR_FD_NISSET(PRInt32 fd, PR_fd_set *set)
-{
- PRUint32 index;
- static PRBool unwarned = PR_TRUE;
- if (unwarned) unwarned = _PR_Obsolete("PR_FD_NISSET (PR_Select)", "PR_Poll");
- for (index = 0; index<set->nsize; index++)
- if (set->narray[index] == fd) {
- return 1;
- }
- return 0;
-}
-
-#include <sys/types.h>
-#include <sys/time.h>
-#if !defined(HPUX) \
- && !defined(LINUX) && !defined(__GNU__) && !defined(__GLIBC__)
-#include <sys/select.h>
-#endif
-
-static PRInt32
-_PR_getset(PR_fd_set *pr_set, fd_set *set)
-{
- PRUint32 index;
- PRInt32 max = 0;
-
- if (!pr_set)
- return 0;
-
- FD_ZERO(set);
-
- /* First set the pr file handle osfds */
- for (index=0; index<pr_set->hsize; index++) {
- FD_SET(pr_set->harray[index]->secret->md.osfd, set);
- if (pr_set->harray[index]->secret->md.osfd > max)
- max = pr_set->harray[index]->secret->md.osfd;
- }
- /* Second set the native osfds */
- for (index=0; index<pr_set->nsize; index++) {
- FD_SET(pr_set->narray[index], set);
- if (pr_set->narray[index] > max)
- max = pr_set->narray[index];
- }
- return max;
-}
-
-static void
-_PR_setset(PR_fd_set *pr_set, fd_set *set)
-{
- PRUint32 index, last_used;
-
- if (!pr_set)
- return;
-
- for (last_used=0, index=0; index<pr_set->hsize; index++) {
- if ( FD_ISSET(pr_set->harray[index]->secret->md.osfd, set) ) {
- pr_set->harray[last_used++] = pr_set->harray[index];
- }
- }
- pr_set->hsize = last_used;
-
- for (last_used=0, index=0; index<pr_set->nsize; index++) {
- if ( FD_ISSET(pr_set->narray[index], set) ) {
- pr_set->narray[last_used++] = pr_set->narray[index];
- }
- }
- pr_set->nsize = last_used;
-}
-
-PR_IMPLEMENT(PRInt32) PR_Select(
- PRInt32 unused, PR_fd_set *pr_rd, PR_fd_set *pr_wr,
- PR_fd_set *pr_ex, PRIntervalTime timeout)
-{
- fd_set rd, wr, ex;
- struct timeval tv, *tvp;
- PRInt32 max, max_fd;
- PRInt32 rv;
- /*
- * For restarting select() if it is interrupted by a Unix signal.
- * We use these variables to figure out how much time has elapsed
- * and how much of the timeout still remains.
- */
- PRIntervalTime start = 0, elapsed, remaining;
-
- static PRBool unwarned = PR_TRUE;
- if (unwarned) unwarned = _PR_Obsolete( "PR_Select", "PR_Poll");
-
- FD_ZERO(&rd);
- FD_ZERO(&wr);
- FD_ZERO(&ex);
-
- max_fd = _PR_getset(pr_rd, &rd);
- max_fd = (max = _PR_getset(pr_wr, &wr))>max_fd?max:max_fd;
- max_fd = (max = _PR_getset(pr_ex, &ex))>max_fd?max:max_fd;
-
- if (timeout == PR_INTERVAL_NO_TIMEOUT) {
- tvp = NULL;
- } else {
- tv.tv_sec = (PRInt32)PR_IntervalToSeconds(timeout);
- tv.tv_usec = (PRInt32)PR_IntervalToMicroseconds(
- timeout - PR_SecondsToInterval(tv.tv_sec));
- tvp = &tv;
- start = PR_IntervalNow();
- }
-
-retry:
- rv = select(max_fd + 1, (_PRSelectFdSetArg_t) &rd,
- (_PRSelectFdSetArg_t) &wr, (_PRSelectFdSetArg_t) &ex, tvp);
-
- if (rv == -1 && errno == EINTR) {
- if (timeout == PR_INTERVAL_NO_TIMEOUT) {
- goto retry;
- } else {
- elapsed = (PRIntervalTime) (PR_IntervalNow() - start);
- if (elapsed > timeout) {
- rv = 0; /* timed out */
- } else {
- remaining = timeout - elapsed;
- tv.tv_sec = (PRInt32)PR_IntervalToSeconds(remaining);
- tv.tv_usec = (PRInt32)PR_IntervalToMicroseconds(
- remaining - PR_SecondsToInterval(tv.tv_sec));
- goto retry;
- }
- }
- }
-
- if (rv > 0) {
- _PR_setset(pr_rd, &rd);
- _PR_setset(pr_wr, &wr);
- _PR_setset(pr_ex, &ex);
- } else if (rv == -1) {
- pt_MapError(_PR_MD_MAP_SELECT_ERROR, errno);
- }
- return rv;
-}
-#endif /* defined(_PR_PTHREADS) */
-
-#ifdef MOZ_UNICODE
-/* ================ UTF16 Interfaces ================================ */
-PR_IMPLEMENT(PRFileDesc*) PR_OpenFileUTF16(
- const PRUnichar *name, PRIntn flags, PRIntn mode)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return NULL;
-}
-
-PR_IMPLEMENT(PRStatus) PR_CloseDirUTF16(PRDir *dir)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-}
-
-PR_IMPLEMENT(PRDirUTF16*) PR_OpenDirUTF16(const PRUnichar *name)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return NULL;
-}
-
-PR_IMPLEMENT(PRDirEntryUTF16*) PR_ReadDirUTF16(PRDirUTF16 *dir, PRDirFlags flags)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return NULL;
-}
-
-PR_IMPLEMENT(PRStatus) PR_GetFileInfo64UTF16(const PRUnichar *fn, PRFileInfo64 *info)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-}
-/* ================ UTF16 Interfaces ================================ */
-#endif /* MOZ_UNICODE */
-
-/* ptio.c */
diff --git a/nspr/pr/src/pthreads/ptmisc.c b/nspr/pr/src/pthreads/ptmisc.c
deleted file mode 100644
index bbc6d56..0000000
--- a/nspr/pr/src/pthreads/ptmisc.c
+++ /dev/null
@@ -1,39 +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/. */
-
-/*
-** File: ptmisc.c
-** Descritpion: Implemenation of miscellaneous methods for pthreads
-*/
-
-#if defined(_PR_PTHREADS)
-
-#include "primpl.h"
-
-#include <stdio.h>
-#ifdef SOLARIS
-#include <thread.h>
-#endif
-
-#define PT_LOG(f)
-
-void _PR_InitCPUs(void) {PT_LOG("_PR_InitCPUs")}
-void _PR_InitStacks(void) {PT_LOG("_PR_InitStacks")}
-
-PR_IMPLEMENT(void) PR_SetConcurrency(PRUintn numCPUs)
-{
-#ifdef SOLARIS
- thr_setconcurrency(numCPUs);
-#else
- PT_LOG("PR_SetConcurrency");
-#endif
-}
-
-PR_IMPLEMENT(void) PR_SetThreadRecycleMode(PRUint32 flag)
- {PT_LOG("PR_SetThreadRecycleMode")}
-
-#endif /* defined(_PR_PTHREADS) */
-
-/* ptmisc.c */
diff --git a/nspr/pr/src/pthreads/ptsynch.c b/nspr/pr/src/pthreads/ptsynch.c
deleted file mode 100644
index 8663a4c..0000000
--- a/nspr/pr/src/pthreads/ptsynch.c
+++ /dev/null
@@ -1,1259 +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/. */
-
-/*
-** File: ptsynch.c
-** Descritpion: Implemenation for thread synchronization using pthreads
-** Exports: prlock.h, prcvar.h, prmon.h, prcmon.h
-*/
-
-#if defined(_PR_PTHREADS)
-
-#include "primpl.h"
-#include "obsolete/prsem.h"
-
-#include <string.h>
-#include <pthread.h>
-#include <sys/time.h>
-
-static pthread_mutexattr_t _pt_mattr;
-static pthread_condattr_t _pt_cvar_attr;
-
-#if defined(DEBUG)
-extern PTDebug pt_debug; /* this is shared between several modules */
-
-#if defined(_PR_DCETHREADS)
-static pthread_t pt_zero_tid; /* a null pthread_t (pthread_t is a struct
- * in DCE threads) to compare with */
-#endif /* defined(_PR_DCETHREADS) */
-#endif /* defined(DEBUG) */
-
-#if defined(FREEBSD)
-/*
- * On older versions of FreeBSD, pthread_mutex_trylock returns EDEADLK.
- * Newer versions return EBUSY. We still need to support both.
- */
-static int
-pt_pthread_mutex_is_locked(pthread_mutex_t *m)
-{
- int rv = pthread_mutex_trylock(m);
- return (EBUSY == rv || EDEADLK == rv);
-}
-#endif
-
-/**************************************************************/
-/**************************************************************/
-/*****************************LOCKS****************************/
-/**************************************************************/
-/**************************************************************/
-
-void _PR_InitLocks(void)
-{
- int rv;
- rv = _PT_PTHREAD_MUTEXATTR_INIT(&_pt_mattr);
- PR_ASSERT(0 == rv);
-
-#ifdef LINUX
-#if (__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)
- rv = pthread_mutexattr_settype(&_pt_mattr, PTHREAD_MUTEX_ADAPTIVE_NP);
- PR_ASSERT(0 == rv);
-#endif
-#endif
-
- rv = _PT_PTHREAD_CONDATTR_INIT(&_pt_cvar_attr);
- PR_ASSERT(0 == rv);
-}
-
-static void pt_PostNotifies(PRLock *lock, PRBool unlock)
-{
- PRIntn index, rv;
- _PT_Notified post;
- _PT_Notified *notified, *prev = NULL;
- /*
- * Time to actually notify any conditions that were affected
- * while the lock was held. Get a copy of the list that's in
- * the lock structure and then zero the original. If it's
- * linked to other such structures, we own that storage.
- */
- post = lock->notified; /* a safe copy; we own the lock */
-
-#if defined(DEBUG)
- memset(&lock->notified, 0, sizeof(_PT_Notified)); /* reset */
-#else
- lock->notified.length = 0; /* these are really sufficient */
- lock->notified.link = NULL;
-#endif
-
- /* should (may) we release lock before notifying? */
- if (unlock)
- {
- rv = pthread_mutex_unlock(&lock->mutex);
- PR_ASSERT(0 == rv);
- }
-
- notified = &post; /* this is where we start */
- do
- {
- for (index = 0; index < notified->length; ++index)
- {
- PRCondVar *cv = notified->cv[index].cv;
- PR_ASSERT(NULL != cv);
- PR_ASSERT(0 != notified->cv[index].times);
- if (-1 == notified->cv[index].times)
- {
- rv = pthread_cond_broadcast(&cv->cv);
- PR_ASSERT(0 == rv);
- }
- else
- {
- while (notified->cv[index].times-- > 0)
- {
- rv = pthread_cond_signal(&cv->cv);
- PR_ASSERT(0 == rv);
- }
- }
-#if defined(DEBUG)
- pt_debug.cvars_notified += 1;
- if (0 > PR_ATOMIC_DECREMENT(&cv->notify_pending))
- {
- pt_debug.delayed_cv_deletes += 1;
- PR_DestroyCondVar(cv);
- }
-#else /* defined(DEBUG) */
- if (0 > PR_ATOMIC_DECREMENT(&cv->notify_pending))
- PR_DestroyCondVar(cv);
-#endif /* defined(DEBUG) */
- }
- prev = notified;
- notified = notified->link;
- if (&post != prev) PR_DELETE(prev);
- } while (NULL != notified);
-} /* pt_PostNotifies */
-
-PR_IMPLEMENT(PRLock*) PR_NewLock(void)
-{
- PRIntn rv;
- PRLock *lock;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- lock = PR_NEWZAP(PRLock);
- if (lock != NULL)
- {
- rv = _PT_PTHREAD_MUTEX_INIT(lock->mutex, _pt_mattr);
- PR_ASSERT(0 == rv);
- }
-#if defined(DEBUG)
- pt_debug.locks_created += 1;
-#endif
- return lock;
-} /* PR_NewLock */
-
-PR_IMPLEMENT(void) PR_DestroyLock(PRLock *lock)
-{
- PRIntn rv;
- PR_ASSERT(NULL != lock);
- PR_ASSERT(PR_FALSE == lock->locked);
- PR_ASSERT(0 == lock->notified.length);
- PR_ASSERT(NULL == lock->notified.link);
- rv = pthread_mutex_destroy(&lock->mutex);
- PR_ASSERT(0 == rv);
-#if defined(DEBUG)
- memset(lock, 0xaf, sizeof(PRLock));
- pt_debug.locks_destroyed += 1;
-#endif
- PR_Free(lock);
-} /* PR_DestroyLock */
-
-PR_IMPLEMENT(void) PR_Lock(PRLock *lock)
-{
- /* Nb: PR_Lock must not call PR_GetCurrentThread to access the |id| or
- * |tid| field of the current thread's PRThread structure because
- * _pt_root calls PR_Lock before setting thred->id and thred->tid. */
- PRIntn rv;
- PR_ASSERT(lock != NULL);
- rv = pthread_mutex_lock(&lock->mutex);
- PR_ASSERT(0 == rv);
- PR_ASSERT(0 == lock->notified.length);
- PR_ASSERT(NULL == lock->notified.link);
- PR_ASSERT(PR_FALSE == lock->locked);
- /* Nb: the order of the next two statements is not critical to
- * the correctness of PR_AssertCurrentThreadOwnsLock(), but
- * this particular order makes the assertion more likely to
- * catch errors. */
- lock->owner = pthread_self();
- lock->locked = PR_TRUE;
-#if defined(DEBUG)
- pt_debug.locks_acquired += 1;
-#endif
-} /* PR_Lock */
-
-PR_IMPLEMENT(PRStatus) PR_Unlock(PRLock *lock)
-{
- pthread_t self = pthread_self();
- PRIntn rv;
-
- PR_ASSERT(lock != NULL);
- PR_ASSERT(_PT_PTHREAD_MUTEX_IS_LOCKED(lock->mutex));
- PR_ASSERT(PR_TRUE == lock->locked);
- PR_ASSERT(pthread_equal(lock->owner, self));
-
- if (!lock->locked || !pthread_equal(lock->owner, self))
- return PR_FAILURE;
-
- lock->locked = PR_FALSE;
- if (0 == lock->notified.length) /* shortcut */
- {
- rv = pthread_mutex_unlock(&lock->mutex);
- PR_ASSERT(0 == rv);
- }
- else pt_PostNotifies(lock, PR_TRUE);
-
-#if defined(DEBUG)
- pt_debug.locks_released += 1;
-#endif
- return PR_SUCCESS;
-} /* PR_Unlock */
-
-PR_IMPLEMENT(void) PR_AssertCurrentThreadOwnsLock(PRLock *lock)
-{
- /* Nb: the order of the |locked| and |owner==me| checks is not critical
- * to the correctness of PR_AssertCurrentThreadOwnsLock(), but
- * this particular order makes the assertion more likely to
- * catch errors. */
- PR_ASSERT(lock->locked && pthread_equal(lock->owner, pthread_self()));
-}
-
-/**************************************************************/
-/**************************************************************/
-/***************************CONDITIONS*************************/
-/**************************************************************/
-/**************************************************************/
-
-
-/*
- * This code is used to compute the absolute time for the wakeup.
- * It's moderately ugly, so it's defined here and called in a
- * couple of places.
- */
-#define PT_NANOPERMICRO 1000UL
-#define PT_BILLION 1000000000UL
-
-static PRIntn pt_TimedWait(
- pthread_cond_t *cv, pthread_mutex_t *ml, PRIntervalTime timeout)
-{
- int rv;
- struct timeval now;
- struct timespec tmo;
- PRUint32 ticks = PR_TicksPerSecond();
-
- tmo.tv_sec = (PRInt32)(timeout / ticks);
- tmo.tv_nsec = (PRInt32)(timeout - (tmo.tv_sec * ticks));
- tmo.tv_nsec = (PRInt32)PR_IntervalToMicroseconds(PT_NANOPERMICRO * tmo.tv_nsec);
-
- /* pthreads wants this in absolute time, off we go ... */
- (void)GETTIMEOFDAY(&now);
- /* that one's usecs, this one's nsecs - grrrr! */
- tmo.tv_sec += now.tv_sec;
- tmo.tv_nsec += (PT_NANOPERMICRO * now.tv_usec);
- tmo.tv_sec += tmo.tv_nsec / PT_BILLION;
- tmo.tv_nsec %= PT_BILLION;
-
- rv = pthread_cond_timedwait(cv, ml, &tmo);
-
- /* NSPR doesn't report timeouts */
-#ifdef _PR_DCETHREADS
- if (rv == -1) return (errno == EAGAIN) ? 0 : errno;
- else return rv;
-#else
- return (rv == ETIMEDOUT) ? 0 : rv;
-#endif
-} /* pt_TimedWait */
-
-
-/*
- * Notifies just get posted to the protecting mutex. The
- * actual notification is done when the lock is released so that
- * MP systems don't contend for a lock that they can't have.
- */
-static void pt_PostNotifyToCvar(PRCondVar *cvar, PRBool broadcast)
-{
- PRIntn index = 0;
- _PT_Notified *notified = &cvar->lock->notified;
-
- PR_ASSERT(PR_TRUE == cvar->lock->locked);
- PR_ASSERT(pthread_equal(cvar->lock->owner, pthread_self()));
- PR_ASSERT(_PT_PTHREAD_MUTEX_IS_LOCKED(cvar->lock->mutex));
-
- while (1)
- {
- for (index = 0; index < notified->length; ++index)
- {
- if (notified->cv[index].cv == cvar)
- {
- if (broadcast)
- notified->cv[index].times = -1;
- else if (-1 != notified->cv[index].times)
- notified->cv[index].times += 1;
- return; /* we're finished */
- }
- }
- /* if not full, enter new CV in this array */
- if (notified->length < PT_CV_NOTIFIED_LENGTH) break;
-
- /* if there's no link, create an empty array and link it */
- if (NULL == notified->link)
- notified->link = PR_NEWZAP(_PT_Notified);
- notified = notified->link;
- }
-
- /* A brand new entry in the array */
- (void)PR_ATOMIC_INCREMENT(&cvar->notify_pending);
- notified->cv[index].times = (broadcast) ? -1 : 1;
- notified->cv[index].cv = cvar;
- notified->length += 1;
-} /* pt_PostNotifyToCvar */
-
-PR_IMPLEMENT(PRCondVar*) PR_NewCondVar(PRLock *lock)
-{
- PRCondVar *cv = PR_NEW(PRCondVar);
- PR_ASSERT(lock != NULL);
- if (cv != NULL)
- {
- int rv = _PT_PTHREAD_COND_INIT(cv->cv, _pt_cvar_attr);
- PR_ASSERT(0 == rv);
- if (0 == rv)
- {
- cv->lock = lock;
- cv->notify_pending = 0;
-#if defined(DEBUG)
- pt_debug.cvars_created += 1;
-#endif
- }
- else
- {
- PR_DELETE(cv);
- cv = NULL;
- }
- }
- return cv;
-} /* PR_NewCondVar */
-
-PR_IMPLEMENT(void) PR_DestroyCondVar(PRCondVar *cvar)
-{
- if (0 > PR_ATOMIC_DECREMENT(&cvar->notify_pending))
- {
- PRIntn rv = pthread_cond_destroy(&cvar->cv);
-#if defined(DEBUG)
- PR_ASSERT(0 == rv);
- memset(cvar, 0xaf, sizeof(PRCondVar));
- pt_debug.cvars_destroyed += 1;
-#else
- (void)rv;
-#endif
- PR_Free(cvar);
- }
-} /* PR_DestroyCondVar */
-
-PR_IMPLEMENT(PRStatus) PR_WaitCondVar(PRCondVar *cvar, PRIntervalTime timeout)
-{
- PRIntn rv;
- PRThread *thred = PR_GetCurrentThread();
-
- PR_ASSERT(cvar != NULL);
- /* We'd better be locked */
- PR_ASSERT(_PT_PTHREAD_MUTEX_IS_LOCKED(cvar->lock->mutex));
- PR_ASSERT(PR_TRUE == cvar->lock->locked);
- /* and it better be by us */
- PR_ASSERT(pthread_equal(cvar->lock->owner, pthread_self()));
-
- if (_PT_THREAD_INTERRUPTED(thred)) goto aborted;
-
- /*
- * The thread waiting is used for PR_Interrupt
- */
- thred->waiting = cvar; /* this is where we're waiting */
-
- /*
- * If we have pending notifies, post them now.
- *
- * This is not optimal. We're going to post these notifies
- * while we're holding the lock. That means on MP systems
- * that they are going to collide for the lock that we will
- * hold until we actually wait.
- */
- if (0 != cvar->lock->notified.length)
- pt_PostNotifies(cvar->lock, PR_FALSE);
-
- /*
- * We're surrendering the lock, so clear out the locked field.
- */
- cvar->lock->locked = PR_FALSE;
-
- if (timeout == PR_INTERVAL_NO_TIMEOUT)
- rv = pthread_cond_wait(&cvar->cv, &cvar->lock->mutex);
- else
- rv = pt_TimedWait(&cvar->cv, &cvar->lock->mutex, timeout);
-
- /* We just got the lock back - this better be empty */
- PR_ASSERT(PR_FALSE == cvar->lock->locked);
- cvar->lock->locked = PR_TRUE;
- cvar->lock->owner = pthread_self();
-
- PR_ASSERT(0 == cvar->lock->notified.length);
- thred->waiting = NULL; /* and now we're not */
- if (_PT_THREAD_INTERRUPTED(thred)) goto aborted;
- if (rv != 0)
- {
- _PR_MD_MAP_DEFAULT_ERROR(rv);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-
-aborted:
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- thred->state &= ~PT_THREAD_ABORTED;
- return PR_FAILURE;
-} /* PR_WaitCondVar */
-
-PR_IMPLEMENT(PRStatus) PR_NotifyCondVar(PRCondVar *cvar)
-{
- PR_ASSERT(cvar != NULL);
- pt_PostNotifyToCvar(cvar, PR_FALSE);
- return PR_SUCCESS;
-} /* PR_NotifyCondVar */
-
-PR_IMPLEMENT(PRStatus) PR_NotifyAllCondVar(PRCondVar *cvar)
-{
- PR_ASSERT(cvar != NULL);
- pt_PostNotifyToCvar(cvar, PR_TRUE);
- return PR_SUCCESS;
-} /* PR_NotifyAllCondVar */
-
-/**************************************************************/
-/**************************************************************/
-/***************************MONITORS***************************/
-/**************************************************************/
-/**************************************************************/
-
-/*
- * Notifies just get posted to the monitor. The actual notification is done
- * when the monitor is fully exited so that MP systems don't contend for a
- * monitor that they can't enter.
- */
-static void pt_PostNotifyToMonitor(PRMonitor *mon, PRBool broadcast)
-{
- PR_ASSERT(NULL != mon);
- PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mon);
-
- /* mon->notifyTimes is protected by the monitor, so we don't need to
- * acquire mon->lock.
- */
- if (broadcast)
- mon->notifyTimes = -1;
- else if (-1 != mon->notifyTimes)
- mon->notifyTimes += 1;
-} /* pt_PostNotifyToMonitor */
-
-static void pt_PostNotifiesFromMonitor(pthread_cond_t *cv, PRIntn times)
-{
- PRIntn rv;
-
- /*
- * Time to actually notify any waits that were affected while the monitor
- * was entered.
- */
- PR_ASSERT(NULL != cv);
- PR_ASSERT(0 != times);
- if (-1 == times)
- {
- rv = pthread_cond_broadcast(cv);
- PR_ASSERT(0 == rv);
- }
- else
- {
- while (times-- > 0)
- {
- rv = pthread_cond_signal(cv);
- PR_ASSERT(0 == rv);
- }
- }
-} /* pt_PostNotifiesFromMonitor */
-
-PR_IMPLEMENT(PRMonitor*) PR_NewMonitor(void)
-{
- PRMonitor *mon;
- int rv;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- mon = PR_NEWZAP(PRMonitor);
- if (mon == NULL)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
-
- rv = _PT_PTHREAD_MUTEX_INIT(mon->lock, _pt_mattr);
- PR_ASSERT(0 == rv);
- if (0 != rv)
- goto error1;
-
- _PT_PTHREAD_INVALIDATE_THR_HANDLE(mon->owner);
-
- rv = _PT_PTHREAD_COND_INIT(mon->entryCV, _pt_cvar_attr);
- PR_ASSERT(0 == rv);
- if (0 != rv)
- goto error2;
-
- rv = _PT_PTHREAD_COND_INIT(mon->waitCV, _pt_cvar_attr);
- PR_ASSERT(0 == rv);
- if (0 != rv)
- goto error3;
-
- mon->notifyTimes = 0;
- mon->entryCount = 0;
- mon->refCount = 1;
- mon->name = NULL;
- return mon;
-
-error3:
- pthread_cond_destroy(&mon->entryCV);
-error2:
- pthread_mutex_destroy(&mon->lock);
-error1:
- PR_Free(mon);
- _PR_MD_MAP_DEFAULT_ERROR(rv);
- return NULL;
-} /* PR_NewMonitor */
-
-PR_IMPLEMENT(PRMonitor*) PR_NewNamedMonitor(const char* name)
-{
- PRMonitor* mon = PR_NewMonitor();
- if (mon)
- mon->name = name;
- return mon;
-}
-
-PR_IMPLEMENT(void) PR_DestroyMonitor(PRMonitor *mon)
-{
- int rv;
-
- PR_ASSERT(mon != NULL);
- if (PR_ATOMIC_DECREMENT(&mon->refCount) == 0)
- {
- rv = pthread_cond_destroy(&mon->waitCV); PR_ASSERT(0 == rv);
- rv = pthread_cond_destroy(&mon->entryCV); PR_ASSERT(0 == rv);
- rv = pthread_mutex_destroy(&mon->lock); PR_ASSERT(0 == rv);
-#if defined(DEBUG)
- memset(mon, 0xaf, sizeof(PRMonitor));
-#endif
- PR_Free(mon);
- }
-} /* PR_DestroyMonitor */
-
-/* The GC uses this; it is quite arguably a bad interface. I'm just
- * duplicating it for now - XXXMB
- */
-PR_IMPLEMENT(PRIntn) PR_GetMonitorEntryCount(PRMonitor *mon)
-{
- pthread_t self = pthread_self();
- PRIntn rv;
- PRIntn count = 0;
-
- rv = pthread_mutex_lock(&mon->lock);
- PR_ASSERT(0 == rv);
- if (pthread_equal(mon->owner, self))
- count = mon->entryCount;
- rv = pthread_mutex_unlock(&mon->lock);
- PR_ASSERT(0 == rv);
- return count;
-}
-
-PR_IMPLEMENT(void) PR_AssertCurrentThreadInMonitor(PRMonitor *mon)
-{
-#if defined(DEBUG) || defined(FORCE_PR_ASSERT)
- PRIntn rv;
-
- rv = pthread_mutex_lock(&mon->lock);
- PR_ASSERT(0 == rv);
- PR_ASSERT(mon->entryCount != 0 &&
- pthread_equal(mon->owner, pthread_self()));
- rv = pthread_mutex_unlock(&mon->lock);
- PR_ASSERT(0 == rv);
-#endif
-}
-
-PR_IMPLEMENT(void) PR_EnterMonitor(PRMonitor *mon)
-{
- pthread_t self = pthread_self();
- PRIntn rv;
-
- PR_ASSERT(mon != NULL);
- rv = pthread_mutex_lock(&mon->lock);
- PR_ASSERT(0 == rv);
- if (mon->entryCount != 0)
- {
- if (pthread_equal(mon->owner, self))
- goto done;
- while (mon->entryCount != 0)
- {
- rv = pthread_cond_wait(&mon->entryCV, &mon->lock);
- PR_ASSERT(0 == rv);
- }
- }
- /* and now I have the monitor */
- PR_ASSERT(0 == mon->notifyTimes);
- PR_ASSERT(_PT_PTHREAD_THR_HANDLE_IS_INVALID(mon->owner));
- _PT_PTHREAD_COPY_THR_HANDLE(self, mon->owner);
-
-done:
- mon->entryCount += 1;
- rv = pthread_mutex_unlock(&mon->lock);
- PR_ASSERT(0 == rv);
-} /* PR_EnterMonitor */
-
-PR_IMPLEMENT(PRStatus) PR_ExitMonitor(PRMonitor *mon)
-{
- pthread_t self = pthread_self();
- PRIntn rv;
- PRBool notifyEntryWaiter = PR_FALSE;
- PRIntn notifyTimes = 0;
-
- PR_ASSERT(mon != NULL);
- rv = pthread_mutex_lock(&mon->lock);
- PR_ASSERT(0 == rv);
- /* the entries should be > 0 and we'd better be the owner */
- PR_ASSERT(mon->entryCount > 0);
- PR_ASSERT(pthread_equal(mon->owner, self));
- if (mon->entryCount == 0 || !pthread_equal(mon->owner, self))
- {
- rv = pthread_mutex_unlock(&mon->lock);
- PR_ASSERT(0 == rv);
- return PR_FAILURE;
- }
-
- mon->entryCount -= 1; /* reduce by one */
- if (mon->entryCount == 0)
- {
- /* and if it transitioned to zero - notify an entry waiter */
- /* make the owner unknown */
- _PT_PTHREAD_INVALIDATE_THR_HANDLE(mon->owner);
- notifyEntryWaiter = PR_TRUE;
- notifyTimes = mon->notifyTimes;
- mon->notifyTimes = 0;
- /* We will access the members of 'mon' after unlocking mon->lock.
- * Add a reference. */
- PR_ATOMIC_INCREMENT(&mon->refCount);
- }
- rv = pthread_mutex_unlock(&mon->lock);
- PR_ASSERT(0 == rv);
- if (notifyEntryWaiter)
- {
- if (notifyTimes)
- pt_PostNotifiesFromMonitor(&mon->waitCV, notifyTimes);
- rv = pthread_cond_signal(&mon->entryCV);
- PR_ASSERT(0 == rv);
- /* We are done accessing the members of 'mon'. Release the
- * reference. */
- PR_DestroyMonitor(mon);
- }
- return PR_SUCCESS;
-} /* PR_ExitMonitor */
-
-PR_IMPLEMENT(PRStatus) PR_Wait(PRMonitor *mon, PRIntervalTime timeout)
-{
- PRStatus rv;
- PRUint32 saved_entries;
- pthread_t saved_owner;
-
- PR_ASSERT(mon != NULL);
- rv = pthread_mutex_lock(&mon->lock);
- PR_ASSERT(0 == rv);
- /* the entries better be positive */
- PR_ASSERT(mon->entryCount > 0);
- /* and it better be owned by us */
- PR_ASSERT(pthread_equal(mon->owner, pthread_self()));
-
- /* tuck these away 'till later */
- saved_entries = mon->entryCount;
- mon->entryCount = 0;
- _PT_PTHREAD_COPY_THR_HANDLE(mon->owner, saved_owner);
- _PT_PTHREAD_INVALIDATE_THR_HANDLE(mon->owner);
- /*
- * If we have pending notifies, post them now.
- *
- * This is not optimal. We're going to post these notifies
- * while we're holding the lock. That means on MP systems
- * that they are going to collide for the lock that we will
- * hold until we actually wait.
- */
- if (0 != mon->notifyTimes)
- {
- pt_PostNotifiesFromMonitor(&mon->waitCV, mon->notifyTimes);
- mon->notifyTimes = 0;
- }
- rv = pthread_cond_signal(&mon->entryCV);
- PR_ASSERT(0 == rv);
-
- if (timeout == PR_INTERVAL_NO_TIMEOUT)
- rv = pthread_cond_wait(&mon->waitCV, &mon->lock);
- else
- rv = pt_TimedWait(&mon->waitCV, &mon->lock, timeout);
- PR_ASSERT(0 == rv);
-
- while (mon->entryCount != 0)
- {
- rv = pthread_cond_wait(&mon->entryCV, &mon->lock);
- PR_ASSERT(0 == rv);
- }
- PR_ASSERT(0 == mon->notifyTimes);
- /* reinstate the interesting information */
- mon->entryCount = saved_entries;
- _PT_PTHREAD_COPY_THR_HANDLE(saved_owner, mon->owner);
-
- rv = pthread_mutex_unlock(&mon->lock);
- PR_ASSERT(0 == rv);
- return rv;
-} /* PR_Wait */
-
-PR_IMPLEMENT(PRStatus) PR_Notify(PRMonitor *mon)
-{
- pt_PostNotifyToMonitor(mon, PR_FALSE);
- return PR_SUCCESS;
-} /* PR_Notify */
-
-PR_IMPLEMENT(PRStatus) PR_NotifyAll(PRMonitor *mon)
-{
- pt_PostNotifyToMonitor(mon, PR_TRUE);
- return PR_SUCCESS;
-} /* PR_NotifyAll */
-
-/**************************************************************/
-/**************************************************************/
-/**************************SEMAPHORES**************************/
-/**************************************************************/
-/**************************************************************/
-PR_IMPLEMENT(void) PR_PostSem(PRSemaphore *semaphore)
-{
- static PRBool unwarned = PR_TRUE;
- if (unwarned) unwarned = _PR_Obsolete(
- "PR_PostSem", "locks & condition variables");
- PR_Lock(semaphore->cvar->lock);
- PR_NotifyCondVar(semaphore->cvar);
- semaphore->count += 1;
- PR_Unlock(semaphore->cvar->lock);
-} /* PR_PostSem */
-
-PR_IMPLEMENT(PRStatus) PR_WaitSem(PRSemaphore *semaphore)
-{
- PRStatus status = PR_SUCCESS;
- static PRBool unwarned = PR_TRUE;
- if (unwarned) unwarned = _PR_Obsolete(
- "PR_WaitSem", "locks & condition variables");
- PR_Lock(semaphore->cvar->lock);
- while ((semaphore->count == 0) && (PR_SUCCESS == status))
- status = PR_WaitCondVar(semaphore->cvar, PR_INTERVAL_NO_TIMEOUT);
- if (PR_SUCCESS == status) semaphore->count -= 1;
- PR_Unlock(semaphore->cvar->lock);
- return status;
-} /* PR_WaitSem */
-
-PR_IMPLEMENT(void) PR_DestroySem(PRSemaphore *semaphore)
-{
- static PRBool unwarned = PR_TRUE;
- if (unwarned) unwarned = _PR_Obsolete(
- "PR_DestroySem", "locks & condition variables");
- PR_DestroyLock(semaphore->cvar->lock);
- PR_DestroyCondVar(semaphore->cvar);
- PR_Free(semaphore);
-} /* PR_DestroySem */
-
-PR_IMPLEMENT(PRSemaphore*) PR_NewSem(PRUintn value)
-{
- PRSemaphore *semaphore;
- static PRBool unwarned = PR_TRUE;
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (unwarned) unwarned = _PR_Obsolete(
- "PR_NewSem", "locks & condition variables");
-
- semaphore = PR_NEWZAP(PRSemaphore);
- if (NULL != semaphore)
- {
- PRLock *lock = PR_NewLock();
- if (NULL != lock)
- {
- semaphore->cvar = PR_NewCondVar(lock);
- if (NULL != semaphore->cvar)
- {
- semaphore->count = value;
- return semaphore;
- }
- PR_DestroyLock(lock);
- }
- PR_Free(semaphore);
- }
- return NULL;
-}
-
-/*
- * Define the interprocess named semaphore functions.
- * There are three implementations:
- * 1. POSIX semaphore based;
- * 2. System V semaphore based;
- * 3. unsupported (fails with PR_NOT_IMPLEMENTED_ERROR).
- */
-
-#ifdef _PR_HAVE_POSIX_SEMAPHORES
-#include <fcntl.h>
-
-PR_IMPLEMENT(PRSem *) PR_OpenSemaphore(
- const char *name,
- PRIntn flags,
- PRIntn mode,
- PRUintn value)
-{
- PRSem *sem;
- char osname[PR_IPC_NAME_SIZE];
-
- if (_PR_MakeNativeIPCName(name, osname, sizeof(osname), _PRIPCSem)
- == PR_FAILURE)
- {
- return NULL;
- }
-
- sem = PR_NEW(PRSem);
- if (NULL == sem)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
-
- if (flags & PR_SEM_CREATE)
- {
- int oflag = O_CREAT;
-
- if (flags & PR_SEM_EXCL) oflag |= O_EXCL;
- sem->sem = sem_open(osname, oflag, mode, value);
- }
- else
- {
-#ifdef HPUX
- /* Pass 0 as the mode and value arguments to work around a bug. */
- sem->sem = sem_open(osname, 0, 0, 0);
-#else
- sem->sem = sem_open(osname, 0);
-#endif
- }
- if ((sem_t *) -1 == sem->sem)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- PR_Free(sem);
- return NULL;
- }
- return sem;
-}
-
-PR_IMPLEMENT(PRStatus) PR_WaitSemaphore(PRSem *sem)
-{
- int rv;
- rv = sem_wait(sem->sem);
- if (0 != rv)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus) PR_PostSemaphore(PRSem *sem)
-{
- int rv;
- rv = sem_post(sem->sem);
- if (0 != rv)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus) PR_CloseSemaphore(PRSem *sem)
-{
- int rv;
- rv = sem_close(sem->sem);
- if (0 != rv)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- return PR_FAILURE;
- }
- PR_Free(sem);
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus) PR_DeleteSemaphore(const char *name)
-{
- int rv;
- char osname[PR_IPC_NAME_SIZE];
-
- if (_PR_MakeNativeIPCName(name, osname, sizeof(osname), _PRIPCSem)
- == PR_FAILURE)
- {
- return PR_FAILURE;
- }
- rv = sem_unlink(osname);
- if (0 != rv)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-#elif defined(_PR_HAVE_SYSV_SEMAPHORES)
-
-#include <fcntl.h>
-#include <sys/sem.h>
-
-/*
- * From the semctl(2) man page in glibc 2.0
- */
-#if (defined(__GNU_LIBRARY__) && !defined(_SEM_SEMUN_UNDEFINED)) \
- || defined(FREEBSD) || defined(OPENBSD) || defined(BSDI) \
- || defined(DARWIN) || defined(SYMBIAN)
-/* union semun is defined by including <sys/sem.h> */
-#else
-/* according to X/OPEN we have to define it ourselves */
-union semun {
- int val;
- struct semid_ds *buf;
- unsigned short *array;
-};
-#endif
-
-/*
- * 'a' (97) is the final closing price of NSCP stock.
- */
-#define NSPR_IPC_KEY_ID 'a' /* the id argument for ftok() */
-
-#define NSPR_SEM_MODE 0666
-
-PR_IMPLEMENT(PRSem *) PR_OpenSemaphore(
- const char *name,
- PRIntn flags,
- PRIntn mode,
- PRUintn value)
-{
- PRSem *sem;
- key_t key;
- union semun arg;
- struct sembuf sop;
- struct semid_ds seminfo;
-#define MAX_TRIES 60
- PRIntn i;
- char osname[PR_IPC_NAME_SIZE];
-
- if (_PR_MakeNativeIPCName(name, osname, sizeof(osname), _PRIPCSem)
- == PR_FAILURE)
- {
- return NULL;
- }
-
- /* Make sure the file exists before calling ftok. */
- if (flags & PR_SEM_CREATE)
- {
- int osfd = open(osname, O_RDWR|O_CREAT, mode);
- if (-1 == osfd)
- {
- _PR_MD_MAP_OPEN_ERROR(errno);
- return NULL;
- }
- if (close(osfd) == -1)
- {
- _PR_MD_MAP_CLOSE_ERROR(errno);
- return NULL;
- }
- }
- key = ftok(osname, NSPR_IPC_KEY_ID);
- if ((key_t)-1 == key)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- return NULL;
- }
-
- sem = PR_NEW(PRSem);
- if (NULL == sem)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
-
- if (flags & PR_SEM_CREATE)
- {
- sem->semid = semget(key, 1, mode|IPC_CREAT|IPC_EXCL);
- if (sem->semid >= 0)
- {
- /* creator of a semaphore is responsible for initializing it */
- arg.val = 0;
- if (semctl(sem->semid, 0, SETVAL, arg) == -1)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- PR_Free(sem);
- return NULL;
- }
- /* call semop to set sem_otime to nonzero */
- sop.sem_num = 0;
- sop.sem_op = value;
- sop.sem_flg = 0;
- if (semop(sem->semid, &sop, 1) == -1)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- PR_Free(sem);
- return NULL;
- }
- return sem;
- }
-
- if (errno != EEXIST || flags & PR_SEM_EXCL)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- PR_Free(sem);
- return NULL;
- }
- }
-
- sem->semid = semget(key, 1, NSPR_SEM_MODE);
- if (sem->semid == -1)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- PR_Free(sem);
- return NULL;
- }
- for (i = 0; i < MAX_TRIES; i++)
- {
- arg.buf = &seminfo;
- semctl(sem->semid, 0, IPC_STAT, arg);
- if (seminfo.sem_otime != 0) break;
- sleep(1);
- }
- if (i == MAX_TRIES)
- {
- PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
- PR_Free(sem);
- return NULL;
- }
- return sem;
-}
-
-PR_IMPLEMENT(PRStatus) PR_WaitSemaphore(PRSem *sem)
-{
- struct sembuf sop;
-
- sop.sem_num = 0;
- sop.sem_op = -1;
- sop.sem_flg = 0;
- if (semop(sem->semid, &sop, 1) == -1)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus) PR_PostSemaphore(PRSem *sem)
-{
- struct sembuf sop;
-
- sop.sem_num = 0;
- sop.sem_op = 1;
- sop.sem_flg = 0;
- if (semop(sem->semid, &sop, 1) == -1)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus) PR_CloseSemaphore(PRSem *sem)
-{
- PR_Free(sem);
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus) PR_DeleteSemaphore(const char *name)
-{
- key_t key;
- int semid;
- /* On some systems (e.g., glibc 2.0) semctl requires a fourth argument */
- union semun unused;
- char osname[PR_IPC_NAME_SIZE];
-
- if (_PR_MakeNativeIPCName(name, osname, sizeof(osname), _PRIPCSem)
- == PR_FAILURE)
- {
- return PR_FAILURE;
- }
- key = ftok(osname, NSPR_IPC_KEY_ID);
- if ((key_t) -1 == key)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- return PR_FAILURE;
- }
- if (unlink(osname) == -1)
- {
- _PR_MD_MAP_UNLINK_ERROR(errno);
- return PR_FAILURE;
- }
- semid = semget(key, 1, NSPR_SEM_MODE);
- if (-1 == semid)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- return PR_FAILURE;
- }
- unused.val = 0;
- if (semctl(semid, 0, IPC_RMID, unused) == -1)
- {
- _PR_MD_MAP_DEFAULT_ERROR(errno);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-#else /* neither POSIX nor System V semaphores are available */
-
-PR_IMPLEMENT(PRSem *) PR_OpenSemaphore(
- const char *name,
- PRIntn flags,
- PRIntn mode,
- PRUintn value)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return NULL;
-}
-
-PR_IMPLEMENT(PRStatus) PR_WaitSemaphore(PRSem *sem)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-}
-
-PR_IMPLEMENT(PRStatus) PR_PostSemaphore(PRSem *sem)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-}
-
-PR_IMPLEMENT(PRStatus) PR_CloseSemaphore(PRSem *sem)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-}
-
-PR_IMPLEMENT(PRStatus) PR_DeleteSemaphore(const char *name)
-{
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return PR_FAILURE;
-}
-
-#endif /* end of interprocess named semaphore functions */
-
-/**************************************************************/
-/**************************************************************/
-/******************ROUTINES FOR DCE EMULATION******************/
-/**************************************************************/
-/**************************************************************/
-
-#include "prpdce.h"
-
-PR_IMPLEMENT(PRStatus) PRP_TryLock(PRLock *lock)
-{
- PRIntn rv = pthread_mutex_trylock(&lock->mutex);
- if (rv == PT_TRYLOCK_SUCCESS)
- {
- PR_ASSERT(PR_FALSE == lock->locked);
- lock->locked = PR_TRUE;
- lock->owner = pthread_self();
- }
- /* XXX set error code? */
- return (PT_TRYLOCK_SUCCESS == rv) ? PR_SUCCESS : PR_FAILURE;
-} /* PRP_TryLock */
-
-PR_IMPLEMENT(PRCondVar*) PRP_NewNakedCondVar(void)
-{
- PRCondVar *cv;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- cv = PR_NEW(PRCondVar);
- if (cv != NULL)
- {
- int rv;
- rv = _PT_PTHREAD_COND_INIT(cv->cv, _pt_cvar_attr);
- PR_ASSERT(0 == rv);
- if (0 == rv)
- {
- cv->lock = _PR_NAKED_CV_LOCK;
- }
- else
- {
- PR_DELETE(cv);
- cv = NULL;
- }
- }
- return cv;
-} /* PRP_NewNakedCondVar */
-
-PR_IMPLEMENT(void) PRP_DestroyNakedCondVar(PRCondVar *cvar)
-{
- int rv;
- rv = pthread_cond_destroy(&cvar->cv); PR_ASSERT(0 == rv);
-#if defined(DEBUG)
- memset(cvar, 0xaf, sizeof(PRCondVar));
-#endif
- PR_Free(cvar);
-} /* PRP_DestroyNakedCondVar */
-
-PR_IMPLEMENT(PRStatus) PRP_NakedWait(
- PRCondVar *cvar, PRLock *ml, PRIntervalTime timeout)
-{
- PRIntn rv;
- PR_ASSERT(cvar != NULL);
- /* XXX do we really want to assert this in a naked wait? */
- PR_ASSERT(_PT_PTHREAD_MUTEX_IS_LOCKED(ml->mutex));
- if (timeout == PR_INTERVAL_NO_TIMEOUT)
- rv = pthread_cond_wait(&cvar->cv, &ml->mutex);
- else
- rv = pt_TimedWait(&cvar->cv, &ml->mutex, timeout);
- if (rv != 0)
- {
- _PR_MD_MAP_DEFAULT_ERROR(rv);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-} /* PRP_NakedWait */
-
-PR_IMPLEMENT(PRStatus) PRP_NakedNotify(PRCondVar *cvar)
-{
- int rv;
- PR_ASSERT(cvar != NULL);
- rv = pthread_cond_signal(&cvar->cv);
- PR_ASSERT(0 == rv);
- return PR_SUCCESS;
-} /* PRP_NakedNotify */
-
-PR_IMPLEMENT(PRStatus) PRP_NakedBroadcast(PRCondVar *cvar)
-{
- int rv;
- PR_ASSERT(cvar != NULL);
- rv = pthread_cond_broadcast(&cvar->cv);
- PR_ASSERT(0 == rv);
- return PR_SUCCESS;
-} /* PRP_NakedBroadcast */
-
-#endif /* defined(_PR_PTHREADS) */
-
-/* ptsynch.c */
diff --git a/nspr/pr/src/pthreads/ptthread.c b/nspr/pr/src/pthreads/ptthread.c
deleted file mode 100644
index 9e12606..0000000
--- a/nspr/pr/src/pthreads/ptthread.c
+++ /dev/null
@@ -1,1822 +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/. */
-
-/*
-** File: ptthread.c
-** Descritpion: Implemenation for threds using pthreds
-** Exports: ptthread.h
-*/
-
-#if defined(_PR_PTHREADS) || defined(_PR_DCETHREADS)
-
-#include "prlog.h"
-#include "primpl.h"
-#include "prpdce.h"
-
-#include <pthread.h>
-#include <unistd.h>
-#include <string.h>
-#include <signal.h>
-#include <dlfcn.h>
-
-#if defined(OPENBSD) || defined(FREEBSD) || defined(DRAGONFLY)
-#include <pthread_np.h>
-#endif
-
-#ifdef SYMBIAN
-/* In Open C sched_get_priority_min/max do not work properly, so we undefine
- * _POSIX_THREAD_PRIORITY_SCHEDULING here.
- */
-#undef _POSIX_THREAD_PRIORITY_SCHEDULING
-#endif
-
-#ifdef _PR_NICE_PRIORITY_SCHEDULING
-#undef _POSIX_THREAD_PRIORITY_SCHEDULING
-#include <sys/resource.h>
-#ifndef HAVE_GETTID
-#define gettid() (syscall(SYS_gettid))
-#endif
-#endif
-
-/*
- * Record whether or not we have the privilege to set the scheduling
- * policy and priority of threads. 0 means that privilege is available.
- * EPERM means that privilege is not available.
- */
-
-static PRIntn pt_schedpriv = 0;
-extern PRLock *_pr_sleeplock;
-
-static struct _PT_Bookeeping
-{
- PRLock *ml; /* a lock to protect ourselves */
- PRCondVar *cv; /* used to signal global things */
- PRInt32 system, user; /* a count of the two different types */
- PRUintn this_many; /* number of threads allowed for exit */
- pthread_key_t key; /* thread private data key */
- PRBool keyCreated; /* whether 'key' should be deleted */
- PRThread *first, *last; /* list of threads we know about */
-#if defined(_PR_DCETHREADS) || _POSIX_THREAD_PRIORITY_SCHEDULING > 0
- PRInt32 minPrio, maxPrio; /* range of scheduling priorities */
-#endif
-} pt_book = {0};
-
-static void _pt_thread_death(void *arg);
-static void _pt_thread_death_internal(void *arg, PRBool callDestructors);
-static void init_pthread_gc_support(void);
-
-#if defined(_PR_DCETHREADS) || _POSIX_THREAD_PRIORITY_SCHEDULING > 0
-static PRIntn pt_PriorityMap(PRThreadPriority pri)
-{
-#ifdef NTO
- /* This priority algorithm causes lots of problems on Neutrino
- * for now I have just hard coded everything to run at priority 10
- * until I can come up with a new algorithm.
- * [email protected]
- */
- return 10;
-#else
- return pt_book.minPrio +
- pri * (pt_book.maxPrio - pt_book.minPrio) / PR_PRIORITY_LAST;
-#endif
-}
-#elif defined(_PR_NICE_PRIORITY_SCHEDULING)
-/*
- * This functions maps higher priorities to lower nice values relative to the
- * nice value specified in the |nice| parameter. The corresponding relative
- * adjustments are:
- *
- * PR_PRIORITY_LOW +1
- * PR_PRIORITY_NORMAL 0
- * PR_PRIORITY_HIGH -1
- * PR_PRIORITY_URGENT -2
- */
-static int pt_RelativePriority(int nice, PRThreadPriority pri)
-{
- return nice + (1 - pri);
-}
-#endif
-
-/*
-** Initialize a stack for a native pthread thread
-*/
-static void _PR_InitializeStack(PRThreadStack *ts)
-{
- if( ts && (ts->stackTop == 0) ) {
- ts->allocBase = (char *) &ts;
- ts->allocSize = ts->stackSize;
-
- /*
- ** Setup stackTop and stackBottom values.
- */
-#ifdef HAVE_STACK_GROWING_UP
- ts->stackBottom = ts->allocBase + ts->stackSize;
- ts->stackTop = ts->allocBase;
-#else
- ts->stackTop = ts->allocBase;
- ts->stackBottom = ts->allocBase - ts->stackSize;
-#endif
- }
-}
-
-static void *_pt_root(void *arg)
-{
- PRIntn rv;
- PRThread *thred = (PRThread*)arg;
- PRBool detached = (thred->state & PT_THREAD_DETACHED) ? PR_TRUE : PR_FALSE;
- pthread_t id = pthread_self();
-#ifdef _PR_NICE_PRIORITY_SCHEDULING
- pid_t tid;
-#endif
-
-#ifdef _PR_NICE_PRIORITY_SCHEDULING
- /*
- * We need to know the kernel thread ID of each thread in order to
- * set its nice value hence we do it here instead of at creation time.
- */
- tid = gettid();
- errno = 0;
- rv = getpriority(PRIO_PROCESS, 0);
-
- /* If we cannot read the main thread's nice value don't try to change the
- * new thread's nice value. */
- if (errno == 0) {
- setpriority(PRIO_PROCESS, tid,
- pt_RelativePriority(rv, thred->priority));
- }
-#endif
-
- /*
- ** DCE Threads can't detach during creation, so do it late.
- ** I would like to do it only here, but that doesn't seem
- ** to work.
- */
-#if defined(_PR_DCETHREADS)
- if (detached)
- {
- /* pthread_detach() modifies its argument, so we must pass a copy */
- pthread_t self = id;
- rv = pthread_detach(&self);
- PR_ASSERT(0 == rv);
- }
-#endif /* defined(_PR_DCETHREADS) */
-
- /* Set up the thread stack information */
- _PR_InitializeStack(thred->stack);
-
- /*
- * Set within the current thread the pointer to our object.
- * This object will be deleted when the thread termintates,
- * whether in a join or detached (see _PR_InitThreads()).
- */
- rv = pthread_setspecific(pt_book.key, thred);
- PR_ASSERT(0 == rv);
-
- /* make the thread visible to the rest of the runtime */
- PR_Lock(pt_book.ml);
- /*
- * Both the parent thread and this new thread set thred->id.
- * The new thread must ensure that thred->id is set before
- * it executes its startFunc. The parent thread must ensure
- * that thred->id is set before PR_CreateThread() returns.
- * Both threads set thred->id while holding pt_book.ml and
- * use thred->idSet to ensure thred->id is written only once.
- */
- if (!thred->idSet)
- {
- thred->id = id;
- thred->idSet = PR_TRUE;
- }
- else
- {
- PR_ASSERT(pthread_equal(thred->id, id));
- }
-
-#ifdef _PR_NICE_PRIORITY_SCHEDULING
- thred->tid = tid;
- PR_NotifyAllCondVar(pt_book.cv);
-#endif
-
- /* If this is a GCABLE thread, set its state appropriately */
- if (thred->suspend & PT_THREAD_SETGCABLE)
- thred->state |= PT_THREAD_GCABLE;
- thred->suspend = 0;
-
- thred->prev = pt_book.last;
- if (pt_book.last)
- pt_book.last->next = thred;
- else
- pt_book.first = thred;
- thred->next = NULL;
- pt_book.last = thred;
- PR_Unlock(pt_book.ml);
-
- thred->startFunc(thred->arg); /* make visible to the client */
-
- /* unhook the thread from the runtime */
- PR_Lock(pt_book.ml);
- /*
- * At this moment, PR_CreateThread() may not have set thred->id yet.
- * It is safe for a detached thread to free thred only after
- * PR_CreateThread() has accessed thred->id and thred->idSet.
- */
- if (detached)
- {
- while (!thred->okToDelete)
- PR_WaitCondVar(pt_book.cv, PR_INTERVAL_NO_TIMEOUT);
- }
-
- if (thred->state & PT_THREAD_SYSTEM)
- pt_book.system -= 1;
- else if (--pt_book.user == pt_book.this_many)
- PR_NotifyAllCondVar(pt_book.cv);
- if (NULL == thred->prev)
- pt_book.first = thred->next;
- else
- thred->prev->next = thred->next;
- if (NULL == thred->next)
- pt_book.last = thred->prev;
- else
- thred->next->prev = thred->prev;
- PR_Unlock(pt_book.ml);
-
- /*
- * Here we set the pthread's backpointer to the PRThread to NULL.
- * Otherwise the destructor would get called eagerly as the thread
- * returns to the pthread runtime. The joining thread would them be
- * the proud possessor of a dangling reference. However, this is the
- * last chance to delete the object if the thread is detached, so
- * just let the destructor do the work.
- */
- if (PR_FALSE == detached)
- {
- /* Call TPD destructors on this thread. */
- _PR_DestroyThreadPrivate(thred);
- rv = pthread_setspecific(pt_book.key, NULL);
- PR_ASSERT(0 == rv);
- }
-
- return NULL;
-} /* _pt_root */
-
-static PRThread* pt_AttachThread(void)
-{
- PRThread *thred = NULL;
-
- /*
- * NSPR must have been initialized when PR_AttachThread is called.
- * We cannot have PR_AttachThread call implicit initialization
- * because if multiple threads call PR_AttachThread simultaneously,
- * NSPR may be initialized more than once.
- * We can't call any function that calls PR_GetCurrentThread()
- * either (e.g., PR_SetError()) as that will result in infinite
- * recursion.
- */
- if (!_pr_initialized) return NULL;
-
- /* PR_NEWZAP must not call PR_GetCurrentThread() */
- thred = PR_NEWZAP(PRThread);
- if (NULL != thred)
- {
- int rv;
-
- thred->priority = PR_PRIORITY_NORMAL;
- thred->id = pthread_self();
- thred->idSet = PR_TRUE;
-#ifdef _PR_NICE_PRIORITY_SCHEDULING
- thred->tid = gettid();
-#endif
- rv = pthread_setspecific(pt_book.key, thred);
- PR_ASSERT(0 == rv);
-
- thred->state = PT_THREAD_GLOBAL | PT_THREAD_FOREIGN;
- PR_Lock(pt_book.ml);
-
- /* then put it into the list */
- thred->prev = pt_book.last;
- if (pt_book.last)
- pt_book.last->next = thred;
- else
- pt_book.first = thred;
- thred->next = NULL;
- pt_book.last = thred;
- PR_Unlock(pt_book.ml);
-
- }
- return thred; /* may be NULL */
-} /* pt_AttachThread */
-
-static PRThread* _PR_CreateThread(
- PRThreadType type, void (*start)(void *arg),
- void *arg, PRThreadPriority priority, PRThreadScope scope,
- PRThreadState state, PRUint32 stackSize, PRBool isGCAble)
-{
- int rv;
- PRThread *thred;
- pthread_attr_t tattr;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if ((PRIntn)PR_PRIORITY_FIRST > (PRIntn)priority)
- priority = PR_PRIORITY_FIRST;
- else if ((PRIntn)PR_PRIORITY_LAST < (PRIntn)priority)
- priority = PR_PRIORITY_LAST;
-
- rv = _PT_PTHREAD_ATTR_INIT(&tattr);
- PR_ASSERT(0 == rv);
-
- if (EPERM != pt_schedpriv)
- {
-#if !defined(_PR_DCETHREADS) && _POSIX_THREAD_PRIORITY_SCHEDULING > 0
- struct sched_param schedule;
-#endif
-
-#if _POSIX_THREAD_PRIORITY_SCHEDULING > 0
- rv = pthread_attr_setinheritsched(&tattr, PTHREAD_EXPLICIT_SCHED);
- PR_ASSERT(0 == rv);
-#endif
-
- /* Use the default scheduling policy */
-
-#if defined(_PR_DCETHREADS)
- rv = pthread_attr_setprio(&tattr, pt_PriorityMap(priority));
- PR_ASSERT(0 == rv);
-#elif _POSIX_THREAD_PRIORITY_SCHEDULING > 0
- rv = pthread_attr_getschedparam(&tattr, &schedule);
- PR_ASSERT(0 == rv);
- schedule.sched_priority = pt_PriorityMap(priority);
- rv = pthread_attr_setschedparam(&tattr, &schedule);
- PR_ASSERT(0 == rv);
-#ifdef NTO
- rv = pthread_attr_setschedpolicy(&tattr, SCHED_RR); /* Round Robin */
- PR_ASSERT(0 == rv);
-#endif
-#endif /* !defined(_PR_DCETHREADS) */
- }
-
- /*
- * DCE threads can't set detach state before creating the thread.
- * AIX can't set detach late. Why can't we all just get along?
- */
-#if !defined(_PR_DCETHREADS)
- rv = pthread_attr_setdetachstate(&tattr,
- ((PR_JOINABLE_THREAD == state) ?
- PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED));
- PR_ASSERT(0 == rv);
-#endif /* !defined(_PR_DCETHREADS) */
-
- /*
- * If stackSize is 0, we use the default pthread stack size.
- */
- if (stackSize)
- {
-#ifdef _MD_MINIMUM_STACK_SIZE
- if (stackSize < _MD_MINIMUM_STACK_SIZE)
- stackSize = _MD_MINIMUM_STACK_SIZE;
-#endif
- rv = pthread_attr_setstacksize(&tattr, stackSize);
- PR_ASSERT(0 == rv);
- }
-
- thred = PR_NEWZAP(PRThread);
- if (NULL == thred)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, errno);
- goto done;
- }
- else
- {
- pthread_t id;
-
- thred->arg = arg;
- thred->startFunc = start;
- thred->priority = priority;
- if (PR_UNJOINABLE_THREAD == state)
- thred->state |= PT_THREAD_DETACHED;
-
- if (PR_LOCAL_THREAD == scope)
- scope = PR_GLOBAL_THREAD;
-
- if (PR_GLOBAL_BOUND_THREAD == scope) {
-#if _POSIX_THREAD_PRIORITY_SCHEDULING > 0
- rv = pthread_attr_setscope(&tattr, PTHREAD_SCOPE_SYSTEM);
- if (rv) {
- /*
- * system scope not supported
- */
- scope = PR_GLOBAL_THREAD;
- /*
- * reset scope
- */
- rv = pthread_attr_setscope(&tattr, PTHREAD_SCOPE_PROCESS);
- PR_ASSERT(0 == rv);
- }
-#endif
- }
- if (PR_GLOBAL_THREAD == scope)
- thred->state |= PT_THREAD_GLOBAL;
- else if (PR_GLOBAL_BOUND_THREAD == scope)
- thred->state |= (PT_THREAD_GLOBAL | PT_THREAD_BOUND);
- else /* force it global */
- thred->state |= PT_THREAD_GLOBAL;
- if (PR_SYSTEM_THREAD == type)
- thred->state |= PT_THREAD_SYSTEM;
-
- thred->suspend =(isGCAble) ? PT_THREAD_SETGCABLE : 0;
-
- thred->stack = PR_NEWZAP(PRThreadStack);
- if (thred->stack == NULL) {
- PRIntn oserr = errno;
- PR_Free(thred); /* all that work ... poof! */
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, oserr);
- thred = NULL; /* and for what? */
- goto done;
- }
- thred->stack->stackSize = stackSize;
- thred->stack->thr = thred;
-
-#ifdef PT_NO_SIGTIMEDWAIT
- pthread_mutex_init(&thred->suspendResumeMutex,NULL);
- pthread_cond_init(&thred->suspendResumeCV,NULL);
-#endif
-
- /* make the thread counted to the rest of the runtime */
- PR_Lock(pt_book.ml);
- if (PR_SYSTEM_THREAD == type)
- pt_book.system += 1;
- else pt_book.user += 1;
- PR_Unlock(pt_book.ml);
-
- /*
- * We pass a pointer to a local copy (instead of thred->id)
- * to pthread_create() because who knows what wacky things
- * pthread_create() may be doing to its argument.
- */
- rv = _PT_PTHREAD_CREATE(&id, tattr, _pt_root, thred);
-
-#if !defined(_PR_DCETHREADS)
- if (EPERM == rv)
- {
-#if defined(IRIX)
- if (PR_GLOBAL_BOUND_THREAD == scope) {
- /*
- * SCOPE_SYSTEM requires appropriate privilege
- * reset to process scope and try again
- */
- rv = pthread_attr_setscope(&tattr, PTHREAD_SCOPE_PROCESS);
- PR_ASSERT(0 == rv);
- thred->state &= ~PT_THREAD_BOUND;
- }
-#else
- /* Remember that we don't have thread scheduling privilege. */
- pt_schedpriv = EPERM;
- PR_LOG(_pr_thread_lm, PR_LOG_MIN,
- ("_PR_CreateThread: no thread scheduling privilege"));
- /* Try creating the thread again without setting priority. */
-#if _POSIX_THREAD_PRIORITY_SCHEDULING > 0
- rv = pthread_attr_setinheritsched(&tattr, PTHREAD_INHERIT_SCHED);
- PR_ASSERT(0 == rv);
-#endif
-#endif /* IRIX */
- rv = _PT_PTHREAD_CREATE(&id, tattr, _pt_root, thred);
- }
-#endif
-
- if (0 != rv)
- {
-#if defined(_PR_DCETHREADS)
- PRIntn oserr = errno;
-#else
- PRIntn oserr = rv;
-#endif
- PR_Lock(pt_book.ml);
- if (thred->state & PT_THREAD_SYSTEM)
- pt_book.system -= 1;
- else if (--pt_book.user == pt_book.this_many)
- PR_NotifyAllCondVar(pt_book.cv);
- PR_Unlock(pt_book.ml);
-
- PR_Free(thred->stack);
- PR_Free(thred); /* all that work ... poof! */
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, oserr);
- thred = NULL; /* and for what? */
- goto done;
- }
-
- PR_Lock(pt_book.ml);
- /*
- * Both the parent thread and this new thread set thred->id.
- * The parent thread must ensure that thred->id is set before
- * PR_CreateThread() returns. (See comments in _pt_root().)
- */
- if (!thred->idSet)
- {
- thred->id = id;
- thred->idSet = PR_TRUE;
- }
- else
- {
- PR_ASSERT(pthread_equal(thred->id, id));
- }
-
- /*
- * If the new thread is detached, tell it that PR_CreateThread() has
- * accessed thred->id and thred->idSet so it's ok to delete thred.
- */
- if (PR_UNJOINABLE_THREAD == state)
- {
- thred->okToDelete = PR_TRUE;
- PR_NotifyAllCondVar(pt_book.cv);
- }
- PR_Unlock(pt_book.ml);
- }
-
-done:
- rv = _PT_PTHREAD_ATTR_DESTROY(&tattr);
- PR_ASSERT(0 == rv);
-
- return thred;
-} /* _PR_CreateThread */
-
-PR_IMPLEMENT(PRThread*) PR_CreateThread(
- PRThreadType type, void (*start)(void *arg), void *arg,
- PRThreadPriority priority, PRThreadScope scope,
- PRThreadState state, PRUint32 stackSize)
-{
- return _PR_CreateThread(
- type, start, arg, priority, scope, state, stackSize, PR_FALSE);
-} /* PR_CreateThread */
-
-PR_IMPLEMENT(PRThread*) PR_CreateThreadGCAble(
- PRThreadType type, void (*start)(void *arg), void *arg,
- PRThreadPriority priority, PRThreadScope scope,
- PRThreadState state, PRUint32 stackSize)
-{
- return _PR_CreateThread(
- type, start, arg, priority, scope, state, stackSize, PR_TRUE);
-} /* PR_CreateThreadGCAble */
-
-PR_IMPLEMENT(void*) GetExecutionEnvironment(PRThread *thred)
-{
- return thred->environment;
-} /* GetExecutionEnvironment */
-
-PR_IMPLEMENT(void) SetExecutionEnvironment(PRThread *thred, void *env)
-{
- thred->environment = env;
-} /* SetExecutionEnvironment */
-
-PR_IMPLEMENT(PRThread*) PR_AttachThread(
- PRThreadType type, PRThreadPriority priority, PRThreadStack *stack)
-{
- return PR_GetCurrentThread();
-} /* PR_AttachThread */
-
-
-PR_IMPLEMENT(PRStatus) PR_JoinThread(PRThread *thred)
-{
- int rv = -1;
- void *result = NULL;
- PR_ASSERT(thred != NULL);
-
- if ((0xafafafaf == thred->state)
- || (PT_THREAD_DETACHED == (PT_THREAD_DETACHED & thred->state))
- || (PT_THREAD_FOREIGN == (PT_THREAD_FOREIGN & thred->state)))
- {
- /*
- * This might be a bad address, but if it isn't, the state should
- * either be an unjoinable thread or it's already had the object
- * deleted. However, the client that called join on a detached
- * thread deserves all the rath I can muster....
- */
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- PR_LogPrint(
- "PR_JoinThread: %p not joinable | already smashed\n", thred);
- }
- else
- {
- pthread_t id = thred->id;
- rv = pthread_join(id, &result);
- PR_ASSERT(rv == 0 && result == NULL);
- if (0 == rv)
- {
-#ifdef _PR_DCETHREADS
- rv = pthread_detach(&id);
- PR_ASSERT(0 == rv);
-#endif
- /*
- * PR_FALSE, because the thread already called the TPD
- * destructors before exiting _pt_root.
- */
- _pt_thread_death_internal(thred, PR_FALSE);
- }
- else
- {
- PRErrorCode prerror;
- switch (rv)
- {
- case EINVAL: /* not a joinable thread */
- case ESRCH: /* no thread with given ID */
- prerror = PR_INVALID_ARGUMENT_ERROR;
- break;
- case EDEADLK: /* a thread joining with itself */
- prerror = PR_DEADLOCK_ERROR;
- break;
- default:
- prerror = PR_UNKNOWN_ERROR;
- break;
- }
- PR_SetError(prerror, rv);
- }
- }
- return (0 == rv) ? PR_SUCCESS : PR_FAILURE;
-} /* PR_JoinThread */
-
-PR_IMPLEMENT(void) PR_DetachThread(void)
-{
- void *thred;
- int rv;
-
- _PT_PTHREAD_GETSPECIFIC(pt_book.key, thred);
- if (NULL == thred) return;
- _pt_thread_death(thred);
- rv = pthread_setspecific(pt_book.key, NULL);
- PR_ASSERT(0 == rv);
-} /* PR_DetachThread */
-
-PR_IMPLEMENT(PRThread*) PR_GetCurrentThread(void)
-{
- void *thred;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- _PT_PTHREAD_GETSPECIFIC(pt_book.key, thred);
- if (NULL == thred) thred = pt_AttachThread();
- PR_ASSERT(NULL != thred);
- return (PRThread*)thred;
-} /* PR_GetCurrentThread */
-
-PR_IMPLEMENT(PRThreadScope) PR_GetThreadScope(const PRThread *thred)
-{
- return (thred->state & PT_THREAD_BOUND) ?
- PR_GLOBAL_BOUND_THREAD : PR_GLOBAL_THREAD;
-} /* PR_GetThreadScope() */
-
-PR_IMPLEMENT(PRThreadType) PR_GetThreadType(const PRThread *thred)
-{
- return (thred->state & PT_THREAD_SYSTEM) ?
- PR_SYSTEM_THREAD : PR_USER_THREAD;
-}
-
-PR_IMPLEMENT(PRThreadState) PR_GetThreadState(const PRThread *thred)
-{
- return (thred->state & PT_THREAD_DETACHED) ?
- PR_UNJOINABLE_THREAD : PR_JOINABLE_THREAD;
-} /* PR_GetThreadState */
-
-PR_IMPLEMENT(PRThreadPriority) PR_GetThreadPriority(const PRThread *thred)
-{
- PR_ASSERT(thred != NULL);
- return thred->priority;
-} /* PR_GetThreadPriority */
-
-PR_IMPLEMENT(void) PR_SetThreadPriority(PRThread *thred, PRThreadPriority newPri)
-{
- PRIntn rv;
-
- PR_ASSERT(NULL != thred);
-
- if ((PRIntn)PR_PRIORITY_FIRST > (PRIntn)newPri)
- newPri = PR_PRIORITY_FIRST;
- else if ((PRIntn)PR_PRIORITY_LAST < (PRIntn)newPri)
- newPri = PR_PRIORITY_LAST;
-
-#if defined(_PR_DCETHREADS)
- rv = pthread_setprio(thred->id, pt_PriorityMap(newPri));
- /* pthread_setprio returns the old priority */
-#elif _POSIX_THREAD_PRIORITY_SCHEDULING > 0
- if (EPERM != pt_schedpriv)
- {
- int policy;
- struct sched_param schedule;
-
- rv = pthread_getschedparam(thred->id, &policy, &schedule);
- if(0 == rv) {
- schedule.sched_priority = pt_PriorityMap(newPri);
- rv = pthread_setschedparam(thred->id, policy, &schedule);
- if (EPERM == rv)
- {
- pt_schedpriv = EPERM;
- PR_LOG(_pr_thread_lm, PR_LOG_MIN,
- ("PR_SetThreadPriority: no thread scheduling privilege"));
- }
- }
- if (rv != 0)
- rv = -1;
- }
-#elif defined(_PR_NICE_PRIORITY_SCHEDULING)
- PR_Lock(pt_book.ml);
- while (thred->tid == 0)
- PR_WaitCondVar(pt_book.cv, PR_INTERVAL_NO_TIMEOUT);
- PR_Unlock(pt_book.ml);
-
- errno = 0;
- rv = getpriority(PRIO_PROCESS, 0);
-
- /* Do not proceed unless we know the main thread's nice value. */
- if (errno == 0) {
- rv = setpriority(PRIO_PROCESS, thred->tid,
- pt_RelativePriority(rv, newPri));
-
- if (rv == -1)
- {
- /* We don't set pt_schedpriv to EPERM in case errno == EPERM
- * because adjusting the nice value might be permitted for certain
- * ranges but not for others. */
- PR_LOG(_pr_thread_lm, PR_LOG_MIN,
- ("PR_SetThreadPriority: setpriority failed with error %d",
- errno));
- }
- }
-#else
- (void)rv; /* rv is unused */
-#endif
-
- thred->priority = newPri;
-} /* PR_SetThreadPriority */
-
-PR_IMPLEMENT(PRStatus) PR_Interrupt(PRThread *thred)
-{
- /*
- ** If the target thread indicates that it's waiting,
- ** find the condition and broadcast to it. Broadcast
- ** since we don't know which thread (if there are more
- ** than one). This sounds risky, but clients must
- ** test their invariants when resumed from a wait and
- ** I don't expect very many threads to be waiting on
- ** a single condition and I don't expect interrupt to
- ** be used very often.
- **
- ** I don't know why I thought this would work. Must have
- ** been one of those weaker momements after I'd been
- ** smelling the vapors.
- **
- ** Even with the followng changes it is possible that
- ** the pointer to the condition variable is pointing
- ** at a bogus value. Will the unerlying code detect
- ** that?
- */
- PRCondVar *cv;
- PR_ASSERT(NULL != thred);
- if (NULL == thred) return PR_FAILURE;
-
- thred->state |= PT_THREAD_ABORTED;
-
- cv = thred->waiting;
- if ((NULL != cv) && !thred->interrupt_blocked)
- {
- PRIntn rv;
- (void)PR_ATOMIC_INCREMENT(&cv->notify_pending);
- rv = pthread_cond_broadcast(&cv->cv);
- PR_ASSERT(0 == rv);
- if (0 > PR_ATOMIC_DECREMENT(&cv->notify_pending))
- PR_DestroyCondVar(cv);
- }
- return PR_SUCCESS;
-} /* PR_Interrupt */
-
-PR_IMPLEMENT(void) PR_ClearInterrupt(void)
-{
- PRThread *me = PR_GetCurrentThread();
- me->state &= ~PT_THREAD_ABORTED;
-} /* PR_ClearInterrupt */
-
-PR_IMPLEMENT(void) PR_BlockInterrupt(void)
-{
- PRThread *me = PR_GetCurrentThread();
- _PT_THREAD_BLOCK_INTERRUPT(me);
-} /* PR_BlockInterrupt */
-
-PR_IMPLEMENT(void) PR_UnblockInterrupt(void)
-{
- PRThread *me = PR_GetCurrentThread();
- _PT_THREAD_UNBLOCK_INTERRUPT(me);
-} /* PR_UnblockInterrupt */
-
-PR_IMPLEMENT(PRStatus) PR_Yield(void)
-{
- static PRBool warning = PR_TRUE;
- if (warning) warning = _PR_Obsolete(
- "PR_Yield()", "PR_Sleep(PR_INTERVAL_NO_WAIT)");
- return PR_Sleep(PR_INTERVAL_NO_WAIT);
-}
-
-PR_IMPLEMENT(PRStatus) PR_Sleep(PRIntervalTime ticks)
-{
- PRStatus rv = PR_SUCCESS;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (PR_INTERVAL_NO_WAIT == ticks)
- {
- _PT_PTHREAD_YIELD();
- }
- else
- {
- PRCondVar *cv;
- PRIntervalTime timein;
-
- timein = PR_IntervalNow();
- cv = PR_NewCondVar(_pr_sleeplock);
- PR_ASSERT(cv != NULL);
- PR_Lock(_pr_sleeplock);
- do
- {
- PRIntervalTime now = PR_IntervalNow();
- PRIntervalTime delta = now - timein;
- if (delta > ticks) break;
- rv = PR_WaitCondVar(cv, ticks - delta);
- } while (PR_SUCCESS == rv);
- PR_Unlock(_pr_sleeplock);
- PR_DestroyCondVar(cv);
- }
- return rv;
-} /* PR_Sleep */
-
-static void _pt_thread_death(void *arg)
-{
- void *thred;
- int rv;
-
- _PT_PTHREAD_GETSPECIFIC(pt_book.key, thred);
- if (NULL == thred)
- {
- /*
- * Have PR_GetCurrentThread return the expected value to the
- * destructors.
- */
- rv = pthread_setspecific(pt_book.key, arg);
- PR_ASSERT(0 == rv);
- }
-
- /* PR_TRUE for: call destructors */
- _pt_thread_death_internal(arg, PR_TRUE);
-
- if (NULL == thred)
- {
- rv = pthread_setspecific(pt_book.key, NULL);
- PR_ASSERT(0 == rv);
- }
-}
-
-static void _pt_thread_death_internal(void *arg, PRBool callDestructors)
-{
- PRThread *thred = (PRThread*)arg;
-
- if (thred->state & (PT_THREAD_FOREIGN|PT_THREAD_PRIMORD))
- {
- PR_Lock(pt_book.ml);
- if (NULL == thred->prev)
- pt_book.first = thred->next;
- else
- thred->prev->next = thred->next;
- if (NULL == thred->next)
- pt_book.last = thred->prev;
- else
- thred->next->prev = thred->prev;
- PR_Unlock(pt_book.ml);
- }
- if (callDestructors)
- _PR_DestroyThreadPrivate(thred);
- PR_Free(thred->privateData);
- if (NULL != thred->errorString)
- PR_Free(thred->errorString);
- if (NULL != thred->name)
- PR_Free(thred->name);
- PR_Free(thred->stack);
- if (NULL != thred->syspoll_list)
- PR_Free(thred->syspoll_list);
-#if defined(_PR_POLL_WITH_SELECT)
- if (NULL != thred->selectfd_list)
- PR_Free(thred->selectfd_list);
-#endif
-#if defined(DEBUG)
- memset(thred, 0xaf, sizeof(PRThread));
-#endif /* defined(DEBUG) */
- PR_Free(thred);
-} /* _pt_thread_death */
-
-void _PR_InitThreads(
- PRThreadType type, PRThreadPriority priority, PRUintn maxPTDs)
-{
- int rv;
- PRThread *thred;
-
- PR_ASSERT(priority == PR_PRIORITY_NORMAL);
-
-#ifdef _PR_NEED_PTHREAD_INIT
- /*
- * On BSD/OS (3.1 and 4.0), the pthread subsystem is lazily
- * initialized, but pthread_self() fails to initialize
- * pthreads and hence returns a null thread ID if invoked
- * by the primordial thread before any other pthread call.
- * So we explicitly initialize pthreads here.
- */
- pthread_init();
-#endif
-
-#if defined(_PR_DCETHREADS) || _POSIX_THREAD_PRIORITY_SCHEDULING > 0
-#if defined(FREEBSD)
- {
- pthread_attr_t attr;
- int policy;
- /* get the min and max priorities of the default policy */
- pthread_attr_init(&attr);
- pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
- pthread_attr_getschedpolicy(&attr, &policy);
- pt_book.minPrio = sched_get_priority_min(policy);
- PR_ASSERT(-1 != pt_book.minPrio);
- pt_book.maxPrio = sched_get_priority_max(policy);
- PR_ASSERT(-1 != pt_book.maxPrio);
- pthread_attr_destroy(&attr);
- }
-#else
- /*
- ** These might be function evaluations
- */
- pt_book.minPrio = PT_PRIO_MIN;
- pt_book.maxPrio = PT_PRIO_MAX;
-#endif
-#endif
-
- PR_ASSERT(NULL == pt_book.ml);
- pt_book.ml = PR_NewLock();
- PR_ASSERT(NULL != pt_book.ml);
- pt_book.cv = PR_NewCondVar(pt_book.ml);
- PR_ASSERT(NULL != pt_book.cv);
- thred = PR_NEWZAP(PRThread);
- PR_ASSERT(NULL != thred);
- thred->arg = NULL;
- thred->startFunc = NULL;
- thred->priority = priority;
- thred->id = pthread_self();
- thred->idSet = PR_TRUE;
-#ifdef _PR_NICE_PRIORITY_SCHEDULING
- thred->tid = gettid();
-#endif
-
- thred->state = (PT_THREAD_DETACHED | PT_THREAD_PRIMORD);
- if (PR_SYSTEM_THREAD == type)
- {
- thred->state |= PT_THREAD_SYSTEM;
- pt_book.system += 1;
- pt_book.this_many = 0;
- }
- else
- {
- pt_book.user += 1;
- pt_book.this_many = 1;
- }
- thred->next = thred->prev = NULL;
- pt_book.first = pt_book.last = thred;
-
- thred->stack = PR_NEWZAP(PRThreadStack);
- PR_ASSERT(thred->stack != NULL);
- thred->stack->stackSize = 0;
- thred->stack->thr = thred;
- _PR_InitializeStack(thred->stack);
-
- /*
- * Create a key for our use to store a backpointer in the pthread
- * to our PRThread object. This object gets deleted when the thread
- * returns from its root in the case of a detached thread. Other
- * threads delete the objects in Join.
- *
- * NB: The destructor logic seems to have a bug so it isn't used.
- * NBB: Oh really? I'm going to give it a spin - AOF 19 June 1998.
- * More info - the problem is that pthreads calls the destructor
- * eagerly as the thread returns from its root, rather than lazily
- * after the thread is joined. Therefore, threads that are joining
- * and holding PRThread references are actually holding pointers to
- * nothing.
- */
- rv = _PT_PTHREAD_KEY_CREATE(&pt_book.key, _pt_thread_death);
- if (0 != rv)
- PR_Assert("0 == rv", __FILE__, __LINE__);
- pt_book.keyCreated = PR_TRUE;
- rv = pthread_setspecific(pt_book.key, thred);
- PR_ASSERT(0 == rv);
-} /* _PR_InitThreads */
-
-#ifdef __GNUC__
-/*
- * GCC supports the constructor and destructor attributes as of
- * version 2.5.
- */
-static void _PR_Fini(void) __attribute__ ((destructor));
-#elif defined(__SUNPRO_C)
-/*
- * Sun Studio compiler
- */
-#pragma fini(_PR_Fini)
-static void _PR_Fini(void);
-#elif defined(HPUX)
-/*
- * Current versions of HP C compiler define __HP_cc.
- * HP C compiler A.11.01.20 doesn't define __HP_cc.
- */
-#if defined(__ia64) || defined(_LP64)
-#pragma FINI "_PR_Fini"
-static void _PR_Fini(void);
-#else
-/*
- * Only HP-UX 10.x style initializers are supported in 32-bit links.
- * Need to use the +I PR_HPUX10xInit linker option.
- */
-#include <dl.h>
-
-static void _PR_Fini(void);
-
-void PR_HPUX10xInit(shl_t handle, int loading)
-{
- /*
- * This function is called when a shared library is loaded as well
- * as when the shared library is unloaded. Note that it may not
- * be called when the user's program terminates.
- *
- * handle is the shl_load API handle for the shared library being
- * initialized.
- *
- * loading is non-zero at startup and zero at termination.
- */
- if (loading) {
- /* ... do some initializations ... */
- } else {
- _PR_Fini();
- }
-}
-#endif
-#elif defined(AIX)
-/* Need to use the -binitfini::_PR_Fini linker option. */
-#endif
-
-void _PR_Fini(void)
-{
- void *thred;
- int rv;
-
- if (!_pr_initialized) {
- /* Either NSPR was never successfully initialized or
- * PR_Cleanup has been called already. */
- if (pt_book.keyCreated)
- {
- rv = pthread_key_delete(pt_book.key);
- PR_ASSERT(0 == rv);
- pt_book.keyCreated = PR_FALSE;
- }
- return;
- }
-
- _PT_PTHREAD_GETSPECIFIC(pt_book.key, thred);
- if (NULL != thred)
- {
- /*
- * PR_FALSE, because it is unsafe to call back to the
- * thread private data destructors at final cleanup.
- */
- _pt_thread_death_internal(thred, PR_FALSE);
- rv = pthread_setspecific(pt_book.key, NULL);
- PR_ASSERT(0 == rv);
- }
- rv = pthread_key_delete(pt_book.key);
- PR_ASSERT(0 == rv);
- pt_book.keyCreated = PR_FALSE;
- /* TODO: free other resources used by NSPR */
- /* _pr_initialized = PR_FALSE; */
-} /* _PR_Fini */
-
-PR_IMPLEMENT(PRStatus) PR_Cleanup(void)
-{
- PRThread *me = PR_GetCurrentThread();
- int rv;
- PR_LOG(_pr_thread_lm, PR_LOG_MIN, ("PR_Cleanup: shutting down NSPR"));
- PR_ASSERT(me->state & PT_THREAD_PRIMORD);
- if (me->state & PT_THREAD_PRIMORD)
- {
- PR_Lock(pt_book.ml);
- while (pt_book.user > pt_book.this_many)
- PR_WaitCondVar(pt_book.cv, PR_INTERVAL_NO_TIMEOUT);
- if (me->state & PT_THREAD_SYSTEM)
- pt_book.system -= 1;
- else
- pt_book.user -= 1;
- PR_Unlock(pt_book.ml);
-
- _PR_MD_EARLY_CLEANUP();
-
- _PR_CleanupMW();
- _PR_CleanupTime();
- _PR_CleanupDtoa();
- _PR_CleanupCallOnce();
- _PR_ShutdownLinker();
- _PR_LogCleanup();
- _PR_CleanupNet();
- /* Close all the fd's before calling _PR_CleanupIO */
- _PR_CleanupIO();
- _PR_CleanupCMon();
-
- _pt_thread_death(me);
- rv = pthread_setspecific(pt_book.key, NULL);
- PR_ASSERT(0 == rv);
- /*
- * I am not sure if it's safe to delete the cv and lock here,
- * since there may still be "system" threads around. If this
- * call isn't immediately prior to exiting, then there's a
- * problem.
- */
- if (0 == pt_book.system)
- {
- PR_DestroyCondVar(pt_book.cv); pt_book.cv = NULL;
- PR_DestroyLock(pt_book.ml); pt_book.ml = NULL;
- }
- PR_DestroyLock(_pr_sleeplock);
- _pr_sleeplock = NULL;
- _PR_CleanupLayerCache();
- _PR_CleanupEnv();
-#ifdef _PR_ZONE_ALLOCATOR
- _PR_DestroyZones();
-#endif
- _pr_initialized = PR_FALSE;
- return PR_SUCCESS;
- }
- return PR_FAILURE;
-} /* PR_Cleanup */
-
-PR_IMPLEMENT(void) PR_ProcessExit(PRIntn status)
-{
- _exit(status);
-}
-
-PR_IMPLEMENT(PRUint32) PR_GetThreadID(PRThread *thred)
-{
-#if defined(_PR_DCETHREADS)
- return (PRUint32)&thred->id; /* this is really a sham! */
-#else
- return (PRUint32)thred->id; /* and I don't know what they will do with it */
-#endif
-}
-
-/*
- * $$$
- * The following two thread-to-processor affinity functions are not
- * yet implemented for pthreads. By the way, these functions should return
- * PRStatus rather than PRInt32 to indicate the success/failure status.
- * $$$
- */
-
-PR_IMPLEMENT(PRInt32) PR_GetThreadAffinityMask(PRThread *thread, PRUint32 *mask)
-{
- return 0; /* not implemented */
-}
-
-PR_IMPLEMENT(PRInt32) PR_SetThreadAffinityMask(PRThread *thread, PRUint32 mask )
-{
- return 0; /* not implemented */
-}
-
-PR_IMPLEMENT(void)
-PR_SetThreadDumpProc(PRThread* thread, PRThreadDumpProc dump, void *arg)
-{
- thread->dump = dump;
- thread->dumpArg = arg;
-}
-
-/*
- * Garbage collection support follows.
- */
-
-#if defined(_PR_DCETHREADS)
-
-/*
- * statics for Garbage Collection support. We don't need to protect these
- * signal masks since the garbage collector itself is protected by a lock
- * and multiple threads will not be garbage collecting at the same time.
- */
-static sigset_t javagc_vtalarm_sigmask;
-static sigset_t javagc_intsoff_sigmask;
-
-#else /* defined(_PR_DCETHREADS) */
-
-/* a bogus signal mask for forcing a timed wait */
-/* Not so bogus in AIX as we really do a sigwait */
-static sigset_t sigwait_set;
-
-static struct timespec onemillisec = {0, 1000000L};
-#ifndef PT_NO_SIGTIMEDWAIT
-static struct timespec hundredmillisec = {0, 100000000L};
-#endif
-
-static void suspend_signal_handler(PRIntn sig);
-
-#ifdef PT_NO_SIGTIMEDWAIT
-static void null_signal_handler(PRIntn sig);
-#endif
-
-#endif /* defined(_PR_DCETHREADS) */
-
-/*
- * Linux pthreads use SIGUSR1 and SIGUSR2 internally, which
- * conflict with the use of these two signals in our GC support.
- * So we don't know how to support GC on Linux pthreads.
- */
-static void init_pthread_gc_support(void)
-{
-#ifndef SYMBIAN
- PRIntn rv;
-
-#if defined(_PR_DCETHREADS)
- rv = sigemptyset(&javagc_vtalarm_sigmask);
- PR_ASSERT(0 == rv);
- rv = sigaddset(&javagc_vtalarm_sigmask, SIGVTALRM);
- PR_ASSERT(0 == rv);
-#else /* defined(_PR_DCETHREADS) */
- {
- struct sigaction sigact_usr2;
-
- sigact_usr2.sa_handler = suspend_signal_handler;
- sigact_usr2.sa_flags = SA_RESTART;
- sigemptyset (&sigact_usr2.sa_mask);
-
- rv = sigaction (SIGUSR2, &sigact_usr2, NULL);
- PR_ASSERT(0 == rv);
-
- sigemptyset (&sigwait_set);
-#if defined(PT_NO_SIGTIMEDWAIT)
- sigaddset (&sigwait_set, SIGUSR1);
-#else
- sigaddset (&sigwait_set, SIGUSR2);
-#endif /* defined(PT_NO_SIGTIMEDWAIT) */
- }
-#if defined(PT_NO_SIGTIMEDWAIT)
- {
- struct sigaction sigact_null;
- sigact_null.sa_handler = null_signal_handler;
- sigact_null.sa_flags = SA_RESTART;
- sigemptyset (&sigact_null.sa_mask);
- rv = sigaction (SIGUSR1, &sigact_null, NULL);
- PR_ASSERT(0 ==rv);
- }
-#endif /* defined(PT_NO_SIGTIMEDWAIT) */
-#endif /* defined(_PR_DCETHREADS) */
-#endif /* SYMBIAN */
-}
-
-PR_IMPLEMENT(void) PR_SetThreadGCAble(void)
-{
- PR_Lock(pt_book.ml);
- PR_GetCurrentThread()->state |= PT_THREAD_GCABLE;
- PR_Unlock(pt_book.ml);
-}
-
-PR_IMPLEMENT(void) PR_ClearThreadGCAble(void)
-{
- PR_Lock(pt_book.ml);
- PR_GetCurrentThread()->state &= (~PT_THREAD_GCABLE);
- PR_Unlock(pt_book.ml);
-}
-
-#if defined(DEBUG)
-static PRBool suspendAllOn = PR_FALSE;
-#endif
-
-static PRBool suspendAllSuspended = PR_FALSE;
-
-PR_IMPLEMENT(PRStatus) PR_EnumerateThreads(PREnumerator func, void *arg)
-{
- PRIntn count = 0;
- PRStatus rv = PR_SUCCESS;
- PRThread* thred = pt_book.first;
-
-#if defined(DEBUG) || defined(FORCE_PR_ASSERT)
-#if !defined(_PR_DCETHREADS)
- PRThread *me = PR_GetCurrentThread();
-#endif
-#endif
-
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS, ("Begin PR_EnumerateThreads\n"));
- /*
- * $$$
- * Need to suspend all threads other than me before doing this.
- * This is really a gross and disgusting thing to do. The only
- * good thing is that since all other threads are suspended, holding
- * the lock during a callback seems like child's play.
- * $$$
- */
- PR_ASSERT(suspendAllOn);
-
- while (thred != NULL)
- {
- /* Steve Morse, 4-23-97: Note that we can't walk a queue by taking
- * qp->next after applying the function "func". In particular, "func"
- * might remove the thread from the queue and put it into another one in
- * which case qp->next no longer points to the next entry in the original
- * queue.
- *
- * To get around this problem, we save qp->next in qp_next before applying
- * "func" and use that saved value as the next value after applying "func".
- */
- PRThread* next = thred->next;
-
- if (_PT_IS_GCABLE_THREAD(thred))
- {
-#if !defined(_PR_DCETHREADS)
- PR_ASSERT((thred == me) || (thred->suspend & PT_THREAD_SUSPENDED));
-#endif
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS,
- ("In PR_EnumerateThreads callback thread %p thid = %X\n",
- thred, thred->id));
-
- rv = func(thred, count++, arg);
- if (rv != PR_SUCCESS)
- return rv;
- }
- thred = next;
- }
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS,
- ("End PR_EnumerateThreads count = %d \n", count));
- return rv;
-} /* PR_EnumerateThreads */
-
-/*
- * PR_SuspendAll and PR_ResumeAll are called during garbage collection. The strategy
- * we use is to send a SIGUSR2 signal to every gc able thread that we intend to suspend.
- * The signal handler will record the stack pointer and will block until resumed by
- * the resume call. Since the signal handler is the last routine called for the
- * suspended thread, the stack pointer will also serve as a place where all the
- * registers have been saved on the stack for the previously executing routines.
- *
- * Through global variables, we also make sure that PR_Suspend and PR_Resume does not
- * proceed until the thread is suspended or resumed.
- */
-
-#if !defined(_PR_DCETHREADS)
-
-/*
- * In the signal handler, we can not use condition variable notify or wait.
- * This does not work consistently across all pthread platforms. We also can not
- * use locking since that does not seem to work reliably across platforms.
- * Only thing we can do is yielding while testing for a global condition
- * to change. This does work on pthread supported platforms. We may have
- * to play with priortities if there are any problems detected.
- */
-
- /*
- * In AIX, you cannot use ANY pthread calls in the signal handler except perhaps
- * pthread_yield. But that is horribly inefficient. Hence we use only sigwait, no
- * sigtimedwait is available. We need to use another user signal, SIGUSR1. Actually
- * SIGUSR1 is also used by exec in Java. So our usage here breaks the exec in Java,
- * for AIX. You cannot use pthread_cond_wait or pthread_delay_np in the signal
- * handler as all synchronization mechanisms just break down.
- */
-
-#if defined(PT_NO_SIGTIMEDWAIT)
-static void null_signal_handler(PRIntn sig)
-{
- return;
-}
-#endif
-
-static void suspend_signal_handler(PRIntn sig)
-{
- PRThread *me = PR_GetCurrentThread();
-
- PR_ASSERT(me != NULL);
- PR_ASSERT(_PT_IS_GCABLE_THREAD(me));
- PR_ASSERT((me->suspend & PT_THREAD_SUSPENDED) == 0);
-
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS,
- ("Begin suspend_signal_handler thred %p thread id = %X\n",
- me, me->id));
-
- /*
- * save stack pointer
- */
- me->sp = &me;
-
- /*
- At this point, the thread's stack pointer has been saved,
- And it is going to enter a wait loop until it is resumed.
- So it is _really_ suspended
- */
-
- me->suspend |= PT_THREAD_SUSPENDED;
-
- /*
- * now, block current thread
- */
-#if defined(PT_NO_SIGTIMEDWAIT)
- pthread_cond_signal(&me->suspendResumeCV);
- while (me->suspend & PT_THREAD_SUSPENDED)
- {
-#if !defined(FREEBSD) && !defined(NETBSD) && !defined(OPENBSD) \
- && !defined(BSDI) && !defined(UNIXWARE) \
- && !defined(DARWIN) && !defined(RISCOS) \
- && !defined(SYMBIAN) /*XXX*/
- PRIntn rv;
- sigwait(&sigwait_set, &rv);
-#endif
- }
- me->suspend |= PT_THREAD_RESUMED;
- pthread_cond_signal(&me->suspendResumeCV);
-#else /* defined(PT_NO_SIGTIMEDWAIT) */
- while (me->suspend & PT_THREAD_SUSPENDED)
- {
- PRIntn rv = sigtimedwait(&sigwait_set, NULL, &hundredmillisec);
- PR_ASSERT(-1 == rv);
- }
- me->suspend |= PT_THREAD_RESUMED;
-#endif
-
- /*
- * At this point, thread has been resumed, so set a global condition.
- * The ResumeAll needs to know that this has really been resumed.
- * So the signal handler sets a flag which PR_ResumeAll will reset.
- * The PR_ResumeAll must reset this flag ...
- */
-
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS,
- ("End suspend_signal_handler thred = %p tid = %X\n", me, me->id));
-} /* suspend_signal_handler */
-
-static void pt_SuspendSet(PRThread *thred)
-{
- PRIntn rv;
-
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS,
- ("pt_SuspendSet thred %p thread id = %X\n", thred, thred->id));
-
-
- /*
- * Check the thread state and signal the thread to suspend
- */
-
- PR_ASSERT((thred->suspend & PT_THREAD_SUSPENDED) == 0);
-
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS,
- ("doing pthread_kill in pt_SuspendSet thred %p tid = %X\n",
- thred, thred->id));
-#if defined(SYMBIAN)
- /* All signal group functions are not implemented in Symbian OS */
- rv = 0;
-#else
- rv = pthread_kill (thred->id, SIGUSR2);
-#endif
- PR_ASSERT(0 == rv);
-}
-
-static void pt_SuspendTest(PRThread *thred)
-{
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS,
- ("Begin pt_SuspendTest thred %p thread id = %X\n", thred, thred->id));
-
-
- /*
- * Wait for the thread to be really suspended. This happens when the
- * suspend signal handler stores the stack pointer and sets the state
- * to suspended.
- */
-
-#if defined(PT_NO_SIGTIMEDWAIT)
- pthread_mutex_lock(&thred->suspendResumeMutex);
- while ((thred->suspend & PT_THREAD_SUSPENDED) == 0)
- {
- pthread_cond_timedwait(
- &thred->suspendResumeCV, &thred->suspendResumeMutex, &onemillisec);
- }
- pthread_mutex_unlock(&thred->suspendResumeMutex);
-#else
- while ((thred->suspend & PT_THREAD_SUSPENDED) == 0)
- {
- PRIntn rv = sigtimedwait(&sigwait_set, NULL, &onemillisec);
- PR_ASSERT(-1 == rv);
- }
-#endif
-
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS,
- ("End pt_SuspendTest thred %p tid %X\n", thred, thred->id));
-} /* pt_SuspendTest */
-
-static void pt_ResumeSet(PRThread *thred)
-{
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS,
- ("pt_ResumeSet thred %p thread id = %X\n", thred, thred->id));
-
- /*
- * Clear the global state and set the thread state so that it will
- * continue past yield loop in the suspend signal handler
- */
-
- PR_ASSERT(thred->suspend & PT_THREAD_SUSPENDED);
-
-
- thred->suspend &= ~PT_THREAD_SUSPENDED;
-
-#if defined(PT_NO_SIGTIMEDWAIT)
-#if defined(SYMBIAN)
- /* All signal group functions are not implemented in Symbian OS */
-#else
- pthread_kill(thred->id, SIGUSR1);
-#endif
-#endif
-
-} /* pt_ResumeSet */
-
-static void pt_ResumeTest(PRThread *thred)
-{
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS,
- ("Begin pt_ResumeTest thred %p thread id = %X\n", thred, thred->id));
-
- /*
- * Wait for the threads resume state to change
- * to indicate it is really resumed
- */
-#if defined(PT_NO_SIGTIMEDWAIT)
- pthread_mutex_lock(&thred->suspendResumeMutex);
- while ((thred->suspend & PT_THREAD_RESUMED) == 0)
- {
- pthread_cond_timedwait(
- &thred->suspendResumeCV, &thred->suspendResumeMutex, &onemillisec);
- }
- pthread_mutex_unlock(&thred->suspendResumeMutex);
-#else
- while ((thred->suspend & PT_THREAD_RESUMED) == 0) {
- PRIntn rv = sigtimedwait(&sigwait_set, NULL, &onemillisec);
- PR_ASSERT(-1 == rv);
- }
-#endif
-
- thred->suspend &= ~PT_THREAD_RESUMED;
-
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS, (
- "End pt_ResumeTest thred %p tid %X\n", thred, thred->id));
-} /* pt_ResumeTest */
-
-static pthread_once_t pt_gc_support_control = PTHREAD_ONCE_INIT;
-
-PR_IMPLEMENT(void) PR_SuspendAll(void)
-{
-#ifdef DEBUG
- PRIntervalTime stime, etime;
-#endif
- PRThread* thred = pt_book.first;
- PRThread *me = PR_GetCurrentThread();
- int rv;
-
- rv = pthread_once(&pt_gc_support_control, init_pthread_gc_support);
- PR_ASSERT(0 == rv);
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS, ("Begin PR_SuspendAll\n"));
- /*
- * Stop all threads which are marked GC able.
- */
- PR_Lock(pt_book.ml);
-#ifdef DEBUG
- suspendAllOn = PR_TRUE;
- stime = PR_IntervalNow();
-#endif
- while (thred != NULL)
- {
- if ((thred != me) && _PT_IS_GCABLE_THREAD(thred))
- pt_SuspendSet(thred);
- thred = thred->next;
- }
-
- /* Wait till they are really suspended */
- thred = pt_book.first;
- while (thred != NULL)
- {
- if ((thred != me) && _PT_IS_GCABLE_THREAD(thred))
- pt_SuspendTest(thred);
- thred = thred->next;
- }
-
- suspendAllSuspended = PR_TRUE;
-
-#ifdef DEBUG
- etime = PR_IntervalNow();
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS,\
- ("End PR_SuspendAll (time %dms)\n",
- PR_IntervalToMilliseconds(etime - stime)));
-#endif
-} /* PR_SuspendAll */
-
-PR_IMPLEMENT(void) PR_ResumeAll(void)
-{
-#ifdef DEBUG
- PRIntervalTime stime, etime;
-#endif
- PRThread* thred = pt_book.first;
- PRThread *me = PR_GetCurrentThread();
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS, ("Begin PR_ResumeAll\n"));
- /*
- * Resume all previously suspended GC able threads.
- */
- suspendAllSuspended = PR_FALSE;
-#ifdef DEBUG
- stime = PR_IntervalNow();
-#endif
-
- while (thred != NULL)
- {
- if ((thred != me) && _PT_IS_GCABLE_THREAD(thred))
- pt_ResumeSet(thred);
- thred = thred->next;
- }
-
- thred = pt_book.first;
- while (thred != NULL)
- {
- if ((thred != me) && _PT_IS_GCABLE_THREAD(thred))
- pt_ResumeTest(thred);
- thred = thred->next;
- }
-
- PR_Unlock(pt_book.ml);
-#ifdef DEBUG
- suspendAllOn = PR_FALSE;
- etime = PR_IntervalNow();
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS,
- ("End PR_ResumeAll (time %dms)\n",
- PR_IntervalToMilliseconds(etime - stime)));
-#endif
-} /* PR_ResumeAll */
-
-/* Return the stack pointer for the given thread- used by the GC */
-PR_IMPLEMENT(void *)PR_GetSP(PRThread *thred)
-{
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS,
- ("in PR_GetSP thred %p thid = %X, sp = %p\n",
- thred, thred->id, thred->sp));
- return thred->sp;
-} /* PR_GetSP */
-
-#else /* !defined(_PR_DCETHREADS) */
-
-static pthread_once_t pt_gc_support_control = pthread_once_init;
-
-/*
- * For DCE threads, there is no pthread_kill or a way of suspending or resuming a
- * particular thread. We will just disable the preemption (virtual timer alarm) and
- * let the executing thread finish the garbage collection. This stops all other threads
- * (GC able or not) and is very inefficient but there is no other choice.
- */
-PR_IMPLEMENT(void) PR_SuspendAll()
-{
- PRIntn rv;
-
- rv = pthread_once(&pt_gc_support_control, init_pthread_gc_support);
- PR_ASSERT(0 == rv); /* returns -1 on failure */
-#ifdef DEBUG
- suspendAllOn = PR_TRUE;
-#endif
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS, ("Begin PR_SuspendAll\n"));
- /*
- * turn off preemption - i.e add virtual alarm signal to the set of
- * blocking signals
- */
- rv = sigprocmask(
- SIG_BLOCK, &javagc_vtalarm_sigmask, &javagc_intsoff_sigmask);
- PR_ASSERT(0 == rv);
- suspendAllSuspended = PR_TRUE;
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS, ("End PR_SuspendAll\n"));
-} /* PR_SuspendAll */
-
-PR_IMPLEMENT(void) PR_ResumeAll()
-{
- PRIntn rv;
-
- suspendAllSuspended = PR_FALSE;
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS, ("Begin PR_ResumeAll\n"));
- /* turn on preemption - i.e re-enable virtual alarm signal */
-
- rv = sigprocmask(SIG_SETMASK, &javagc_intsoff_sigmask, (sigset_t *)NULL);
- PR_ASSERT(0 == rv);
-#ifdef DEBUG
- suspendAllOn = PR_FALSE;
-#endif
-
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS, ("End PR_ResumeAll\n"));
-} /* PR_ResumeAll */
-
-/* Return the stack pointer for the given thread- used by the GC */
-PR_IMPLEMENT(void*)PR_GetSP(PRThread *thred)
-{
- pthread_t tid = thred->id;
- char *thread_tcb, *top_sp;
-
- /*
- * For HPUX DCE threads, pthread_t is a struct with the
- * following three fields (see pthread.h, dce/cma.h):
- * cma_t_address field1;
- * short int field2;
- * short int field3;
- * where cma_t_address is typedef'd to be either void*
- * or char*.
- */
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS, ("Begin PR_GetSP\n"));
- thread_tcb = (char*)tid.field1;
- top_sp = *(char**)(thread_tcb + 128);
- PR_LOG(_pr_gc_lm, PR_LOG_ALWAYS, ("End PR_GetSP %p \n", top_sp));
- return top_sp;
-} /* PR_GetSP */
-
-#endif /* !defined(_PR_DCETHREADS) */
-
-PR_IMPLEMENT(PRStatus) PR_SetCurrentThreadName(const char *name)
-{
- PRThread *thread;
- size_t nameLen;
- int result = 0;
-
- if (!name) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
-
- thread = PR_GetCurrentThread();
- if (!thread)
- return PR_FAILURE;
-
- PR_Free(thread->name);
- nameLen = strlen(name);
- thread->name = (char *)PR_Malloc(nameLen + 1);
- if (!thread->name)
- return PR_FAILURE;
- memcpy(thread->name, name, nameLen + 1);
-
-#if defined(OPENBSD) || defined(FREEBSD) || defined(DRAGONFLY)
- pthread_set_name_np(thread->id, name);
-#elif defined(NETBSD)
- result = pthread_setname_np(thread->id, "%s", (void *)name);
-#else /* not BSD */
- /*
- * On OSX, pthread_setname_np is only available in 10.6 or later, so test
- * for it at runtime. It also may not be available on all linux distros.
- */
-#if defined(DARWIN)
- int (*dynamic_pthread_setname_np)(const char*);
-#else
- int (*dynamic_pthread_setname_np)(pthread_t, const char*);
-#endif
-
- *(void**)(&dynamic_pthread_setname_np) =
- dlsym(RTLD_DEFAULT, "pthread_setname_np");
- if (!dynamic_pthread_setname_np)
- return PR_SUCCESS;
-
- /*
- * The 15-character name length limit is an experimentally determined
- * length of a null-terminated string that most linux distros and OS X
- * accept as an argument to pthread_setname_np. Otherwise the E2BIG
- * error is returned by the function.
- */
-#define SETNAME_LENGTH_CONSTRAINT 15
-#define SETNAME_FRAGMENT1_LENGTH (SETNAME_LENGTH_CONSTRAINT >> 1)
-#define SETNAME_FRAGMENT2_LENGTH \
- (SETNAME_LENGTH_CONSTRAINT - SETNAME_FRAGMENT1_LENGTH - 1)
- char name_dup[SETNAME_LENGTH_CONSTRAINT + 1];
- if (nameLen > SETNAME_LENGTH_CONSTRAINT) {
- memcpy(name_dup, name, SETNAME_FRAGMENT1_LENGTH);
- name_dup[SETNAME_FRAGMENT1_LENGTH] = '~';
- /* Note that this also copies the null terminator. */
- memcpy(name_dup + SETNAME_FRAGMENT1_LENGTH + 1,
- name + nameLen - SETNAME_FRAGMENT2_LENGTH,
- SETNAME_FRAGMENT2_LENGTH + 1);
- name = name_dup;
- }
-
-#if defined(DARWIN)
- result = dynamic_pthread_setname_np(name);
-#else
- result = dynamic_pthread_setname_np(thread->id, name);
-#endif
-#endif /* not BSD */
-
- if (result) {
- PR_SetError(PR_UNKNOWN_ERROR, result);
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(const char *) PR_GetThreadName(const PRThread *thread)
-{
- if (!thread)
- return NULL;
- return thread->name;
-}
-
-#endif /* defined(_PR_PTHREADS) || defined(_PR_DCETHREADS) */
-
-/* ptthread.c */
diff --git a/nspr/pr/src/threads/combined/prucpu.c b/nspr/pr/src/threads/combined/prucpu.c
deleted file mode 100644
index 3913dc8..0000000
--- a/nspr/pr/src/threads/combined/prucpu.c
+++ /dev/null
@@ -1,405 +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/. */
-
-#include "primpl.h"
-
-_PRCPU *_pr_primordialCPU = NULL;
-
-PRInt32 _pr_md_idle_cpus; /* number of idle cpus */
-/*
- * The idle threads in MxN models increment/decrement _pr_md_idle_cpus.
- * If _PR_HAVE_ATOMIC_OPS is not defined, they can't use the atomic
- * increment/decrement routines (which are based on PR_Lock/PR_Unlock),
- * because PR_Lock asserts that the calling thread is not an idle thread.
- * So we use a _MDLock to protect _pr_md_idle_cpus.
- */
-#if !defined(_PR_LOCAL_THREADS_ONLY) && !defined(_PR_GLOBAL_THREADS_ONLY)
-#ifndef _PR_HAVE_ATOMIC_OPS
-static _MDLock _pr_md_idle_cpus_lock;
-#endif
-#endif
-PRUintn _pr_numCPU;
-PRInt32 _pr_cpus_exit;
-PRUint32 _pr_cpu_affinity_mask = 0;
-
-#if !defined (_PR_GLOBAL_THREADS_ONLY)
-
-static PRUintn _pr_cpuID;
-
-static void PR_CALLBACK _PR_CPU_Idle(void *);
-
-static _PRCPU *_PR_CreateCPU(void);
-static PRStatus _PR_StartCPU(_PRCPU *cpu, PRThread *thread);
-
-#if !defined(_PR_LOCAL_THREADS_ONLY)
-static void _PR_RunCPU(void *arg);
-#endif
-
-void _PR_InitCPUs()
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if (_native_threads_only)
- return;
-
- _pr_cpuID = 0;
- _MD_NEW_LOCK( &_pr_cpuLock);
-#if !defined(_PR_LOCAL_THREADS_ONLY) && !defined(_PR_GLOBAL_THREADS_ONLY)
-#ifndef _PR_HAVE_ATOMIC_OPS
- _MD_NEW_LOCK(&_pr_md_idle_cpus_lock);
-#endif
-#endif
-
-#ifdef _PR_LOCAL_THREADS_ONLY
-
-#ifdef HAVE_CUSTOM_USER_THREADS
- _PR_MD_CREATE_PRIMORDIAL_USER_THREAD(me);
-#endif
-
- /* Now start the first CPU. */
- _pr_primordialCPU = _PR_CreateCPU();
- _pr_numCPU = 1;
- _PR_StartCPU(_pr_primordialCPU, me);
-
- _PR_MD_SET_CURRENT_CPU(_pr_primordialCPU);
-
- /* Initialize cpu for current thread (could be different from me) */
- _PR_MD_CURRENT_THREAD()->cpu = _pr_primordialCPU;
-
- _PR_MD_SET_LAST_THREAD(me);
-
-#else /* Combined MxN model */
-
- _pr_primordialCPU = _PR_CreateCPU();
- _pr_numCPU = 1;
- _PR_CreateThread(PR_SYSTEM_THREAD,
- _PR_RunCPU,
- _pr_primordialCPU,
- PR_PRIORITY_NORMAL,
- PR_GLOBAL_THREAD,
- PR_UNJOINABLE_THREAD,
- 0,
- _PR_IDLE_THREAD);
-
-#endif /* _PR_LOCAL_THREADS_ONLY */
-
- _PR_MD_INIT_CPUS();
-}
-
-#ifdef WINNT
-/*
- * Right now this function merely stops the CPUs and does
- * not do any other cleanup.
- *
- * It is only implemented for WINNT because bug 161998 only
- * affects the WINNT version of NSPR, but it would be nice
- * to implement this function for other platforms too.
- */
-void _PR_CleanupCPUs(void)
-{
- PRUintn i;
- PRCList *qp;
- _PRCPU *cpu;
-
- _pr_cpus_exit = 1;
- for (i = 0; i < _pr_numCPU; i++) {
- _PR_MD_WAKEUP_WAITER(NULL);
- }
- for (qp = _PR_CPUQ().next; qp != &_PR_CPUQ(); qp = qp->next) {
- cpu = _PR_CPU_PTR(qp);
- _PR_MD_JOIN_THREAD(&cpu->thread->md);
- }
-}
-#endif
-
-static _PRCPUQueue *_PR_CreateCPUQueue(void)
-{
- PRInt32 index;
- _PRCPUQueue *cpuQueue;
- cpuQueue = PR_NEWZAP(_PRCPUQueue);
-
- _MD_NEW_LOCK( &cpuQueue->runQLock );
- _MD_NEW_LOCK( &cpuQueue->sleepQLock );
- _MD_NEW_LOCK( &cpuQueue->miscQLock );
-
- for (index = 0; index < PR_ARRAY_SIZE(cpuQueue->runQ); index++)
- PR_INIT_CLIST( &(cpuQueue->runQ[index]) );
- PR_INIT_CLIST( &(cpuQueue->sleepQ) );
- PR_INIT_CLIST( &(cpuQueue->pauseQ) );
- PR_INIT_CLIST( &(cpuQueue->suspendQ) );
- PR_INIT_CLIST( &(cpuQueue->waitingToJoinQ) );
-
- cpuQueue->numCPUs = 1;
-
- return cpuQueue;
-}
-
-/*
- * Create a new CPU.
- *
- * This function initializes enough of the _PRCPU structure so
- * that it can be accessed safely by a global thread or another
- * CPU. This function does not create the native thread that
- * will run the CPU nor does it initialize the parts of _PRCPU
- * that must be initialized by that native thread.
- *
- * The reason we cannot simply have the native thread create
- * and fully initialize a new CPU is that we need to be able to
- * create a usable _pr_primordialCPU in _PR_InitCPUs without
- * assuming that the primordial CPU thread we created can run
- * during NSPR initialization. For example, on Windows while
- * new threads can be created by DllMain, they won't be able
- * to run during DLL initialization. If NSPR is initialized
- * by DllMain, the primordial CPU thread won't run until DLL
- * initialization is finished.
- */
-static _PRCPU *_PR_CreateCPU(void)
-{
- _PRCPU *cpu;
-
- cpu = PR_NEWZAP(_PRCPU);
- if (cpu) {
- cpu->queue = _PR_CreateCPUQueue();
- if (!cpu->queue) {
- PR_DELETE(cpu);
- return NULL;
- }
- }
- return cpu;
-}
-
-/*
- * Start a new CPU.
- *
- * 'cpu' is a _PRCPU structure created by _PR_CreateCPU().
- * 'thread' is the native thread that will run the CPU.
- *
- * If this function fails, 'cpu' is destroyed.
- */
-static PRStatus _PR_StartCPU(_PRCPU *cpu, PRThread *thread)
-{
- /*
- ** Start a new cpu. The assumption this code makes is that the
- ** underlying operating system creates a stack to go with the new
- ** native thread. That stack will be used by the cpu when pausing.
- */
-
- PR_ASSERT(!_native_threads_only);
-
- cpu->last_clock = PR_IntervalNow();
-
- /* Before we create any threads on this CPU we have to
- * set the current CPU
- */
- _PR_MD_SET_CURRENT_CPU(cpu);
- _PR_MD_INIT_RUNNING_CPU(cpu);
- thread->cpu = cpu;
-
- cpu->idle_thread = _PR_CreateThread(PR_SYSTEM_THREAD,
- _PR_CPU_Idle,
- (void *)cpu,
- PR_PRIORITY_NORMAL,
- PR_LOCAL_THREAD,
- PR_UNJOINABLE_THREAD,
- 0,
- _PR_IDLE_THREAD);
-
- if (!cpu->idle_thread) {
- /* didn't clean up CPU queue XXXMB */
- PR_DELETE(cpu);
- return PR_FAILURE;
- }
- PR_ASSERT(cpu->idle_thread->cpu == cpu);
-
- cpu->idle_thread->no_sched = 0;
-
- cpu->thread = thread;
-
- if (_pr_cpu_affinity_mask)
- PR_SetThreadAffinityMask(thread, _pr_cpu_affinity_mask);
-
- /* Created and started a new CPU */
- _PR_CPU_LIST_LOCK();
- cpu->id = _pr_cpuID++;
- PR_APPEND_LINK(&cpu->links, &_PR_CPUQ());
- _PR_CPU_LIST_UNLOCK();
-
- return PR_SUCCESS;
-}
-
-#if !defined(_PR_GLOBAL_THREADS_ONLY) && !defined(_PR_LOCAL_THREADS_ONLY)
-/*
-** This code is used during a cpu's initial creation.
-*/
-static void _PR_RunCPU(void *arg)
-{
- _PRCPU *cpu = (_PRCPU *)arg;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- PR_ASSERT(NULL != me);
-
- /*
- * _PR_StartCPU calls _PR_CreateThread to create the
- * idle thread. Because _PR_CreateThread calls PR_Lock,
- * the current thread has to remain a global thread
- * during the _PR_StartCPU call so that it can wait for
- * the lock if the lock is held by another thread. If
- * we clear the _PR_GLOBAL_SCOPE flag in
- * _PR_MD_CREATE_PRIMORDIAL_THREAD, the current thread
- * will be treated as a local thread and have trouble
- * waiting for the lock because the CPU is not fully
- * constructed yet.
- *
- * After the CPU is started, it is safe to mark the
- * current thread as a local thread.
- */
-
-#ifdef HAVE_CUSTOM_USER_THREADS
- _PR_MD_CREATE_PRIMORDIAL_USER_THREAD(me);
-#endif
-
- me->no_sched = 1;
- _PR_StartCPU(cpu, me);
-
-#ifdef HAVE_CUSTOM_USER_THREADS
- me->flags &= (~_PR_GLOBAL_SCOPE);
-#endif
-
- _PR_MD_SET_CURRENT_CPU(cpu);
- _PR_MD_SET_CURRENT_THREAD(cpu->thread);
- me->cpu = cpu;
-
- while(1) {
- PRInt32 is;
- if (!_PR_IS_NATIVE_THREAD(me)) _PR_INTSOFF(is);
- _PR_MD_START_INTERRUPTS();
- _PR_MD_SWITCH_CONTEXT(me);
- }
-}
-#endif
-
-static void PR_CALLBACK _PR_CPU_Idle(void *_cpu)
-{
- _PRCPU *cpu = (_PRCPU *)_cpu;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- PR_ASSERT(NULL != me);
-
- me->cpu = cpu;
- cpu->idle_thread = me;
- if (_MD_LAST_THREAD())
- _MD_LAST_THREAD()->no_sched = 0;
- if (!_PR_IS_NATIVE_THREAD(me)) _PR_MD_SET_INTSOFF(0);
- while(1) {
- PRInt32 is;
- PRIntervalTime timeout;
- if (!_PR_IS_NATIVE_THREAD(me)) _PR_INTSOFF(is);
-
- _PR_RUNQ_LOCK(cpu);
-#if !defined(_PR_LOCAL_THREADS_ONLY) && !defined(_PR_GLOBAL_THREADS_ONLY)
-#ifdef _PR_HAVE_ATOMIC_OPS
- _PR_MD_ATOMIC_INCREMENT(&_pr_md_idle_cpus);
-#else
- _PR_MD_LOCK(&_pr_md_idle_cpus_lock);
- _pr_md_idle_cpus++;
- _PR_MD_UNLOCK(&_pr_md_idle_cpus_lock);
-#endif /* _PR_HAVE_ATOMIC_OPS */
-#endif
- /* If someone on runq; do a nonblocking PAUSECPU */
- if (_PR_RUNQREADYMASK(me->cpu) != 0) {
- _PR_RUNQ_UNLOCK(cpu);
- timeout = PR_INTERVAL_NO_WAIT;
- } else {
- _PR_RUNQ_UNLOCK(cpu);
-
- _PR_SLEEPQ_LOCK(cpu);
- if (PR_CLIST_IS_EMPTY(&_PR_SLEEPQ(me->cpu))) {
- timeout = PR_INTERVAL_NO_TIMEOUT;
- } else {
- PRThread *wakeThread;
- wakeThread = _PR_THREAD_PTR(_PR_SLEEPQ(me->cpu).next);
- timeout = wakeThread->sleep;
- }
- _PR_SLEEPQ_UNLOCK(cpu);
- }
-
- /* Wait for an IO to complete */
- (void)_PR_MD_PAUSE_CPU(timeout);
-
-#ifdef WINNT
- if (_pr_cpus_exit) {
- /* _PR_CleanupCPUs tells us to exit */
- _PR_MD_END_THREAD();
- }
-#endif
-
-#if !defined(_PR_LOCAL_THREADS_ONLY) && !defined(_PR_GLOBAL_THREADS_ONLY)
-#ifdef _PR_HAVE_ATOMIC_OPS
- _PR_MD_ATOMIC_DECREMENT(&_pr_md_idle_cpus);
-#else
- _PR_MD_LOCK(&_pr_md_idle_cpus_lock);
- _pr_md_idle_cpus--;
- _PR_MD_UNLOCK(&_pr_md_idle_cpus_lock);
-#endif /* _PR_HAVE_ATOMIC_OPS */
-#endif
-
- _PR_ClockInterrupt();
-
- /* Now schedule any thread that is on the runq
- * INTS must be OFF when calling PR_Schedule()
- */
- me->state = _PR_RUNNABLE;
- _PR_MD_SWITCH_CONTEXT(me);
- if (!_PR_IS_NATIVE_THREAD(me)) _PR_FAST_INTSON(is);
- }
-}
-#endif /* _PR_GLOBAL_THREADS_ONLY */
-
-PR_IMPLEMENT(void) PR_SetConcurrency(PRUintn numCPUs)
-{
-#if defined(_PR_GLOBAL_THREADS_ONLY) || defined(_PR_LOCAL_THREADS_ONLY)
-
- /* do nothing */
-
-#else /* combined, MxN thread model */
-
- PRUintn newCPU;
- _PRCPU *cpu;
- PRThread *thr;
-
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (_native_threads_only)
- return;
-
- _PR_CPU_LIST_LOCK();
- if (_pr_numCPU < numCPUs) {
- newCPU = numCPUs - _pr_numCPU;
- _pr_numCPU = numCPUs;
- } else newCPU = 0;
- _PR_CPU_LIST_UNLOCK();
-
- for (; newCPU; newCPU--) {
- cpu = _PR_CreateCPU();
- thr = _PR_CreateThread(PR_SYSTEM_THREAD,
- _PR_RunCPU,
- cpu,
- PR_PRIORITY_NORMAL,
- PR_GLOBAL_THREAD,
- PR_UNJOINABLE_THREAD,
- 0,
- _PR_IDLE_THREAD);
- }
-#endif
-}
-
-PR_IMPLEMENT(_PRCPU *) _PR_GetPrimordialCPU(void)
-{
- if (_pr_primordialCPU)
- return _pr_primordialCPU;
- else
- return _PR_MD_CURRENT_CPU();
-}
diff --git a/nspr/pr/src/threads/combined/prucv.c b/nspr/pr/src/threads/combined/prucv.c
deleted file mode 100644
index d0bf4c4..0000000
--- a/nspr/pr/src/threads/combined/prucv.c
+++ /dev/null
@@ -1,655 +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/. */
-
-
-#include "primpl.h"
-#include "prinrval.h"
-#include "prtypes.h"
-
-#if defined(WIN95)
-/*
-** Some local variables report warnings on Win95 because the code paths
-** using them are conditioned on HAVE_CUSTOME_USER_THREADS.
-** The pragma suppresses the warning.
-**
-*/
-#pragma warning(disable : 4101)
-#endif
-
-
-/*
-** Notify one thread that it has finished waiting on a condition variable
-** Caller must hold the _PR_CVAR_LOCK(cv)
-*/
-PRBool _PR_NotifyThread (PRThread *thread, PRThread *me)
-{
- PRBool rv;
-
- PR_ASSERT(_PR_IS_NATIVE_THREAD(me) || _PR_MD_GET_INTSOFF() != 0);
-
- _PR_THREAD_LOCK(thread);
- PR_ASSERT(!(thread->flags & _PR_IDLE_THREAD));
- if ( !_PR_IS_NATIVE_THREAD(thread) ) {
- if (thread->wait.cvar != NULL) {
- thread->wait.cvar = NULL;
-
- _PR_SLEEPQ_LOCK(thread->cpu);
- /* The notify and timeout can collide; in which case both may
- * attempt to delete from the sleepQ; only let one do it.
- */
- if (thread->flags & (_PR_ON_SLEEPQ|_PR_ON_PAUSEQ))
- _PR_DEL_SLEEPQ(thread, PR_TRUE);
- _PR_SLEEPQ_UNLOCK(thread->cpu);
-
- if (thread->flags & _PR_SUSPENDING) {
- /*
- * set thread state to SUSPENDED; a Resume operation
- * on the thread will move it to the runQ
- */
- thread->state = _PR_SUSPENDED;
- _PR_MISCQ_LOCK(thread->cpu);
- _PR_ADD_SUSPENDQ(thread, thread->cpu);
- _PR_MISCQ_UNLOCK(thread->cpu);
- _PR_THREAD_UNLOCK(thread);
- } else {
- /* Make thread runnable */
- thread->state = _PR_RUNNABLE;
- _PR_THREAD_UNLOCK(thread);
-
- _PR_AddThreadToRunQ(me, thread);
- _PR_MD_WAKEUP_WAITER(thread);
- }
-
- rv = PR_TRUE;
- } else {
- /* Thread has already been notified */
- _PR_THREAD_UNLOCK(thread);
- rv = PR_FALSE;
- }
- } else { /* If the thread is a native thread */
- if (thread->wait.cvar) {
- thread->wait.cvar = NULL;
-
- if (thread->flags & _PR_SUSPENDING) {
- /*
- * set thread state to SUSPENDED; a Resume operation
- * on the thread will enable the thread to run
- */
- thread->state = _PR_SUSPENDED;
- } else
- thread->state = _PR_RUNNING;
- _PR_THREAD_UNLOCK(thread);
- _PR_MD_WAKEUP_WAITER(thread);
- rv = PR_TRUE;
- } else {
- _PR_THREAD_UNLOCK(thread);
- rv = PR_FALSE;
- }
- }
-
- return rv;
-}
-
-/*
- * Notify thread waiting on cvar; called when thread is interrupted
- * The thread lock is held on entry and released before return
- */
-void _PR_NotifyLockedThread (PRThread *thread)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRCondVar *cvar;
- PRThreadPriority pri;
-
- if ( !_PR_IS_NATIVE_THREAD(me))
- PR_ASSERT(_PR_MD_GET_INTSOFF() != 0);
-
- cvar = thread->wait.cvar;
- thread->wait.cvar = NULL;
- _PR_THREAD_UNLOCK(thread);
-
- _PR_CVAR_LOCK(cvar);
- _PR_THREAD_LOCK(thread);
-
- if (!_PR_IS_NATIVE_THREAD(thread)) {
- _PR_SLEEPQ_LOCK(thread->cpu);
- /* The notify and timeout can collide; in which case both may
- * attempt to delete from the sleepQ; only let one do it.
- */
- if (thread->flags & (_PR_ON_SLEEPQ|_PR_ON_PAUSEQ))
- _PR_DEL_SLEEPQ(thread, PR_TRUE);
- _PR_SLEEPQ_UNLOCK(thread->cpu);
-
- /* Make thread runnable */
- pri = thread->priority;
- thread->state = _PR_RUNNABLE;
-
- PR_ASSERT(!(thread->flags & _PR_IDLE_THREAD));
-
- _PR_AddThreadToRunQ(me, thread);
- _PR_THREAD_UNLOCK(thread);
-
- _PR_MD_WAKEUP_WAITER(thread);
- } else {
- if (thread->flags & _PR_SUSPENDING) {
- /*
- * set thread state to SUSPENDED; a Resume operation
- * on the thread will enable the thread to run
- */
- thread->state = _PR_SUSPENDED;
- } else
- thread->state = _PR_RUNNING;
- _PR_THREAD_UNLOCK(thread);
- _PR_MD_WAKEUP_WAITER(thread);
- }
-
- _PR_CVAR_UNLOCK(cvar);
- return;
-}
-
-/*
-** Make the given thread wait for the given condition variable
-*/
-PRStatus _PR_WaitCondVar(
- PRThread *thread, PRCondVar *cvar, PRLock *lock, PRIntervalTime timeout)
-{
- PRIntn is;
- PRStatus rv = PR_SUCCESS;
-
- PR_ASSERT(thread == _PR_MD_CURRENT_THREAD());
- PR_ASSERT(!(thread->flags & _PR_IDLE_THREAD));
-
-#ifdef _PR_GLOBAL_THREADS_ONLY
- if (_PR_PENDING_INTERRUPT(thread)) {
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- thread->flags &= ~_PR_INTERRUPT;
- return PR_FAILURE;
- }
-
- thread->wait.cvar = cvar;
- lock->owner = NULL;
- _PR_MD_WAIT_CV(&cvar->md,&lock->ilock, timeout);
- thread->wait.cvar = NULL;
- lock->owner = thread;
- if (_PR_PENDING_INTERRUPT(thread)) {
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- thread->flags &= ~_PR_INTERRUPT;
- return PR_FAILURE;
- }
-
- return PR_SUCCESS;
-#else /* _PR_GLOBAL_THREADS_ONLY */
-
- if ( !_PR_IS_NATIVE_THREAD(thread))
- _PR_INTSOFF(is);
-
- _PR_CVAR_LOCK(cvar);
- _PR_THREAD_LOCK(thread);
-
- if (_PR_PENDING_INTERRUPT(thread)) {
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- thread->flags &= ~_PR_INTERRUPT;
- _PR_CVAR_UNLOCK(cvar);
- _PR_THREAD_UNLOCK(thread);
- if ( !_PR_IS_NATIVE_THREAD(thread))
- _PR_INTSON(is);
- return PR_FAILURE;
- }
-
- thread->state = _PR_COND_WAIT;
- thread->wait.cvar = cvar;
-
- /*
- ** Put the caller thread on the condition variable's wait Q
- */
- PR_APPEND_LINK(&thread->waitQLinks, &cvar->condQ);
-
- /* Note- for global scope threads, we don't put them on the
- * global sleepQ, so each global thread must put itself
- * to sleep only for the time it wants to.
- */
- if ( !_PR_IS_NATIVE_THREAD(thread) ) {
- _PR_SLEEPQ_LOCK(thread->cpu);
- _PR_ADD_SLEEPQ(thread, timeout);
- _PR_SLEEPQ_UNLOCK(thread->cpu);
- }
- _PR_CVAR_UNLOCK(cvar);
- _PR_THREAD_UNLOCK(thread);
-
- /*
- ** Release lock protecting the condition variable and thereby giving time
- ** to the next thread which can potentially notify on the condition variable
- */
- PR_Unlock(lock);
-
- PR_LOG(_pr_cvar_lm, PR_LOG_MIN,
- ("PR_Wait: cvar=%p waiting for %d", cvar, timeout));
-
- rv = _PR_MD_WAIT(thread, timeout);
-
- _PR_CVAR_LOCK(cvar);
- PR_REMOVE_LINK(&thread->waitQLinks);
- _PR_CVAR_UNLOCK(cvar);
-
- PR_LOG(_pr_cvar_lm, PR_LOG_MIN,
- ("PR_Wait: cvar=%p done waiting", cvar));
-
- if ( !_PR_IS_NATIVE_THREAD(thread))
- _PR_INTSON(is);
-
- /* Acquire lock again that we had just relinquished */
- PR_Lock(lock);
-
- if (_PR_PENDING_INTERRUPT(thread)) {
- PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
- thread->flags &= ~_PR_INTERRUPT;
- return PR_FAILURE;
- }
-
- return rv;
-#endif /* _PR_GLOBAL_THREADS_ONLY */
-}
-
-void _PR_NotifyCondVar(PRCondVar *cvar, PRThread *me)
-{
-#ifdef _PR_GLOBAL_THREADS_ONLY
- _PR_MD_NOTIFY_CV(&cvar->md, &cvar->lock->ilock);
-#else /* _PR_GLOBAL_THREADS_ONLY */
-
- PRCList *q;
- PRIntn is;
-
- if ( !_PR_IS_NATIVE_THREAD(me))
- _PR_INTSOFF(is);
- PR_ASSERT(_PR_IS_NATIVE_THREAD(me) || _PR_MD_GET_INTSOFF() != 0);
-
- _PR_CVAR_LOCK(cvar);
- q = cvar->condQ.next;
- while (q != &cvar->condQ) {
- PR_LOG(_pr_cvar_lm, PR_LOG_MIN, ("_PR_NotifyCondVar: cvar=%p", cvar));
- if (_PR_THREAD_CONDQ_PTR(q)->wait.cvar) {
- if (_PR_NotifyThread(_PR_THREAD_CONDQ_PTR(q), me) == PR_TRUE)
- break;
- }
- q = q->next;
- }
- _PR_CVAR_UNLOCK(cvar);
-
- if ( !_PR_IS_NATIVE_THREAD(me))
- _PR_INTSON(is);
-
-#endif /* _PR_GLOBAL_THREADS_ONLY */
-}
-
-/*
-** Cndition variable debugging log info.
-*/
-PRUint32 _PR_CondVarToString(PRCondVar *cvar, char *buf, PRUint32 buflen)
-{
- PRUint32 nb;
-
- if (cvar->lock->owner) {
- nb = PR_snprintf(buf, buflen, "[%p] owner=%ld[%p]",
- cvar, cvar->lock->owner->id, cvar->lock->owner);
- } else {
- nb = PR_snprintf(buf, buflen, "[%p]", cvar);
- }
- return nb;
-}
-
-/*
-** Expire condition variable waits that are ready to expire. "now" is the current
-** time.
-*/
-void _PR_ClockInterrupt(void)
-{
- PRThread *thread, *me = _PR_MD_CURRENT_THREAD();
- _PRCPU *cpu = me->cpu;
- PRIntervalTime elapsed, now;
-
- PR_ASSERT(_PR_MD_GET_INTSOFF() != 0);
- /* Figure out how much time elapsed since the last clock tick */
- now = PR_IntervalNow();
- elapsed = now - cpu->last_clock;
- cpu->last_clock = now;
-
- PR_LOG(_pr_clock_lm, PR_LOG_MAX,
- ("ExpireWaits: elapsed=%lld usec", elapsed));
-
- while(1) {
- _PR_SLEEPQ_LOCK(cpu);
- if (_PR_SLEEPQ(cpu).next == &_PR_SLEEPQ(cpu)) {
- _PR_SLEEPQ_UNLOCK(cpu);
- break;
- }
-
- thread = _PR_THREAD_PTR(_PR_SLEEPQ(cpu).next);
- PR_ASSERT(thread->cpu == cpu);
-
- if (elapsed < thread->sleep) {
- thread->sleep -= elapsed;
- _PR_SLEEPQMAX(thread->cpu) -= elapsed;
- _PR_SLEEPQ_UNLOCK(cpu);
- break;
- }
- _PR_SLEEPQ_UNLOCK(cpu);
-
- PR_ASSERT(!_PR_IS_NATIVE_THREAD(thread));
-
- _PR_THREAD_LOCK(thread);
-
- if (thread->cpu != cpu) {
- /*
- ** The thread was switched to another CPU
- ** between the time we unlocked the sleep
- ** queue and the time we acquired the thread
- ** lock, so it is none of our business now.
- */
- _PR_THREAD_UNLOCK(thread);
- continue;
- }
-
- /*
- ** Consume this sleeper's amount of elapsed time from the elapsed
- ** time value. The next remaining piece of elapsed time will be
- ** available for the next sleeping thread's timer.
- */
- _PR_SLEEPQ_LOCK(cpu);
- PR_ASSERT(!(thread->flags & _PR_ON_PAUSEQ));
- if (thread->flags & _PR_ON_SLEEPQ) {
- _PR_DEL_SLEEPQ(thread, PR_FALSE);
- elapsed -= thread->sleep;
- _PR_SLEEPQ_UNLOCK(cpu);
- } else {
- /* Thread was already handled; Go get another one */
- _PR_SLEEPQ_UNLOCK(cpu);
- _PR_THREAD_UNLOCK(thread);
- continue;
- }
-
- /* Notify the thread waiting on the condition variable */
- if (thread->flags & _PR_SUSPENDING) {
- PR_ASSERT((thread->state == _PR_IO_WAIT) ||
- (thread->state == _PR_COND_WAIT));
- /*
- ** Thread is suspended and its condition timeout
- ** expired. Transfer thread from sleepQ to suspendQ.
- */
- thread->wait.cvar = NULL;
- _PR_MISCQ_LOCK(cpu);
- thread->state = _PR_SUSPENDED;
- _PR_ADD_SUSPENDQ(thread, cpu);
- _PR_MISCQ_UNLOCK(cpu);
- } else {
- if (thread->wait.cvar) {
- PRThreadPriority pri;
-
- /* Do work very similar to what _PR_NotifyThread does */
- PR_ASSERT( !_PR_IS_NATIVE_THREAD(thread) );
-
- /* Make thread runnable */
- pri = thread->priority;
- thread->state = _PR_RUNNABLE;
- PR_ASSERT(!(thread->flags & _PR_IDLE_THREAD));
-
- PR_ASSERT(thread->cpu == cpu);
- _PR_RUNQ_LOCK(cpu);
- _PR_ADD_RUNQ(thread, cpu, pri);
- _PR_RUNQ_UNLOCK(cpu);
-
- if (pri > me->priority)
- _PR_SET_RESCHED_FLAG();
-
- thread->wait.cvar = NULL;
-
- _PR_MD_WAKEUP_WAITER(thread);
-
- } else if (thread->io_pending == PR_TRUE) {
- /* Need to put IO sleeper back on runq */
- int pri = thread->priority;
-
- thread->io_suspended = PR_TRUE;
-#ifdef WINNT
- /*
- * For NT, record the cpu on which I/O was issued
- * I/O cancellation is done on the same cpu
- */
- thread->md.thr_bound_cpu = cpu;
-#endif
-
- PR_ASSERT(!(thread->flags & _PR_IDLE_THREAD));
- PR_ASSERT(thread->cpu == cpu);
- thread->state = _PR_RUNNABLE;
- _PR_RUNQ_LOCK(cpu);
- _PR_ADD_RUNQ(thread, cpu, pri);
- _PR_RUNQ_UNLOCK(cpu);
- }
- }
- _PR_THREAD_UNLOCK(thread);
- }
-}
-
-/************************************************************************/
-
-/*
-** Create a new condition variable.
-** "lock" is the lock to use with the condition variable.
-**
-** Condition variables are synchronization objects that threads can use
-** to wait for some condition to occur.
-**
-** This may fail if memory is tight or if some operating system resource
-** is low.
-*/
-PR_IMPLEMENT(PRCondVar*) PR_NewCondVar(PRLock *lock)
-{
- PRCondVar *cvar;
-
- cvar = PR_NEWZAP(PRCondVar);
- if (cvar) {
- if (_PR_InitCondVar(cvar, lock) != PR_SUCCESS) {
- PR_DELETE(cvar);
- return NULL;
- }
- } else {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- }
- return cvar;
-}
-
-PRStatus _PR_InitCondVar(PRCondVar *cvar, PRLock *lock)
-{
- PR_ASSERT(lock != NULL);
-
-#ifdef _PR_GLOBAL_THREADS_ONLY
- if(_PR_MD_NEW_CV(&cvar->md)) {
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
- return PR_FAILURE;
- }
-#endif
- if (_PR_MD_NEW_LOCK(&(cvar->ilock)) != PR_SUCCESS) {
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
- return PR_FAILURE;
- }
- cvar->lock = lock;
- PR_INIT_CLIST(&cvar->condQ);
- return PR_SUCCESS;
-}
-
-/*
-** Destroy a condition variable. There must be no thread
-** waiting on the condvar. The caller is responsible for guaranteeing
-** that the condvar is no longer in use.
-**
-*/
-PR_IMPLEMENT(void) PR_DestroyCondVar(PRCondVar *cvar)
-{
- _PR_FreeCondVar(cvar);
- PR_DELETE(cvar);
-}
-
-void _PR_FreeCondVar(PRCondVar *cvar)
-{
- PR_ASSERT(cvar->condQ.next == &cvar->condQ);
-
-#ifdef _PR_GLOBAL_THREADS_ONLY
- _PR_MD_FREE_CV(&cvar->md);
-#endif
- _PR_MD_FREE_LOCK(&(cvar->ilock));
-}
-
-/*
-** Wait for a notify on the condition variable. Sleep for "tiemout" amount
-** of ticks (if "timeout" is zero then the sleep is indefinite). While
-** the thread is waiting it unlocks lock. When the wait has
-** finished the thread regains control of the condition variable after
-** locking the associated lock.
-**
-** The thread waiting on the condvar will be resumed when the condvar is
-** notified (assuming the thread is the next in line to receive the
-** notify) or when the timeout elapses.
-**
-** Returns PR_FAILURE if the caller has not locked the lock associated
-** with the condition variable or the thread has been interrupted.
-*/
-extern PRThread *suspendAllThread;
-PR_IMPLEMENT(PRStatus) PR_WaitCondVar(PRCondVar *cvar, PRIntervalTime timeout)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- PR_ASSERT(cvar->lock->owner == me);
- PR_ASSERT(me != suspendAllThread);
- if (cvar->lock->owner != me) return PR_FAILURE;
-
- return _PR_WaitCondVar(me, cvar, cvar->lock, timeout);
-}
-
-/*
-** Notify the highest priority thread waiting on the condition
-** variable. If a thread is waiting on the condition variable (using
-** PR_Wait) then it is awakened and begins waiting on the lock.
-*/
-PR_IMPLEMENT(PRStatus) PR_NotifyCondVar(PRCondVar *cvar)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- PR_ASSERT(cvar->lock->owner == me);
- PR_ASSERT(me != suspendAllThread);
- if (cvar->lock->owner != me) return PR_FAILURE;
-
- _PR_NotifyCondVar(cvar, me);
- return PR_SUCCESS;
-}
-
-/*
-** Notify all of the threads waiting on the condition variable. All of
-** threads are notified in turn. The highest priority thread will
-** probably acquire the lock.
-*/
-PR_IMPLEMENT(PRStatus) PR_NotifyAllCondVar(PRCondVar *cvar)
-{
- PRCList *q;
- PRIntn is;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- PR_ASSERT(cvar->lock->owner == me);
- if (cvar->lock->owner != me) return PR_FAILURE;
-
-#ifdef _PR_GLOBAL_THREADS_ONLY
- _PR_MD_NOTIFYALL_CV(&cvar->md, &cvar->lock->ilock);
- return PR_SUCCESS;
-#else /* _PR_GLOBAL_THREADS_ONLY */
- if ( !_PR_IS_NATIVE_THREAD(me))
- _PR_INTSOFF(is);
- _PR_CVAR_LOCK(cvar);
- q = cvar->condQ.next;
- while (q != &cvar->condQ) {
- PR_LOG(_pr_cvar_lm, PR_LOG_MIN, ("PR_NotifyAll: cvar=%p", cvar));
- _PR_NotifyThread(_PR_THREAD_CONDQ_PTR(q), me);
- q = q->next;
- }
- _PR_CVAR_UNLOCK(cvar);
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSON(is);
-
- return PR_SUCCESS;
-#endif /* _PR_GLOBAL_THREADS_ONLY */
-}
-
-
-/*********************************************************************/
-/*********************************************************************/
-/********************ROUTINES FOR DCE EMULATION***********************/
-/*********************************************************************/
-/*********************************************************************/
-#include "prpdce.h"
-
-PR_IMPLEMENT(PRCondVar*) PRP_NewNakedCondVar(void)
-{
- PRCondVar *cvar = PR_NEWZAP(PRCondVar);
- if (NULL != cvar)
- {
- if (_PR_MD_NEW_LOCK(&(cvar->ilock)) == PR_FAILURE)
- {
- PR_DELETE(cvar); cvar = NULL;
- }
- else
- {
- PR_INIT_CLIST(&cvar->condQ);
- cvar->lock = _PR_NAKED_CV_LOCK;
- }
-
- }
- return cvar;
-}
-
-PR_IMPLEMENT(void) PRP_DestroyNakedCondVar(PRCondVar *cvar)
-{
- PR_ASSERT(cvar->condQ.next == &cvar->condQ);
- PR_ASSERT(_PR_NAKED_CV_LOCK == cvar->lock);
-
- _PR_MD_FREE_LOCK(&(cvar->ilock));
-
- PR_DELETE(cvar);
-}
-
-PR_IMPLEMENT(PRStatus) PRP_NakedWait(
- PRCondVar *cvar, PRLock *lock, PRIntervalTime timeout)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PR_ASSERT(_PR_NAKED_CV_LOCK == cvar->lock);
- return _PR_WaitCondVar(me, cvar, lock, timeout);
-} /* PRP_NakedWait */
-
-PR_IMPLEMENT(PRStatus) PRP_NakedNotify(PRCondVar *cvar)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PR_ASSERT(_PR_NAKED_CV_LOCK == cvar->lock);
-
- _PR_NotifyCondVar(cvar, me);
-
- return PR_SUCCESS;
-} /* PRP_NakedNotify */
-
-PR_IMPLEMENT(PRStatus) PRP_NakedBroadcast(PRCondVar *cvar)
-{
- PRCList *q;
- PRIntn is;
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PR_ASSERT(_PR_NAKED_CV_LOCK == cvar->lock);
-
- if ( !_PR_IS_NATIVE_THREAD(me)) _PR_INTSOFF(is);
- _PR_MD_LOCK( &(cvar->ilock) );
- q = cvar->condQ.next;
- while (q != &cvar->condQ) {
- PR_LOG(_pr_cvar_lm, PR_LOG_MIN, ("PR_NotifyAll: cvar=%p", cvar));
- _PR_NotifyThread(_PR_THREAD_CONDQ_PTR(q), me);
- q = q->next;
- }
- _PR_MD_UNLOCK( &(cvar->ilock) );
- if (!_PR_IS_NATIVE_THREAD(me)) _PR_INTSON(is);
-
- return PR_SUCCESS;
-} /* PRP_NakedBroadcast */
-
diff --git a/nspr/pr/src/threads/combined/prulock.c b/nspr/pr/src/threads/combined/prulock.c
deleted file mode 100644
index 8b2f41e..0000000
--- a/nspr/pr/src/threads/combined/prulock.c
+++ /dev/null
@@ -1,446 +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/. */
-
-#include "primpl.h"
-
-#if defined(WIN95)
-/*
-** Some local variables report warnings on Win95 because the code paths
-** using them are conditioned on HAVE_CUSTOME_USER_THREADS.
-** The pragma suppresses the warning.
-**
-*/
-#pragma warning(disable : 4101)
-#endif
-
-
-void _PR_InitLocks(void)
-{
- _PR_MD_INIT_LOCKS();
-}
-
-/*
-** Deal with delayed interrupts/requested reschedule during interrupt
-** re-enables.
-*/
-void _PR_IntsOn(_PRCPU *cpu)
-{
- PRUintn missed, pri, i;
- _PRInterruptTable *it;
- PRThread *me;
-
- PR_ASSERT(cpu); /* Global threads don't have CPUs */
- PR_ASSERT(_PR_MD_GET_INTSOFF() > 0);
- me = _PR_MD_CURRENT_THREAD();
- PR_ASSERT(!(me->flags & _PR_IDLE_THREAD));
-
- /*
- ** Process delayed interrupts. This logic is kinda scary because we
- ** need to avoid losing an interrupt (it's ok to delay an interrupt
- ** until later).
- **
- ** There are two missed state words. _pr_ints.where indicates to the
- ** interrupt handler which state word is currently safe for
- ** modification.
- **
- ** This code scans both interrupt state words, using the where flag
- ** to indicate to the interrupt which state word is safe for writing.
- ** If an interrupt comes in during a scan the other word will be
- ** modified. This modification will be noticed during the next
- ** iteration of the loop or during the next call to this routine.
- */
- for (i = 0; i < 2; i++) {
- cpu->where = (1 - i);
- missed = cpu->u.missed[i];
- if (missed != 0) {
- cpu->u.missed[i] = 0;
- for (it = _pr_interruptTable; it->name; it++) {
- if (missed & it->missed_bit) {
- PR_LOG(_pr_sched_lm, PR_LOG_MIN,
- ("IntsOn[0]: %s intr", it->name));
- (*it->handler)();
- }
- }
- }
- }
-
- if (cpu->u.missed[3] != 0) {
- _PRCPU *cpu;
-
- _PR_THREAD_LOCK(me);
- me->state = _PR_RUNNABLE;
- pri = me->priority;
-
- cpu = me->cpu;
- _PR_RUNQ_LOCK(cpu);
- _PR_ADD_RUNQ(me, cpu, pri);
- _PR_RUNQ_UNLOCK(cpu);
- _PR_THREAD_UNLOCK(me);
- _PR_MD_SWITCH_CONTEXT(me);
- }
-}
-
-/*
-** Unblock the first runnable waiting thread. Skip over
-** threads that are trying to be suspended
-** Note: Caller must hold _PR_LOCK_LOCK()
-*/
-void _PR_UnblockLockWaiter(PRLock *lock)
-{
- PRThread *t = NULL;
- PRThread *me;
- PRCList *q;
-
- q = lock->waitQ.next;
- PR_ASSERT(q != &lock->waitQ);
- while (q != &lock->waitQ) {
- /* Unblock first waiter */
- t = _PR_THREAD_CONDQ_PTR(q);
-
- /*
- ** We are about to change the thread's state to runnable and for local
- ** threads, we are going to assign a cpu to it. So, protect thread's
- ** data structure.
- */
- _PR_THREAD_LOCK(t);
-
- if (t->flags & _PR_SUSPENDING) {
- q = q->next;
- _PR_THREAD_UNLOCK(t);
- continue;
- }
-
- /* Found a runnable thread */
- PR_ASSERT(t->state == _PR_LOCK_WAIT);
- PR_ASSERT(t->wait.lock == lock);
- t->wait.lock = 0;
- PR_REMOVE_LINK(&t->waitQLinks); /* take it off lock's waitQ */
-
- /*
- ** If this is a native thread, nothing else to do except to wake it
- ** up by calling the machine dependent wakeup routine.
- **
- ** If this is a local thread, we need to assign it a cpu and
- ** put the thread on that cpu's run queue. There are two cases to
- ** take care of. If the currently running thread is also a local
- ** thread, we just assign our own cpu to that thread and put it on
- ** the cpu's run queue. If the the currently running thread is a
- ** native thread, we assign the primordial cpu to it (on NT,
- ** MD_WAKEUP handles the cpu assignment).
- */
-
- if ( !_PR_IS_NATIVE_THREAD(t) ) {
-
- t->state = _PR_RUNNABLE;
-
- me = _PR_MD_CURRENT_THREAD();
-
- _PR_AddThreadToRunQ(me, t);
- _PR_THREAD_UNLOCK(t);
- } else {
- t->state = _PR_RUNNING;
- _PR_THREAD_UNLOCK(t);
- }
- _PR_MD_WAKEUP_WAITER(t);
- break;
- }
- return;
-}
-
-/************************************************************************/
-
-
-PR_IMPLEMENT(PRLock*) PR_NewLock(void)
-{
- PRLock *lock;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- lock = PR_NEWZAP(PRLock);
- if (lock) {
- if (_PR_InitLock(lock) != PR_SUCCESS) {
- PR_DELETE(lock);
- return NULL;
- }
- }
- return lock;
-}
-
-PRStatus _PR_InitLock(PRLock *lock)
-{
- if (_PR_MD_NEW_LOCK(&lock->ilock) != PR_SUCCESS) {
- return PR_FAILURE;
- }
- PR_INIT_CLIST(&lock->links);
- PR_INIT_CLIST(&lock->waitQ);
- return PR_SUCCESS;
-}
-
-/*
-** Destroy the given lock "lock". There is no point in making this race
-** free because if some other thread has the pointer to this lock all
-** bets are off.
-*/
-PR_IMPLEMENT(void) PR_DestroyLock(PRLock *lock)
-{
- _PR_FreeLock(lock);
- PR_DELETE(lock);
-}
-
-void _PR_FreeLock(PRLock *lock)
-{
- PR_ASSERT(lock->owner == 0);
- _PR_MD_FREE_LOCK(&lock->ilock);
-}
-
-extern PRThread *suspendAllThread;
-/*
-** Lock the lock.
-*/
-PR_IMPLEMENT(void) PR_Lock(PRLock *lock)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRIntn is;
- PRThread *t;
- PRCList *q;
-
- PR_ASSERT(me != suspendAllThread);
- PR_ASSERT(!(me->flags & _PR_IDLE_THREAD));
- PR_ASSERT(lock != NULL);
-#ifdef _PR_GLOBAL_THREADS_ONLY
- _PR_MD_LOCK(&lock->ilock);
- PR_ASSERT(lock->owner == 0);
- lock->owner = me;
- return;
-#else /* _PR_GLOBAL_THREADS_ONLY */
-
- if (_native_threads_only) {
- _PR_MD_LOCK(&lock->ilock);
- PR_ASSERT(lock->owner == 0);
- lock->owner = me;
- return;
- }
-
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSOFF(is);
-
- PR_ASSERT(_PR_IS_NATIVE_THREAD(me) || _PR_MD_GET_INTSOFF() != 0);
-
-retry:
- _PR_LOCK_LOCK(lock);
- if (lock->owner == 0) {
- /* Just got the lock */
- lock->owner = me;
- lock->priority = me->priority;
- /* Add the granted lock to this owning thread's lock list */
- PR_APPEND_LINK(&lock->links, &me->lockList);
- _PR_LOCK_UNLOCK(lock);
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_FAST_INTSON(is);
- return;
- }
-
- /* If this thread already owns this lock, then it is a deadlock */
- PR_ASSERT(lock->owner != me);
-
- PR_ASSERT(_PR_IS_NATIVE_THREAD(me) || _PR_MD_GET_INTSOFF() != 0);
-
-#if 0
- if (me->priority > lock->owner->priority) {
- /*
- ** Give the lock owner a priority boost until we get the
- ** lock. Record the priority we boosted it to.
- */
- lock->boostPriority = me->priority;
- _PR_SetThreadPriority(lock->owner, me->priority);
- }
-#endif
-
- /*
- Add this thread to the asked for lock's list of waiting threads. We
- add this thread thread in the right priority order so when the unlock
- occurs, the thread with the higher priority will get the lock.
- */
- q = lock->waitQ.next;
- if (q == &lock->waitQ || _PR_THREAD_CONDQ_PTR(q)->priority ==
- _PR_THREAD_CONDQ_PTR(lock->waitQ.prev)->priority) {
- /*
- * If all the threads in the lock waitQ have the same priority,
- * then avoid scanning the list: insert the element at the end.
- */
- q = &lock->waitQ;
- } else {
- /* Sort thread into lock's waitQ at appropriate point */
- /* Now scan the list for where to insert this entry */
- while (q != &lock->waitQ) {
- t = _PR_THREAD_CONDQ_PTR(lock->waitQ.next);
- if (me->priority > t->priority) {
- /* Found a lower priority thread to insert in front of */
- break;
- }
- q = q->next;
- }
- }
- PR_INSERT_BEFORE(&me->waitQLinks, q);
-
- /*
- Now grab the threadLock since we are about to change the state. We have
- to do this since a PR_Suspend or PR_SetThreadPriority type call that takes
- a PRThread* as an argument could be changing the state of this thread from
- a thread running on a different cpu.
- */
-
- _PR_THREAD_LOCK(me);
- me->state = _PR_LOCK_WAIT;
- me->wait.lock = lock;
- _PR_THREAD_UNLOCK(me);
-
- _PR_LOCK_UNLOCK(lock);
-
- _PR_MD_WAIT(me, PR_INTERVAL_NO_TIMEOUT);
- goto retry;
-
-#endif /* _PR_GLOBAL_THREADS_ONLY */
-}
-
-/*
-** Unlock the lock.
-*/
-PR_IMPLEMENT(PRStatus) PR_Unlock(PRLock *lock)
-{
- PRCList *q;
- PRThreadPriority pri, boost;
- PRIntn is;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- PR_ASSERT(lock != NULL);
- PR_ASSERT(lock->owner == me);
- PR_ASSERT(me != suspendAllThread);
- PR_ASSERT(!(me->flags & _PR_IDLE_THREAD));
- if (lock->owner != me) {
- return PR_FAILURE;
- }
-
-#ifdef _PR_GLOBAL_THREADS_ONLY
- lock->owner = 0;
- _PR_MD_UNLOCK(&lock->ilock);
- return PR_SUCCESS;
-#else /* _PR_GLOBAL_THREADS_ONLY */
-
- if (_native_threads_only) {
- lock->owner = 0;
- _PR_MD_UNLOCK(&lock->ilock);
- return PR_SUCCESS;
- }
-
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSOFF(is);
- _PR_LOCK_LOCK(lock);
-
- /* Remove the lock from the owning thread's lock list */
- PR_REMOVE_LINK(&lock->links);
- pri = lock->priority;
- boost = lock->boostPriority;
- if (boost > pri) {
- /*
- ** We received a priority boost during the time we held the lock.
- ** We need to figure out what priority to move to by scanning
- ** down our list of lock's that we are still holding and using
- ** the highest boosted priority found.
- */
- q = me->lockList.next;
- while (q != &me->lockList) {
- PRLock *ll = _PR_LOCK_PTR(q);
- if (ll->boostPriority > pri) {
- pri = ll->boostPriority;
- }
- q = q->next;
- }
- if (pri != me->priority) {
- _PR_SetThreadPriority(me, pri);
- }
- }
-
- /* Unblock the first waiting thread */
- q = lock->waitQ.next;
- if (q != &lock->waitQ)
- _PR_UnblockLockWaiter(lock);
- lock->boostPriority = PR_PRIORITY_LOW;
- lock->owner = 0;
- _PR_LOCK_UNLOCK(lock);
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSON(is);
- return PR_SUCCESS;
-#endif /* _PR_GLOBAL_THREADS_ONLY */
-}
-
-/*
-** If the current thread owns |lock|, this assertion is guaranteed to
-** succeed. Otherwise, the behavior of this function is undefined.
-*/
-PR_IMPLEMENT(void) PR_AssertCurrentThreadOwnsLock(PRLock *lock)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PR_ASSERT(lock->owner == me);
-}
-
-/*
-** Test and then lock the lock if it's not already locked by some other
-** thread. Return PR_FALSE if some other thread owned the lock at the
-** time of the call.
-*/
-PR_IMPLEMENT(PRBool) PR_TestAndLock(PRLock *lock)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRBool rv = PR_FALSE;
- PRIntn is;
-
-#ifdef _PR_GLOBAL_THREADS_ONLY
- is = _PR_MD_TEST_AND_LOCK(&lock->ilock);
- if (is == 0) {
- lock->owner = me;
- return PR_TRUE;
- }
- return PR_FALSE;
-#else /* _PR_GLOBAL_THREADS_ONLY */
-
-#ifndef _PR_LOCAL_THREADS_ONLY
- if (_native_threads_only) {
- is = _PR_MD_TEST_AND_LOCK(&lock->ilock);
- if (is == 0) {
- lock->owner = me;
- return PR_TRUE;
- }
- return PR_FALSE;
- }
-#endif
-
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSOFF(is);
-
- _PR_LOCK_LOCK(lock);
- if (lock->owner == 0) {
- /* Just got the lock */
- lock->owner = me;
- lock->priority = me->priority;
- /* Add the granted lock to this owning thread's lock list */
- PR_APPEND_LINK(&lock->links, &me->lockList);
- rv = PR_TRUE;
- }
- _PR_LOCK_UNLOCK(lock);
-
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSON(is);
- return rv;
-#endif /* _PR_GLOBAL_THREADS_ONLY */
-}
-
-/************************************************************************/
-/************************************************************************/
-/***********************ROUTINES FOR DCE EMULATION***********************/
-/************************************************************************/
-/************************************************************************/
-PR_IMPLEMENT(PRStatus) PRP_TryLock(PRLock *lock)
- { return (PR_TestAndLock(lock)) ? PR_SUCCESS : PR_FAILURE; }
diff --git a/nspr/pr/src/threads/combined/prustack.c b/nspr/pr/src/threads/combined/prustack.c
deleted file mode 100644
index 59562ba..0000000
--- a/nspr/pr/src/threads/combined/prustack.c
+++ /dev/null
@@ -1,174 +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/. */
-
-#include "primpl.h"
-
-/* List of free stack virtual memory chunks */
-PRLock *_pr_stackLock;
-PRCList _pr_freeStacks = PR_INIT_STATIC_CLIST(&_pr_freeStacks);
-PRIntn _pr_numFreeStacks;
-PRIntn _pr_maxFreeStacks = 4;
-
-#ifdef DEBUG
-/*
-** A variable that can be set via the debugger...
-*/
-PRBool _pr_debugStacks = PR_FALSE;
-#endif
-
-/* How much space to leave between the stacks, at each end */
-#define REDZONE (2 << _pr_pageShift)
-
-#define _PR_THREAD_STACK_PTR(_qp) \
- ((PRThreadStack*) ((char*) (_qp) - offsetof(PRThreadStack,links)))
-
-void _PR_InitStacks(void)
-{
- _pr_stackLock = PR_NewLock();
-}
-
-void _PR_CleanupStacks(void)
-{
- if (_pr_stackLock) {
- PR_DestroyLock(_pr_stackLock);
- _pr_stackLock = NULL;
- }
-}
-
-/*
-** Allocate a stack for a thread.
-*/
-PRThreadStack *_PR_NewStack(PRUint32 stackSize)
-{
- PRCList *qp;
- PRThreadStack *ts;
- PRThread *thr;
-
- /*
- ** Trim the list of free stacks. Trim it backwards, tossing out the
- ** oldest stack found first (this way more recent stacks have a
- ** chance of being present in the data cache).
- */
- PR_Lock(_pr_stackLock);
- qp = _pr_freeStacks.prev;
- while ((_pr_numFreeStacks > _pr_maxFreeStacks) && (qp != &_pr_freeStacks)) {
- ts = _PR_THREAD_STACK_PTR(qp);
- thr = _PR_THREAD_STACK_TO_PTR(ts);
- qp = qp->prev;
- /*
- * skip stacks which are still being used
- */
- if (thr->no_sched)
- continue;
- PR_REMOVE_LINK(&ts->links);
-
- /* Give platform OS to clear out the stack for debugging */
- _PR_MD_CLEAR_STACK(ts);
-
- _pr_numFreeStacks--;
- _PR_DestroySegment(ts->seg);
- PR_DELETE(ts);
- }
-
- /*
- ** Find a free thread stack. This searches the list of free'd up
- ** virtually mapped thread stacks.
- */
- qp = _pr_freeStacks.next;
- ts = 0;
- while (qp != &_pr_freeStacks) {
- ts = _PR_THREAD_STACK_PTR(qp);
- thr = _PR_THREAD_STACK_TO_PTR(ts);
- qp = qp->next;
- /*
- * skip stacks which are still being used
- */
- if ((!(thr->no_sched)) && ((ts->allocSize - 2*REDZONE) >= stackSize)) {
- /*
- ** Found a stack that is not in use and is big enough. Change
- ** stackSize to fit it.
- */
- stackSize = ts->allocSize - 2*REDZONE;
- PR_REMOVE_LINK(&ts->links);
- _pr_numFreeStacks--;
- ts->links.next = 0;
- ts->links.prev = 0;
- PR_Unlock(_pr_stackLock);
- goto done;
- }
- ts = 0;
- }
- PR_Unlock(_pr_stackLock);
-
- if (!ts) {
- /* Make a new thread stack object. */
- ts = PR_NEWZAP(PRThreadStack);
- if (!ts) {
- return NULL;
- }
-
- /*
- ** Assign some of the virtual space to the new stack object. We
- ** may not get that piece of VM, but if nothing else we will
- ** advance the pointer so we don't collide (unless the OS screws
- ** up).
- */
- ts->allocSize = stackSize + 2*REDZONE;
- ts->seg = _PR_NewSegment(ts->allocSize, 0);
- if (!ts->seg) {
- PR_DELETE(ts);
- return NULL;
- }
- }
-
- done:
- ts->allocBase = (char*)ts->seg->vaddr;
- ts->flags = _PR_STACK_MAPPED;
- ts->stackSize = stackSize;
-
-#ifdef HAVE_STACK_GROWING_UP
- ts->stackTop = ts->allocBase + REDZONE;
- ts->stackBottom = ts->stackTop + stackSize;
-#else
- ts->stackBottom = ts->allocBase + REDZONE;
- ts->stackTop = ts->stackBottom + stackSize;
-#endif
-
- PR_LOG(_pr_thread_lm, PR_LOG_NOTICE,
- ("thread stack: base=0x%x limit=0x%x bottom=0x%x top=0x%x\n",
- ts->allocBase, ts->allocBase + ts->allocSize - 1,
- ts->allocBase + REDZONE,
- ts->allocBase + REDZONE + stackSize - 1));
-
- _PR_MD_INIT_STACK(ts,REDZONE);
-
- return ts;
-}
-
-/*
-** Free the stack for the current thread
-*/
-void _PR_FreeStack(PRThreadStack *ts)
-{
- if (!ts) {
- return;
- }
- if (ts->flags & _PR_STACK_PRIMORDIAL) {
- PR_DELETE(ts);
- return;
- }
-
- /*
- ** Put the stack on the free list. This is done because we are still
- ** using the stack. Next time a thread is created we will trim the
- ** list down; it's safe to do it then because we will have had to
- ** context switch to a live stack before another thread can be
- ** created.
- */
- PR_Lock(_pr_stackLock);
- PR_APPEND_LINK(&ts->links, _pr_freeStacks.prev);
- _pr_numFreeStacks++;
- PR_Unlock(_pr_stackLock);
-}
diff --git a/nspr/pr/src/threads/combined/pruthr.c b/nspr/pr/src/threads/combined/pruthr.c
deleted file mode 100644
index 4625ab2..0000000
--- a/nspr/pr/src/threads/combined/pruthr.c
+++ /dev/null
@@ -1,1889 +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/. */
-
-#include "primpl.h"
-#include <signal.h>
-#include <string.h>
-
-#if defined(WIN95)
-/*
-** Some local variables report warnings on Win95 because the code paths
-** using them are conditioned on HAVE_CUSTOME_USER_THREADS.
-** The pragma suppresses the warning.
-**
-*/
-#pragma warning(disable : 4101)
-#endif
-
-/* _pr_activeLock protects the following global variables */
-PRLock *_pr_activeLock;
-PRInt32 _pr_primordialExitCount; /* In PR_Cleanup(), the primordial thread
- * waits until all other user (non-system)
- * threads have terminated before it exits.
- * So whenever we decrement _pr_userActive,
- * it is compared with
- * _pr_primordialExitCount.
- * If the primordial thread is a system
- * thread, then _pr_primordialExitCount
- * is 0. If the primordial thread is
- * itself a user thread, then
- * _pr_primordialThread is 1.
- */
-PRCondVar *_pr_primordialExitCVar; /* When _pr_userActive is decremented to
- * _pr_primordialExitCount, this condition
- * variable is notified.
- */
-
-PRLock *_pr_deadQLock;
-PRUint32 _pr_numNativeDead;
-PRUint32 _pr_numUserDead;
-PRCList _pr_deadNativeQ;
-PRCList _pr_deadUserQ;
-
-PRUint32 _pr_join_counter;
-
-PRUint32 _pr_local_threads;
-PRUint32 _pr_global_threads;
-
-PRBool suspendAllOn = PR_FALSE;
-PRThread *suspendAllThread = NULL;
-
-extern PRCList _pr_active_global_threadQ;
-extern PRCList _pr_active_local_threadQ;
-
-static void _PR_DecrActiveThreadCount(PRThread *thread);
-static PRThread *_PR_AttachThread(PRThreadType, PRThreadPriority, PRThreadStack *);
-static void _PR_InitializeNativeStack(PRThreadStack *ts);
-static void _PR_InitializeRecycledThread(PRThread *thread);
-static void _PR_UserRunThread(void);
-
-void _PR_InitThreads(PRThreadType type, PRThreadPriority priority,
- PRUintn maxPTDs)
-{
- PRThread *thread;
- PRThreadStack *stack;
-
- PR_ASSERT(priority == PR_PRIORITY_NORMAL);
-
- _pr_terminationCVLock = PR_NewLock();
- _pr_activeLock = PR_NewLock();
-
-#ifndef HAVE_CUSTOM_USER_THREADS
- stack = PR_NEWZAP(PRThreadStack);
-#ifdef HAVE_STACK_GROWING_UP
- stack->stackTop = (char*) ((((PRWord)&type) >> _pr_pageShift)
- << _pr_pageShift);
-#else
-#if defined(SOLARIS) || defined (UNIXWARE) && defined (USR_SVR4_THREADS)
- stack->stackTop = (char*) &thread;
-#else
- stack->stackTop = (char*) ((((PRWord)&type + _pr_pageSize - 1)
- >> _pr_pageShift) << _pr_pageShift);
-#endif
-#endif
-#else
- /* If stack is NULL, we're using custom user threads like NT fibers. */
- stack = PR_NEWZAP(PRThreadStack);
- if (stack) {
- stack->stackSize = 0;
- _PR_InitializeNativeStack(stack);
- }
-#endif /* HAVE_CUSTOM_USER_THREADS */
-
- thread = _PR_AttachThread(type, priority, stack);
- if (thread) {
- _PR_MD_SET_CURRENT_THREAD(thread);
-
- if (type == PR_SYSTEM_THREAD) {
- thread->flags = _PR_SYSTEM;
- _pr_systemActive++;
- _pr_primordialExitCount = 0;
- } else {
- _pr_userActive++;
- _pr_primordialExitCount = 1;
- }
- thread->no_sched = 1;
- _pr_primordialExitCVar = PR_NewCondVar(_pr_activeLock);
- }
-
- if (!thread) PR_Abort();
-#ifdef _PR_LOCAL_THREADS_ONLY
- thread->flags |= _PR_PRIMORDIAL;
-#else
- thread->flags |= _PR_PRIMORDIAL | _PR_GLOBAL_SCOPE;
-#endif
-
- /*
- * Needs _PR_PRIMORDIAL flag set before calling
- * _PR_MD_INIT_THREAD()
- */
- if (_PR_MD_INIT_THREAD(thread) == PR_FAILURE) {
- /*
- * XXX do what?
- */
- }
-
- if (_PR_IS_NATIVE_THREAD(thread)) {
- PR_APPEND_LINK(&thread->active, &_PR_ACTIVE_GLOBAL_THREADQ());
- _pr_global_threads++;
- } else {
- PR_APPEND_LINK(&thread->active, &_PR_ACTIVE_LOCAL_THREADQ());
- _pr_local_threads++;
- }
-
- _pr_recycleThreads = 0;
- _pr_deadQLock = PR_NewLock();
- _pr_numNativeDead = 0;
- _pr_numUserDead = 0;
- PR_INIT_CLIST(&_pr_deadNativeQ);
- PR_INIT_CLIST(&_pr_deadUserQ);
-}
-
-void _PR_CleanupThreads(void)
-{
- if (_pr_terminationCVLock) {
- PR_DestroyLock(_pr_terminationCVLock);
- _pr_terminationCVLock = NULL;
- }
- if (_pr_activeLock) {
- PR_DestroyLock(_pr_activeLock);
- _pr_activeLock = NULL;
- }
- if (_pr_primordialExitCVar) {
- PR_DestroyCondVar(_pr_primordialExitCVar);
- _pr_primordialExitCVar = NULL;
- }
- /* TODO _pr_dead{Native,User}Q need to be deleted */
- if (_pr_deadQLock) {
- PR_DestroyLock(_pr_deadQLock);
- _pr_deadQLock = NULL;
- }
-}
-
-/*
-** Initialize a stack for a native thread
-*/
-static void _PR_InitializeNativeStack(PRThreadStack *ts)
-{
- if( ts && (ts->stackTop == 0) ) {
- ts->allocSize = ts->stackSize;
-
- /*
- ** Setup stackTop and stackBottom values.
- */
-#ifdef HAVE_STACK_GROWING_UP
- ts->allocBase = (char*) ((((PRWord)&ts) >> _pr_pageShift)
- << _pr_pageShift);
- ts->stackBottom = ts->allocBase + ts->stackSize;
- ts->stackTop = ts->allocBase;
-#else
- ts->allocBase = (char*) ((((PRWord)&ts + _pr_pageSize - 1)
- >> _pr_pageShift) << _pr_pageShift);
- ts->stackTop = ts->allocBase;
- ts->stackBottom = ts->allocBase - ts->stackSize;
-#endif
- }
-}
-
-void _PR_NotifyJoinWaiters(PRThread *thread)
-{
- /*
- ** Handle joinable threads. Change the state to waiting for join.
- ** Remove from our run Q and put it on global waiting to join Q.
- ** Notify on our "termination" condition variable so that joining
- ** thread will know about our termination. Switch our context and
- ** come back later on to continue the cleanup.
- */
- PR_ASSERT(thread == _PR_MD_CURRENT_THREAD());
- if (thread->term != NULL) {
- PR_Lock(_pr_terminationCVLock);
- _PR_THREAD_LOCK(thread);
- thread->state = _PR_JOIN_WAIT;
- if ( !_PR_IS_NATIVE_THREAD(thread) ) {
- _PR_MISCQ_LOCK(thread->cpu);
- _PR_ADD_JOINQ(thread, thread->cpu);
- _PR_MISCQ_UNLOCK(thread->cpu);
- }
- _PR_THREAD_UNLOCK(thread);
- PR_NotifyCondVar(thread->term);
- PR_Unlock(_pr_terminationCVLock);
- _PR_MD_WAIT(thread, PR_INTERVAL_NO_TIMEOUT);
- PR_ASSERT(thread->state != _PR_JOIN_WAIT);
- }
-
-}
-
-/*
- * Zero some of the data members of a recycled thread.
- *
- * Note that we can do this either when a dead thread is added to
- * the dead thread queue or when it is reused. Here, we are doing
- * this lazily, when the thread is reused in _PR_CreateThread().
- */
-static void _PR_InitializeRecycledThread(PRThread *thread)
-{
- /*
- * Assert that the following data members are already zeroed
- * by _PR_CleanupThread().
- */
-#ifdef DEBUG
- if (thread->privateData) {
- unsigned int i;
- for (i = 0; i < thread->tpdLength; i++) {
- PR_ASSERT(thread->privateData[i] == NULL);
- }
- }
-#endif
- PR_ASSERT(thread->dumpArg == 0 && thread->dump == 0);
- PR_ASSERT(thread->errorString == 0 && thread->errorStringSize == 0);
- PR_ASSERT(thread->errorStringLength == 0);
- PR_ASSERT(thread->name == 0);
-
- /* Reset data members in thread structure */
- thread->errorCode = thread->osErrorCode = 0;
- thread->io_pending = thread->io_suspended = PR_FALSE;
- thread->environment = 0;
- PR_INIT_CLIST(&thread->lockList);
-}
-
-PRStatus _PR_RecycleThread(PRThread *thread)
-{
- if ( _PR_IS_NATIVE_THREAD(thread) &&
- _PR_NUM_DEADNATIVE < _pr_recycleThreads) {
- _PR_DEADQ_LOCK;
- PR_APPEND_LINK(&thread->links, &_PR_DEADNATIVEQ);
- _PR_INC_DEADNATIVE;
- _PR_DEADQ_UNLOCK;
- return (PR_SUCCESS);
- } else if ( !_PR_IS_NATIVE_THREAD(thread) &&
- _PR_NUM_DEADUSER < _pr_recycleThreads) {
- _PR_DEADQ_LOCK;
- PR_APPEND_LINK(&thread->links, &_PR_DEADUSERQ);
- _PR_INC_DEADUSER;
- _PR_DEADQ_UNLOCK;
- return (PR_SUCCESS);
- }
- return (PR_FAILURE);
-}
-
-/*
- * Decrement the active thread count, either _pr_systemActive or
- * _pr_userActive, depending on whether the thread is a system thread
- * or a user thread. If all the user threads, except possibly
- * the primordial thread, have terminated, we notify the primordial
- * thread of this condition.
- *
- * Since this function will lock _pr_activeLock, do not call this
- * function while holding the _pr_activeLock lock, as this will result
- * in a deadlock.
- */
-
-static void
-_PR_DecrActiveThreadCount(PRThread *thread)
-{
- PR_Lock(_pr_activeLock);
- if (thread->flags & _PR_SYSTEM) {
- _pr_systemActive--;
- } else {
- _pr_userActive--;
- if (_pr_userActive == _pr_primordialExitCount) {
- PR_NotifyCondVar(_pr_primordialExitCVar);
- }
- }
- PR_Unlock(_pr_activeLock);
-}
-
-/*
-** Detach thread structure
-*/
-static void
-_PR_DestroyThread(PRThread *thread)
-{
- _PR_MD_FREE_LOCK(&thread->threadLock);
- PR_DELETE(thread);
-}
-
-void
-_PR_NativeDestroyThread(PRThread *thread)
-{
- if(thread->term) {
- PR_DestroyCondVar(thread->term);
- thread->term = 0;
- }
- if (NULL != thread->privateData) {
- PR_ASSERT(0 != thread->tpdLength);
- PR_DELETE(thread->privateData);
- thread->tpdLength = 0;
- }
- PR_DELETE(thread->stack);
- _PR_DestroyThread(thread);
-}
-
-void
-_PR_UserDestroyThread(PRThread *thread)
-{
- if(thread->term) {
- PR_DestroyCondVar(thread->term);
- thread->term = 0;
- }
- if (NULL != thread->privateData) {
- PR_ASSERT(0 != thread->tpdLength);
- PR_DELETE(thread->privateData);
- thread->tpdLength = 0;
- }
- _PR_MD_FREE_LOCK(&thread->threadLock);
- if (thread->threadAllocatedOnStack == 1) {
- _PR_MD_CLEAN_THREAD(thread);
- /*
- * Because the no_sched field is set, this thread/stack will
- * will not be re-used until the flag is cleared by the thread
- * we will context switch to.
- */
- _PR_FreeStack(thread->stack);
- } else {
-#ifdef WINNT
- _PR_MD_CLEAN_THREAD(thread);
-#else
- /*
- * This assertion does not apply to NT. On NT, every fiber
- * has its threadAllocatedOnStack equal to 0. Elsewhere,
- * only the primordial thread has its threadAllocatedOnStack
- * equal to 0.
- */
- PR_ASSERT(thread->flags & _PR_PRIMORDIAL);
-#endif
- }
-}
-
-
-/*
-** Run a thread's start function. When the start function returns the
-** thread is done executing and no longer needs the CPU. If there are no
-** more user threads running then we can exit the program.
-*/
-void _PR_NativeRunThread(void *arg)
-{
- PRThread *thread = (PRThread *)arg;
-
- _PR_MD_SET_CURRENT_THREAD(thread);
-
- _PR_MD_SET_CURRENT_CPU(NULL);
-
- /* Set up the thread stack information */
- _PR_InitializeNativeStack(thread->stack);
-
- /* Set up the thread md information */
- if (_PR_MD_INIT_THREAD(thread) == PR_FAILURE) {
- /*
- * thread failed to initialize itself, possibly due to
- * failure to allocate per-thread resources
- */
- return;
- }
-
- while(1) {
- thread->state = _PR_RUNNING;
-
- /*
- * Add to list of active threads
- */
- PR_Lock(_pr_activeLock);
- PR_APPEND_LINK(&thread->active, &_PR_ACTIVE_GLOBAL_THREADQ());
- _pr_global_threads++;
- PR_Unlock(_pr_activeLock);
-
- (*thread->startFunc)(thread->arg);
-
- /*
- * The following two assertions are meant for NT asynch io.
- *
- * The thread should have no asynch io in progress when it
- * exits, otherwise the overlapped buffer, which is part of
- * the thread structure, would become invalid.
- */
- PR_ASSERT(thread->io_pending == PR_FALSE);
- /*
- * This assertion enforces the programming guideline that
- * if an io function times out or is interrupted, the thread
- * should close the fd to force the asynch io to abort
- * before it exits. Right now, closing the fd is the only
- * way to clear the io_suspended flag.
- */
- PR_ASSERT(thread->io_suspended == PR_FALSE);
-
- /*
- * remove thread from list of active threads
- */
- PR_Lock(_pr_activeLock);
- PR_REMOVE_LINK(&thread->active);
- _pr_global_threads--;
- PR_Unlock(_pr_activeLock);
-
- PR_LOG(_pr_thread_lm, PR_LOG_MIN, ("thread exiting"));
-
- /* All done, time to go away */
- _PR_CleanupThread(thread);
-
- _PR_NotifyJoinWaiters(thread);
-
- _PR_DecrActiveThreadCount(thread);
-
- thread->state = _PR_DEAD_STATE;
-
- if (!_pr_recycleThreads || (_PR_RecycleThread(thread) ==
- PR_FAILURE)) {
- /*
- * thread not recycled
- * platform-specific thread exit processing
- * - for stuff like releasing native-thread resources, etc.
- */
- _PR_MD_EXIT_THREAD(thread);
- /*
- * Free memory allocated for the thread
- */
- _PR_NativeDestroyThread(thread);
- /*
- * thread gone, cannot de-reference thread now
- */
- return;
- }
-
- /* Now wait for someone to activate us again... */
- _PR_MD_WAIT(thread, PR_INTERVAL_NO_TIMEOUT);
- }
-}
-
-static void _PR_UserRunThread(void)
-{
- PRThread *thread = _PR_MD_CURRENT_THREAD();
- PRIntn is;
-
- if (_MD_LAST_THREAD())
- _MD_LAST_THREAD()->no_sched = 0;
-
-#ifdef HAVE_CUSTOM_USER_THREADS
- if (thread->stack == NULL) {
- thread->stack = PR_NEWZAP(PRThreadStack);
- _PR_InitializeNativeStack(thread->stack);
- }
-#endif /* HAVE_CUSTOM_USER_THREADS */
-
- while(1) {
- /* Run thread main */
- if ( !_PR_IS_NATIVE_THREAD(thread)) _PR_MD_SET_INTSOFF(0);
-
- /*
- * Add to list of active threads
- */
- if (!(thread->flags & _PR_IDLE_THREAD)) {
- PR_Lock(_pr_activeLock);
- PR_APPEND_LINK(&thread->active, &_PR_ACTIVE_LOCAL_THREADQ());
- _pr_local_threads++;
- PR_Unlock(_pr_activeLock);
- }
-
- (*thread->startFunc)(thread->arg);
-
- /*
- * The following two assertions are meant for NT asynch io.
- *
- * The thread should have no asynch io in progress when it
- * exits, otherwise the overlapped buffer, which is part of
- * the thread structure, would become invalid.
- */
- PR_ASSERT(thread->io_pending == PR_FALSE);
- /*
- * This assertion enforces the programming guideline that
- * if an io function times out or is interrupted, the thread
- * should close the fd to force the asynch io to abort
- * before it exits. Right now, closing the fd is the only
- * way to clear the io_suspended flag.
- */
- PR_ASSERT(thread->io_suspended == PR_FALSE);
-
- PR_Lock(_pr_activeLock);
- /*
- * remove thread from list of active threads
- */
- if (!(thread->flags & _PR_IDLE_THREAD)) {
- PR_REMOVE_LINK(&thread->active);
- _pr_local_threads--;
- }
- PR_Unlock(_pr_activeLock);
- PR_LOG(_pr_thread_lm, PR_LOG_MIN, ("thread exiting"));
-
- /* All done, time to go away */
- _PR_CleanupThread(thread);
-
- _PR_INTSOFF(is);
-
- _PR_NotifyJoinWaiters(thread);
-
- _PR_DecrActiveThreadCount(thread);
-
- thread->state = _PR_DEAD_STATE;
-
- if (!_pr_recycleThreads || (_PR_RecycleThread(thread) ==
- PR_FAILURE)) {
- /*
- ** Destroy the thread resources
- */
- _PR_UserDestroyThread(thread);
- }
-
- /*
- ** Find another user thread to run. This cpu has finished the
- ** previous threads main and is now ready to run another thread.
- */
- {
- PRInt32 is;
- _PR_INTSOFF(is);
- _PR_MD_SWITCH_CONTEXT(thread);
- }
-
- /* Will land here when we get scheduled again if we are recycling... */
- }
-}
-
-void _PR_SetThreadPriority(PRThread *thread, PRThreadPriority newPri)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRIntn is;
-
- if ( _PR_IS_NATIVE_THREAD(thread) ) {
- _PR_MD_SET_PRIORITY(&(thread->md), newPri);
- return;
- }
-
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSOFF(is);
- _PR_THREAD_LOCK(thread);
- if (newPri != thread->priority) {
- _PRCPU *cpu = thread->cpu;
-
- switch (thread->state) {
- case _PR_RUNNING:
- /* Change my priority */
-
- _PR_RUNQ_LOCK(cpu);
- thread->priority = newPri;
- if (_PR_RUNQREADYMASK(cpu) >> (newPri + 1)) {
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_SET_RESCHED_FLAG();
- }
- _PR_RUNQ_UNLOCK(cpu);
- break;
-
- case _PR_RUNNABLE:
-
- _PR_RUNQ_LOCK(cpu);
- /* Move to different runQ */
- _PR_DEL_RUNQ(thread);
- thread->priority = newPri;
- PR_ASSERT(!(thread->flags & _PR_IDLE_THREAD));
- _PR_ADD_RUNQ(thread, cpu, newPri);
- _PR_RUNQ_UNLOCK(cpu);
-
- if (newPri > me->priority) {
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_SET_RESCHED_FLAG();
- }
-
- break;
-
- case _PR_LOCK_WAIT:
- case _PR_COND_WAIT:
- case _PR_IO_WAIT:
- case _PR_SUSPENDED:
-
- thread->priority = newPri;
- break;
- }
- }
- _PR_THREAD_UNLOCK(thread);
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSON(is);
-}
-
-/*
-** Suspend the named thread and copy its gc registers into regBuf
-*/
-static void _PR_Suspend(PRThread *thread)
-{
- PRIntn is;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- PR_ASSERT(thread != me);
- PR_ASSERT(!_PR_IS_NATIVE_THREAD(thread) || (!thread->cpu));
-
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSOFF(is);
- _PR_THREAD_LOCK(thread);
- switch (thread->state) {
- case _PR_RUNNABLE:
- if (!_PR_IS_NATIVE_THREAD(thread)) {
- _PR_RUNQ_LOCK(thread->cpu);
- _PR_DEL_RUNQ(thread);
- _PR_RUNQ_UNLOCK(thread->cpu);
-
- _PR_MISCQ_LOCK(thread->cpu);
- _PR_ADD_SUSPENDQ(thread, thread->cpu);
- _PR_MISCQ_UNLOCK(thread->cpu);
- } else {
- /*
- * Only LOCAL threads are suspended by _PR_Suspend
- */
- PR_ASSERT(0);
- }
- thread->state = _PR_SUSPENDED;
- break;
-
- case _PR_RUNNING:
- /*
- * The thread being suspended should be a LOCAL thread with
- * _pr_numCPUs == 1. Hence, the thread cannot be in RUNNING state
- */
- PR_ASSERT(0);
- break;
-
- case _PR_LOCK_WAIT:
- case _PR_IO_WAIT:
- case _PR_COND_WAIT:
- if (_PR_IS_NATIVE_THREAD(thread)) {
- _PR_MD_SUSPEND_THREAD(thread);
- }
- thread->flags |= _PR_SUSPENDING;
- break;
-
- default:
- PR_Abort();
- }
- _PR_THREAD_UNLOCK(thread);
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSON(is);
-}
-
-static void _PR_Resume(PRThread *thread)
-{
- PRThreadPriority pri;
- PRIntn is;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSOFF(is);
- _PR_THREAD_LOCK(thread);
- switch (thread->state) {
- case _PR_SUSPENDED:
- thread->state = _PR_RUNNABLE;
- thread->flags &= ~_PR_SUSPENDING;
- if (!_PR_IS_NATIVE_THREAD(thread)) {
- _PR_MISCQ_LOCK(thread->cpu);
- _PR_DEL_SUSPENDQ(thread);
- _PR_MISCQ_UNLOCK(thread->cpu);
-
- pri = thread->priority;
-
- _PR_RUNQ_LOCK(thread->cpu);
- _PR_ADD_RUNQ(thread, thread->cpu, pri);
- _PR_RUNQ_UNLOCK(thread->cpu);
-
- if (pri > _PR_MD_CURRENT_THREAD()->priority) {
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_SET_RESCHED_FLAG();
- }
- } else {
- PR_ASSERT(0);
- }
- break;
-
- case _PR_IO_WAIT:
- case _PR_COND_WAIT:
- thread->flags &= ~_PR_SUSPENDING;
-/* PR_ASSERT(thread->wait.monitor->stickyCount == 0); */
- break;
-
- case _PR_LOCK_WAIT:
- {
- PRLock *wLock = thread->wait.lock;
-
- thread->flags &= ~_PR_SUSPENDING;
-
- _PR_LOCK_LOCK(wLock);
- if (thread->wait.lock->owner == 0) {
- _PR_UnblockLockWaiter(thread->wait.lock);
- }
- _PR_LOCK_UNLOCK(wLock);
- break;
- }
- case _PR_RUNNABLE:
- break;
- case _PR_RUNNING:
- /*
- * The thread being suspended should be a LOCAL thread with
- * _pr_numCPUs == 1. Hence, the thread cannot be in RUNNING state
- */
- PR_ASSERT(0);
- break;
-
- default:
- /*
- * thread should have been in one of the above-listed blocked states
- * (_PR_JOIN_WAIT, _PR_IO_WAIT, _PR_UNBORN, _PR_DEAD_STATE)
- */
- PR_Abort();
- }
- _PR_THREAD_UNLOCK(thread);
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSON(is);
-
-}
-
-#if !defined(_PR_LOCAL_THREADS_ONLY) && defined(XP_UNIX)
-static PRThread *get_thread(_PRCPU *cpu, PRBool *wakeup_cpus)
-{
- PRThread *thread;
- PRIntn pri;
- PRUint32 r;
- PRCList *qp;
- PRIntn priMin, priMax;
-
- _PR_RUNQ_LOCK(cpu);
- r = _PR_RUNQREADYMASK(cpu);
- if (r==0) {
- priMin = priMax = PR_PRIORITY_FIRST;
- } else if (r == (1<<PR_PRIORITY_NORMAL) ) {
- priMin = priMax = PR_PRIORITY_NORMAL;
- } else {
- priMin = PR_PRIORITY_FIRST;
- priMax = PR_PRIORITY_LAST;
- }
- thread = NULL;
- for (pri = priMax; pri >= priMin ; pri-- ) {
- if (r & (1 << pri)) {
- for (qp = _PR_RUNQ(cpu)[pri].next;
- qp != &_PR_RUNQ(cpu)[pri];
- qp = qp->next) {
- thread = _PR_THREAD_PTR(qp);
- /*
- * skip non-schedulable threads
- */
- PR_ASSERT(!(thread->flags & _PR_IDLE_THREAD));
- if (thread->no_sched) {
- thread = NULL;
- /*
- * Need to wakeup cpus to avoid missing a
- * runnable thread
- * Waking up all CPU's need happen only once.
- */
-
- *wakeup_cpus = PR_TRUE;
- continue;
- } else if (thread->flags & _PR_BOUND_THREAD) {
- /*
- * Thread bound to cpu 0
- */
-
- thread = NULL;
-#ifdef IRIX
- _PR_MD_WAKEUP_PRIMORDIAL_CPU();
-#endif
- continue;
- } else if (thread->io_pending == PR_TRUE) {
- /*
- * A thread that is blocked for I/O needs to run
- * on the same cpu on which it was blocked. This is because
- * the cpu's ioq is accessed without lock protection and scheduling
- * the thread on a different cpu would preclude this optimization.
- */
- thread = NULL;
- continue;
- } else {
- /* Pull thread off of its run queue */
- _PR_DEL_RUNQ(thread);
- _PR_RUNQ_UNLOCK(cpu);
- return(thread);
- }
- }
- }
- thread = NULL;
- }
- _PR_RUNQ_UNLOCK(cpu);
- return(thread);
-}
-#endif /* !defined(_PR_LOCAL_THREADS_ONLY) && defined(XP_UNIX) */
-
-/*
-** Schedule this native thread by finding the highest priority nspr
-** thread that is ready to run.
-**
-** Note- everyone really needs to call _PR_MD_SWITCH_CONTEXT (which calls
-** PR_Schedule() rather than calling PR_Schedule. Otherwise if there
-** is initialization required for switching from SWITCH_CONTEXT,
-** it will not get done!
-*/
-void _PR_Schedule(void)
-{
- PRThread *thread, *me = _PR_MD_CURRENT_THREAD();
- _PRCPU *cpu = _PR_MD_CURRENT_CPU();
- PRIntn pri;
- PRUint32 r;
- PRCList *qp;
- PRIntn priMin, priMax;
-#if !defined(_PR_LOCAL_THREADS_ONLY) && defined(XP_UNIX)
- PRBool wakeup_cpus;
-#endif
-
- /* Interrupts must be disabled */
- PR_ASSERT(_PR_IS_NATIVE_THREAD(me) || _PR_MD_GET_INTSOFF() != 0);
-
- /* Since we are rescheduling, we no longer want to */
- _PR_CLEAR_RESCHED_FLAG();
-
- /*
- ** Find highest priority thread to run. Bigger priority numbers are
- ** higher priority threads
- */
- _PR_RUNQ_LOCK(cpu);
- /*
- * if we are in SuspendAll mode, can schedule only the thread
- * that called PR_SuspendAll
- *
- * The thread may be ready to run now, after completing an I/O
- * operation, for example
- */
- if ((thread = suspendAllThread) != 0) {
- if ((!(thread->no_sched)) && (thread->state == _PR_RUNNABLE)) {
- /* Pull thread off of its run queue */
- _PR_DEL_RUNQ(thread);
- _PR_RUNQ_UNLOCK(cpu);
- goto found_thread;
- } else {
- thread = NULL;
- _PR_RUNQ_UNLOCK(cpu);
- goto idle_thread;
- }
- }
- r = _PR_RUNQREADYMASK(cpu);
- if (r==0) {
- priMin = priMax = PR_PRIORITY_FIRST;
- } else if (r == (1<<PR_PRIORITY_NORMAL) ) {
- priMin = priMax = PR_PRIORITY_NORMAL;
- } else {
- priMin = PR_PRIORITY_FIRST;
- priMax = PR_PRIORITY_LAST;
- }
- thread = NULL;
- for (pri = priMax; pri >= priMin ; pri-- ) {
- if (r & (1 << pri)) {
- for (qp = _PR_RUNQ(cpu)[pri].next;
- qp != &_PR_RUNQ(cpu)[pri];
- qp = qp->next) {
- thread = _PR_THREAD_PTR(qp);
- /*
- * skip non-schedulable threads
- */
- PR_ASSERT(!(thread->flags & _PR_IDLE_THREAD));
- if ((thread->no_sched) && (me != thread)){
- thread = NULL;
- continue;
- } else {
- /* Pull thread off of its run queue */
- _PR_DEL_RUNQ(thread);
- _PR_RUNQ_UNLOCK(cpu);
- goto found_thread;
- }
- }
- }
- thread = NULL;
- }
- _PR_RUNQ_UNLOCK(cpu);
-
-#if !defined(_PR_LOCAL_THREADS_ONLY) && defined(XP_UNIX)
-
- wakeup_cpus = PR_FALSE;
- _PR_CPU_LIST_LOCK();
- for (qp = _PR_CPUQ().next; qp != &_PR_CPUQ(); qp = qp->next) {
- if (cpu != _PR_CPU_PTR(qp)) {
- if ((thread = get_thread(_PR_CPU_PTR(qp), &wakeup_cpus))
- != NULL) {
- thread->cpu = cpu;
- _PR_CPU_LIST_UNLOCK();
- if (wakeup_cpus == PR_TRUE)
- _PR_MD_WAKEUP_CPUS();
- goto found_thread;
- }
- }
- }
- _PR_CPU_LIST_UNLOCK();
- if (wakeup_cpus == PR_TRUE)
- _PR_MD_WAKEUP_CPUS();
-
-#endif /* _PR_LOCAL_THREADS_ONLY */
-
-idle_thread:
- /*
- ** There are no threads to run. Switch to the idle thread
- */
- PR_LOG(_pr_sched_lm, PR_LOG_MAX, ("pausing"));
- thread = _PR_MD_CURRENT_CPU()->idle_thread;
-
-found_thread:
- PR_ASSERT((me == thread) || ((thread->state == _PR_RUNNABLE) &&
- (!(thread->no_sched))));
-
- /* Resume the thread */
- PR_LOG(_pr_sched_lm, PR_LOG_MAX,
- ("switching to %d[%p]", thread->id, thread));
- PR_ASSERT(thread->state != _PR_RUNNING);
- thread->state = _PR_RUNNING;
-
- /* If we are on the runq, it just means that we went to sleep on some
- * resource, and by the time we got here another real native thread had
- * already given us the resource and put us back on the runqueue
- */
- PR_ASSERT(thread->cpu == _PR_MD_CURRENT_CPU());
- if (thread != me)
- _PR_MD_RESTORE_CONTEXT(thread);
-#if 0
- /* XXXMB; with setjmp/longjmp it is impossible to land here, but
- * it is not with fibers... Is this a bad thing? I believe it is
- * still safe.
- */
- PR_NOT_REACHED("impossible return from schedule");
-#endif
-}
-
-/*
-** Attaches a thread.
-** Does not set the _PR_MD_CURRENT_THREAD.
-** Does not specify the scope of the thread.
-*/
-static PRThread *
-_PR_AttachThread(PRThreadType type, PRThreadPriority priority,
- PRThreadStack *stack)
-{
- PRThread *thread;
- char *mem;
-
- if (priority > PR_PRIORITY_LAST) {
- priority = PR_PRIORITY_LAST;
- } else if (priority < PR_PRIORITY_FIRST) {
- priority = PR_PRIORITY_FIRST;
- }
-
- mem = (char*) PR_CALLOC(sizeof(PRThread));
- if (mem) {
- thread = (PRThread*) mem;
- thread->priority = priority;
- thread->stack = stack;
- thread->state = _PR_RUNNING;
- PR_INIT_CLIST(&thread->lockList);
- if (_PR_MD_NEW_LOCK(&thread->threadLock) == PR_FAILURE) {
- PR_DELETE(thread);
- return 0;
- }
-
- return thread;
- }
- return 0;
-}
-
-
-
-PR_IMPLEMENT(PRThread*)
-_PR_NativeCreateThread(PRThreadType type,
- void (*start)(void *arg),
- void *arg,
- PRThreadPriority priority,
- PRThreadScope scope,
- PRThreadState state,
- PRUint32 stackSize,
- PRUint32 flags)
-{
- PRThread *thread;
-
- thread = _PR_AttachThread(type, priority, NULL);
-
- if (thread) {
- PR_Lock(_pr_activeLock);
- thread->flags = (flags | _PR_GLOBAL_SCOPE);
- thread->id = ++_pr_utid;
- if (type == PR_SYSTEM_THREAD) {
- thread->flags |= _PR_SYSTEM;
- _pr_systemActive++;
- } else {
- _pr_userActive++;
- }
- PR_Unlock(_pr_activeLock);
-
- thread->stack = PR_NEWZAP(PRThreadStack);
- if (!thread->stack) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- goto done;
- }
- thread->stack->stackSize = stackSize?stackSize:_MD_DEFAULT_STACK_SIZE;
- thread->stack->thr = thread;
- thread->startFunc = start;
- thread->arg = arg;
-
- /*
- Set thread flags related to scope and joinable state. If joinable
- thread, allocate a "termination" conidition variable.
- */
- if (state == PR_JOINABLE_THREAD) {
- thread->term = PR_NewCondVar(_pr_terminationCVLock);
- if (thread->term == NULL) {
- PR_DELETE(thread->stack);
- goto done;
- }
- }
-
- thread->state = _PR_RUNNING;
- if (_PR_MD_CREATE_THREAD(thread, _PR_NativeRunThread, priority,
- scope,state,stackSize) == PR_SUCCESS) {
- return thread;
- }
- if (thread->term) {
- PR_DestroyCondVar(thread->term);
- thread->term = NULL;
- }
- PR_DELETE(thread->stack);
- }
-
-done:
- if (thread) {
- _PR_DecrActiveThreadCount(thread);
- _PR_DestroyThread(thread);
- }
- return NULL;
-}
-
-/************************************************************************/
-
-PR_IMPLEMENT(PRThread*) _PR_CreateThread(PRThreadType type,
- void (*start)(void *arg),
- void *arg,
- PRThreadPriority priority,
- PRThreadScope scope,
- PRThreadState state,
- PRUint32 stackSize,
- PRUint32 flags)
-{
- PRThread *me;
- PRThread *thread = NULL;
- PRThreadStack *stack;
- char *top;
- PRIntn is;
- PRIntn native = 0;
- PRIntn useRecycled = 0;
- PRBool status;
-
- /*
- First, pin down the priority. Not all compilers catch passing out of
- range enum here. If we let bad values thru, priority queues won't work.
- */
- if (priority > PR_PRIORITY_LAST) {
- priority = PR_PRIORITY_LAST;
- } else if (priority < PR_PRIORITY_FIRST) {
- priority = PR_PRIORITY_FIRST;
- }
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (! (flags & _PR_IDLE_THREAD))
- me = _PR_MD_CURRENT_THREAD();
-
-#if defined(_PR_GLOBAL_THREADS_ONLY)
- /*
- * can create global threads only
- */
- if (scope == PR_LOCAL_THREAD)
- scope = PR_GLOBAL_THREAD;
-#endif
-
- if (_native_threads_only)
- scope = PR_GLOBAL_THREAD;
-
- native = (((scope == PR_GLOBAL_THREAD)|| (scope == PR_GLOBAL_BOUND_THREAD))
- && _PR_IS_NATIVE_THREAD_SUPPORTED());
-
- _PR_ADJUST_STACKSIZE(stackSize);
-
- if (native) {
- /*
- * clear the IDLE_THREAD flag which applies to LOCAL
- * threads only
- */
- flags &= ~_PR_IDLE_THREAD;
- flags |= _PR_GLOBAL_SCOPE;
- if (_PR_NUM_DEADNATIVE > 0) {
- _PR_DEADQ_LOCK;
-
- if (_PR_NUM_DEADNATIVE == 0) { /* Thread safe check */
- _PR_DEADQ_UNLOCK;
- } else {
- thread = _PR_THREAD_PTR(_PR_DEADNATIVEQ.next);
- PR_REMOVE_LINK(&thread->links);
- _PR_DEC_DEADNATIVE;
- _PR_DEADQ_UNLOCK;
-
- _PR_InitializeRecycledThread(thread);
- thread->startFunc = start;
- thread->arg = arg;
- thread->flags = (flags | _PR_GLOBAL_SCOPE);
- if (type == PR_SYSTEM_THREAD)
- {
- thread->flags |= _PR_SYSTEM;
- PR_ATOMIC_INCREMENT(&_pr_systemActive);
- }
- else PR_ATOMIC_INCREMENT(&_pr_userActive);
-
- if (state == PR_JOINABLE_THREAD) {
- if (!thread->term)
- thread->term = PR_NewCondVar(_pr_terminationCVLock);
- }
- else {
- if(thread->term) {
- PR_DestroyCondVar(thread->term);
- thread->term = 0;
- }
- }
-
- thread->priority = priority;
- _PR_MD_SET_PRIORITY(&(thread->md), priority);
- /* XXX what about stackSize? */
- thread->state = _PR_RUNNING;
- _PR_MD_WAKEUP_WAITER(thread);
- return thread;
- }
- }
- thread = _PR_NativeCreateThread(type, start, arg, priority,
- scope, state, stackSize, flags);
- } else {
- if (_PR_NUM_DEADUSER > 0) {
- _PR_DEADQ_LOCK;
-
- if (_PR_NUM_DEADUSER == 0) { /* thread safe check */
- _PR_DEADQ_UNLOCK;
- } else {
- PRCList *ptr;
-
- /* Go down list checking for a recycled thread with a
- * large enough stack. XXXMB - this has a bad degenerate case.
- */
- ptr = _PR_DEADUSERQ.next;
- while( ptr != &_PR_DEADUSERQ ) {
- thread = _PR_THREAD_PTR(ptr);
- if ((thread->stack->stackSize >= stackSize) &&
- (!thread->no_sched)) {
- PR_REMOVE_LINK(&thread->links);
- _PR_DEC_DEADUSER;
- break;
- } else {
- ptr = ptr->next;
- thread = NULL;
- }
- }
-
- _PR_DEADQ_UNLOCK;
-
- if (thread) {
- _PR_InitializeRecycledThread(thread);
- thread->startFunc = start;
- thread->arg = arg;
- thread->priority = priority;
- if (state == PR_JOINABLE_THREAD) {
- if (!thread->term)
- thread->term = PR_NewCondVar(_pr_terminationCVLock);
- } else {
- if(thread->term) {
- PR_DestroyCondVar(thread->term);
- thread->term = 0;
- }
- }
- useRecycled++;
- }
- }
- }
- if (thread == NULL) {
-#ifndef HAVE_CUSTOM_USER_THREADS
- stack = _PR_NewStack(stackSize);
- if (!stack) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
-
- /* Allocate thread object and per-thread data off the top of the stack*/
- top = stack->stackTop;
-#ifdef HAVE_STACK_GROWING_UP
- thread = (PRThread*) top;
- top = top + sizeof(PRThread);
- /*
- * Make stack 64-byte aligned
- */
- if ((PRUptrdiff)top & 0x3f) {
- top = (char*)(((PRUptrdiff)top + 0x40) & ~0x3f);
- }
-#else
- top = top - sizeof(PRThread);
- thread = (PRThread*) top;
- /*
- * Make stack 64-byte aligned
- */
- if ((PRUptrdiff)top & 0x3f) {
- top = (char*)((PRUptrdiff)top & ~0x3f);
- }
-#endif
- stack->thr = thread;
- memset(thread, 0, sizeof(PRThread));
- thread->threadAllocatedOnStack = 1;
-#else
- thread = _PR_MD_CREATE_USER_THREAD(stackSize, start, arg);
- if (!thread) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
- thread->threadAllocatedOnStack = 0;
- stack = NULL;
- top = NULL;
-#endif
-
- /* Initialize thread */
- thread->tpdLength = 0;
- thread->privateData = NULL;
- thread->stack = stack;
- thread->priority = priority;
- thread->startFunc = start;
- thread->arg = arg;
- PR_INIT_CLIST(&thread->lockList);
-
- if (_PR_MD_INIT_THREAD(thread) == PR_FAILURE) {
- if (thread->threadAllocatedOnStack == 1)
- _PR_FreeStack(thread->stack);
- else {
- PR_DELETE(thread);
- }
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
- return NULL;
- }
-
- if (_PR_MD_NEW_LOCK(&thread->threadLock) == PR_FAILURE) {
- if (thread->threadAllocatedOnStack == 1)
- _PR_FreeStack(thread->stack);
- else {
- PR_DELETE(thread->privateData);
- PR_DELETE(thread);
- }
- PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
- return NULL;
- }
-
- _PR_MD_INIT_CONTEXT(thread, top, _PR_UserRunThread, &status);
-
- if (status == PR_FALSE) {
- _PR_MD_FREE_LOCK(&thread->threadLock);
- if (thread->threadAllocatedOnStack == 1)
- _PR_FreeStack(thread->stack);
- else {
- PR_DELETE(thread->privateData);
- PR_DELETE(thread);
- }
- return NULL;
- }
-
- /*
- Set thread flags related to scope and joinable state. If joinable
- thread, allocate a "termination" condition variable.
- */
- if (state == PR_JOINABLE_THREAD) {
- thread->term = PR_NewCondVar(_pr_terminationCVLock);
- if (thread->term == NULL) {
- _PR_MD_FREE_LOCK(&thread->threadLock);
- if (thread->threadAllocatedOnStack == 1)
- _PR_FreeStack(thread->stack);
- else {
- PR_DELETE(thread->privateData);
- PR_DELETE(thread);
- }
- return NULL;
- }
- }
-
- }
-
- /* Update thread type counter */
- PR_Lock(_pr_activeLock);
- thread->flags = flags;
- thread->id = ++_pr_utid;
- if (type == PR_SYSTEM_THREAD) {
- thread->flags |= _PR_SYSTEM;
- _pr_systemActive++;
- } else {
- _pr_userActive++;
- }
-
- /* Make thread runnable */
- thread->state = _PR_RUNNABLE;
- /*
- * Add to list of active threads
- */
- PR_Unlock(_pr_activeLock);
-
- if ((! (thread->flags & _PR_IDLE_THREAD)) && _PR_IS_NATIVE_THREAD(me) )
- thread->cpu = _PR_GetPrimordialCPU();
- else
- thread->cpu = _PR_MD_CURRENT_CPU();
-
- PR_ASSERT(!_PR_IS_NATIVE_THREAD(thread));
-
- if ((! (thread->flags & _PR_IDLE_THREAD)) && !_PR_IS_NATIVE_THREAD(me)) {
- _PR_INTSOFF(is);
- _PR_RUNQ_LOCK(thread->cpu);
- _PR_ADD_RUNQ(thread, thread->cpu, priority);
- _PR_RUNQ_UNLOCK(thread->cpu);
- }
-
- if (thread->flags & _PR_IDLE_THREAD) {
- /*
- ** If the creating thread is a kernel thread, we need to
- ** awaken the user thread idle thread somehow; potentially
- ** it could be sleeping in its idle loop, and we need to poke
- ** it. To do so, wake the idle thread...
- */
- _PR_MD_WAKEUP_WAITER(NULL);
- } else if (_PR_IS_NATIVE_THREAD(me)) {
- _PR_MD_WAKEUP_WAITER(thread);
- }
- if ((! (thread->flags & _PR_IDLE_THREAD)) && !_PR_IS_NATIVE_THREAD(me) )
- _PR_INTSON(is);
- }
-
- return thread;
-}
-
-PR_IMPLEMENT(PRThread*) PR_CreateThread(PRThreadType type,
- void (*start)(void *arg),
- void *arg,
- PRThreadPriority priority,
- PRThreadScope scope,
- PRThreadState state,
- PRUint32 stackSize)
-{
- return _PR_CreateThread(type, start, arg, priority, scope, state,
- stackSize, 0);
-}
-
-/*
-** Associate a thread object with an existing native thread.
-** "type" is the type of thread object to attach
-** "priority" is the priority to assign to the thread
-** "stack" defines the shape of the threads stack
-**
-** This can return NULL if some kind of error occurs, or if memory is
-** tight.
-**
-** This call is not normally needed unless you create your own native
-** thread. PR_Init does this automatically for the primordial thread.
-*/
-PRThread* _PRI_AttachThread(PRThreadType type,
- PRThreadPriority priority, PRThreadStack *stack, PRUint32 flags)
-{
- PRThread *thread;
-
- if ((thread = _PR_MD_GET_ATTACHED_THREAD()) != NULL) {
- return thread;
- }
- _PR_MD_SET_CURRENT_THREAD(NULL);
-
- /* Clear out any state if this thread was attached before */
- _PR_MD_SET_CURRENT_CPU(NULL);
-
- thread = _PR_AttachThread(type, priority, stack);
- if (thread) {
- PRIntn is;
-
- _PR_MD_SET_CURRENT_THREAD(thread);
-
- thread->flags = flags | _PR_GLOBAL_SCOPE | _PR_ATTACHED;
-
- if (!stack) {
- thread->stack = PR_NEWZAP(PRThreadStack);
- if (!thread->stack) {
- _PR_DestroyThread(thread);
- return NULL;
- }
- thread->stack->stackSize = _MD_DEFAULT_STACK_SIZE;
- }
- PR_INIT_CLIST(&thread->links);
-
- if (_PR_MD_INIT_ATTACHED_THREAD(thread) == PR_FAILURE) {
- PR_DELETE(thread->stack);
- _PR_DestroyThread(thread);
- return NULL;
- }
-
- _PR_MD_SET_CURRENT_CPU(NULL);
-
- if (_PR_MD_CURRENT_CPU()) {
- _PR_INTSOFF(is);
- PR_Lock(_pr_activeLock);
- }
- if (type == PR_SYSTEM_THREAD) {
- thread->flags |= _PR_SYSTEM;
- _pr_systemActive++;
- } else {
- _pr_userActive++;
- }
- if (_PR_MD_CURRENT_CPU()) {
- PR_Unlock(_pr_activeLock);
- _PR_INTSON(is);
- }
- }
- return thread;
-}
-
-PR_IMPLEMENT(PRThread*) PR_AttachThread(PRThreadType type,
- PRThreadPriority priority, PRThreadStack *stack)
-{
- return PR_GetCurrentThread();
-}
-
-PR_IMPLEMENT(void) PR_DetachThread(void)
-{
- /*
- * On IRIX, Solaris, and Windows, foreign threads are detached when
- * they terminate.
- */
-#if !defined(IRIX) && !defined(WIN32) \
- && !(defined(SOLARIS) && defined(_PR_GLOBAL_THREADS_ONLY))
- PRThread *me;
- if (_pr_initialized) {
- me = _PR_MD_GET_ATTACHED_THREAD();
- if ((me != NULL) && (me->flags & _PR_ATTACHED))
- _PRI_DetachThread();
- }
-#endif
-}
-
-void _PRI_DetachThread(void)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if (me->flags & _PR_PRIMORDIAL) {
- /*
- * ignore, if primordial thread
- */
- return;
- }
- PR_ASSERT(me->flags & _PR_ATTACHED);
- PR_ASSERT(_PR_IS_NATIVE_THREAD(me));
- _PR_CleanupThread(me);
- PR_DELETE(me->privateData);
-
- _PR_DecrActiveThreadCount(me);
-
- _PR_MD_CLEAN_THREAD(me);
- _PR_MD_SET_CURRENT_THREAD(NULL);
- if (!me->threadAllocatedOnStack)
- PR_DELETE(me->stack);
- _PR_MD_FREE_LOCK(&me->threadLock);
- PR_DELETE(me);
-}
-
-/*
-** Wait for thread termination:
-** "thread" is the target thread
-**
-** This can return PR_FAILURE if no joinable thread could be found
-** corresponding to the specified target thread.
-**
-** The calling thread is suspended until the target thread completes.
-** Several threads cannot wait for the same thread to complete; one thread
-** will complete successfully and others will terminate with an error PR_FAILURE.
-** The calling thread will not be blocked if the target thread has already
-** terminated.
-*/
-PR_IMPLEMENT(PRStatus) PR_JoinThread(PRThread *thread)
-{
- PRIntn is;
- PRCondVar *term;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSOFF(is);
- term = thread->term;
- /* can't join a non-joinable thread */
- if (term == NULL) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- goto ErrorExit;
- }
-
- /* multiple threads can't wait on the same joinable thread */
- if (term->condQ.next != &term->condQ) {
- goto ErrorExit;
- }
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSON(is);
-
- /* wait for the target thread's termination cv invariant */
- PR_Lock (_pr_terminationCVLock);
- while (thread->state != _PR_JOIN_WAIT) {
- (void) PR_WaitCondVar(term, PR_INTERVAL_NO_TIMEOUT);
- }
- (void) PR_Unlock (_pr_terminationCVLock);
-
- /*
- Remove target thread from global waiting to join Q; make it runnable
- again and put it back on its run Q. When it gets scheduled later in
- _PR_RunThread code, it will clean up its stack.
- */
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSOFF(is);
- thread->state = _PR_RUNNABLE;
- if ( !_PR_IS_NATIVE_THREAD(thread) ) {
- _PR_THREAD_LOCK(thread);
-
- _PR_MISCQ_LOCK(thread->cpu);
- _PR_DEL_JOINQ(thread);
- _PR_MISCQ_UNLOCK(thread->cpu);
-
- _PR_AddThreadToRunQ(me, thread);
- _PR_THREAD_UNLOCK(thread);
- }
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSON(is);
-
- _PR_MD_WAKEUP_WAITER(thread);
-
- return PR_SUCCESS;
-
-ErrorExit:
- if ( !_PR_IS_NATIVE_THREAD(me)) _PR_INTSON(is);
- return PR_FAILURE;
-}
-
-PR_IMPLEMENT(void) PR_SetThreadPriority(PRThread *thread,
- PRThreadPriority newPri)
-{
-
- /*
- First, pin down the priority. Not all compilers catch passing out of
- range enum here. If we let bad values thru, priority queues won't work.
- */
- if ((PRIntn)newPri > (PRIntn)PR_PRIORITY_LAST) {
- newPri = PR_PRIORITY_LAST;
- } else if ((PRIntn)newPri < (PRIntn)PR_PRIORITY_FIRST) {
- newPri = PR_PRIORITY_FIRST;
- }
-
- if ( _PR_IS_NATIVE_THREAD(thread) ) {
- thread->priority = newPri;
- _PR_MD_SET_PRIORITY(&(thread->md), newPri);
- } else _PR_SetThreadPriority(thread, newPri);
-}
-
-PR_IMPLEMENT(PRStatus) PR_SetCurrentThreadName(const char *name)
-{
- PRThread *thread;
- size_t nameLen;
-
- if (!name) {
- PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
- return PR_FAILURE;
- }
-
- thread = PR_GetCurrentThread();
- if (!thread)
- return PR_FAILURE;
-
- PR_Free(thread->name);
- nameLen = strlen(name);
- thread->name = (char *)PR_Malloc(nameLen + 1);
- if (!thread->name)
- return PR_FAILURE;
- memcpy(thread->name, name, nameLen + 1);
- _PR_MD_SET_CURRENT_THREAD_NAME(thread->name);
- return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(const char *) PR_GetThreadName(const PRThread *thread)
-{
- if (!thread)
- return NULL;
- return thread->name;
-}
-
-
-/*
-** This routine prevents all other threads from running. This call is needed by
-** the garbage collector.
-*/
-PR_IMPLEMENT(void) PR_SuspendAll(void)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRCList *qp;
-
- /*
- * Stop all user and native threads which are marked GC able.
- */
- PR_Lock(_pr_activeLock);
- suspendAllOn = PR_TRUE;
- suspendAllThread = _PR_MD_CURRENT_THREAD();
- _PR_MD_BEGIN_SUSPEND_ALL();
- for (qp = _PR_ACTIVE_LOCAL_THREADQ().next;
- qp != &_PR_ACTIVE_LOCAL_THREADQ(); qp = qp->next) {
- if ((me != _PR_ACTIVE_THREAD_PTR(qp)) &&
- _PR_IS_GCABLE_THREAD(_PR_ACTIVE_THREAD_PTR(qp))) {
- _PR_Suspend(_PR_ACTIVE_THREAD_PTR(qp));
- PR_ASSERT((_PR_ACTIVE_THREAD_PTR(qp))->state != _PR_RUNNING);
- }
- }
- for (qp = _PR_ACTIVE_GLOBAL_THREADQ().next;
- qp != &_PR_ACTIVE_GLOBAL_THREADQ(); qp = qp->next) {
- if ((me != _PR_ACTIVE_THREAD_PTR(qp)) &&
- _PR_IS_GCABLE_THREAD(_PR_ACTIVE_THREAD_PTR(qp)))
- /* PR_Suspend(_PR_ACTIVE_THREAD_PTR(qp)); */
- _PR_MD_SUSPEND_THREAD(_PR_ACTIVE_THREAD_PTR(qp));
- }
- _PR_MD_END_SUSPEND_ALL();
-}
-
-/*
-** This routine unblocks all other threads that were suspended from running by
-** PR_SuspendAll(). This call is needed by the garbage collector.
-*/
-PR_IMPLEMENT(void) PR_ResumeAll(void)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRCList *qp;
-
- /*
- * Resume all user and native threads which are marked GC able.
- */
- _PR_MD_BEGIN_RESUME_ALL();
- for (qp = _PR_ACTIVE_LOCAL_THREADQ().next;
- qp != &_PR_ACTIVE_LOCAL_THREADQ(); qp = qp->next) {
- if ((me != _PR_ACTIVE_THREAD_PTR(qp)) &&
- _PR_IS_GCABLE_THREAD(_PR_ACTIVE_THREAD_PTR(qp)))
- _PR_Resume(_PR_ACTIVE_THREAD_PTR(qp));
- }
- for (qp = _PR_ACTIVE_GLOBAL_THREADQ().next;
- qp != &_PR_ACTIVE_GLOBAL_THREADQ(); qp = qp->next) {
- if ((me != _PR_ACTIVE_THREAD_PTR(qp)) &&
- _PR_IS_GCABLE_THREAD(_PR_ACTIVE_THREAD_PTR(qp)))
- _PR_MD_RESUME_THREAD(_PR_ACTIVE_THREAD_PTR(qp));
- }
- _PR_MD_END_RESUME_ALL();
- suspendAllThread = NULL;
- suspendAllOn = PR_FALSE;
- PR_Unlock(_pr_activeLock);
-}
-
-PR_IMPLEMENT(PRStatus) PR_EnumerateThreads(PREnumerator func, void *arg)
-{
- PRCList *qp, *qp_next;
- PRIntn i = 0;
- PRStatus rv = PR_SUCCESS;
- PRThread* t;
-
- /*
- ** Currently Enumerate threads happen only with suspension and
- ** pr_activeLock held
- */
- PR_ASSERT(suspendAllOn);
-
- /* Steve Morse, 4-23-97: Note that we can't walk a queue by taking
- * qp->next after applying the function "func". In particular, "func"
- * might remove the thread from the queue and put it into another one in
- * which case qp->next no longer points to the next entry in the original
- * queue.
- *
- * To get around this problem, we save qp->next in qp_next before applying
- * "func" and use that saved value as the next value after applying "func".
- */
-
- /*
- * Traverse the list of local and global threads
- */
- for (qp = _PR_ACTIVE_LOCAL_THREADQ().next;
- qp != &_PR_ACTIVE_LOCAL_THREADQ(); qp = qp_next)
- {
- qp_next = qp->next;
- t = _PR_ACTIVE_THREAD_PTR(qp);
- if (_PR_IS_GCABLE_THREAD(t))
- {
- rv = (*func)(t, i, arg);
- if (rv != PR_SUCCESS)
- return rv;
- i++;
- }
- }
- for (qp = _PR_ACTIVE_GLOBAL_THREADQ().next;
- qp != &_PR_ACTIVE_GLOBAL_THREADQ(); qp = qp_next)
- {
- qp_next = qp->next;
- t = _PR_ACTIVE_THREAD_PTR(qp);
- if (_PR_IS_GCABLE_THREAD(t))
- {
- rv = (*func)(t, i, arg);
- if (rv != PR_SUCCESS)
- return rv;
- i++;
- }
- }
- return rv;
-}
-
-/* FUNCTION: _PR_AddSleepQ
-** DESCRIPTION:
-** Adds a thread to the sleep/pauseQ.
-** RESTRICTIONS:
-** Caller must have the RUNQ lock.
-** Caller must be a user level thread
-*/
-PR_IMPLEMENT(void)
-_PR_AddSleepQ(PRThread *thread, PRIntervalTime timeout)
-{
- _PRCPU *cpu = thread->cpu;
-
- if (timeout == PR_INTERVAL_NO_TIMEOUT) {
- /* append the thread to the global pause Q */
- PR_APPEND_LINK(&thread->links, &_PR_PAUSEQ(thread->cpu));
- thread->flags |= _PR_ON_PAUSEQ;
- } else {
- PRIntervalTime sleep;
- PRCList *q;
- PRThread *t;
-
- /* sort onto global sleepQ */
- sleep = timeout;
-
- /* Check if we are longest timeout */
- if (timeout >= _PR_SLEEPQMAX(cpu)) {
- PR_INSERT_BEFORE(&thread->links, &_PR_SLEEPQ(cpu));
- thread->sleep = timeout - _PR_SLEEPQMAX(cpu);
- _PR_SLEEPQMAX(cpu) = timeout;
- } else {
- /* Sort thread into global sleepQ at appropriate point */
- q = _PR_SLEEPQ(cpu).next;
-
- /* Now scan the list for where to insert this entry */
- while (q != &_PR_SLEEPQ(cpu)) {
- t = _PR_THREAD_PTR(q);
- if (sleep < t->sleep) {
- /* Found sleeper to insert in front of */
- break;
- }
- sleep -= t->sleep;
- q = q->next;
- }
- thread->sleep = sleep;
- PR_INSERT_BEFORE(&thread->links, q);
-
- /*
- ** Subtract our sleep time from the sleeper that follows us (there
- ** must be one) so that they remain relative to us.
- */
- PR_ASSERT (thread->links.next != &_PR_SLEEPQ(cpu));
-
- t = _PR_THREAD_PTR(thread->links.next);
- PR_ASSERT(_PR_THREAD_PTR(t->links.prev) == thread);
- t->sleep -= sleep;
- }
-
- thread->flags |= _PR_ON_SLEEPQ;
- }
-}
-
-/* FUNCTION: _PR_DelSleepQ
-** DESCRIPTION:
-** Removes a thread from the sleep/pauseQ.
-** INPUTS:
-** If propogate_time is true, then the thread following the deleted
-** thread will be get the time from the deleted thread. This is used
-** when deleting a sleeper that has not timed out.
-** RESTRICTIONS:
-** Caller must have the RUNQ lock.
-** Caller must be a user level thread
-*/
-PR_IMPLEMENT(void)
-_PR_DelSleepQ(PRThread *thread, PRBool propogate_time)
-{
- _PRCPU *cpu = thread->cpu;
-
- /* Remove from pauseQ/sleepQ */
- if (thread->flags & (_PR_ON_PAUSEQ|_PR_ON_SLEEPQ)) {
- if (thread->flags & _PR_ON_SLEEPQ) {
- PRCList *q = thread->links.next;
- if (q != &_PR_SLEEPQ(cpu)) {
- if (propogate_time == PR_TRUE) {
- PRThread *after = _PR_THREAD_PTR(q);
- after->sleep += thread->sleep;
- } else
- _PR_SLEEPQMAX(cpu) -= thread->sleep;
- } else {
- /* Check if prev is the beggining of the list; if so,
- * we are the only element on the list.
- */
- if (thread->links.prev != &_PR_SLEEPQ(cpu))
- _PR_SLEEPQMAX(cpu) -= thread->sleep;
- else
- _PR_SLEEPQMAX(cpu) = 0;
- }
- thread->flags &= ~_PR_ON_SLEEPQ;
- } else {
- thread->flags &= ~_PR_ON_PAUSEQ;
- }
- PR_REMOVE_LINK(&thread->links);
- } else
- PR_ASSERT(0);
-}
-
-void
-_PR_AddThreadToRunQ(
- PRThread *me, /* the current thread */
- PRThread *thread) /* the local thread to be added to a run queue */
-{
- PRThreadPriority pri = thread->priority;
- _PRCPU *cpu = thread->cpu;
-
- PR_ASSERT(!_PR_IS_NATIVE_THREAD(thread));
-
-#if defined(WINNT)
- /*
- * On NT, we can only reliably know that the current CPU
- * is not idle. We add the awakened thread to the run
- * queue of its CPU if its CPU is the current CPU.
- * For any other CPU, we don't really know whether it
- * is busy or idle. So in all other cases, we just
- * "post" the awakened thread to the IO completion port
- * for the next idle CPU to execute (this is done in
- * _PR_MD_WAKEUP_WAITER).
- * Threads with a suspended I/O operation remain bound to
- * the same cpu until I/O is cancelled
- *
- * NOTE: the boolean expression below must be the exact
- * opposite of the corresponding boolean expression in
- * _PR_MD_WAKEUP_WAITER.
- */
- if ((!_PR_IS_NATIVE_THREAD(me) && (cpu == me->cpu)) ||
- (thread->md.thr_bound_cpu)) {
- PR_ASSERT(!thread->md.thr_bound_cpu ||
- (thread->md.thr_bound_cpu == cpu));
- _PR_RUNQ_LOCK(cpu);
- _PR_ADD_RUNQ(thread, cpu, pri);
- _PR_RUNQ_UNLOCK(cpu);
- }
-#else
- _PR_RUNQ_LOCK(cpu);
- _PR_ADD_RUNQ(thread, cpu, pri);
- _PR_RUNQ_UNLOCK(cpu);
- if (!_PR_IS_NATIVE_THREAD(me) && (cpu == me->cpu)) {
- if (pri > me->priority) {
- _PR_SET_RESCHED_FLAG();
- }
- }
-#endif
-}
diff --git a/nspr/pr/src/threads/prcmon.c b/nspr/pr/src/threads/prcmon.c
deleted file mode 100644
index 2a196e9..0000000
--- a/nspr/pr/src/threads/prcmon.c
+++ /dev/null
@@ -1,431 +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/. */
-
-#include "primpl.h"
-
-#include <stdlib.h>
-#include <stddef.h>
-
-/* Lock used to lock the monitor cache */
-#ifdef _PR_NO_PREEMPT
-#define _PR_NEW_LOCK_MCACHE()
-#define _PR_DESTROY_LOCK_MCACHE()
-#define _PR_LOCK_MCACHE()
-#define _PR_UNLOCK_MCACHE()
-#else
-#ifdef _PR_LOCAL_THREADS_ONLY
-#define _PR_NEW_LOCK_MCACHE()
-#define _PR_DESTROY_LOCK_MCACHE()
-#define _PR_LOCK_MCACHE() { PRIntn _is; _PR_INTSOFF(_is)
-#define _PR_UNLOCK_MCACHE() _PR_INTSON(_is); }
-#else
-PRLock *_pr_mcacheLock;
-#define _PR_NEW_LOCK_MCACHE() (_pr_mcacheLock = PR_NewLock())
-#define _PR_DESTROY_LOCK_MCACHE() \
- PR_BEGIN_MACRO \
- if (_pr_mcacheLock) { \
- PR_DestroyLock(_pr_mcacheLock); \
- _pr_mcacheLock = NULL; \
- } \
- PR_END_MACRO
-#define _PR_LOCK_MCACHE() PR_Lock(_pr_mcacheLock)
-#define _PR_UNLOCK_MCACHE() PR_Unlock(_pr_mcacheLock)
-#endif
-#endif
-
-/************************************************************************/
-
-typedef struct MonitorCacheEntryStr MonitorCacheEntry;
-
-struct MonitorCacheEntryStr {
- MonitorCacheEntry* next;
- void* address;
- PRMonitor* mon;
- long cacheEntryCount;
-};
-
-/*
-** An array of MonitorCacheEntry's, plus a pointer to link these
-** arrays together.
-*/
-
-typedef struct MonitorCacheEntryBlockStr MonitorCacheEntryBlock;
-
-struct MonitorCacheEntryBlockStr {
- MonitorCacheEntryBlock* next;
- MonitorCacheEntry entries[1];
-};
-
-static PRUint32 hash_mask;
-static PRUintn num_hash_buckets;
-static PRUintn num_hash_buckets_log2;
-static MonitorCacheEntry **hash_buckets;
-static MonitorCacheEntry *free_entries;
-static PRUintn num_free_entries;
-static PRBool expanding;
-static MonitorCacheEntryBlock *mcache_blocks;
-
-static void (*OnMonitorRecycle)(void *address);
-
-#define HASH(address) \
- ((PRUint32) ( ((PRUptrdiff)(address) >> 2) ^ \
- ((PRUptrdiff)(address) >> 10) ) \
- & hash_mask)
-
-/*
-** Expand the monitor cache. This grows the hash buckets and allocates a
-** new chunk of cache entries and throws them on the free list. We keep
-** as many hash buckets as there are entries.
-**
-** Because we call malloc and malloc may need the monitor cache, we must
-** ensure that there are several free monitor cache entries available for
-** malloc to get. FREE_THRESHOLD is used to prevent monitor cache
-** starvation during monitor cache expansion.
-*/
-
-#define FREE_THRESHOLD 5
-
-static PRStatus ExpandMonitorCache(PRUintn new_size_log2)
-{
- MonitorCacheEntry **old_hash_buckets, *p;
- PRUintn i, entries, old_num_hash_buckets, added;
- MonitorCacheEntry **new_hash_buckets;
- MonitorCacheEntryBlock *new_block;
-
- entries = 1L << new_size_log2;
-
- /*
- ** Expand the monitor-cache-entry free list
- */
- new_block = (MonitorCacheEntryBlock*)
- PR_CALLOC(sizeof(MonitorCacheEntryBlock)
- + (entries - 1) * sizeof(MonitorCacheEntry));
- if (NULL == new_block) return PR_FAILURE;
-
- /*
- ** Allocate system monitors for the new monitor cache entries. If we
- ** run out of system monitors, break out of the loop.
- */
- for (i = 0, p = new_block->entries; i < entries; i++, p++) {
- p->mon = PR_NewMonitor();
- if (!p->mon)
- break;
- }
- added = i;
- if (added != entries) {
- MonitorCacheEntryBlock *realloc_block;
-
- if (added == 0) {
- /* Totally out of system monitors. Lossage abounds */
- PR_DELETE(new_block);
- return PR_FAILURE;
- }
-
- /*
- ** We were able to allocate some of the system monitors. Use
- ** realloc to shrink down the new_block memory. If that fails,
- ** carry on with the too-large new_block.
- */
- realloc_block = (MonitorCacheEntryBlock*)
- PR_REALLOC(new_block, sizeof(MonitorCacheEntryBlock)
- + (added - 1) * sizeof(MonitorCacheEntry));
- if (realloc_block)
- new_block = realloc_block;
- }
-
- /*
- ** Now that we have allocated all of the system monitors, build up
- ** the new free list. We can just update the free_list because we own
- ** the mcache-lock and we aren't calling anyone who might want to use
- ** it.
- */
- for (i = 0, p = new_block->entries; i < added - 1; i++, p++)
- p->next = p + 1;
- p->next = free_entries;
- free_entries = new_block->entries;
- num_free_entries += added;
- new_block->next = mcache_blocks;
- mcache_blocks = new_block;
-
- /* Try to expand the hash table */
- new_hash_buckets = (MonitorCacheEntry**)
- PR_CALLOC(entries * sizeof(MonitorCacheEntry*));
- if (NULL == new_hash_buckets) {
- /*
- ** Partial lossage. In this situation we don't get any more hash
- ** buckets, which just means that the table lookups will take
- ** longer. This is bad, but not fatal
- */
- PR_LOG(_pr_cmon_lm, PR_LOG_WARNING,
- ("unable to grow monitor cache hash buckets"));
- return PR_SUCCESS;
- }
-
- /*
- ** Compute new hash mask value. This value is used to mask an address
- ** until it's bits are in the right spot for indexing into the hash
- ** table.
- */
- hash_mask = entries - 1;
-
- /*
- ** Expand the hash table. We have to rehash everything in the old
- ** table into the new table.
- */
- old_hash_buckets = hash_buckets;
- old_num_hash_buckets = num_hash_buckets;
- for (i = 0; i < old_num_hash_buckets; i++) {
- p = old_hash_buckets[i];
- while (p) {
- MonitorCacheEntry *next = p->next;
-
- /* Hash based on new table size, and then put p in the new table */
- PRUintn hash = HASH(p->address);
- p->next = new_hash_buckets[hash];
- new_hash_buckets[hash] = p;
-
- p = next;
- }
- }
-
- /*
- ** Switch over to new hash table and THEN call free of the old
- ** table. Since free might re-enter _pr_mcache_lock, things would
- ** break terribly if it used the old hash table.
- */
- hash_buckets = new_hash_buckets;
- num_hash_buckets = entries;
- num_hash_buckets_log2 = new_size_log2;
- PR_DELETE(old_hash_buckets);
-
- PR_LOG(_pr_cmon_lm, PR_LOG_NOTICE,
- ("expanded monitor cache to %d (buckets %d)",
- num_free_entries, entries));
-
- return PR_SUCCESS;
-} /* ExpandMonitorCache */
-
-/*
-** Lookup a monitor cache entry by address. Return a pointer to the
-** pointer to the monitor cache entry on success, null on failure.
-*/
-static MonitorCacheEntry **LookupMonitorCacheEntry(void *address)
-{
- PRUintn hash;
- MonitorCacheEntry **pp, *p;
-
- hash = HASH(address);
- pp = hash_buckets + hash;
- while ((p = *pp) != 0) {
- if (p->address == address) {
- if (p->cacheEntryCount > 0)
- return pp;
- return NULL;
- }
- pp = &p->next;
- }
- return NULL;
-}
-
-/*
-** Try to create a new cached monitor. If it's already in the cache,
-** great - return it. Otherwise get a new free cache entry and set it
-** up. If the cache free space is getting low, expand the cache.
-*/
-static PRMonitor *CreateMonitor(void *address)
-{
- PRUintn hash;
- MonitorCacheEntry **pp, *p;
-
- hash = HASH(address);
- pp = hash_buckets + hash;
- while ((p = *pp) != 0) {
- if (p->address == address) goto gotit;
-
- pp = &p->next;
- }
-
- /* Expand the monitor cache if we have run out of free slots in the table */
- if (num_free_entries < FREE_THRESHOLD) {
- /* Expand monitor cache */
-
- /*
- ** This function is called with the lock held. So what's the 'expanding'
- ** boolean all about? Seems a bit redundant.
- */
- if (!expanding) {
- PRStatus rv;
-
- expanding = PR_TRUE;
- rv = ExpandMonitorCache(num_hash_buckets_log2 + 1);
- expanding = PR_FALSE;
- if (PR_FAILURE == rv) return NULL;
-
- /* redo the hash because it'll be different now */
- hash = HASH(address);
- } else {
- /*
- ** We are in process of expanding and we need a cache
- ** monitor. Make sure we have enough!
- */
- PR_ASSERT(num_free_entries > 0);
- }
- }
-
- /* Make a new monitor */
- p = free_entries;
- free_entries = p->next;
- num_free_entries--;
- if (OnMonitorRecycle && p->address)
- OnMonitorRecycle(p->address);
- p->address = address;
- p->next = hash_buckets[hash];
- hash_buckets[hash] = p;
- PR_ASSERT(p->cacheEntryCount == 0);
-
- gotit:
- p->cacheEntryCount++;
- return p->mon;
-}
-
-/*
-** Initialize the monitor cache
-*/
-void _PR_InitCMon(void)
-{
- _PR_NEW_LOCK_MCACHE();
- ExpandMonitorCache(3);
-}
-
-/*
-** Destroy the monitor cache
-*/
-void _PR_CleanupCMon(void)
-{
- _PR_DESTROY_LOCK_MCACHE();
-
- while (free_entries) {
- PR_DestroyMonitor(free_entries->mon);
- free_entries = free_entries->next;
- }
- num_free_entries = 0;
-
- while (mcache_blocks) {
- MonitorCacheEntryBlock *block;
-
- block = mcache_blocks;
- mcache_blocks = block->next;
- PR_DELETE(block);
- }
-
- PR_DELETE(hash_buckets);
- hash_mask = 0;
- num_hash_buckets = 0;
- num_hash_buckets_log2 = 0;
-
- expanding = PR_FALSE;
- OnMonitorRecycle = NULL;
-}
-
-/*
-** Create monitor for address. Don't enter the monitor while we have the
-** mcache locked because we might block!
-*/
-PR_IMPLEMENT(PRMonitor*) PR_CEnterMonitor(void *address)
-{
- PRMonitor *mon;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- _PR_LOCK_MCACHE();
- mon = CreateMonitor(address);
- _PR_UNLOCK_MCACHE();
-
- if (!mon) return NULL;
-
- PR_EnterMonitor(mon);
- return mon;
-}
-
-PR_IMPLEMENT(PRStatus) PR_CExitMonitor(void *address)
-{
- MonitorCacheEntry **pp, *p;
- PRStatus status = PR_SUCCESS;
-
- _PR_LOCK_MCACHE();
- pp = LookupMonitorCacheEntry(address);
- if (pp != NULL) {
- p = *pp;
- if (--p->cacheEntryCount == 0) {
- /*
- ** Nobody is using the system monitor. Put it on the cached free
- ** list. We are safe from somebody trying to use it because we
- ** have the mcache locked.
- */
- p->address = 0; /* defensive move */
- *pp = p->next; /* unlink from hash_buckets */
- p->next = free_entries; /* link into free list */
- free_entries = p;
- num_free_entries++; /* count it as free */
- }
- status = PR_ExitMonitor(p->mon);
- } else {
- status = PR_FAILURE;
- }
- _PR_UNLOCK_MCACHE();
-
- return status;
-}
-
-PR_IMPLEMENT(PRStatus) PR_CWait(void *address, PRIntervalTime ticks)
-{
- MonitorCacheEntry **pp;
- PRMonitor *mon;
-
- _PR_LOCK_MCACHE();
- pp = LookupMonitorCacheEntry(address);
- mon = pp ? ((*pp)->mon) : NULL;
- _PR_UNLOCK_MCACHE();
-
- if (mon == NULL)
- return PR_FAILURE;
- return PR_Wait(mon, ticks);
-}
-
-PR_IMPLEMENT(PRStatus) PR_CNotify(void *address)
-{
- MonitorCacheEntry **pp;
- PRMonitor *mon;
-
- _PR_LOCK_MCACHE();
- pp = LookupMonitorCacheEntry(address);
- mon = pp ? ((*pp)->mon) : NULL;
- _PR_UNLOCK_MCACHE();
-
- if (mon == NULL)
- return PR_FAILURE;
- return PR_Notify(mon);
-}
-
-PR_IMPLEMENT(PRStatus) PR_CNotifyAll(void *address)
-{
- MonitorCacheEntry **pp;
- PRMonitor *mon;
-
- _PR_LOCK_MCACHE();
- pp = LookupMonitorCacheEntry(address);
- mon = pp ? ((*pp)->mon) : NULL;
- _PR_UNLOCK_MCACHE();
-
- if (mon == NULL)
- return PR_FAILURE;
- return PR_NotifyAll(mon);
-}
-
-PR_IMPLEMENT(void)
-PR_CSetOnMonitorRecycle(void (*callback)(void *address))
-{
- OnMonitorRecycle = callback;
-}
diff --git a/nspr/pr/src/threads/prcthr.c b/nspr/pr/src/threads/prcthr.c
deleted file mode 100644
index 2688144..0000000
--- a/nspr/pr/src/threads/prcthr.c
+++ /dev/null
@@ -1,395 +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/. */
-
-#include "primpl.h"
-
-#if defined(WIN95)
-/*
-** Some local variables report warnings on Win95 because the code paths
-** using them are conditioned on HAVE_CUSTOME_USER_THREADS.
-** The pragma suppresses the warning.
-**
-*/
-#pragma warning(disable : 4101)
-#endif
-
-
-extern PRLock *_pr_sleeplock; /* allocated and initialized in prinit */
-/*
-** Routines common to both native and user threads.
-**
-**
-** Clean up a thread object, releasing all of the attached data. Do not
-** free the object itself (it may not have been malloc'd)
-*/
-void _PR_CleanupThread(PRThread *thread)
-{
- /* Free up per-thread-data */
- _PR_DestroyThreadPrivate(thread);
-
- /* Free any thread dump procs */
- if (thread->dumpArg) {
- PR_DELETE(thread->dumpArg);
- }
- thread->dump = 0;
-
- PR_DELETE(thread->name);
- PR_DELETE(thread->errorString);
- thread->errorStringSize = 0;
- thread->errorStringLength = 0;
- thread->environment = NULL;
-}
-
-PR_IMPLEMENT(PRStatus) PR_Yield()
-{
- static PRBool warning = PR_TRUE;
- if (warning) warning = _PR_Obsolete(
- "PR_Yield()", "PR_Sleep(PR_INTERVAL_NO_WAIT)");
- return (PR_Sleep(PR_INTERVAL_NO_WAIT));
-}
-
-/*
-** Make the current thread sleep until "timeout" ticks amount of time
-** has expired. If "timeout" is PR_INTERVAL_NO_WAIT then the call is
-** equivalent to a yield. Waiting for an infinite amount of time is
-** allowed in the expectation that another thread will interrupt().
-**
-** A single lock is used for all threads calling sleep. Each caller
-** does get its own condition variable since each is expected to have
-** a unique 'timeout'.
-*/
-PR_IMPLEMENT(PRStatus) PR_Sleep(PRIntervalTime timeout)
-{
- PRStatus rv = PR_SUCCESS;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (PR_INTERVAL_NO_WAIT == timeout)
- {
- /*
- ** This is a simple yield, nothing more, nothing less.
- */
- PRIntn is;
- PRThread *me = PR_GetCurrentThread();
- PRUintn pri = me->priority;
- _PRCPU *cpu = _PR_MD_CURRENT_CPU();
-
- if ( _PR_IS_NATIVE_THREAD(me) ) _PR_MD_YIELD();
- else
- {
- _PR_INTSOFF(is);
- _PR_RUNQ_LOCK(cpu);
- if (_PR_RUNQREADYMASK(cpu) >> pri) {
- me->cpu = cpu;
- me->state = _PR_RUNNABLE;
- _PR_ADD_RUNQ(me, cpu, pri);
- _PR_RUNQ_UNLOCK(cpu);
-
- PR_LOG(_pr_sched_lm, PR_LOG_MIN, ("PR_Yield: yielding"));
- _PR_MD_SWITCH_CONTEXT(me);
- PR_LOG(_pr_sched_lm, PR_LOG_MIN, ("PR_Yield: done"));
-
- _PR_FAST_INTSON(is);
- }
- else
- {
- _PR_RUNQ_UNLOCK(cpu);
- _PR_INTSON(is);
- }
- }
- }
- else
- {
- /*
- ** This is waiting for some finite period of time.
- ** A thread in this state is interruptible (PR_Interrupt()),
- ** but the lock and cvar used are local to the implementation
- ** and not visible to the caller, therefore not notifiable.
- */
- PRCondVar *cv;
- PRIntervalTime timein;
-
- timein = PR_IntervalNow();
- cv = PR_NewCondVar(_pr_sleeplock);
- PR_ASSERT(cv != NULL);
- PR_Lock(_pr_sleeplock);
- do
- {
- PRIntervalTime delta = PR_IntervalNow() - timein;
- if (delta > timeout) break;
- rv = PR_WaitCondVar(cv, timeout - delta);
- } while (rv == PR_SUCCESS);
- PR_Unlock(_pr_sleeplock);
- PR_DestroyCondVar(cv);
- }
- return rv;
-}
-
-PR_IMPLEMENT(PRUint32) PR_GetThreadID(PRThread *thread)
-{
- return thread->id;
-}
-
-PR_IMPLEMENT(PRThreadPriority) PR_GetThreadPriority(const PRThread *thread)
-{
- return (PRThreadPriority) thread->priority;
-}
-
-PR_IMPLEMENT(PRThread *) PR_GetCurrentThread()
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
- return _PR_MD_CURRENT_THREAD();
-}
-
-/*
-** Set the interrupt flag for a thread. The thread will be unable to
-** block in i/o functions when this happens. Also, any PR_Wait's in
-** progress will be undone. The interrupt remains in force until
-** PR_ClearInterrupt is called.
-*/
-PR_IMPLEMENT(PRStatus) PR_Interrupt(PRThread *thread)
-{
-#ifdef _PR_GLOBAL_THREADS_ONLY
- PRCondVar *victim;
-
- _PR_THREAD_LOCK(thread);
- thread->flags |= _PR_INTERRUPT;
- victim = thread->wait.cvar;
- _PR_THREAD_UNLOCK(thread);
- if ((NULL != victim) && (!(thread->flags & _PR_INTERRUPT_BLOCKED))) {
- int haveLock = (victim->lock->owner == _PR_MD_CURRENT_THREAD());
-
- if (!haveLock) PR_Lock(victim->lock);
- PR_NotifyAllCondVar(victim);
- if (!haveLock) PR_Unlock(victim->lock);
- }
- return PR_SUCCESS;
-#else /* ! _PR_GLOBAL_THREADS_ONLY */
- PRIntn is;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSOFF(is);
-
- _PR_THREAD_LOCK(thread);
- thread->flags |= _PR_INTERRUPT;
- switch (thread->state) {
- case _PR_COND_WAIT:
- /*
- * call is made with thread locked;
- * on return lock is released
- */
- if (!(thread->flags & _PR_INTERRUPT_BLOCKED))
- _PR_NotifyLockedThread(thread);
- break;
- case _PR_IO_WAIT:
- /*
- * Need to hold the thread lock when calling
- * _PR_Unblock_IO_Wait(). On return lock is
- * released.
- */
-#if defined(XP_UNIX) || defined(WINNT) || defined(WIN16)
- if (!(thread->flags & _PR_INTERRUPT_BLOCKED))
- _PR_Unblock_IO_Wait(thread);
-#else
- _PR_THREAD_UNLOCK(thread);
-#endif
- break;
- case _PR_RUNNING:
- case _PR_RUNNABLE:
- case _PR_LOCK_WAIT:
- default:
- _PR_THREAD_UNLOCK(thread);
- break;
- }
- if (!_PR_IS_NATIVE_THREAD(me))
- _PR_INTSON(is);
- return PR_SUCCESS;
-#endif /* _PR_GLOBAL_THREADS_ONLY */
-}
-
-/*
-** Clear the interrupt flag for self.
-*/
-PR_IMPLEMENT(void) PR_ClearInterrupt()
-{
- PRIntn is;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if ( !_PR_IS_NATIVE_THREAD(me)) _PR_INTSOFF(is);
- _PR_THREAD_LOCK(me);
- me->flags &= ~_PR_INTERRUPT;
- _PR_THREAD_UNLOCK(me);
- if ( !_PR_IS_NATIVE_THREAD(me)) _PR_INTSON(is);
-}
-
-PR_IMPLEMENT(void) PR_BlockInterrupt()
-{
- PRIntn is;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if ( !_PR_IS_NATIVE_THREAD(me)) _PR_INTSOFF(is);
- _PR_THREAD_LOCK(me);
- _PR_THREAD_BLOCK_INTERRUPT(me);
- _PR_THREAD_UNLOCK(me);
- if ( !_PR_IS_NATIVE_THREAD(me)) _PR_INTSON(is);
-} /* PR_BlockInterrupt */
-
-PR_IMPLEMENT(void) PR_UnblockInterrupt()
-{
- PRIntn is;
- PRThread *me = _PR_MD_CURRENT_THREAD();
-
- if ( !_PR_IS_NATIVE_THREAD(me)) _PR_INTSOFF(is);
- _PR_THREAD_LOCK(me);
- _PR_THREAD_UNBLOCK_INTERRUPT(me);
- _PR_THREAD_UNLOCK(me);
- if ( !_PR_IS_NATIVE_THREAD(me)) _PR_INTSON(is);
-} /* PR_UnblockInterrupt */
-
-/*
-** Return the thread stack pointer of the given thread.
-*/
-PR_IMPLEMENT(void *) PR_GetSP(PRThread *thread)
-{
- return (void *)_PR_MD_GET_SP(thread);
-}
-
-PR_IMPLEMENT(void*) GetExecutionEnvironment(PRThread *thread)
-{
- return thread->environment;
-}
-
-PR_IMPLEMENT(void) SetExecutionEnvironment(PRThread *thread, void *env)
-{
- thread->environment = env;
-}
-
-
-PR_IMPLEMENT(PRInt32) PR_GetThreadAffinityMask(PRThread *thread, PRUint32 *mask)
-{
-#ifdef HAVE_THREAD_AFFINITY
- return _PR_MD_GETTHREADAFFINITYMASK(thread, mask);
-#else
- return 0;
-#endif
-}
-
-PR_IMPLEMENT(PRInt32) PR_SetThreadAffinityMask(PRThread *thread, PRUint32 mask )
-{
-#ifdef HAVE_THREAD_AFFINITY
-#ifndef IRIX
- return _PR_MD_SETTHREADAFFINITYMASK(thread, mask);
-#else
- return 0;
-#endif
-#else
- return 0;
-#endif
-}
-
-/* This call is thread unsafe if another thread is calling SetConcurrency()
- */
-PR_IMPLEMENT(PRInt32) PR_SetCPUAffinityMask(PRUint32 mask)
-{
-#ifdef HAVE_THREAD_AFFINITY
- PRCList *qp;
- extern PRUint32 _pr_cpu_affinity_mask;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- _pr_cpu_affinity_mask = mask;
-
- qp = _PR_CPUQ().next;
- while(qp != &_PR_CPUQ()) {
- _PRCPU *cpu;
-
- cpu = _PR_CPU_PTR(qp);
- PR_SetThreadAffinityMask(cpu->thread, mask);
-
- qp = qp->next;
- }
-#endif
-
- return 0;
-}
-
-PRUint32 _pr_recycleThreads = 0;
-PR_IMPLEMENT(void) PR_SetThreadRecycleMode(PRUint32 count)
-{
- _pr_recycleThreads = count;
-}
-
-PR_IMPLEMENT(PRThread*) PR_CreateThreadGCAble(PRThreadType type,
- void (*start)(void *arg),
- void *arg,
- PRThreadPriority priority,
- PRThreadScope scope,
- PRThreadState state,
- PRUint32 stackSize)
-{
- return _PR_CreateThread(type, start, arg, priority, scope, state,
- stackSize, _PR_GCABLE_THREAD);
-}
-
-#ifdef SOLARIS
-PR_IMPLEMENT(PRThread*) PR_CreateThreadBound(PRThreadType type,
- void (*start)(void *arg),
- void *arg,
- PRUintn priority,
- PRThreadScope scope,
- PRThreadState state,
- PRUint32 stackSize)
-{
- return _PR_CreateThread(type, start, arg, priority, scope, state,
- stackSize, _PR_BOUND_THREAD);
-}
-#endif
-
-
-PR_IMPLEMENT(PRThread*) PR_AttachThreadGCAble(
- PRThreadType type, PRThreadPriority priority, PRThreadStack *stack)
-{
- /* $$$$ not sure how to finese this one */
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return NULL;
-}
-
-PR_IMPLEMENT(void) PR_SetThreadGCAble()
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
- PR_Lock(_pr_activeLock);
- _PR_MD_CURRENT_THREAD()->flags |= _PR_GCABLE_THREAD;
- PR_Unlock(_pr_activeLock);
-}
-
-PR_IMPLEMENT(void) PR_ClearThreadGCAble()
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
- PR_Lock(_pr_activeLock);
- _PR_MD_CURRENT_THREAD()->flags &= (~_PR_GCABLE_THREAD);
- PR_Unlock(_pr_activeLock);
-}
-
-PR_IMPLEMENT(PRThreadScope) PR_GetThreadScope(const PRThread *thread)
-{
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- if (_PR_IS_NATIVE_THREAD(thread)) {
- return (thread->flags & _PR_BOUND_THREAD) ? PR_GLOBAL_BOUND_THREAD :
- PR_GLOBAL_THREAD;
- } else
- return PR_LOCAL_THREAD;
-}
-
-PR_IMPLEMENT(PRThreadType) PR_GetThreadType(const PRThread *thread)
-{
- return (thread->flags & _PR_SYSTEM) ? PR_SYSTEM_THREAD : PR_USER_THREAD;
-}
-
-PR_IMPLEMENT(PRThreadState) PR_GetThreadState(const PRThread *thread)
-{
- return (NULL == thread->term) ? PR_UNJOINABLE_THREAD : PR_JOINABLE_THREAD;
-} /* PR_GetThreadState */
diff --git a/nspr/pr/src/threads/prdump.c b/nspr/pr/src/threads/prdump.c
deleted file mode 100644
index b40bee3..0000000
--- a/nspr/pr/src/threads/prdump.c
+++ /dev/null
@@ -1,121 +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/. */
-
-#include "primpl.h"
-
-#if defined(WIN95)
-/*
-** Some local variables report warnings on Win95 because the code paths
-** using them are conditioned on HAVE_CUSTOME_USER_THREADS.
-** The pragma suppresses the warning.
-**
-*/
-#pragma warning(disable : 4101)
-#endif
-
-/* XXX use unbuffered nspr stdio */
-
-PRFileDesc *_pr_dumpOut;
-
-PRUint32 _PR_DumpPrintf(PRFileDesc *fd, const char *fmt, ...)
-{
- char buf[100];
- PRUint32 nb;
- va_list ap;
-
- va_start(ap, fmt);
- nb = PR_vsnprintf(buf, sizeof(buf), fmt, ap);
- va_end(ap);
- PR_Write(fd, buf, nb);
-
- return nb;
-}
-
-void _PR_DumpThread(PRFileDesc *fd, PRThread *thread)
-{
-
-#ifndef _PR_GLOBAL_THREADS_ONLY
- _PR_DumpPrintf(fd, "%05d[%08p] pri=%2d flags=0x%02x",
- thread->id, thread, thread->priority, thread->flags);
- switch (thread->state) {
- case _PR_RUNNABLE:
- case _PR_RUNNING:
- break;
- case _PR_LOCK_WAIT:
- _PR_DumpPrintf(fd, " lock=%p", thread->wait.lock);
- break;
- case _PR_COND_WAIT:
- _PR_DumpPrintf(fd, " condvar=%p sleep=%lldms",
- thread->wait.cvar, thread->sleep);
- break;
- case _PR_SUSPENDED:
- _PR_DumpPrintf(fd, " suspended");
- break;
- }
- PR_Write(fd, "\n", 1);
-#endif
-
- /* Now call dump routine */
- if (thread->dump) {
- thread->dump(fd, thread, thread->dumpArg);
- }
-}
-
-static void DumpThreadQueue(PRFileDesc *fd, PRCList *list)
-{
-#ifndef _PR_GLOBAL_THREADS_ONLY
- PRCList *q;
-
- q = list->next;
- while (q != list) {
- PRThread *t = _PR_THREAD_PTR(q);
- _PR_DumpThread(fd, t);
- q = q->next;
- }
-#endif
-}
-
-void _PR_DumpThreads(PRFileDesc *fd)
-{
- PRThread *t;
- PRIntn i;
-
- _PR_DumpPrintf(fd, "Current Thread:\n");
- t = _PR_MD_CURRENT_THREAD();
- _PR_DumpThread(fd, t);
-
- _PR_DumpPrintf(fd, "Runnable Threads:\n");
- for (i = 0; i < PR_ARRAY_SIZE(_PR_RUNQ(t->cpu)); i++) {
- DumpThreadQueue(fd, &_PR_RUNQ(t->cpu)[i]);
- }
-
- _PR_DumpPrintf(fd, "CondVar timed wait Threads:\n");
- DumpThreadQueue(fd, &_PR_SLEEPQ(t->cpu));
-
- _PR_DumpPrintf(fd, "CondVar wait Threads:\n");
- DumpThreadQueue(fd, &_PR_PAUSEQ(t->cpu));
-
- _PR_DumpPrintf(fd, "Suspended Threads:\n");
- DumpThreadQueue(fd, &_PR_SUSPENDQ(t->cpu));
-}
-
-PR_IMPLEMENT(void) PR_ShowStatus(void)
-{
- PRIntn is;
-
- if ( _PR_MD_CURRENT_THREAD()
- && !_PR_IS_NATIVE_THREAD(_PR_MD_CURRENT_THREAD())) _PR_INTSOFF(is);
- _pr_dumpOut = _pr_stderr;
- _PR_DumpThreads(_pr_dumpOut);
- if ( _PR_MD_CURRENT_THREAD()
- && !_PR_IS_NATIVE_THREAD(_PR_MD_CURRENT_THREAD())) _PR_FAST_INTSON(is);
-}
-
-PR_IMPLEMENT(void)
-PR_SetThreadDumpProc(PRThread* thread, PRThreadDumpProc dump, void *arg)
-{
- thread->dump = dump;
- thread->dumpArg = arg;
-}
diff --git a/nspr/pr/src/threads/prmon.c b/nspr/pr/src/threads/prmon.c
deleted file mode 100644
index 36be8a9..0000000
--- a/nspr/pr/src/threads/prmon.c
+++ /dev/null
@@ -1,346 +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/. */
-
-#include "primpl.h"
-
-/************************************************************************/
-
-/*
- * Notifies just get posted to the monitor. The actual notification is done
- * when the monitor is fully exited so that MP systems don't contend for a
- * monitor that they can't enter.
- */
-static void _PR_PostNotifyToMonitor(PRMonitor *mon, PRBool broadcast)
-{
- PR_ASSERT(mon != NULL);
- PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mon);
-
- /* mon->notifyTimes is protected by the monitor, so we don't need to
- * acquire mon->lock.
- */
- if (broadcast)
- mon->notifyTimes = -1;
- else if (mon->notifyTimes != -1)
- mon->notifyTimes += 1;
-}
-
-static void _PR_PostNotifiesFromMonitor(PRCondVar *cv, PRIntn times)
-{
- PRStatus rv;
-
- /*
- * Time to actually notify any waits that were affected while the monitor
- * was entered.
- */
- PR_ASSERT(cv != NULL);
- PR_ASSERT(times != 0);
- if (times == -1) {
- rv = PR_NotifyAllCondVar(cv);
- PR_ASSERT(rv == PR_SUCCESS);
- } else {
- while (times-- > 0) {
- rv = PR_NotifyCondVar(cv);
- PR_ASSERT(rv == PR_SUCCESS);
- }
- }
-}
-
-/*
-** Create a new monitor.
-*/
-PR_IMPLEMENT(PRMonitor*) PR_NewMonitor()
-{
- PRMonitor *mon;
- PRStatus rv;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- mon = PR_NEWZAP(PRMonitor);
- if (mon == NULL) {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return NULL;
- }
-
- rv = _PR_InitLock(&mon->lock);
- PR_ASSERT(rv == PR_SUCCESS);
- if (rv != PR_SUCCESS)
- goto error1;
-
- mon->owner = NULL;
-
- rv = _PR_InitCondVar(&mon->entryCV, &mon->lock);
- PR_ASSERT(rv == PR_SUCCESS);
- if (rv != PR_SUCCESS)
- goto error2;
-
- rv = _PR_InitCondVar(&mon->waitCV, &mon->lock);
- PR_ASSERT(rv == PR_SUCCESS);
- if (rv != PR_SUCCESS)
- goto error3;
-
- mon->notifyTimes = 0;
- mon->entryCount = 0;
- mon->name = NULL;
- return mon;
-
-error3:
- _PR_FreeCondVar(&mon->entryCV);
-error2:
- _PR_FreeLock(&mon->lock);
-error1:
- PR_Free(mon);
- return NULL;
-}
-
-PR_IMPLEMENT(PRMonitor*) PR_NewNamedMonitor(const char* name)
-{
- PRMonitor* mon = PR_NewMonitor();
- if (mon)
- mon->name = name;
- return mon;
-}
-
-/*
-** Destroy a monitor. There must be no thread waiting on the monitor's
-** condition variable. The caller is responsible for guaranteeing that the
-** monitor is no longer in use.
-*/
-PR_IMPLEMENT(void) PR_DestroyMonitor(PRMonitor *mon)
-{
- PR_ASSERT(mon != NULL);
- _PR_FreeCondVar(&mon->waitCV);
- _PR_FreeCondVar(&mon->entryCV);
- _PR_FreeLock(&mon->lock);
-#if defined(DEBUG)
- memset(mon, 0xaf, sizeof(PRMonitor));
-#endif
- PR_Free(mon);
-}
-
-/*
-** Enter the lock associated with the monitor.
-*/
-PR_IMPLEMENT(void) PR_EnterMonitor(PRMonitor *mon)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRStatus rv;
-
- PR_ASSERT(mon != NULL);
- PR_Lock(&mon->lock);
- if (mon->entryCount != 0) {
- if (mon->owner == me)
- goto done;
- while (mon->entryCount != 0) {
- rv = PR_WaitCondVar(&mon->entryCV, PR_INTERVAL_NO_TIMEOUT);
- PR_ASSERT(rv == PR_SUCCESS);
- }
- }
- /* and now I have the monitor */
- PR_ASSERT(mon->notifyTimes == 0);
- PR_ASSERT(mon->owner == NULL);
- mon->owner = me;
-
-done:
- mon->entryCount += 1;
- rv = PR_Unlock(&mon->lock);
- PR_ASSERT(rv == PR_SUCCESS);
-}
-
-/*
-** Test and then enter the lock associated with the monitor if it's not
-** already entered by some other thread. Return PR_FALSE if some other
-** thread owned the lock at the time of the call.
-*/
-PR_IMPLEMENT(PRBool) PR_TestAndEnterMonitor(PRMonitor *mon)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRStatus rv;
-
- PR_ASSERT(mon != NULL);
- PR_Lock(&mon->lock);
- if (mon->entryCount != 0) {
- if (mon->owner == me)
- goto done;
- rv = PR_Unlock(&mon->lock);
- PR_ASSERT(rv == PR_SUCCESS);
- return PR_FALSE;
- }
- /* and now I have the monitor */
- PR_ASSERT(mon->notifyTimes == 0);
- PR_ASSERT(mon->owner == NULL);
- mon->owner = me;
-
-done:
- mon->entryCount += 1;
- rv = PR_Unlock(&mon->lock);
- PR_ASSERT(rv == PR_SUCCESS);
- return PR_TRUE;
-}
-
-/*
-** Exit the lock associated with the monitor once.
-*/
-PR_IMPLEMENT(PRStatus) PR_ExitMonitor(PRMonitor *mon)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRStatus rv;
-
- PR_ASSERT(mon != NULL);
- PR_Lock(&mon->lock);
- /* the entries should be > 0 and we'd better be the owner */
- PR_ASSERT(mon->entryCount > 0);
- PR_ASSERT(mon->owner == me);
- if (mon->entryCount == 0 || mon->owner != me)
- {
- rv = PR_Unlock(&mon->lock);
- PR_ASSERT(rv == PR_SUCCESS);
- return PR_FAILURE;
- }
-
- mon->entryCount -= 1; /* reduce by one */
- if (mon->entryCount == 0)
- {
- /* and if it transitioned to zero - notify an entry waiter */
- /* make the owner unknown */
- mon->owner = NULL;
- if (mon->notifyTimes != 0) {
- _PR_PostNotifiesFromMonitor(&mon->waitCV, mon->notifyTimes);
- mon->notifyTimes = 0;
- }
- rv = PR_NotifyCondVar(&mon->entryCV);
- PR_ASSERT(rv == PR_SUCCESS);
- }
- rv = PR_Unlock(&mon->lock);
- PR_ASSERT(rv == PR_SUCCESS);
- return PR_SUCCESS;
-}
-
-/*
-** Return the number of times that the current thread has entered the
-** lock. Returns zero if the current thread has not entered the lock.
-*/
-PR_IMPLEMENT(PRIntn) PR_GetMonitorEntryCount(PRMonitor *mon)
-{
- PRThread *me = _PR_MD_CURRENT_THREAD();
- PRStatus rv;
- PRIntn count = 0;
-
- PR_Lock(&mon->lock);
- if (mon->owner == me)
- count = mon->entryCount;
- rv = PR_Unlock(&mon->lock);
- PR_ASSERT(rv == PR_SUCCESS);
- return count;
-}
-
-PR_IMPLEMENT(void) PR_AssertCurrentThreadInMonitor(PRMonitor *mon)
-{
-#if defined(DEBUG) || defined(FORCE_PR_ASSERT)
- PRStatus rv;
-
- PR_Lock(&mon->lock);
- PR_ASSERT(mon->entryCount != 0 &&
- mon->owner == _PR_MD_CURRENT_THREAD());
- rv = PR_Unlock(&mon->lock);
- PR_ASSERT(rv == PR_SUCCESS);
-#endif
-}
-
-/*
-** Wait for a notify on the condition variable. Sleep for "ticks" amount
-** of time (if "tick" is 0 then the sleep is indefinite). While
-** the thread is waiting it exits the monitors lock (as if it called
-** PR_ExitMonitor as many times as it had called PR_EnterMonitor). When
-** the wait has finished the thread regains control of the monitors lock
-** with the same entry count as before the wait began.
-**
-** The thread waiting on the monitor will be resumed when the monitor is
-** notified (assuming the thread is the next in line to receive the
-** notify) or when the "ticks" elapses.
-**
-** Returns PR_FAILURE if the caller has not locked the lock associated
-** with the condition variable.
-** This routine can return PR_PENDING_INTERRUPT_ERROR if the waiting thread
-** has been interrupted.
-*/
-PR_IMPLEMENT(PRStatus) PR_Wait(PRMonitor *mon, PRIntervalTime ticks)
-{
- PRStatus rv;
- PRUint32 saved_entries;
- PRThread *saved_owner;
-
- PR_ASSERT(mon != NULL);
- PR_Lock(&mon->lock);
- /* the entries better be positive */
- PR_ASSERT(mon->entryCount > 0);
- /* and it better be owned by us */
- PR_ASSERT(mon->owner == _PR_MD_CURRENT_THREAD()); /* XXX return failure */
-
- /* tuck these away 'till later */
- saved_entries = mon->entryCount;
- mon->entryCount = 0;
- saved_owner = mon->owner;
- mon->owner = NULL;
- /* If we have pending notifies, post them now. */
- if (mon->notifyTimes != 0) {
- _PR_PostNotifiesFromMonitor(&mon->waitCV, mon->notifyTimes);
- mon->notifyTimes = 0;
- }
- rv = PR_NotifyCondVar(&mon->entryCV);
- PR_ASSERT(rv == PR_SUCCESS);
-
- rv = PR_WaitCondVar(&mon->waitCV, ticks);
- PR_ASSERT(rv == PR_SUCCESS);
-
- while (mon->entryCount != 0) {
- rv = PR_WaitCondVar(&mon->entryCV, PR_INTERVAL_NO_TIMEOUT);
- PR_ASSERT(rv == PR_SUCCESS);
- }
- PR_ASSERT(mon->notifyTimes == 0);
- /* reinstate the interesting information */
- mon->entryCount = saved_entries;
- mon->owner = saved_owner;
-
- rv = PR_Unlock(&mon->lock);
- PR_ASSERT(rv == PR_SUCCESS);
- return rv;
-}
-
-/*
-** Notify the highest priority thread waiting on the condition
-** variable. If a thread is waiting on the condition variable (using
-** PR_Wait) then it is awakened and begins waiting on the monitor's lock.
-*/
-PR_IMPLEMENT(PRStatus) PR_Notify(PRMonitor *mon)
-{
- _PR_PostNotifyToMonitor(mon, PR_FALSE);
- return PR_SUCCESS;
-}
-
-/*
-** Notify all of the threads waiting on the condition variable. All of
-** threads are notified in turn. The highest priority thread will
-** probably acquire the monitor first when the monitor is exited.
-*/
-PR_IMPLEMENT(PRStatus) PR_NotifyAll(PRMonitor *mon)
-{
- _PR_PostNotifyToMonitor(mon, PR_TRUE);
- return PR_SUCCESS;
-}
-
-/************************************************************************/
-
-PRUint32 _PR_MonitorToString(PRMonitor *mon, char *buf, PRUint32 buflen)
-{
- PRUint32 nb;
-
- if (mon->owner) {
- nb = PR_snprintf(buf, buflen, "[%p] owner=%d[%p] count=%ld",
- mon, mon->owner->id, mon->owner, mon->entryCount);
- } else {
- nb = PR_snprintf(buf, buflen, "[%p]", mon);
- }
- return nb;
-}
diff --git a/nspr/pr/src/threads/prrwlock.c b/nspr/pr/src/threads/prrwlock.c
deleted file mode 100644
index 2e0f9ea..0000000
--- a/nspr/pr/src/threads/prrwlock.c
+++ /dev/null
@@ -1,483 +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/. */
-
-#include "primpl.h"
-
-#include <string.h>
-
-#if defined(HPUX) && defined(_PR_PTHREADS) && !defined(_PR_DCETHREADS)
-
-#include <pthread.h>
-#define HAVE_UNIX98_RWLOCK
-#define RWLOCK_T pthread_rwlock_t
-#define RWLOCK_INIT(lock) pthread_rwlock_init(lock, NULL)
-#define RWLOCK_DESTROY(lock) pthread_rwlock_destroy(lock)
-#define RWLOCK_RDLOCK(lock) pthread_rwlock_rdlock(lock)
-#define RWLOCK_WRLOCK(lock) pthread_rwlock_wrlock(lock)
-#define RWLOCK_UNLOCK(lock) pthread_rwlock_unlock(lock)
-
-#elif defined(SOLARIS) && (defined(_PR_PTHREADS) \
- || defined(_PR_GLOBAL_THREADS_ONLY))
-
-#include <synch.h>
-#define HAVE_UI_RWLOCK
-#define RWLOCK_T rwlock_t
-#define RWLOCK_INIT(lock) rwlock_init(lock, USYNC_THREAD, NULL)
-#define RWLOCK_DESTROY(lock) rwlock_destroy(lock)
-#define RWLOCK_RDLOCK(lock) rw_rdlock(lock)
-#define RWLOCK_WRLOCK(lock) rw_wrlock(lock)
-#define RWLOCK_UNLOCK(lock) rw_unlock(lock)
-
-#endif
-
-/*
- * Reader-writer lock
- */
-struct PRRWLock {
- char *rw_name; /* lock name */
- PRUint32 rw_rank; /* rank of the lock */
-
-#if defined(HAVE_UNIX98_RWLOCK) || defined(HAVE_UI_RWLOCK)
- RWLOCK_T rw_lock;
-#else
- PRLock *rw_lock;
- PRInt32 rw_lock_cnt; /* == 0, if unlocked */
- /* == -1, if write-locked */
- /* > 0 , # of read locks */
- PRUint32 rw_reader_cnt; /* number of waiting readers */
- PRUint32 rw_writer_cnt; /* number of waiting writers */
- PRCondVar *rw_reader_waitq; /* cvar for readers */
- PRCondVar *rw_writer_waitq; /* cvar for writers */
-#ifdef DEBUG
- PRThread *rw_owner; /* lock owner for write-lock */
-#endif
-#endif
-};
-
-#ifdef DEBUG
-#define _PR_RWLOCK_RANK_ORDER_DEBUG /* enable deadlock detection using
- rank-order for locks
- */
-#endif
-
-#ifdef _PR_RWLOCK_RANK_ORDER_DEBUG
-
-static PRUintn pr_thread_rwlock_key; /* TPD key for lock stack */
-static PRUintn pr_thread_rwlock_alloc_failed;
-
-#define _PR_RWLOCK_RANK_ORDER_LIMIT 10
-
-typedef struct thread_rwlock_stack {
- PRInt32 trs_index; /* top of stack */
- PRRWLock *trs_stack[_PR_RWLOCK_RANK_ORDER_LIMIT]; /* stack of lock
- pointers */
-
-} thread_rwlock_stack;
-
-static void _PR_SET_THREAD_RWLOCK_RANK(PRRWLock *rwlock);
-static PRUint32 _PR_GET_THREAD_RWLOCK_RANK(void);
-static void _PR_UNSET_THREAD_RWLOCK_RANK(PRRWLock *rwlock);
-static void _PR_RELEASE_LOCK_STACK(void *lock_stack);
-
-#endif
-
-/*
- * Reader/Writer Locks
- */
-
-/*
- * PR_NewRWLock
- * Create a reader-writer lock, with the given lock rank and lock name
- *
- */
-
-PR_IMPLEMENT(PRRWLock *)
-PR_NewRWLock(PRUint32 lock_rank, const char *lock_name)
-{
- PRRWLock *rwlock;
-#if defined(HAVE_UNIX98_RWLOCK) || defined(HAVE_UI_RWLOCK)
- int err;
-#endif
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- rwlock = PR_NEWZAP(PRRWLock);
- if (rwlock == NULL)
- return NULL;
-
- rwlock->rw_rank = lock_rank;
- if (lock_name != NULL) {
- rwlock->rw_name = (char*) PR_Malloc(strlen(lock_name) + 1);
- if (rwlock->rw_name == NULL) {
- PR_DELETE(rwlock);
- return(NULL);
- }
- strcpy(rwlock->rw_name, lock_name);
- } else {
- rwlock->rw_name = NULL;
- }
-
-#if defined(HAVE_UNIX98_RWLOCK) || defined(HAVE_UI_RWLOCK)
- err = RWLOCK_INIT(&rwlock->rw_lock);
- if (err != 0) {
- PR_SetError(PR_UNKNOWN_ERROR, err);
- PR_Free(rwlock->rw_name);
- PR_DELETE(rwlock);
- return NULL;
- }
- return rwlock;
-#else
- rwlock->rw_lock = PR_NewLock();
- if (rwlock->rw_lock == NULL) {
- goto failed;
- }
- rwlock->rw_reader_waitq = PR_NewCondVar(rwlock->rw_lock);
- if (rwlock->rw_reader_waitq == NULL) {
- goto failed;
- }
- rwlock->rw_writer_waitq = PR_NewCondVar(rwlock->rw_lock);
- if (rwlock->rw_writer_waitq == NULL) {
- goto failed;
- }
- rwlock->rw_reader_cnt = 0;
- rwlock->rw_writer_cnt = 0;
- rwlock->rw_lock_cnt = 0;
- return rwlock;
-
-failed:
- if (rwlock->rw_reader_waitq != NULL) {
- PR_DestroyCondVar(rwlock->rw_reader_waitq);
- }
- if (rwlock->rw_lock != NULL) {
- PR_DestroyLock(rwlock->rw_lock);
- }
- PR_Free(rwlock->rw_name);
- PR_DELETE(rwlock);
- return NULL;
-#endif
-}
-
-/*
-** Destroy the given RWLock "lock".
-*/
-PR_IMPLEMENT(void)
-PR_DestroyRWLock(PRRWLock *rwlock)
-{
-#if defined(HAVE_UNIX98_RWLOCK) || defined(HAVE_UI_RWLOCK)
- int err;
- err = RWLOCK_DESTROY(&rwlock->rw_lock);
- PR_ASSERT(err == 0);
-#else
- PR_ASSERT(rwlock->rw_reader_cnt == 0);
- PR_DestroyCondVar(rwlock->rw_reader_waitq);
- PR_DestroyCondVar(rwlock->rw_writer_waitq);
- PR_DestroyLock(rwlock->rw_lock);
-#endif
- if (rwlock->rw_name != NULL)
- PR_Free(rwlock->rw_name);
- PR_DELETE(rwlock);
-}
-
-/*
-** Read-lock the RWLock.
-*/
-PR_IMPLEMENT(void)
-PR_RWLock_Rlock(PRRWLock *rwlock)
-{
-#if defined(HAVE_UNIX98_RWLOCK) || defined(HAVE_UI_RWLOCK)
-int err;
-#endif
-
-#ifdef _PR_RWLOCK_RANK_ORDER_DEBUG
- /*
- * assert that rank ordering is not violated; the rank of 'rwlock' should
- * be equal to or greater than the highest rank of all the locks held by
- * the thread.
- */
- PR_ASSERT((rwlock->rw_rank == PR_RWLOCK_RANK_NONE) ||
- (rwlock->rw_rank >= _PR_GET_THREAD_RWLOCK_RANK()));
-#endif
-
-#if defined(HAVE_UNIX98_RWLOCK) || defined(HAVE_UI_RWLOCK)
- err = RWLOCK_RDLOCK(&rwlock->rw_lock);
- PR_ASSERT(err == 0);
-#else
- PR_Lock(rwlock->rw_lock);
- /*
- * wait if write-locked or if a writer is waiting; preference for writers
- */
- while ((rwlock->rw_lock_cnt < 0) ||
- (rwlock->rw_writer_cnt > 0)) {
- rwlock->rw_reader_cnt++;
- PR_WaitCondVar(rwlock->rw_reader_waitq, PR_INTERVAL_NO_TIMEOUT);
- rwlock->rw_reader_cnt--;
- }
- /*
- * Increment read-lock count
- */
- rwlock->rw_lock_cnt++;
-
- PR_Unlock(rwlock->rw_lock);
-#endif
-
-#ifdef _PR_RWLOCK_RANK_ORDER_DEBUG
- /*
- * update thread's lock rank
- */
- if (rwlock->rw_rank != PR_RWLOCK_RANK_NONE)
- _PR_SET_THREAD_RWLOCK_RANK(rwlock);
-#endif
-}
-
-/*
-** Write-lock the RWLock.
-*/
-PR_IMPLEMENT(void)
-PR_RWLock_Wlock(PRRWLock *rwlock)
-{
-#if defined(DEBUG)
-PRThread *me = PR_GetCurrentThread();
-#endif
-#if defined(HAVE_UNIX98_RWLOCK) || defined(HAVE_UI_RWLOCK)
-int err;
-#endif
-
-#ifdef _PR_RWLOCK_RANK_ORDER_DEBUG
- /*
- * assert that rank ordering is not violated; the rank of 'rwlock' should
- * be equal to or greater than the highest rank of all the locks held by
- * the thread.
- */
- PR_ASSERT((rwlock->rw_rank == PR_RWLOCK_RANK_NONE) ||
- (rwlock->rw_rank >= _PR_GET_THREAD_RWLOCK_RANK()));
-#endif
-
-#if defined(HAVE_UNIX98_RWLOCK) || defined(HAVE_UI_RWLOCK)
- err = RWLOCK_WRLOCK(&rwlock->rw_lock);
- PR_ASSERT(err == 0);
-#else
- PR_Lock(rwlock->rw_lock);
- /*
- * wait if read locked
- */
- while (rwlock->rw_lock_cnt != 0) {
- rwlock->rw_writer_cnt++;
- PR_WaitCondVar(rwlock->rw_writer_waitq, PR_INTERVAL_NO_TIMEOUT);
- rwlock->rw_writer_cnt--;
- }
- /*
- * apply write lock
- */
- rwlock->rw_lock_cnt--;
- PR_ASSERT(rwlock->rw_lock_cnt == -1);
-#ifdef DEBUG
- PR_ASSERT(me != NULL);
- rwlock->rw_owner = me;
-#endif
- PR_Unlock(rwlock->rw_lock);
-#endif
-
-#ifdef _PR_RWLOCK_RANK_ORDER_DEBUG
- /*
- * update thread's lock rank
- */
- if (rwlock->rw_rank != PR_RWLOCK_RANK_NONE)
- _PR_SET_THREAD_RWLOCK_RANK(rwlock);
-#endif
-}
-
-/*
-** Unlock the RW lock.
-*/
-PR_IMPLEMENT(void)
-PR_RWLock_Unlock(PRRWLock *rwlock)
-{
-#if defined(DEBUG)
-PRThread *me = PR_GetCurrentThread();
-#endif
-#if defined(HAVE_UNIX98_RWLOCK) || defined(HAVE_UI_RWLOCK)
-int err;
-#endif
-
-#if defined(HAVE_UNIX98_RWLOCK) || defined(HAVE_UI_RWLOCK)
- err = RWLOCK_UNLOCK(&rwlock->rw_lock);
- PR_ASSERT(err == 0);
-#else
- PR_Lock(rwlock->rw_lock);
- /*
- * lock must be read or write-locked
- */
- PR_ASSERT(rwlock->rw_lock_cnt != 0);
- if (rwlock->rw_lock_cnt > 0) {
-
- /*
- * decrement read-lock count
- */
- rwlock->rw_lock_cnt--;
- if (rwlock->rw_lock_cnt == 0) {
- /*
- * lock is not read-locked anymore; wakeup a waiting writer
- */
- if (rwlock->rw_writer_cnt > 0)
- PR_NotifyCondVar(rwlock->rw_writer_waitq);
- }
- } else {
- PR_ASSERT(rwlock->rw_lock_cnt == -1);
-
- rwlock->rw_lock_cnt = 0;
-#ifdef DEBUG
- PR_ASSERT(rwlock->rw_owner == me);
- rwlock->rw_owner = NULL;
-#endif
- /*
- * wakeup a writer, if present; preference for writers
- */
- if (rwlock->rw_writer_cnt > 0)
- PR_NotifyCondVar(rwlock->rw_writer_waitq);
- /*
- * else, wakeup all readers, if any
- */
- else if (rwlock->rw_reader_cnt > 0)
- PR_NotifyAllCondVar(rwlock->rw_reader_waitq);
- }
- PR_Unlock(rwlock->rw_lock);
-#endif
-
-#ifdef _PR_RWLOCK_RANK_ORDER_DEBUG
- /*
- * update thread's lock rank
- */
- if (rwlock->rw_rank != PR_RWLOCK_RANK_NONE)
- _PR_UNSET_THREAD_RWLOCK_RANK(rwlock);
-#endif
- return;
-}
-
-#ifndef _PR_RWLOCK_RANK_ORDER_DEBUG
-
-void _PR_InitRWLocks(void) { }
-
-#else
-
-void _PR_InitRWLocks(void)
-{
- /*
- * allocated thread-private-data index for rwlock list
- */
- if (PR_NewThreadPrivateIndex(&pr_thread_rwlock_key,
- _PR_RELEASE_LOCK_STACK) == PR_FAILURE) {
- pr_thread_rwlock_alloc_failed = 1;
- return;
- }
-}
-
-/*
- * _PR_SET_THREAD_RWLOCK_RANK
- * Set a thread's lock rank, which is the highest of the ranks of all
- * the locks held by the thread. Pointers to the locks are added to a
- * per-thread list, which is anchored off a thread-private data key.
- */
-
-static void
-_PR_SET_THREAD_RWLOCK_RANK(PRRWLock *rwlock)
-{
-thread_rwlock_stack *lock_stack;
-PRStatus rv;
-
- /*
- * allocate a lock stack
- */
- if ((lock_stack = PR_GetThreadPrivate(pr_thread_rwlock_key)) == NULL) {
- lock_stack = (thread_rwlock_stack *)
- PR_CALLOC(1 * sizeof(thread_rwlock_stack));
- if (lock_stack) {
- rv = PR_SetThreadPrivate(pr_thread_rwlock_key, lock_stack);
- if (rv == PR_FAILURE) {
- PR_DELETE(lock_stack);
- pr_thread_rwlock_alloc_failed = 1;
- return;
- }
- } else {
- pr_thread_rwlock_alloc_failed = 1;
- return;
- }
- }
- /*
- * add rwlock to lock stack, if limit is not exceeded
- */
- if (lock_stack) {
- if (lock_stack->trs_index < _PR_RWLOCK_RANK_ORDER_LIMIT)
- lock_stack->trs_stack[lock_stack->trs_index++] = rwlock;
- }
-}
-
-static void
-_PR_RELEASE_LOCK_STACK(void *lock_stack)
-{
- PR_ASSERT(lock_stack);
- PR_DELETE(lock_stack);
-}
-
-/*
- * _PR_GET_THREAD_RWLOCK_RANK
- *
- * return thread's lock rank. If thread-private-data for the lock
- * stack is not allocated, return PR_RWLOCK_RANK_NONE.
- */
-
-static PRUint32
-_PR_GET_THREAD_RWLOCK_RANK(void)
-{
- thread_rwlock_stack *lock_stack;
-
- lock_stack = PR_GetThreadPrivate(pr_thread_rwlock_key);
- if (lock_stack == NULL || lock_stack->trs_index == 0)
- return (PR_RWLOCK_RANK_NONE);
- else
- return(lock_stack->trs_stack[lock_stack->trs_index - 1]->rw_rank);
-}
-
-/*
- * _PR_UNSET_THREAD_RWLOCK_RANK
- *
- * remove the rwlock from the lock stack. Since locks may not be
- * unlocked in a FIFO order, the entire lock stack is searched.
- */
-
-static void
-_PR_UNSET_THREAD_RWLOCK_RANK(PRRWLock *rwlock)
-{
- thread_rwlock_stack *lock_stack;
- int new_index = 0, index, done = 0;
-
- lock_stack = PR_GetThreadPrivate(pr_thread_rwlock_key);
-
- PR_ASSERT(lock_stack != NULL);
-
- for (index = lock_stack->trs_index - 1; index >= 0; index--) {
- if (!done && (lock_stack->trs_stack[index] == rwlock)) {
- /*
- * reset the slot for rwlock
- */
- lock_stack->trs_stack[index] = NULL;
- done = 1;
- }
- /*
- * search for the lowest-numbered empty slot, above which there are
- * no non-empty slots
- */
- if (!new_index && (lock_stack->trs_stack[index] != NULL))
- new_index = index + 1;
- if (done && new_index)
- break;
- }
- /*
- * set top of stack to highest numbered empty slot
- */
- lock_stack->trs_index = new_index;
-
-}
-
-#endif /* _PR_RWLOCK_RANK_ORDER_DEBUG */
diff --git a/nspr/pr/src/threads/prsem.c b/nspr/pr/src/threads/prsem.c
deleted file mode 100644
index f5f261f..0000000
--- a/nspr/pr/src/threads/prsem.c
+++ /dev/null
@@ -1,138 +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/. */
-
-#include "primpl.h"
-#include "obsolete/prsem.h"
-
-/************************************************************************/
-
-/*
-** Create a new semaphore.
-*/
-PR_IMPLEMENT(PRSemaphore*) PR_NewSem(PRUintn value)
-{
- PRSemaphore *sem;
- PRCondVar *cvar;
- PRLock *lock;
-
- sem = PR_NEWZAP(PRSemaphore);
- if (sem) {
-#ifdef HAVE_CVAR_BUILT_ON_SEM
- _PR_MD_NEW_SEM(&sem->md, value);
-#else
- lock = PR_NewLock();
- if (!lock) {
- PR_DELETE(sem);
- return NULL;
- }
-
- cvar = PR_NewCondVar(lock);
- if (!cvar) {
- PR_DestroyLock(lock);
- PR_DELETE(sem);
- return NULL;
- }
- sem->cvar = cvar;
- sem->count = value;
-#endif
- }
- return sem;
-}
-
-/*
-** Destroy a semaphore. There must be no thread waiting on the semaphore.
-** The caller is responsible for guaranteeing that the semaphore is
-** no longer in use.
-*/
-PR_IMPLEMENT(void) PR_DestroySem(PRSemaphore *sem)
-{
-#ifdef HAVE_CVAR_BUILT_ON_SEM
- _PR_MD_DESTROY_SEM(&sem->md);
-#else
- PR_ASSERT(sem->waiters == 0);
-
- PR_DestroyLock(sem->cvar->lock);
- PR_DestroyCondVar(sem->cvar);
-#endif
- PR_DELETE(sem);
-}
-
-/*
-** Wait on a Semaphore.
-**
-** This routine allows a calling thread to wait or proceed depending upon the
-** state of the semahore sem. The thread can proceed only if the counter value
-** of the semaphore sem is currently greater than 0. If the value of semaphore
-** sem is positive, it is decremented by one and the routine returns immediately
-** allowing the calling thread to continue. If the value of semaphore sem is 0,
-** the calling thread blocks awaiting the semaphore to be released by another
-** thread.
-**
-** This routine can return PR_PENDING_INTERRUPT if the waiting thread
-** has been interrupted.
-*/
-PR_IMPLEMENT(PRStatus) PR_WaitSem(PRSemaphore *sem)
-{
- PRStatus status = PR_SUCCESS;
-
-#ifdef HAVE_CVAR_BUILT_ON_SEM
- return _PR_MD_WAIT_SEM(&sem->md);
-#else
- PR_Lock(sem->cvar->lock);
- while (sem->count == 0) {
- sem->waiters++;
- status = PR_WaitCondVar(sem->cvar, PR_INTERVAL_NO_TIMEOUT);
- sem->waiters--;
- if (status != PR_SUCCESS)
- break;
- }
- if (status == PR_SUCCESS)
- sem->count--;
- PR_Unlock(sem->cvar->lock);
-#endif
-
- return (status);
-}
-
-/*
-** This routine increments the counter value of the semaphore. If other threads
-** are blocked for the semaphore, then the scheduler will determine which ONE
-** thread will be unblocked.
-*/
-PR_IMPLEMENT(void) PR_PostSem(PRSemaphore *sem)
-{
-#ifdef HAVE_CVAR_BUILT_ON_SEM
- _PR_MD_POST_SEM(&sem->md);
-#else
- PR_Lock(sem->cvar->lock);
- if (sem->waiters)
- PR_NotifyCondVar(sem->cvar);
- sem->count++;
- PR_Unlock(sem->cvar->lock);
-#endif
-}
-
-#if DEBUG
-/*
-** Returns the value of the semaphore referenced by sem without affecting
-** the state of the semaphore. The value represents the semaphore vaule
-** at the time of the call, but may not be the actual value when the
-** caller inspects it. (FOR DEBUGGING ONLY)
-*/
-PR_IMPLEMENT(PRUintn) PR_GetValueSem(PRSemaphore *sem)
-{
- PRUintn rv;
-
-#ifdef HAVE_CVAR_BUILT_ON_SEM
- rv = _PR_MD_GET_VALUE_SEM(&sem->md);
-#else
- PR_Lock(sem->cvar->lock);
- rv = sem->count;
- PR_Unlock(sem->cvar->lock);
-#endif
-
- return rv;
-}
-#endif
diff --git a/nspr/pr/src/threads/prtpd.c b/nspr/pr/src/threads/prtpd.c
deleted file mode 100644
index 0eb2a01..0000000
--- a/nspr/pr/src/threads/prtpd.c
+++ /dev/null
@@ -1,252 +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/. */
-
-/*
-** Thread Private Data
-**
-** There is an aribitrary limit on the number of keys that will be allocated
-** by the runtime. It's largish, so it is intended to be a sanity check, not
-** an impediment.
-**
-** There is a counter, initialized to zero and incremented every time a
-** client asks for a new key, that holds the high water mark for keys. All
-** threads logically have the same high water mark and are permitted to
-** ask for TPD up to that key value.
-**
-** The vector to hold the TPD are allocated when PR_SetThreadPrivate() is
-** called. The size of the vector will be some value greater than or equal
-** to the current high water mark. Each thread has its own TPD length and
-** vector.
-**
-** Threads that get private data for keys they have not set (or perhaps
-** don't even exist for that thread) get a NULL return. If the key is
-** beyond the high water mark, an error will be returned.
-*/
-
-/*
-** As of this time, BeOS has its own TPD implementation. Integrating
-** this standard one is a TODO for anyone with a bit of spare time on
-** their hand. For now, we just #ifdef out this whole file and use
-** the routines in pr/src/btthreads/
-*/
-
-#ifndef XP_BEOS
-
-#include "primpl.h"
-
-#include <string.h>
-
-#if defined(WIN95)
-/*
-** Some local variables report warnings on Win95 because the code paths
-** using them are conditioned on HAVE_CUSTOME_USER_THREADS.
-** The pragma suppresses the warning.
-**
-*/
-#pragma warning(disable : 4101)
-#endif
-
-#define _PR_TPD_LIMIT 128 /* arbitary limit on the TPD slots */
-static PRInt32 _pr_tpd_length = 0; /* current length of destructor vector */
-static PRInt32 _pr_tpd_highwater = 0; /* next TPD key to be assigned */
-static PRThreadPrivateDTOR *_pr_tpd_destructors = NULL;
- /* the destructors are associated with
- the keys, therefore asserting that
- the TPD key depicts the data's 'type' */
-
-/*
-** Initialize the thread private data manipulation
-*/
-void _PR_InitTPD(void)
-{
- _pr_tpd_destructors = (PRThreadPrivateDTOR*)
- PR_CALLOC(_PR_TPD_LIMIT * sizeof(PRThreadPrivateDTOR*));
- PR_ASSERT(NULL != _pr_tpd_destructors);
- _pr_tpd_length = _PR_TPD_LIMIT;
-}
-
-/*
-** Clean up the thread private data manipulation
-*/
-void _PR_CleanupTPD(void)
-{
-} /* _PR_CleanupTPD */
-
-/*
-** This routine returns a new index for per-thread-private data table.
-** The index is visible to all threads within a process. This index can
-** be used with the PR_SetThreadPrivate() and PR_GetThreadPrivate() routines
-** to save and retrieve data associated with the index for a thread.
-**
-** The index independently maintains specific values for each binding thread.
-** A thread can only get access to its own thread-specific-data.
-**
-** Upon a new index return the value associated with the index for all threads
-** is NULL, and upon thread creation the value associated with all indices for
-** that thread is NULL.
-**
-** "dtor" is the destructor function to invoke when the private
-** data is set or destroyed
-**
-** Returns PR_FAILURE if the total number of indices will exceed the maximun
-** allowed.
-*/
-
-PR_IMPLEMENT(PRStatus) PR_NewThreadPrivateIndex(
- PRUintn *newIndex, PRThreadPrivateDTOR dtor)
-{
- PRStatus rv;
- PRInt32 index;
-
- if (!_pr_initialized) _PR_ImplicitInitialization();
-
- PR_ASSERT(NULL != newIndex);
- PR_ASSERT(NULL != _pr_tpd_destructors);
-
- index = PR_ATOMIC_INCREMENT(&_pr_tpd_highwater) - 1; /* allocate index */
- if (_PR_TPD_LIMIT <= index)
- {
- PR_SetError(PR_TPD_RANGE_ERROR, 0);
- rv = PR_FAILURE; /* that's just wrong */
- }
- else
- {
- _pr_tpd_destructors[index] = dtor; /* record destructor @index */
- *newIndex = (PRUintn)index; /* copy into client's location */
- rv = PR_SUCCESS; /* that's okay */
- }
-
- return rv;
-}
-
-/*
-** Define some per-thread-private data.
-** "index" is an index into the per-thread private data table
-** "priv" is the per-thread-private data
-**
-** If the per-thread private data table has a previously registered
-** destructor function and a non-NULL per-thread-private data value,
-** the destructor function is invoked.
-**
-** This can return PR_FAILURE if index is invalid (ie., beyond the limit
-** on the TPD slots) or memory is insufficient to allocate an expanded
-** vector.
-*/
-
-PR_IMPLEMENT(PRStatus) PR_SetThreadPrivate(PRUintn index, void *priv)
-{
- PRThread *self = PR_GetCurrentThread();
-
- /*
- ** To improve performance, we don't check if the index has been
- ** allocated.
- */
- if (index >= _PR_TPD_LIMIT)
- {
- PR_SetError(PR_TPD_RANGE_ERROR, 0);
- return PR_FAILURE;
- }
-
- PR_ASSERT(((NULL == self->privateData) && (0 == self->tpdLength))
- || ((NULL != self->privateData) && (0 != self->tpdLength)));
-
- /*
- ** If this thread does not have a sufficient vector for the index
- ** being set, go ahead and extend this vector now.
- */
- if ((NULL == self->privateData) || (self->tpdLength <= index))
- {
- void *extension = PR_CALLOC(_pr_tpd_length * sizeof(void*));
- if (NULL == extension)
- {
- PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
- return PR_FAILURE;
- }
- if (self->privateData) {
- (void)memcpy(
- extension, self->privateData,
- self->tpdLength * sizeof(void*));
- PR_DELETE(self->privateData);
- }
- self->tpdLength = _pr_tpd_length;
- self->privateData = (void**)extension;
- }
- /*
- ** There wasn't much chance of having to call the destructor
- ** unless the slot already existed.
- */
- else if (self->privateData[index] && _pr_tpd_destructors[index])
- {
- void *data = self->privateData[index];
- self->privateData[index] = NULL;
- (*_pr_tpd_destructors[index])(data);
- }
-
- PR_ASSERT(index < self->tpdLength);
- self->privateData[index] = priv;
-
- return PR_SUCCESS;
-}
-
-/*
-** Recover the per-thread-private data for the current thread. "index" is
-** the index into the per-thread private data table.
-**
-** The returned value may be NULL which is indistinguishable from an error
-** condition.
-**
-*/
-
-PR_IMPLEMENT(void*) PR_GetThreadPrivate(PRUintn index)
-{
- PRThread *self = PR_GetCurrentThread();
- void *tpd = ((NULL == self->privateData) || (index >= self->tpdLength)) ?
- NULL : self->privateData[index];
-
- return tpd;
-}
-
-/*
-** Destroy the thread's private data, if any exists. This is called at
-** thread termination time only. There should be no threading issues
-** since this is being called by the thread itself.
-*/
-void _PR_DestroyThreadPrivate(PRThread* self)
-{
-#define _PR_TPD_DESTRUCTOR_ITERATIONS 4
-
- if (NULL != self->privateData) /* we have some */
- {
- PRBool clean;
- PRUint32 index;
- PRInt32 passes = _PR_TPD_DESTRUCTOR_ITERATIONS;
- PR_ASSERT(0 != self->tpdLength);
- do
- {
- clean = PR_TRUE;
- for (index = 0; index < self->tpdLength; ++index)
- {
- void *priv = self->privateData[index]; /* extract */
- if (NULL != priv) /* we have data at this index */
- {
- if (NULL != _pr_tpd_destructors[index])
- {
- self->privateData[index] = NULL; /* precondition */
- (*_pr_tpd_destructors[index])(priv); /* destroy */
- clean = PR_FALSE; /* unknown side effects */
- }
- }
- }
- } while ((--passes > 0) && !clean); /* limit # of passes */
- /*
- ** We give up after a fixed number of passes. Any non-NULL
- ** thread-private data value with a registered destructor
- ** function is not destroyed.
- */
- memset(self->privateData, 0, self->tpdLength * sizeof(void*));
- }
-} /* _PR_DestroyThreadPrivate */
-
-#endif /* !XP_BEOS */
diff --git a/nss.gyp b/nss.gyp
deleted file mode 100644
index 5cc8316..0000000
--- a/nss.gyp
+++ /dev/null
@@ -1,990 +0,0 @@
-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'target_defaults': {
- 'configurations': {
- 'Debug': {
- 'defines': [
- 'DEBUG',
- '_DEBUG',
- ],
- },
- 'Release': {
- 'defines': [
- 'NDEBUG',
- ],
- },
- },
- },
- 'conditions': [
- # To ensure no dependency on NSS is accidentally added to a BoringSSL port,
- # define the NSS and NSPR targets conditionally.
- ['use_openssl==0', {
- 'targets': [
- {
- 'target_name': 'nspr',
- 'product_name': 'crnspr',
- 'type': '<(component)',
- 'sources': [
- 'nspr/lib/ds/plarena.c',
- 'nspr/lib/ds/plarena.h',
- 'nspr/lib/ds/plarenas.h',
- 'nspr/lib/ds/plhash.c',
- 'nspr/lib/ds/plhash.h',
- 'nspr/lib/libc/include/plbase64.h',
- 'nspr/lib/libc/include/plerror.h',
- 'nspr/lib/libc/include/plgetopt.h',
- 'nspr/lib/libc/include/plstr.h',
- 'nspr/lib/libc/src/base64.c',
- 'nspr/lib/libc/src/plerror.c',
- 'nspr/lib/libc/src/plgetopt.c',
- 'nspr/lib/libc/src/strcase.c',
- 'nspr/lib/libc/src/strcat.c',
- 'nspr/lib/libc/src/strchr.c',
- 'nspr/lib/libc/src/strcmp.c',
- 'nspr/lib/libc/src/strcpy.c',
- 'nspr/lib/libc/src/strdup.c',
- 'nspr/lib/libc/src/strlen.c',
- 'nspr/lib/libc/src/strpbrk.c',
- 'nspr/lib/libc/src/strstr.c',
- 'nspr/lib/libc/src/strtok.c',
- 'nspr/pr/include/md/prosdep.h',
- 'nspr/pr/include/md/_darwin.cfg',
- 'nspr/pr/include/md/_darwin.h',
- 'nspr/pr/include/md/_pcos.h',
- 'nspr/pr/include/md/_pth.h',
- 'nspr/pr/include/md/_unixos.h',
- 'nspr/pr/include/md/_unix_errors.h',
- 'nspr/pr/include/md/_win32_errors.h',
- 'nspr/pr/include/md/_win95.cfg',
- 'nspr/pr/include/md/_win95.h',
- 'nspr/pr/include/nspr.h',
- 'nspr/pr/include/obsolete/pralarm.h',
- 'nspr/pr/include/obsolete/probslet.h',
- 'nspr/pr/include/obsolete/protypes.h',
- 'nspr/pr/include/obsolete/prsem.h',
- 'nspr/pr/include/pratom.h',
- 'nspr/pr/include/prbit.h',
- 'nspr/pr/include/prclist.h',
- 'nspr/pr/include/prcmon.h',
- 'nspr/pr/include/prcountr.h',
- 'nspr/pr/include/prcpucfg.h',
- 'nspr/pr/include/prcvar.h',
- 'nspr/pr/include/prdtoa.h',
- 'nspr/pr/include/prenv.h',
- 'nspr/pr/include/prerr.h',
- 'nspr/pr/include/prerror.h',
- 'nspr/pr/include/prinet.h',
- 'nspr/pr/include/prinit.h',
- 'nspr/pr/include/prinrval.h',
- 'nspr/pr/include/prio.h',
- 'nspr/pr/include/pripcsem.h',
- 'nspr/pr/include/private/pprio.h',
- 'nspr/pr/include/private/pprmwait.h',
- 'nspr/pr/include/private/pprthred.h',
- 'nspr/pr/include/private/primpl.h',
- 'nspr/pr/include/private/prpriv.h',
- 'nspr/pr/include/prlink.h',
- 'nspr/pr/include/prlock.h',
- 'nspr/pr/include/prlog.h',
- 'nspr/pr/include/prlong.h',
- 'nspr/pr/include/prmem.h',
- 'nspr/pr/include/prmon.h',
- 'nspr/pr/include/prmwait.h',
- 'nspr/pr/include/prnetdb.h',
- 'nspr/pr/include/prolock.h',
- 'nspr/pr/include/prpdce.h',
- 'nspr/pr/include/prprf.h',
- 'nspr/pr/include/prproces.h',
- 'nspr/pr/include/prrng.h',
- 'nspr/pr/include/prrwlock.h',
- 'nspr/pr/include/prshm.h',
- 'nspr/pr/include/prshma.h',
- 'nspr/pr/include/prsystem.h',
- 'nspr/pr/include/prthread.h',
- 'nspr/pr/include/prtime.h',
- 'nspr/pr/include/prtpool.h',
- 'nspr/pr/include/prtrace.h',
- 'nspr/pr/include/prtypes.h',
- 'nspr/pr/include/prvrsion.h',
- 'nspr/pr/include/prwin16.h',
- 'nspr/pr/src/io/prfdcach.c',
- 'nspr/pr/src/io/priometh.c',
- 'nspr/pr/src/io/pripv6.c',
- 'nspr/pr/src/io/prlayer.c',
- 'nspr/pr/src/io/prlog.c',
- 'nspr/pr/src/io/prmapopt.c',
- 'nspr/pr/src/io/prmmap.c',
- 'nspr/pr/src/io/prmwait.c',
- 'nspr/pr/src/io/prpolevt.c',
- 'nspr/pr/src/io/prprf.c',
- 'nspr/pr/src/io/prscanf.c',
- 'nspr/pr/src/io/prstdio.c',
- 'nspr/pr/src/linking/prlink.c',
- 'nspr/pr/src/malloc/prmalloc.c',
- 'nspr/pr/src/malloc/prmem.c',
- 'nspr/pr/src/md/prosdep.c',
- 'nspr/pr/src/md/unix/darwin.c',
- 'nspr/pr/src/md/unix/os_Darwin.s',
- 'nspr/pr/src/md/unix/os_Darwin_x86.s',
- 'nspr/pr/src/md/unix/os_Darwin_x86_64.s',
- 'nspr/pr/src/md/unix/unix.c',
- 'nspr/pr/src/md/unix/unix_errors.c',
- 'nspr/pr/src/md/unix/uxproces.c',
- 'nspr/pr/src/md/unix/uxrng.c',
- 'nspr/pr/src/md/unix/uxshm.c',
- 'nspr/pr/src/md/unix/uxwrap.c',
- 'nspr/pr/src/memory/prseg.c',
- 'nspr/pr/src/memory/prshm.c',
- 'nspr/pr/src/memory/prshma.c',
- 'nspr/pr/src/misc/pralarm.c',
- 'nspr/pr/src/misc/pratom.c',
- 'nspr/pr/src/misc/praton.c',
- 'nspr/pr/src/misc/prcountr.c',
- 'nspr/pr/src/misc/prdtoa.c',
- 'nspr/pr/src/misc/prenv.c',
- 'nspr/pr/src/misc/prerr.c',
- 'nspr/pr/src/misc/prerror.c',
- 'nspr/pr/src/misc/prerrortable.c',
- 'nspr/pr/src/misc/prinit.c',
- 'nspr/pr/src/misc/prinrval.c',
- 'nspr/pr/src/misc/pripc.c',
- 'nspr/pr/src/misc/prlog2.c',
- 'nspr/pr/src/misc/prlong.c',
- 'nspr/pr/src/misc/prnetdb.c',
- 'nspr/pr/src/misc/prolock.c',
- 'nspr/pr/src/misc/prrng.c',
- 'nspr/pr/src/misc/prsystem.c',
- 'nspr/pr/src/misc/prthinfo.c',
- 'nspr/pr/src/misc/prtime.c',
- 'nspr/pr/src/misc/prtpool.c',
- 'nspr/pr/src/misc/prtrace.c',
- 'nspr/pr/src/pthreads/ptio.c',
- 'nspr/pr/src/pthreads/ptmisc.c',
- 'nspr/pr/src/pthreads/ptsynch.c',
- 'nspr/pr/src/pthreads/ptthread.c',
- 'nspr/pr/src/threads/prcmon.c',
- 'nspr/pr/src/threads/prrwlock.c',
- 'nspr/pr/src/threads/prtpd.c',
- ],
- 'defines': [
- '_NSPR_BUILD_',
- 'FORCE_PR_LOG',
- ],
- 'include_dirs': [
- 'nspr/pr/include',
- 'nspr/pr/include/private',
- 'nspr/lib/ds',
- 'nspr/lib/libc/include',
- ],
- 'direct_dependent_settings': {
- 'defines': [
- 'NO_NSPR_10_SUPPORT',
- ],
- 'include_dirs': [
- 'nspr/pr/include',
- 'nspr/lib/ds',
- 'nspr/lib/libc/include',
- ],
- },
- 'variables': {
- 'clang_warning_flags': [
- # nspr passes "const char*" through "void*".
- '-Wno-incompatible-pointer-types',
- # nspr passes "int*" through "unsigned int*".
- '-Wno-pointer-sign',
- ],
- 'clang_warning_flags_unset': [
- # nspr uses assert(!"foo") instead of assert(false && "foo").
- '-Wstring-conversion',
- ],
- },
- 'conditions': [
- ['OS=="ios"', {
- 'defines': [
- 'XP_UNIX',
- 'DARWIN',
- 'XP_MACOSX',
- '_PR_PTHREADS',
- 'HAVE_BSD_FLOCK',
- 'HAVE_DLADDR',
- 'HAVE_LCHOWN',
- 'HAVE_SOCKLEN_T',
- 'HAVE_STRERROR',
- ],
- 'sources!': [
- # os_Darwin_x86.s and os_Darwin_x86_64.s are included by
- # os_Darwin.s.
- 'nspr/pr/src/md/unix/os_Darwin_x86.s',
- 'nspr/pr/src/md/unix/os_Darwin_x86_64.s',
- ],
- }],
- ['component == "static_library"', {
- 'defines': [
- 'NSPR_STATIC',
- ],
- 'direct_dependent_settings': {
- 'defines': [
- 'NSPR_STATIC',
- ],
- },
- }],
- ['clang==1', {
- 'xcode_settings': {
- 'WARNING_CFLAGS': [
- # nspr uses a bunch of deprecated functions (NSLinkModule etc) in
- # prlink.c on mac.
- '-Wno-deprecated-declarations',
- ],
- },
- }],
- ],
- },
- {
- 'target_name': 'nss',
- 'product_name': 'crnss',
- 'type': '<(component)',
- 'dependencies': [
- 'nss_static',
- 'nssckbi',
- ],
- 'export_dependent_settings': [
- 'nss_static',
- 'nssckbi',
- ],
- 'sources': [
- # Ensure at least one object file is produced, so that MSVC does not
- # warn when creating the static/shared library. See the note for
- # the 'nssckbi' target for why the 'nss' target was split as such.
- 'nss/lib/nss/nssver.c',
- ],
- },
- {
- # This is really more of a pseudo-target to work around the fact that
- # a single static_library target cannot contain two object files of the
- # same name (hash.o / hash.obj). Logically, this is part of the
- # 'nss_static' target. By separating it out, it creates a possible
- # circular dependency between 'nss_static' and 'nssckbi' when
- # 'exclude_nss_root_certs' is not specified, as 'nss_static' depends on
- # the 'builtinsC_GetFunctionList' exported by this target. This is an
- # artifact of how NSS is being statically built, which is not an
- # officially supported configuration - normally, 'nssckbi.dll/so' would
- # depend on libnss3.dll/so, and the higher layer caller would instruct
- # libnss3.dll to dynamically load nssckbi.dll, breaking the circle.
- #
- # TODO(rsleevi): http://crbug.com/128134 - Break the circular dependency
- # without requiring nssckbi to be built as a shared library.
- 'target_name': 'nssckbi',
- 'product_name': 'crnssckbi',
- 'type': 'static_library',
- # This target is an implementation detail - the public dependencies
- # should be on 'nss'.
- 'suppress_wildcard': 1,
- 'sources': [
- 'nss/lib/ckfw/builtins/anchor.c',
- 'nss/lib/ckfw/builtins/bfind.c',
- 'nss/lib/ckfw/builtins/binst.c',
- 'nss/lib/ckfw/builtins/bobject.c',
- 'nss/lib/ckfw/builtins/bsession.c',
- 'nss/lib/ckfw/builtins/bslot.c',
- 'nss/lib/ckfw/builtins/btoken.c',
- 'nss/lib/ckfw/builtins/builtins.h',
- 'nss/lib/ckfw/builtins/certdata.c',
- 'nss/lib/ckfw/builtins/ckbiver.c',
- 'nss/lib/ckfw/builtins/constants.c',
- 'nss/lib/ckfw/builtins/nssckbi.h',
- 'nss/lib/ckfw/ck.h',
- 'nss/lib/ckfw/ckfw.h',
- 'nss/lib/ckfw/ckfwm.h',
- 'nss/lib/ckfw/ckfwtm.h',
- 'nss/lib/ckfw/ckmd.h',
- 'nss/lib/ckfw/ckt.h',
- 'nss/lib/ckfw/crypto.c',
- 'nss/lib/ckfw/find.c',
- 'nss/lib/ckfw/hash.c',
- 'nss/lib/ckfw/instance.c',
- 'nss/lib/ckfw/mechanism.c',
- 'nss/lib/ckfw/mutex.c',
- 'nss/lib/ckfw/nssck.api',
- 'nss/lib/ckfw/nssckepv.h',
- 'nss/lib/ckfw/nssckft.h',
- 'nss/lib/ckfw/nssckfw.h',
- 'nss/lib/ckfw/nssckfwc.h',
- 'nss/lib/ckfw/nssckfwt.h',
- 'nss/lib/ckfw/nssckg.h',
- 'nss/lib/ckfw/nssckmdt.h',
- 'nss/lib/ckfw/nssckt.h',
- 'nss/lib/ckfw/object.c',
- 'nss/lib/ckfw/session.c',
- 'nss/lib/ckfw/sessobj.c',
- 'nss/lib/ckfw/slot.c',
- 'nss/lib/ckfw/token.c',
- 'nss/lib/ckfw/wrap.c',
- ],
- 'dependencies': [
- 'nss_static',
- ],
- 'export_dependent_settings': [
- 'nss_static',
- ],
- 'include_dirs': [
- 'nss/lib/ckfw',
- ],
- 'direct_dependent_settings': {
- 'include_dirs': [
- 'nss/lib/ckfw/builtins',
- ],
- },
- },
- {
- 'target_name': 'nss_static',
- 'type': 'static_library',
- # This target is an implementation detail - the public dependencies
- # should be on 'nss'.
- 'suppress_wildcard': 1,
- 'sources': [
- 'nss/lib/base/arena.c',
- 'nss/lib/base/base.h',
- 'nss/lib/base/baset.h',
- 'nss/lib/base/error.c',
- 'nss/lib/base/errorval.c',
- 'nss/lib/base/hash.c',
- 'nss/lib/base/hashops.c',
- 'nss/lib/base/item.c',
- 'nss/lib/base/libc.c',
- 'nss/lib/base/list.c',
- 'nss/lib/base/nssbase.h',
- 'nss/lib/base/nssbaset.h',
- 'nss/lib/base/nssutf8.c',
- 'nss/lib/base/tracker.c',
- 'nss/lib/certdb/alg1485.c',
- 'nss/lib/certdb/cert.h',
- 'nss/lib/certdb/certdb.c',
- 'nss/lib/certdb/certdb.h',
- 'nss/lib/certdb/certi.h',
- 'nss/lib/certdb/certt.h',
- 'nss/lib/certdb/certv3.c',
- 'nss/lib/certdb/certxutl.c',
- 'nss/lib/certdb/certxutl.h',
- 'nss/lib/certdb/crl.c',
- 'nss/lib/certdb/genname.c',
- 'nss/lib/certdb/genname.h',
- 'nss/lib/certdb/polcyxtn.c',
- 'nss/lib/certdb/secname.c',
- 'nss/lib/certdb/stanpcertdb.c',
- 'nss/lib/certdb/xauthkid.c',
- 'nss/lib/certdb/xbsconst.c',
- 'nss/lib/certdb/xconst.c',
- 'nss/lib/certdb/xconst.h',
- 'nss/lib/certhigh/certhigh.c',
- 'nss/lib/certhigh/certhtml.c',
- 'nss/lib/certhigh/certreq.c',
- 'nss/lib/certhigh/certvfy.c',
- 'nss/lib/certhigh/certvfypkix.c',
- 'nss/lib/certhigh/crlv2.c',
- 'nss/lib/certhigh/ocsp.c',
- 'nss/lib/certhigh/ocsp.h',
- 'nss/lib/certhigh/ocspi.h',
- 'nss/lib/certhigh/ocspsig.c',
- 'nss/lib/certhigh/ocspt.h',
- 'nss/lib/certhigh/ocspti.h',
- 'nss/lib/certhigh/xcrldist.c',
- 'nss/lib/cryptohi/cryptohi.h',
- 'nss/lib/cryptohi/cryptoht.h',
- 'nss/lib/cryptohi/dsautil.c',
- 'nss/lib/cryptohi/key.h',
- 'nss/lib/cryptohi/keyhi.h',
- 'nss/lib/cryptohi/keyi.h',
- 'nss/lib/cryptohi/keyt.h',
- 'nss/lib/cryptohi/keythi.h',
- 'nss/lib/cryptohi/sechash.c',
- 'nss/lib/cryptohi/sechash.h',
- 'nss/lib/cryptohi/seckey.c',
- 'nss/lib/cryptohi/secsign.c',
- 'nss/lib/cryptohi/secvfy.c',
- 'nss/lib/dev/ckhelper.c',
- 'nss/lib/dev/ckhelper.h',
- 'nss/lib/dev/dev.h',
- 'nss/lib/dev/devm.h',
- 'nss/lib/dev/devslot.c',
- 'nss/lib/dev/devt.h',
- 'nss/lib/dev/devtm.h',
- 'nss/lib/dev/devtoken.c',
- 'nss/lib/dev/devutil.c',
- 'nss/lib/dev/nssdev.h',
- 'nss/lib/dev/nssdevt.h',
- 'nss/lib/freebl/aeskeywrap.c',
- 'nss/lib/freebl/alg2268.c',
- 'nss/lib/freebl/alghmac.c',
- 'nss/lib/freebl/alghmac.h',
- 'nss/lib/freebl/arcfive.c',
- 'nss/lib/freebl/arcfour.c',
- 'nss/lib/freebl/blapi.h',
- 'nss/lib/freebl/blapii.h',
- 'nss/lib/freebl/blapit.h',
- 'nss/lib/freebl/camellia.c',
- 'nss/lib/freebl/camellia.h',
- 'nss/lib/freebl/chacha20.c',
- 'nss/lib/freebl/chacha20.h',
- 'nss/lib/freebl/chacha20_vec.c',
- 'nss/lib/freebl/chacha20poly1305.c',
- 'nss/lib/freebl/chacha20poly1305.h',
- 'nss/lib/freebl/ctr.c',
- 'nss/lib/freebl/ctr.h',
- 'nss/lib/freebl/cts.c',
- 'nss/lib/freebl/cts.h',
- 'nss/lib/freebl/des.c',
- 'nss/lib/freebl/des.h',
- 'nss/lib/freebl/desblapi.c',
- 'nss/lib/freebl/dh.c',
- 'nss/lib/freebl/drbg.c',
- 'nss/lib/freebl/dsa.c',
- 'nss/lib/freebl/ec.c',
- 'nss/lib/freebl/ec.h',
- 'nss/lib/freebl/ecdecode.c',
- 'nss/lib/freebl/ecl/ec2.h',
- 'nss/lib/freebl/ecl/ecl-curve.h',
- 'nss/lib/freebl/ecl/ecl-exp.h',
- 'nss/lib/freebl/ecl/ecl-priv.h',
- 'nss/lib/freebl/ecl/ecl.c',
- 'nss/lib/freebl/ecl/ecl.h',
- 'nss/lib/freebl/ecl/ecl_curve.c',
- 'nss/lib/freebl/ecl/ecl_gf.c',
- 'nss/lib/freebl/ecl/ecl_mult.c',
- 'nss/lib/freebl/ecl/ecp.h',
- 'nss/lib/freebl/ecl/ecp_256.c',
- 'nss/lib/freebl/ecl/ecp_256_32.c',
- 'nss/lib/freebl/ecl/ecp_384.c',
- 'nss/lib/freebl/ecl/ecp_521.c',
- 'nss/lib/freebl/ecl/ecp_aff.c',
- 'nss/lib/freebl/ecl/ecp_jac.c',
- 'nss/lib/freebl/ecl/ecp_jm.c',
- 'nss/lib/freebl/ecl/ecp_mont.c',
- 'nss/lib/freebl/ecl/ec_naf.c',
- 'nss/lib/freebl/gcm.c',
- 'nss/lib/freebl/gcm.h',
- 'nss/lib/freebl/intel-aes.h',
- 'nss/lib/freebl/hmacct.c',
- 'nss/lib/freebl/hmacct.h',
- 'nss/lib/freebl/jpake.c',
- 'nss/lib/freebl/md2.c',
- 'nss/lib/freebl/md5.c',
- 'nss/lib/freebl/mpi/logtab.h',
- 'nss/lib/freebl/mpi/mpcpucache.c',
- 'nss/lib/freebl/mpi/mpi-config.h',
- 'nss/lib/freebl/mpi/mpi-priv.h',
- 'nss/lib/freebl/mpi/mpi.c',
- 'nss/lib/freebl/mpi/mpi.h',
- 'nss/lib/freebl/mpi/mpi_arm.c',
- 'nss/lib/freebl/mpi/mpi_arm_mac.c',
- 'nss/lib/freebl/mpi/mplogic.c',
- 'nss/lib/freebl/mpi/mplogic.h',
- 'nss/lib/freebl/mpi/mpmontg.c',
- 'nss/lib/freebl/mpi/mpprime.c',
- 'nss/lib/freebl/mpi/mpprime.h',
- 'nss/lib/freebl/mpi/mp_gf2m-priv.h',
- 'nss/lib/freebl/mpi/mp_gf2m.c',
- 'nss/lib/freebl/mpi/mp_gf2m.h',
- 'nss/lib/freebl/mpi/primes.c',
- 'nss/lib/freebl/nss_build_config_mac.h',
- 'nss/lib/freebl/poly1305-donna-x64-sse2-incremental-source.c',
- 'nss/lib/freebl/poly1305.c',
- 'nss/lib/freebl/poly1305.h',
- 'nss/lib/freebl/pqg.c',
- 'nss/lib/freebl/pqg.h',
- 'nss/lib/freebl/rawhash.c',
- 'nss/lib/freebl/rijndael.c',
- 'nss/lib/freebl/rijndael.h',
- 'nss/lib/freebl/rijndael32.tab',
- 'nss/lib/freebl/rsa.c',
- 'nss/lib/freebl/rsapkcs.c',
- 'nss/lib/freebl/secmpi.h',
- 'nss/lib/freebl/secrng.h',
- 'nss/lib/freebl/seed.c',
- 'nss/lib/freebl/seed.h',
- 'nss/lib/freebl/sha256.h',
- 'nss/lib/freebl/sha512.c',
- 'nss/lib/freebl/sha_fast.c',
- 'nss/lib/freebl/sha_fast.h',
- 'nss/lib/freebl/shsign.h',
- 'nss/lib/freebl/shvfy.c',
- 'nss/lib/freebl/sysrand.c',
- 'nss/lib/freebl/tlsprfalg.c',
- 'nss/lib/freebl/unix_rand.c',
- 'nss/lib/freebl/win_rand.c',
- 'nss/lib/libpkix/include/pkix.h',
- 'nss/lib/libpkix/include/pkix_certsel.h',
- 'nss/lib/libpkix/include/pkix_certstore.h',
- 'nss/lib/libpkix/include/pkix_checker.h',
- 'nss/lib/libpkix/include/pkix_crlsel.h',
- 'nss/lib/libpkix/include/pkix_errorstrings.h',
- 'nss/lib/libpkix/include/pkix_params.h',
- 'nss/lib/libpkix/include/pkix_pl_pki.h',
- 'nss/lib/libpkix/include/pkix_pl_system.h',
- 'nss/lib/libpkix/include/pkix_results.h',
- 'nss/lib/libpkix/include/pkix_revchecker.h',
- 'nss/lib/libpkix/include/pkix_sample_modules.h',
- 'nss/lib/libpkix/include/pkix_util.h',
- 'nss/lib/libpkix/include/pkixt.h',
- 'nss/lib/libpkix/pkix/certsel/pkix_certselector.c',
- 'nss/lib/libpkix/pkix/certsel/pkix_certselector.h',
- 'nss/lib/libpkix/pkix/certsel/pkix_comcertselparams.c',
- 'nss/lib/libpkix/pkix/certsel/pkix_comcertselparams.h',
- 'nss/lib/libpkix/pkix/checker/pkix_basicconstraintschecker.c',
- 'nss/lib/libpkix/pkix/checker/pkix_basicconstraintschecker.h',
- 'nss/lib/libpkix/pkix/checker/pkix_certchainchecker.c',
- 'nss/lib/libpkix/pkix/checker/pkix_certchainchecker.h',
- 'nss/lib/libpkix/pkix/checker/pkix_crlchecker.c',
- 'nss/lib/libpkix/pkix/checker/pkix_crlchecker.h',
- 'nss/lib/libpkix/pkix/checker/pkix_ekuchecker.c',
- 'nss/lib/libpkix/pkix/checker/pkix_ekuchecker.h',
- 'nss/lib/libpkix/pkix/checker/pkix_expirationchecker.c',
- 'nss/lib/libpkix/pkix/checker/pkix_expirationchecker.h',
- 'nss/lib/libpkix/pkix/checker/pkix_namechainingchecker.c',
- 'nss/lib/libpkix/pkix/checker/pkix_namechainingchecker.h',
- 'nss/lib/libpkix/pkix/checker/pkix_nameconstraintschecker.c',
- 'nss/lib/libpkix/pkix/checker/pkix_nameconstraintschecker.h',
- 'nss/lib/libpkix/pkix/checker/pkix_ocspchecker.c',
- 'nss/lib/libpkix/pkix/checker/pkix_ocspchecker.h',
- 'nss/lib/libpkix/pkix/checker/pkix_policychecker.c',
- 'nss/lib/libpkix/pkix/checker/pkix_policychecker.h',
- 'nss/lib/libpkix/pkix/checker/pkix_revocationchecker.c',
- 'nss/lib/libpkix/pkix/checker/pkix_revocationchecker.h',
- 'nss/lib/libpkix/pkix/checker/pkix_revocationmethod.c',
- 'nss/lib/libpkix/pkix/checker/pkix_revocationmethod.h',
- 'nss/lib/libpkix/pkix/checker/pkix_signaturechecker.c',
- 'nss/lib/libpkix/pkix/checker/pkix_signaturechecker.h',
- 'nss/lib/libpkix/pkix/checker/pkix_targetcertchecker.c',
- 'nss/lib/libpkix/pkix/checker/pkix_targetcertchecker.h',
- 'nss/lib/libpkix/pkix/crlsel/pkix_comcrlselparams.c',
- 'nss/lib/libpkix/pkix/crlsel/pkix_comcrlselparams.h',
- 'nss/lib/libpkix/pkix/crlsel/pkix_crlselector.c',
- 'nss/lib/libpkix/pkix/crlsel/pkix_crlselector.h',
- 'nss/lib/libpkix/pkix/params/pkix_procparams.c',
- 'nss/lib/libpkix/pkix/params/pkix_procparams.h',
- 'nss/lib/libpkix/pkix/params/pkix_resourcelimits.c',
- 'nss/lib/libpkix/pkix/params/pkix_resourcelimits.h',
- 'nss/lib/libpkix/pkix/params/pkix_trustanchor.c',
- 'nss/lib/libpkix/pkix/params/pkix_trustanchor.h',
- 'nss/lib/libpkix/pkix/params/pkix_valparams.c',
- 'nss/lib/libpkix/pkix/params/pkix_valparams.h',
- 'nss/lib/libpkix/pkix/results/pkix_buildresult.c',
- 'nss/lib/libpkix/pkix/results/pkix_buildresult.h',
- 'nss/lib/libpkix/pkix/results/pkix_policynode.c',
- 'nss/lib/libpkix/pkix/results/pkix_policynode.h',
- 'nss/lib/libpkix/pkix/results/pkix_valresult.c',
- 'nss/lib/libpkix/pkix/results/pkix_valresult.h',
- 'nss/lib/libpkix/pkix/results/pkix_verifynode.c',
- 'nss/lib/libpkix/pkix/results/pkix_verifynode.h',
- 'nss/lib/libpkix/pkix/store/pkix_store.c',
- 'nss/lib/libpkix/pkix/store/pkix_store.h',
- 'nss/lib/libpkix/pkix/top/pkix_build.c',
- 'nss/lib/libpkix/pkix/top/pkix_build.h',
- 'nss/lib/libpkix/pkix/top/pkix_lifecycle.c',
- 'nss/lib/libpkix/pkix/top/pkix_lifecycle.h',
- 'nss/lib/libpkix/pkix/top/pkix_validate.c',
- 'nss/lib/libpkix/pkix/top/pkix_validate.h',
- 'nss/lib/libpkix/pkix/util/pkix_error.c',
- 'nss/lib/libpkix/pkix/util/pkix_error.h',
- 'nss/lib/libpkix/pkix/util/pkix_errpaths.c',
- 'nss/lib/libpkix/pkix/util/pkix_list.c',
- 'nss/lib/libpkix/pkix/util/pkix_list.h',
- 'nss/lib/libpkix/pkix/util/pkix_logger.c',
- 'nss/lib/libpkix/pkix/util/pkix_logger.h',
- 'nss/lib/libpkix/pkix/util/pkix_tools.c',
- 'nss/lib/libpkix/pkix/util/pkix_tools.h',
- 'nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_aiamgr.c',
- 'nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_aiamgr.h',
- 'nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_colcertstore.c',
- 'nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_colcertstore.h',
- 'nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpcertstore.c',
- 'nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpcertstore.h',
- 'nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpdefaultclient.c',
- 'nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpdefaultclient.h',
- 'nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_nsscontext.c',
- 'nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_nsscontext.h',
- 'nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_pk11certstore.c',
- 'nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_pk11certstore.h',
- 'nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_socket.c',
- 'nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_socket.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_basicconstraints.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_basicconstraints.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_cert.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_cert.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_certpolicyinfo.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_certpolicyinfo.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_certpolicymap.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_certpolicymap.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_certpolicyqualifier.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_certpolicyqualifier.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crl.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crl.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crldp.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crldp.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crlentry.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crlentry.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_date.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_date.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_generalname.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_generalname.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_infoaccess.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_infoaccess.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_nameconstraints.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_nameconstraints.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocspcertid.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocspcertid.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocsprequest.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocsprequest.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocspresponse.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocspresponse.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_publickey.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_publickey.h',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_x500name.c',
- 'nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_x500name.h',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_bigint.c',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_bigint.h',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_bytearray.c',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_bytearray.h',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_common.c',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_common.h',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_error.c',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_hashtable.c',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_hashtable.h',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_lifecycle.c',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_lifecycle.h',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_mem.c',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_mem.h',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_monitorlock.c',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_monitorlock.h',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_mutex.c',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_mutex.h',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_object.c',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_object.h',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_oid.c',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_oid.h',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_primhash.c',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_primhash.h',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_rwlock.c',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_rwlock.h',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_string.c',
- 'nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_string.h',
- 'nss/lib/nss/nss.h',
- 'nss/lib/nss/nssinit.c',
- 'nss/lib/nss/nssoptions.c',
- 'nss/lib/nss/nssoptions.h',
- 'nss/lib/nss/nssrenam.h',
- 'nss/lib/nss/utilwrap.c',
- 'nss/lib/pk11wrap/debug_module.c',
- 'nss/lib/pk11wrap/dev3hack.c',
- 'nss/lib/pk11wrap/dev3hack.h',
- 'nss/lib/pk11wrap/pk11akey.c',
- 'nss/lib/pk11wrap/pk11auth.c',
- 'nss/lib/pk11wrap/pk11cert.c',
- 'nss/lib/pk11wrap/pk11cxt.c',
- 'nss/lib/pk11wrap/pk11err.c',
- 'nss/lib/pk11wrap/pk11func.h',
- 'nss/lib/pk11wrap/pk11kea.c',
- 'nss/lib/pk11wrap/pk11list.c',
- 'nss/lib/pk11wrap/pk11load.c',
- 'nss/lib/pk11wrap/pk11mech.c',
- 'nss/lib/pk11wrap/pk11merge.c',
- 'nss/lib/pk11wrap/pk11nobj.c',
- 'nss/lib/pk11wrap/pk11obj.c',
- 'nss/lib/pk11wrap/pk11pars.c',
- 'nss/lib/pk11wrap/pk11pbe.c',
- 'nss/lib/pk11wrap/pk11pk12.c',
- 'nss/lib/pk11wrap/pk11pqg.c',
- 'nss/lib/pk11wrap/pk11pqg.h',
- 'nss/lib/pk11wrap/pk11priv.h',
- 'nss/lib/pk11wrap/pk11pub.h',
- 'nss/lib/pk11wrap/pk11sdr.c',
- 'nss/lib/pk11wrap/pk11sdr.h',
- 'nss/lib/pk11wrap/pk11skey.c',
- 'nss/lib/pk11wrap/pk11slot.c',
- 'nss/lib/pk11wrap/pk11util.c',
- 'nss/lib/pk11wrap/secmod.h',
- 'nss/lib/pk11wrap/secmodi.h',
- 'nss/lib/pk11wrap/secmodt.h',
- 'nss/lib/pk11wrap/secmodti.h',
- 'nss/lib/pk11wrap/secpkcs5.h',
- 'nss/lib/pkcs7/certread.c',
- 'nss/lib/pkcs7/p7common.c',
- 'nss/lib/pkcs7/p7create.c',
- 'nss/lib/pkcs7/p7decode.c',
- 'nss/lib/pkcs7/p7encode.c',
- 'nss/lib/pkcs7/p7local.c',
- 'nss/lib/pkcs7/p7local.h',
- 'nss/lib/pkcs7/pkcs7t.h',
- 'nss/lib/pkcs7/secmime.c',
- 'nss/lib/pkcs7/secmime.h',
- 'nss/lib/pkcs7/secpkcs7.h',
- 'nss/lib/pki/asymmkey.c',
- 'nss/lib/pki/certdecode.c',
- 'nss/lib/pki/certificate.c',
- 'nss/lib/pki/cryptocontext.c',
- 'nss/lib/pki/nsspki.h',
- 'nss/lib/pki/nsspkit.h',
- 'nss/lib/pki/pki.h',
- 'nss/lib/pki/pki3hack.c',
- 'nss/lib/pki/pki3hack.h',
- 'nss/lib/pki/pkibase.c',
- 'nss/lib/pki/pkim.h',
- 'nss/lib/pki/pkistore.c',
- 'nss/lib/pki/pkistore.h',
- 'nss/lib/pki/pkit.h',
- 'nss/lib/pki/pkitm.h',
- 'nss/lib/pki/symmkey.c',
- 'nss/lib/pki/tdcache.c',
- 'nss/lib/pki/trustdomain.c',
- 'nss/lib/smime/cms.h',
- 'nss/lib/smime/cmslocal.h',
- 'nss/lib/smime/cmsreclist.h',
- 'nss/lib/smime/cmst.h',
- 'nss/lib/smime/smime.h',
- 'nss/lib/softoken/fipsaudt.c',
- 'nss/lib/softoken/fipstest.c',
- 'nss/lib/softoken/fipstokn.c',
- 'nss/lib/softoken/jpakesftk.c',
- 'nss/lib/softoken/lgglue.c',
- 'nss/lib/softoken/lgglue.h',
- 'nss/lib/softoken/lowkey.c',
- 'nss/lib/softoken/lowkeyi.h',
- 'nss/lib/softoken/lowkeyti.h',
- 'nss/lib/softoken/lowpbe.c',
- 'nss/lib/softoken/lowpbe.h',
- 'nss/lib/softoken/padbuf.c',
- 'nss/lib/softoken/pkcs11.c',
- 'nss/lib/softoken/pkcs11c.c',
- 'nss/lib/softoken/pkcs11i.h',
- 'nss/lib/softoken/pkcs11ni.h',
- 'nss/lib/softoken/pkcs11u.c',
- 'nss/lib/softoken/sdb.c',
- 'nss/lib/softoken/sdb.h',
- 'nss/lib/softoken/sftkdb.c',
- 'nss/lib/softoken/sftkdb.h',
- 'nss/lib/softoken/sftkdbt.h',
- 'nss/lib/softoken/sftkdbti.h',
- 'nss/lib/softoken/sftkhmac.c',
- 'nss/lib/softoken/sftkpars.c',
- 'nss/lib/softoken/sftkpars.h',
- 'nss/lib/softoken/sftkpwd.c',
- 'nss/lib/softoken/softkver.c',
- 'nss/lib/softoken/softkver.h',
- 'nss/lib/softoken/softoken.h',
- 'nss/lib/softoken/softoknt.h',
- 'nss/lib/softoken/tlsprf.c',
- 'nss/lib/ssl/sslerr.h',
- 'nss/lib/util/SECerrs.h',
- 'nss/lib/util/base64.h',
- 'nss/lib/util/ciferfam.h',
- 'nss/lib/util/derdec.c',
- 'nss/lib/util/derenc.c',
- 'nss/lib/util/dersubr.c',
- 'nss/lib/util/dertime.c',
- 'nss/lib/util/errstrs.c',
- 'nss/lib/util/hasht.h',
- 'nss/lib/util/nssb64.h',
- 'nss/lib/util/nssb64d.c',
- 'nss/lib/util/nssb64e.c',
- 'nss/lib/util/nssb64t.h',
- 'nss/lib/util/nssilckt.h',
- 'nss/lib/util/nssilock.c',
- 'nss/lib/util/nssilock.h',
- 'nss/lib/util/nsslocks.h',
- 'nss/lib/util/nssrwlk.c',
- 'nss/lib/util/nssrwlk.h',
- 'nss/lib/util/nssrwlkt.h',
- 'nss/lib/util/nssutil.h',
- 'nss/lib/util/oidstring.c',
- 'nss/lib/util/pkcs11.h',
- 'nss/lib/util/pkcs11f.h',
- 'nss/lib/util/pkcs11n.h',
- 'nss/lib/util/pkcs11p.h',
- 'nss/lib/util/pkcs11t.h',
- 'nss/lib/util/pkcs11u.h',
- 'nss/lib/util/pkcs1sig.c',
- 'nss/lib/util/pkcs1sig.h',
- 'nss/lib/util/portreg.c',
- 'nss/lib/util/portreg.h',
- 'nss/lib/util/quickder.c',
- 'nss/lib/util/secalgid.c',
- 'nss/lib/util/secasn1.h',
- 'nss/lib/util/secasn1d.c',
- 'nss/lib/util/secasn1e.c',
- 'nss/lib/util/secasn1t.h',
- 'nss/lib/util/secasn1u.c',
- 'nss/lib/util/seccomon.h',
- 'nss/lib/util/secder.h',
- 'nss/lib/util/secdert.h',
- 'nss/lib/util/secdig.c',
- 'nss/lib/util/secdig.h',
- 'nss/lib/util/secdigt.h',
- 'nss/lib/util/secerr.h',
- 'nss/lib/util/secitem.c',
- 'nss/lib/util/secitem.h',
- 'nss/lib/util/secoid.c',
- 'nss/lib/util/secoid.h',
- 'nss/lib/util/secoidt.h',
- 'nss/lib/util/secport.c',
- 'nss/lib/util/secport.h',
- 'nss/lib/util/sectime.c',
- 'nss/lib/util/templates.c',
- 'nss/lib/util/utf8.c',
- 'nss/lib/util/utilmod.c',
- 'nss/lib/util/utilmodt.h',
- 'nss/lib/util/utilpars.c',
- 'nss/lib/util/utilpars.h',
- 'nss/lib/util/utilparst.h',
- 'nss/lib/util/utilrename.h',
- 'nss/lib/util/verref.h',
- ],
- 'sources!': [
- # mpi_arm.c is included by mpi_arm_mac.c.
- # NOTE: mpi_arm.c can be used directly on Linux. mpi_arm.c will need
- # to be excluded conditionally if we start to build NSS on Linux.
- 'nss/lib/freebl/mpi/mpi_arm.c',
- # primes.c is included by mpprime.c.
- 'nss/lib/freebl/mpi/primes.c',
- # unix_rand.c and win_rand.c are included by sysrand.c.
- 'nss/lib/freebl/unix_rand.c',
- 'nss/lib/freebl/win_rand.c',
- # debug_module.c is included by pk11load.c.
- 'nss/lib/pk11wrap/debug_module.c',
- ],
- 'dependencies': [
- 'nspr',
- '../sqlite/sqlite.gyp:sqlite',
- ],
- 'export_dependent_settings': [
- 'nspr',
- ],
- 'defines': [
- 'MP_API_COMPATIBLE',
- 'NSS_DISABLE_DBM',
- 'NSS_STATIC',
- 'NSS_USE_STATIC_LIBS',
- 'RIJNDAEL_INCLUDE_TABLES',
- 'SHLIB_VERSION=\"3\"',
- 'SOFTOKEN_SHLIB_VERSION=\"3\"',
- 'USE_UTIL_DIRECTLY',
- 'NSS_PKIX_NO_LDAP',
- ],
- 'include_dirs': [
- 'nss/lib/base',
- 'nss/lib/certdb',
- 'nss/lib/certhigh',
- 'nss/lib/cryptohi',
- 'nss/lib/dev',
- 'nss/lib/freebl',
- 'nss/lib/freebl/ecl',
- 'nss/lib/freebl/mpi',
- 'nss/lib/libpkix/include',
- 'nss/lib/libpkix/pkix/certsel',
- 'nss/lib/libpkix/pkix/checker',
- 'nss/lib/libpkix/pkix/crlsel',
- 'nss/lib/libpkix/pkix/params',
- 'nss/lib/libpkix/pkix/results',
- 'nss/lib/libpkix/pkix/store',
- 'nss/lib/libpkix/pkix/top',
- 'nss/lib/libpkix/pkix/util',
- 'nss/lib/libpkix/pkix_pl_nss/module',
- 'nss/lib/libpkix/pkix_pl_nss/pki',
- 'nss/lib/libpkix/pkix_pl_nss/system',
- 'nss/lib/nss',
- 'nss/lib/pk11wrap',
- 'nss/lib/pkcs7',
- 'nss/lib/pki',
- 'nss/lib/smime',
- 'nss/lib/softoken',
- 'nss/lib/ssl',
- 'nss/lib/util',
- ],
- 'direct_dependent_settings': {
- 'defines': [
- 'NSS_STATIC',
- 'NSS_USE_STATIC_LIBS',
- 'USE_UTIL_DIRECTLY',
- ],
- 'include_dirs': [
- 'nspr/pr/include',
- 'nspr/lib/ds',
- 'nspr/lib/libc/include',
- 'nss/lib/base',
- 'nss/lib/certdb',
- 'nss/lib/certhigh',
- 'nss/lib/cryptohi',
- 'nss/lib/dev',
- 'nss/lib/freebl',
- 'nss/lib/freebl/ecl',
- 'nss/lib/nss',
- 'nss/lib/pk11wrap',
- 'nss/lib/pkcs7',
- 'nss/lib/pki',
- 'nss/lib/smime',
- 'nss/lib/softoken',
- 'nss/lib/util',
- ],
- },
- 'variables': {
- 'clang_warning_flags': [
- # nss doesn't explicitly cast between different enum types.
- '-Wno-conversion',
- # nss passes "const char*" through "void*".
- '-Wno-incompatible-pointer-types',
- # nss prefers `a && b || c` over `(a && b) || c`.
- '-Wno-logical-op-parentheses',
- # nss doesn't use exhaustive switches on enums
- '-Wno-switch',
- # nss has some `unsigned < 0` checks.
- '-Wno-tautological-compare',
- # nss-urandom-abort.patch removed the only call to
- # rng_systemFromNoise
- '-Wno-unused-function',
- ],
- },
- 'conditions': [
- ['target_arch=="x64" and OS!="win"', {
- 'sources!': [
- 'nss/lib/freebl/chacha20.c',
- 'nss/lib/freebl/poly1305.c',
- ],
- }, { # else: target_arch!="x64" or OS=="win"
- 'sources!': [
- 'nss/lib/freebl/chacha20_vec.c',
- 'nss/lib/freebl/poly1305-donna-x64-sse2-incremental-source.c',
- ],
- }],
- ['OS=="ios"', {
- 'defines': [
- 'XP_UNIX',
- 'DARWIN',
- 'HAVE_STRERROR',
- 'HAVE_BSD_FLOCK',
- 'SHLIB_SUFFIX=\"dylib\"',
- 'SHLIB_PREFIX=\"lib\"',
- 'SOFTOKEN_LIB_NAME=\"libsoftokn3.dylib\"',
- ],
- 'variables': {
- 'forced_include_file': 'nss_build_config_mac.h',
- },
- 'xcode_settings': {
- 'conditions': [
- ['component == "shared_library"', {
- 'GCC_SYMBOLS_PRIVATE_EXTERN': 'NO', # no -fvisibility=hidden
- }],
- ],
- # Define processor architecture specific macros in
- # <(forced_include_file).
- 'OTHER_CFLAGS': [
- '-include', '<(forced_include_file)',
- ],
- },
- }],
- ],
- },
- ],
- }],
- ],
-}
diff --git a/nss/COPYING b/nss/COPYING
deleted file mode 100644
index 212af5b..0000000
--- a/nss/COPYING
+++ /dev/null
@@ -1,403 +0,0 @@
-NSS is available under the Mozilla Public License, version 2, a copy of which
-is below.
-
-Note on GPL Compatibility
--------------------------
-
-The MPL 2, section 3.3, permits you to combine NSS with code under the GNU
-General Public License (GPL) version 2, or any later version of that
-license, to make a Larger Work, and distribute the result under the GPL.
-The only condition is that you must also make NSS, and any changes you
-have made to it, available to recipients under the terms of the MPL 2 also.
-
-Anyone who receives the combined code from you does not have to continue
-to dual licence in this way, and may, if they wish, distribute under the
-terms of either of the two licences - either the MPL alone or the GPL
-alone. However, we discourage people from distributing copies of NSS under
-the GPL alone, because it means that any improvements they make cannot be
-reincorporated into the main version of NSS. There is never a need to do
-this for license compatibility reasons.
-
-Note on LGPL Compatibility
---------------------------
-
-The above also applies to combining MPLed code in a single library with
-code under the GNU Lesser General Public License (LGPL) version 2.1, or
-any later version of that license. If the LGPLed code and the MPLed code
-are not in the same library, then the copyleft coverage of the two
-licences does not overlap, so no issues arise.
-
-
-Mozilla Public License Version 2.0
-==================================
-
-1. Definitions
---------------
-
-1.1. "Contributor"
- means each individual or legal entity that creates, contributes to
- the creation of, or owns Covered Software.
-
-1.2. "Contributor Version"
- means the combination of the Contributions of others (if any) used
- by a Contributor and that particular Contributor's Contribution.
-
-1.3. "Contribution"
- means Covered Software of a particular Contributor.
-
-1.4. "Covered Software"
- means Source Code Form to which the initial Contributor has attached
- the notice in Exhibit A, the Executable Form of such Source Code
- Form, and Modifications of such Source Code Form, in each case
- including portions thereof.
-
-1.5. "Incompatible With Secondary Licenses"
- means
-
- (a) that the initial Contributor has attached the notice described
- in Exhibit B to the Covered Software; or
-
- (b) that the Covered Software was made available under the terms of
- version 1.1 or earlier of the License, but not also under the
- terms of a Secondary License.
-
-1.6. "Executable Form"
- means any form of the work other than Source Code Form.
-
-1.7. "Larger Work"
- means a work that combines Covered Software with other material, in
- a separate file or files, that is not Covered Software.
-
-1.8. "License"
- means this document.
-
-1.9. "Licensable"
- means having the right to grant, to the maximum extent possible,
- whether at the time of the initial grant or subsequently, any and
- all of the rights conveyed by this License.
-
-1.10. "Modifications"
- means any of the following:
-
- (a) any file in Source Code Form that results from an addition to,
- deletion from, or modification of the contents of Covered
- Software; or
-
- (b) any new file in Source Code Form that contains any Covered
- Software.
-
-1.11. "Patent Claims" of a Contributor
- means any patent claim(s), including without limitation, method,
- process, and apparatus claims, in any patent Licensable by such
- Contributor that would be infringed, but for the grant of the
- License, by the making, using, selling, offering for sale, having
- made, import, or transfer of either its Contributions or its
- Contributor Version.
-
-1.12. "Secondary License"
- means either the GNU General Public License, Version 2.0, the GNU
- Lesser General Public License, Version 2.1, the GNU Affero General
- Public License, Version 3.0, or any later versions of those
- licenses.
-
-1.13. "Source Code Form"
- means the form of the work preferred for making modifications.
-
-1.14. "You" (or "Your")
- means an individual or a legal entity exercising rights under this
- License. For legal entities, "You" includes any entity that
- controls, is controlled by, or is under common control with You. For
- purposes of this definition, "control" means (a) the power, direct
- or indirect, to cause the direction or management of such entity,
- whether by contract or otherwise, or (b) ownership of more than
- fifty percent (50%) of the outstanding shares or beneficial
- ownership of such entity.
-
-2. License Grants and Conditions
---------------------------------
-
-2.1. Grants
-
-Each Contributor hereby grants You a world-wide, royalty-free,
-non-exclusive license:
-
-(a) under intellectual property rights (other than patent or trademark)
- Licensable by such Contributor to use, reproduce, make available,
- modify, display, perform, distribute, and otherwise exploit its
- Contributions, either on an unmodified basis, with Modifications, or
- as part of a Larger Work; and
-
-(b) under Patent Claims of such Contributor to make, use, sell, offer
- for sale, have made, import, and otherwise transfer either its
- Contributions or its Contributor Version.
-
-2.2. Effective Date
-
-The licenses granted in Section 2.1 with respect to any Contribution
-become effective for each Contribution on the date the Contributor first
-distributes such Contribution.
-
-2.3. Limitations on Grant Scope
-
-The licenses granted in this Section 2 are the only rights granted under
-this License. No additional rights or licenses will be implied from the
-distribution or licensing of Covered Software under this License.
-Notwithstanding Section 2.1(b) above, no patent license is granted by a
-Contributor:
-
-(a) for any code that a Contributor has removed from Covered Software;
- or
-
-(b) for infringements caused by: (i) Your and any other third party's
- modifications of Covered Software, or (ii) the combination of its
- Contributions with other software (except as part of its Contributor
- Version); or
-
-(c) under Patent Claims infringed by Covered Software in the absence of
- its Contributions.
-
-This License does not grant any rights in the trademarks, service marks,
-or logos of any Contributor (except as may be necessary to comply with
-the notice requirements in Section 3.4).
-
-2.4. Subsequent Licenses
-
-No Contributor makes additional grants as a result of Your choice to
-distribute the Covered Software under a subsequent version of this
-License (see Section 10.2) or under the terms of a Secondary License (if
-permitted under the terms of Section 3.3).
-
-2.5. Representation
-
-Each Contributor represents that the Contributor believes its
-Contributions are its original creation(s) or it has sufficient rights
-to grant the rights to its Contributions conveyed by this License.
-
-2.6. Fair Use
-
-This License is not intended to limit any rights You have under
-applicable copyright doctrines of fair use, fair dealing, or other
-equivalents.
-
-2.7. Conditions
-
-Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
-in Section 2.1.
-
-3. Responsibilities
--------------------
-
-3.1. Distribution of Source Form
-
-All distribution of Covered Software in Source Code Form, including any
-Modifications that You create or to which You contribute, must be under
-the terms of this License. You must inform recipients that the Source
-Code Form of the Covered Software is governed by the terms of this
-License, and how they can obtain a copy of this License. You may not
-attempt to alter or restrict the recipients' rights in the Source Code
-Form.
-
-3.2. Distribution of Executable Form
-
-If You distribute Covered Software in Executable Form then:
-
-(a) such Covered Software must also be made available in Source Code
- Form, as described in Section 3.1, and You must inform recipients of
- the Executable Form how they can obtain a copy of such Source Code
- Form by reasonable means in a timely manner, at a charge no more
- than the cost of distribution to the recipient; and
-
-(b) You may distribute such Executable Form under the terms of this
- License, or sublicense it under different terms, provided that the
- license for the Executable Form does not attempt to limit or alter
- the recipients' rights in the Source Code Form under this License.
-
-3.3. Distribution of a Larger Work
-
-You may create and distribute a Larger Work under terms of Your choice,
-provided that You also comply with the requirements of this License for
-the Covered Software. If the Larger Work is a combination of Covered
-Software with a work governed by one or more Secondary Licenses, and the
-Covered Software is not Incompatible With Secondary Licenses, this
-License permits You to additionally distribute such Covered Software
-under the terms of such Secondary License(s), so that the recipient of
-the Larger Work may, at their option, further distribute the Covered
-Software under the terms of either this License or such Secondary
-License(s).
-
-3.4. Notices
-
-You may not remove or alter the substance of any license notices
-(including copyright notices, patent notices, disclaimers of warranty,
-or limitations of liability) contained within the Source Code Form of
-the Covered Software, except that You may alter any license notices to
-the extent required to remedy known factual inaccuracies.
-
-3.5. Application of Additional Terms
-
-You may choose to offer, and to charge a fee for, warranty, support,
-indemnity or liability obligations to one or more recipients of Covered
-Software. However, You may do so only on Your own behalf, and not on
-behalf of any Contributor. You must make it absolutely clear that any
-such warranty, support, indemnity, or liability obligation is offered by
-You alone, and You hereby agree to indemnify every Contributor for any
-liability incurred by such Contributor as a result of warranty, support,
-indemnity or liability terms You offer. You may include additional
-disclaimers of warranty and limitations of liability specific to any
-jurisdiction.
-
-4. Inability to Comply Due to Statute or Regulation
----------------------------------------------------
-
-If it is impossible for You to comply with any of the terms of this
-License with respect to some or all of the Covered Software due to
-statute, judicial order, or regulation then You must: (a) comply with
-the terms of this License to the maximum extent possible; and (b)
-describe the limitations and the code they affect. Such description must
-be placed in a text file included with all distributions of the Covered
-Software under this License. Except to the extent prohibited by statute
-or regulation, such description must be sufficiently detailed for a
-recipient of ordinary skill to be able to understand it.
-
-5. Termination
---------------
-
-5.1. The rights granted under this License will terminate automatically
-if You fail to comply with any of its terms. However, if You become
-compliant, then the rights granted under this License from a particular
-Contributor are reinstated (a) provisionally, unless and until such
-Contributor explicitly and finally terminates Your grants, and (b) on an
-ongoing basis, if such Contributor fails to notify You of the
-non-compliance by some reasonable means prior to 60 days after You have
-come back into compliance. Moreover, Your grants from a particular
-Contributor are reinstated on an ongoing basis if such Contributor
-notifies You of the non-compliance by some reasonable means, this is the
-first time You have received notice of non-compliance with this License
-from such Contributor, and You become compliant prior to 30 days after
-Your receipt of the notice.
-
-5.2. If You initiate litigation against any entity by asserting a patent
-infringement claim (excluding declaratory judgment actions,
-counter-claims, and cross-claims) alleging that a Contributor Version
-directly or indirectly infringes any patent, then the rights granted to
-You by any and all Contributors for the Covered Software under Section
-2.1 of this License shall terminate.
-
-5.3. In the event of termination under Sections 5.1 or 5.2 above, all
-end user license agreements (excluding distributors and resellers) which
-have been validly granted by You or Your distributors under this License
-prior to termination shall survive termination.
-
-************************************************************************
-* *
-* 6. Disclaimer of Warranty *
-* ------------------------- *
-* *
-* Covered Software is provided under this License on an "as is" *
-* basis, without warranty of any kind, either expressed, implied, or *
-* statutory, including, without limitation, warranties that the *
-* Covered Software is free of defects, merchantable, fit for a *
-* particular purpose or non-infringing. The entire risk as to the *
-* quality and performance of the Covered Software is with You. *
-* Should any Covered Software prove defective in any respect, You *
-* (not any Contributor) assume the cost of any necessary servicing, *
-* repair, or correction. This disclaimer of warranty constitutes an *
-* essential part of this License. No use of any Covered Software is *
-* authorized under this License except under this disclaimer. *
-* *
-************************************************************************
-
-************************************************************************
-* *
-* 7. Limitation of Liability *
-* -------------------------- *
-* *
-* Under no circumstances and under no legal theory, whether tort *
-* (including negligence), contract, or otherwise, shall any *
-* Contributor, or anyone who distributes Covered Software as *
-* permitted above, be liable to You for any direct, indirect, *
-* special, incidental, or consequential damages of any character *
-* including, without limitation, damages for lost profits, loss of *
-* goodwill, work stoppage, computer failure or malfunction, or any *
-* and all other commercial damages or losses, even if such party *
-* shall have been informed of the possibility of such damages. This *
-* limitation of liability shall not apply to liability for death or *
-* personal injury resulting from such party's negligence to the *
-* extent applicable law prohibits such limitation. Some *
-* jurisdictions do not allow the exclusion or limitation of *
-* incidental or consequential damages, so this exclusion and *
-* limitation may not apply to You. *
-* *
-************************************************************************
-
-8. Litigation
--------------
-
-Any litigation relating to this License may be brought only in the
-courts of a jurisdiction where the defendant maintains its principal
-place of business and such litigation shall be governed by laws of that
-jurisdiction, without reference to its conflict-of-law provisions.
-Nothing in this Section shall prevent a party's ability to bring
-cross-claims or counter-claims.
-
-9. Miscellaneous
-----------------
-
-This License represents the complete agreement concerning the subject
-matter hereof. If any provision of this License is held to be
-unenforceable, such provision shall be reformed only to the extent
-necessary to make it enforceable. Any law or regulation which provides
-that the language of a contract shall be construed against the drafter
-shall not be used to construe this License against a Contributor.
-
-10. Versions of the License
----------------------------
-
-10.1. New Versions
-
-Mozilla Foundation is the license steward. Except as provided in Section
-10.3, no one other than the license steward has the right to modify or
-publish new versions of this License. Each version will be given a
-distinguishing version number.
-
-10.2. Effect of New Versions
-
-You may distribute the Covered Software under the terms of the version
-of the License under which You originally received the Covered Software,
-or under the terms of any subsequent version published by the license
-steward.
-
-10.3. Modified Versions
-
-If you create software not governed by this License, and you want to
-create a new license for such software, you may create and use a
-modified version of this License if you rename the license and remove
-any references to the name of the license steward (except to note that
-such modified license differs from this License).
-
-10.4. Distributing Source Code Form that is Incompatible With Secondary
-Licenses
-
-If You choose to distribute Source Code Form that is Incompatible With
-Secondary Licenses under the terms of this version of the License, the
-notice described in Exhibit B of this License must be attached.
-
-Exhibit A - Source Code Form License Notice
--------------------------------------------
-
- 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/.
-
-If it is not possible or desirable to put the notice in a particular
-file, then You may include the notice in a location (such as a LICENSE
-file in a relevant directory) where a recipient would be likely to look
-for such a notice.
-
-You may add additional accurate notices of copyright ownership.
-
-Exhibit B - "Incompatible With Secondary Licenses" Notice
----------------------------------------------------------
-
- This Source Code Form is "Incompatible With Secondary Licenses", as
- defined by the Mozilla Public License, v. 2.0.
diff --git a/nss/lib/base/arena.c b/nss/lib/base/arena.c
deleted file mode 100644
index b8e6464..0000000
--- a/nss/lib/base/arena.c
+++ /dev/null
@@ -1,1143 +0,0 @@
-/* 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/. */
-
-/*
- * arena.c
- *
- * This contains the implementation of NSS's thread-safe arenas.
- */
-
-#ifndef BASE_H
-#include "base.h"
-#endif /* BASE_H */
-
-#ifdef ARENA_THREADMARK
-#include "prthread.h"
-#endif /* ARENA_THREADMARK */
-
-#include "prlock.h"
-#include "plarena.h"
-
-#include <string.h>
-
-/*
- * NSSArena
- *
- * This is based on NSPR's arena code, but it is threadsafe.
- *
- * The public methods relating to this type are:
- *
- * NSSArena_Create -- constructor
- * NSSArena_Destroy
- * NSS_ZAlloc
- * NSS_ZRealloc
- * NSS_ZFreeIf
- *
- * The nonpublic methods relating to this type are:
- *
- * nssArena_Create -- constructor
- * nssArena_Destroy
- * nssArena_Mark
- * nssArena_Release
- * nssArena_Unmark
- *
- * nss_ZAlloc
- * nss_ZFreeIf
- * nss_ZRealloc
- *
- * In debug builds, the following calls are available:
- *
- * nssArena_verifyPointer
- * nssArena_registerDestructor
- * nssArena_deregisterDestructor
- */
-
-struct NSSArenaStr {
- PLArenaPool pool;
- PRLock *lock;
-#ifdef ARENA_THREADMARK
- PRThread *marking_thread;
- nssArenaMark *first_mark;
- nssArenaMark *last_mark;
-#endif /* ARENA_THREADMARK */
-#ifdef ARENA_DESTRUCTOR_LIST
- struct arena_destructor_node *first_destructor;
- struct arena_destructor_node *last_destructor;
-#endif /* ARENA_DESTRUCTOR_LIST */
-};
-
-/*
- * nssArenaMark
- *
- * This type is used to mark the current state of an NSSArena.
- */
-
-struct nssArenaMarkStr {
- PRUint32 magic;
- void *mark;
-#ifdef ARENA_THREADMARK
- nssArenaMark *next;
-#endif /* ARENA_THREADMARK */
-#ifdef ARENA_DESTRUCTOR_LIST
- struct arena_destructor_node *next_destructor;
- struct arena_destructor_node *prev_destructor;
-#endif /* ARENA_DESTRUCTOR_LIST */
-};
-
-#define MARK_MAGIC 0x4d41524b /* "MARK" how original */
-
-/*
- * But first, the pointer-tracking code
- */
-#ifdef DEBUG
-extern const NSSError NSS_ERROR_INTERNAL_ERROR;
-
-static nssPointerTracker arena_pointer_tracker;
-
-static PRStatus
-arena_add_pointer(const NSSArena *arena)
-{
- PRStatus rv;
-
- rv = nssPointerTracker_initialize(&arena_pointer_tracker);
- if (PR_SUCCESS != rv) {
- return rv;
- }
-
- rv = nssPointerTracker_add(&arena_pointer_tracker, arena);
- if (PR_SUCCESS != rv) {
- NSSError e = NSS_GetError();
- if (NSS_ERROR_NO_MEMORY != e) {
- nss_SetError(NSS_ERROR_INTERNAL_ERROR);
- }
-
- return rv;
- }
-
- return PR_SUCCESS;
-}
-
-static PRStatus
-arena_remove_pointer(const NSSArena *arena)
-{
- PRStatus rv;
-
- rv = nssPointerTracker_remove(&arena_pointer_tracker, arena);
- if (PR_SUCCESS != rv) {
- nss_SetError(NSS_ERROR_INTERNAL_ERROR);
- }
-
- return rv;
-}
-
-/*
- * nssArena_verifyPointer
- *
- * This method is only present in debug builds.
- *
- * If the specified pointer is a valid pointer to an NSSArena object,
- * this routine will return PR_SUCCESS. Otherwise, it will put an
- * error on the error stack and return PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- *
- * Return value:
- * PR_SUCCESS if the pointer is valid
- * PR_FAILURE if it isn't
- */
-
-NSS_IMPLEMENT PRStatus
-nssArena_verifyPointer(const NSSArena *arena)
-{
- PRStatus rv;
-
- rv = nssPointerTracker_initialize(&arena_pointer_tracker);
- if (PR_SUCCESS != rv) {
- /*
- * This is a little disingenious. We have to initialize the
- * tracker, because someone could "legitimately" try to verify
- * an arena pointer before one is ever created. And this step
- * might fail, due to lack of memory. But the only way that
- * this step can fail is if it's doing the call_once stuff,
- * (later calls just no-op). And if it didn't no-op, there
- * aren't any valid arenas.. so the argument certainly isn't one.
- */
- nss_SetError(NSS_ERROR_INVALID_ARENA);
- return PR_FAILURE;
- }
-
- rv = nssPointerTracker_verify(&arena_pointer_tracker, arena);
- if (PR_SUCCESS != rv) {
- nss_SetError(NSS_ERROR_INVALID_ARENA);
- return PR_FAILURE;
- }
-
- return PR_SUCCESS;
-}
-#endif /* DEBUG */
-
-#ifdef ARENA_DESTRUCTOR_LIST
-
-struct arena_destructor_node {
- struct arena_destructor_node *next;
- struct arena_destructor_node *prev;
- void (*destructor)(void *argument);
- void *arg;
-};
-
-/*
- * nssArena_registerDestructor
- *
- * This routine stores a pointer to a callback and an arbitrary
- * pointer-sized argument in the arena, at the current point in
- * the mark stack. If the arena is destroyed, or an "earlier"
- * mark is released, then this destructor will be called at that
- * time. Note that the destructor will be called with the arena
- * locked, which means the destructor may free memory in that
- * arena, but it may not allocate or cause to be allocated any
- * memory. This callback facility was included to support our
- * debug-version pointer-tracker feature; overuse runs counter to
- * the the original intent of arenas. This routine returns a
- * PRStatus value; if successful, it will return PR_SUCCESS. If
- * unsuccessful, it will set an error on the error stack and
- * return PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- * NSS_ERROR_NO_MEMORY
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-
-NSS_IMPLEMENT PRStatus
-nssArena_registerDestructor(NSSArena *arena, void (*destructor)(void *argument),
- void *arg)
-{
- struct arena_destructor_node *it;
-
-#ifdef NSSDEBUG
- if (PR_SUCCESS != nssArena_verifyPointer(arena)) {
- return PR_FAILURE;
- }
-#endif /* NSSDEBUG */
-
- it = nss_ZNEW(arena, struct arena_destructor_node);
- if ((struct arena_destructor_node *)NULL == it) {
- return PR_FAILURE;
- }
-
- it->prev = arena->last_destructor;
- arena->last_destructor->next = it;
- arena->last_destructor = it;
- it->destructor = destructor;
- it->arg = arg;
-
- if ((nssArenaMark *)NULL != arena->last_mark) {
- arena->last_mark->prev_destructor = it->prev;
- arena->last_mark->next_destructor = it->next;
- }
-
- return PR_SUCCESS;
-}
-
-NSS_IMPLEMENT PRStatus
-nssArena_deregisterDestructor(NSSArena *arena,
- void (*destructor)(void *argument), void *arg)
-{
- struct arena_destructor_node *it;
-
-#ifdef NSSDEBUG
- if (PR_SUCCESS != nssArena_verifyPointer(arena)) {
- return PR_FAILURE;
- }
-#endif /* NSSDEBUG */
-
- for (it = arena->first_destructor; it; it = it->next) {
- if ((it->destructor == destructor) && (it->arg == arg)) {
- break;
- }
- }
-
- if ((struct arena_destructor_node *)NULL == it) {
- nss_SetError(NSS_ERROR_NOT_FOUND);
- return PR_FAILURE;
- }
-
- if (it == arena->first_destructor) {
- arena->first_destructor = it->next;
- }
-
- if (it == arena->last_destructor) {
- arena->last_destructor = it->prev;
- }
-
- if ((struct arena_destructor_node *)NULL != it->prev) {
- it->prev->next = it->next;
- }
-
- if ((struct arena_destructor_node *)NULL != it->next) {
- it->next->prev = it->prev;
- }
-
- {
- nssArenaMark *m;
- for (m = arena->first_mark; m; m = m->next) {
- if (m->next_destructor == it) {
- m->next_destructor = it->next;
- }
- if (m->prev_destructor == it) {
- m->prev_destructor = it->prev;
- }
- }
- }
-
- nss_ZFreeIf(it);
- return PR_SUCCESS;
-}
-
-static void
-nss_arena_call_destructor_chain(struct arena_destructor_node *it)
-{
- for (; it; it = it->next) {
- (*(it->destructor))(it->arg);
- }
-}
-
-#endif /* ARENA_DESTRUCTOR_LIST */
-
-/*
- * NSSArena_Create
- *
- * This routine creates a new memory arena. This routine may return
- * NULL upon error, in which case it will have created an error stack.
- *
- * The top-level error may be one of the following values:
- * NSS_ERROR_NO_MEMORY
- *
- * Return value:
- * NULL upon error
- * A pointer to an NSSArena upon success
- */
-
-NSS_IMPLEMENT NSSArena *
-NSSArena_Create(void)
-{
- nss_ClearErrorStack();
- return nssArena_Create();
-}
-
-/*
- * nssArena_Create
- *
- * This routine creates a new memory arena. This routine may return
- * NULL upon error, in which case it will have set an error on the
- * error stack.
- *
- * The error may be one of the following values:
- * NSS_ERROR_NO_MEMORY
- *
- * Return value:
- * NULL upon error
- * A pointer to an NSSArena upon success
- */
-
-NSS_IMPLEMENT NSSArena *
-nssArena_Create(void)
-{
- NSSArena *rv = (NSSArena *)NULL;
-
- rv = nss_ZNEW((NSSArena *)NULL, NSSArena);
- if ((NSSArena *)NULL == rv) {
- nss_SetError(NSS_ERROR_NO_MEMORY);
- return (NSSArena *)NULL;
- }
-
- rv->lock = PR_NewLock();
- if ((PRLock *)NULL == rv->lock) {
- (void)nss_ZFreeIf(rv);
- nss_SetError(NSS_ERROR_NO_MEMORY);
- return (NSSArena *)NULL;
- }
-
- /*
- * Arena sizes. The current security code has 229 occurrences of
- * PORT_NewArena. The default chunksizes specified break down as
- *
- * Size Mult. Specified as
- * 512 1 512
- * 1024 7 1024
- * 2048 5 2048
- * 2048 5 CRMF_DEFAULT_ARENA_SIZE
- * 2048 190 DER_DEFAULT_CHUNKSIZE
- * 2048 20 SEC_ASN1_DEFAULT_ARENA_SIZE
- * 4096 1 4096
- *
- * Obviously this "default chunksize" flexibility isn't very
- * useful to us, so I'll just pick 2048.
- */
-
- PL_InitArenaPool(&rv->pool, "NSS", 2048, sizeof(double));
-
-#ifdef DEBUG
- {
- PRStatus st;
- st = arena_add_pointer(rv);
- if (PR_SUCCESS != st) {
- PL_FinishArenaPool(&rv->pool);
- PR_DestroyLock(rv->lock);
- (void)nss_ZFreeIf(rv);
- return (NSSArena *)NULL;
- }
- }
-#endif /* DEBUG */
-
- return rv;
-}
-
-/*
- * NSSArena_Destroy
- *
- * This routine will destroy the specified arena, freeing all memory
- * allocated from it. This routine returns a PRStatus value; if
- * successful, it will return PR_SUCCESS. If unsuccessful, it will
- * create an error stack and return PR_FAILURE.
- *
- * The top-level error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- *
- * Return value:
- * PR_SUCCESS upon success
- * PR_FAILURE upon failure
- */
-
-NSS_IMPLEMENT PRStatus
-NSSArena_Destroy(NSSArena *arena)
-{
- nss_ClearErrorStack();
-
-#ifdef DEBUG
- if (PR_SUCCESS != nssArena_verifyPointer(arena)) {
- return PR_FAILURE;
- }
-#endif /* DEBUG */
-
- return nssArena_Destroy(arena);
-}
-
-/*
- * nssArena_Destroy
- *
- * This routine will destroy the specified arena, freeing all memory
- * allocated from it. This routine returns a PRStatus value; if
- * successful, it will return PR_SUCCESS. If unsuccessful, it will
- * set an error on the error stack and return PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-
-NSS_IMPLEMENT PRStatus
-nssArena_Destroy(NSSArena *arena)
-{
- PRLock *lock;
-
-#ifdef NSSDEBUG
- if (PR_SUCCESS != nssArena_verifyPointer(arena)) {
- return PR_FAILURE;
- }
-#endif /* NSSDEBUG */
-
- if ((PRLock *)NULL == arena->lock) {
- /* Just got destroyed */
- nss_SetError(NSS_ERROR_INVALID_ARENA);
- return PR_FAILURE;
- }
- PR_Lock(arena->lock);
-
-#ifdef DEBUG
- if (PR_SUCCESS != arena_remove_pointer(arena)) {
- PR_Unlock(arena->lock);
- return PR_FAILURE;
- }
-#endif /* DEBUG */
-
-#ifdef ARENA_DESTRUCTOR_LIST
- /* Note that the arena is locked at this time */
- nss_arena_call_destructor_chain(arena->first_destructor);
-#endif /* ARENA_DESTRUCTOR_LIST */
-
- PL_FinishArenaPool(&arena->pool);
- lock = arena->lock;
- arena->lock = (PRLock *)NULL;
- PR_Unlock(lock);
- PR_DestroyLock(lock);
- (void)nss_ZFreeIf(arena);
- return PR_SUCCESS;
-}
-
-static void *nss_zalloc_arena_locked(NSSArena *arena, PRUint32 size);
-
-/*
- * nssArena_Mark
- *
- * This routine "marks" the current state of an arena. Space
- * allocated after the arena has been marked can be freed by
- * releasing the arena back to the mark with nssArena_Release,
- * or committed by calling nssArena_Unmark. When successful,
- * this routine returns a valid nssArenaMark pointer. This
- * routine may return NULL upon error, in which case it will
- * have set an error on the error stack.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- * NSS_ERROR_NO_MEMORY
- * NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD
- *
- * Return value:
- * NULL upon failure
- * An nssArenaMark pointer upon success
- */
-
-NSS_IMPLEMENT nssArenaMark *
-nssArena_Mark(NSSArena *arena)
-{
- nssArenaMark *rv;
- void *p;
-
-#ifdef NSSDEBUG
- if (PR_SUCCESS != nssArena_verifyPointer(arena)) {
- return (nssArenaMark *)NULL;
- }
-#endif /* NSSDEBUG */
-
- if ((PRLock *)NULL == arena->lock) {
- /* Just got destroyed */
- nss_SetError(NSS_ERROR_INVALID_ARENA);
- return (nssArenaMark *)NULL;
- }
- PR_Lock(arena->lock);
-
-#ifdef ARENA_THREADMARK
- if ((PRThread *)NULL == arena->marking_thread) {
- /* Unmarked. Store our thread ID */
- arena->marking_thread = PR_GetCurrentThread();
- /* This call never fails. */
- } else {
- /* Marked. Verify it's the current thread */
- if (PR_GetCurrentThread() != arena->marking_thread) {
- PR_Unlock(arena->lock);
- nss_SetError(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD);
- return (nssArenaMark *)NULL;
- }
- }
-#endif /* ARENA_THREADMARK */
-
- p = PL_ARENA_MARK(&arena->pool);
- /* No error possible */
-
- /* Do this after the mark */
- rv = (nssArenaMark *)nss_zalloc_arena_locked(arena, sizeof(nssArenaMark));
- if ((nssArenaMark *)NULL == rv) {
- PR_Unlock(arena->lock);
- nss_SetError(NSS_ERROR_NO_MEMORY);
- return (nssArenaMark *)NULL;
- }
-
-#ifdef ARENA_THREADMARK
- if ((nssArenaMark *)NULL == arena->first_mark) {
- arena->first_mark = rv;
- arena->last_mark = rv;
- } else {
- arena->last_mark->next = rv;
- arena->last_mark = rv;
- }
-#endif /* ARENA_THREADMARK */
-
- rv->mark = p;
- rv->magic = MARK_MAGIC;
-
-#ifdef ARENA_DESTRUCTOR_LIST
- rv->prev_destructor = arena->last_destructor;
-#endif /* ARENA_DESTRUCTOR_LIST */
-
- PR_Unlock(arena->lock);
-
- return rv;
-}
-
-/*
- * nss_arena_unmark_release
- *
- * This static routine implements the routines nssArena_Release
- * ans nssArena_Unmark, which are almost identical.
- */
-
-static PRStatus
-nss_arena_unmark_release(NSSArena *arena, nssArenaMark *arenaMark,
- PRBool release)
-{
- void *inner_mark;
-
-#ifdef NSSDEBUG
- if (PR_SUCCESS != nssArena_verifyPointer(arena)) {
- return PR_FAILURE;
- }
-#endif /* NSSDEBUG */
-
- if (MARK_MAGIC != arenaMark->magic) {
- nss_SetError(NSS_ERROR_INVALID_ARENA_MARK);
- return PR_FAILURE;
- }
-
- if ((PRLock *)NULL == arena->lock) {
- /* Just got destroyed */
- nss_SetError(NSS_ERROR_INVALID_ARENA);
- return PR_FAILURE;
- }
- PR_Lock(arena->lock);
-
-#ifdef ARENA_THREADMARK
- if ((PRThread *)NULL != arena->marking_thread) {
- if (PR_GetCurrentThread() != arena->marking_thread) {
- PR_Unlock(arena->lock);
- nss_SetError(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD);
- return PR_FAILURE;
- }
- }
-#endif /* ARENA_THREADMARK */
-
- if (MARK_MAGIC != arenaMark->magic) {
- /* Just got released */
- PR_Unlock(arena->lock);
- nss_SetError(NSS_ERROR_INVALID_ARENA_MARK);
- return PR_FAILURE;
- }
-
- arenaMark->magic = 0;
- inner_mark = arenaMark->mark;
-
-#ifdef ARENA_THREADMARK
- {
- nssArenaMark **pMark = &arena->first_mark;
- nssArenaMark *rest;
- nssArenaMark *last = (nssArenaMark *)NULL;
-
- /* Find this mark */
- while (*pMark != arenaMark) {
- last = *pMark;
- pMark = &(*pMark)->next;
- }
-
- /* Remember the pointer, then zero it */
- rest = (*pMark)->next;
- *pMark = (nssArenaMark *)NULL;
-
- arena->last_mark = last;
-
- /* Invalidate any later marks being implicitly released */
- for (; (nssArenaMark *)NULL != rest; rest = rest->next) {
- rest->magic = 0;
- }
-
- /* If we just got rid of the first mark, clear the thread ID */
- if ((nssArenaMark *)NULL == arena->first_mark) {
- arena->marking_thread = (PRThread *)NULL;
- }
- }
-#endif /* ARENA_THREADMARK */
-
- if (release) {
-#ifdef ARENA_DESTRUCTOR_LIST
- if ((struct arena_destructor_node *)NULL !=
- arenaMark->prev_destructor) {
- arenaMark->prev_destructor->next =
- (struct arena_destructor_node *)NULL;
- }
- arena->last_destructor = arenaMark->prev_destructor;
-
- /* Note that the arena is locked at this time */
- nss_arena_call_destructor_chain(arenaMark->next_destructor);
-#endif /* ARENA_DESTRUCTOR_LIST */
-
- PL_ARENA_RELEASE(&arena->pool, inner_mark);
- /* No error return */
- }
-
- PR_Unlock(arena->lock);
- return PR_SUCCESS;
-}
-
-/*
- * nssArena_Release
- *
- * This routine invalidates and releases all memory allocated from
- * the specified arena after the point at which the specified mark
- * was obtained. This routine returns a PRStatus value; if successful,
- * it will return PR_SUCCESS. If unsuccessful, it will set an error
- * on the error stack and return PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- * NSS_ERROR_INVALID_ARENA_MARK
- * NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-
-NSS_IMPLEMENT PRStatus
-nssArena_Release(NSSArena *arena, nssArenaMark *arenaMark)
-{
- return nss_arena_unmark_release(arena, arenaMark, PR_TRUE);
-}
-
-/*
- * nssArena_Unmark
- *
- * This routine "commits" the indicated mark and any marks after
- * it, making them unreleasable. Note that any earlier marks can
- * still be released, and such a release will invalidate these
- * later unmarked regions. If an arena is to be safely shared by
- * more than one thread, all marks must be either released or
- * unmarked. This routine returns a PRStatus value; if successful,
- * it will return PR_SUCCESS. If unsuccessful, it will set an error
- * on the error stack and return PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- * NSS_ERROR_INVALID_ARENA_MARK
- * NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-
-NSS_IMPLEMENT PRStatus
-nssArena_Unmark(NSSArena *arena, nssArenaMark *arenaMark)
-{
- return nss_arena_unmark_release(arena, arenaMark, PR_FALSE);
-}
-
-/*
- * We prefix this header to all allocated blocks. It is a multiple
- * of the alignment size. Note that this usage of a header may make
- * purify spew bogus warnings about "potentially leaked blocks" of
- * memory; if that gets too annoying we can add in a pointer to the
- * header in the header itself. There's not a lot of safety here;
- * maybe we should add a magic value?
- */
-struct pointer_header {
- NSSArena *arena;
- PRUint32 size;
-};
-
-static void *
-nss_zalloc_arena_locked(NSSArena *arena, PRUint32 size)
-{
- void *p;
- void *rv;
- struct pointer_header *h;
- PRUint32 my_size = size + sizeof(struct pointer_header);
- PL_ARENA_ALLOCATE(p, &arena->pool, my_size);
- if ((void *)NULL == p) {
- nss_SetError(NSS_ERROR_NO_MEMORY);
- return (void *)NULL;
- }
- /*
- * Do this before we unlock. This way if the user is using
- * an arena in one thread while destroying it in another, he'll
- * fault/FMR in his code, not ours.
- */
- h = (struct pointer_header *)p;
- h->arena = arena;
- h->size = size;
- rv = (void *)((char *)h + sizeof(struct pointer_header));
- (void)nsslibc_memset(rv, 0, size);
- return rv;
-}
-
-/*
- * NSS_ZAlloc
- *
- * This routine allocates and zeroes a section of memory of the
- * size, and returns to the caller a pointer to that memory. If
- * the optional arena argument is non-null, the memory will be
- * obtained from that arena; otherwise, the memory will be obtained
- * from the heap. This routine may return NULL upon error, in
- * which case it will have set an error upon the error stack. The
- * value specified for size may be zero; in which case a valid
- * zero-length block of memory will be allocated. This block may
- * be expanded by calling NSS_ZRealloc.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- * NSS_ERROR_NO_MEMORY
- * NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD
- *
- * Return value:
- * NULL upon error
- * A pointer to the new segment of zeroed memory
- */
-
-NSS_IMPLEMENT void *
-NSS_ZAlloc(NSSArena *arenaOpt, PRUint32 size)
-{
- return nss_ZAlloc(arenaOpt, size);
-}
-
-/*
- * nss_ZAlloc
- *
- * This routine allocates and zeroes a section of memory of the
- * size, and returns to the caller a pointer to that memory. If
- * the optional arena argument is non-null, the memory will be
- * obtained from that arena; otherwise, the memory will be obtained
- * from the heap. This routine may return NULL upon error, in
- * which case it will have set an error upon the error stack. The
- * value specified for size may be zero; in which case a valid
- * zero-length block of memory will be allocated. This block may
- * be expanded by calling nss_ZRealloc.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- * NSS_ERROR_NO_MEMORY
- * NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD
- *
- * Return value:
- * NULL upon error
- * A pointer to the new segment of zeroed memory
- */
-
-NSS_IMPLEMENT void *
-nss_ZAlloc(NSSArena *arenaOpt, PRUint32 size)
-{
- struct pointer_header *h;
- PRUint32 my_size = size + sizeof(struct pointer_header);
-
- if (my_size < sizeof(struct pointer_header)) {
- /* Wrapped */
- nss_SetError(NSS_ERROR_NO_MEMORY);
- return (void *)NULL;
- }
-
- if ((NSSArena *)NULL == arenaOpt) {
- /* Heap allocation, no locking required. */
- h = (struct pointer_header *)PR_Calloc(1, my_size);
- if ((struct pointer_header *)NULL == h) {
- nss_SetError(NSS_ERROR_NO_MEMORY);
- return (void *)NULL;
- }
-
- h->arena = (NSSArena *)NULL;
- h->size = size;
- /* We used calloc: it's already zeroed */
-
- return (void *)((char *)h + sizeof(struct pointer_header));
- } else {
- void *rv;
-/* Arena allocation */
-#ifdef NSSDEBUG
- if (PR_SUCCESS != nssArena_verifyPointer(arenaOpt)) {
- return (void *)NULL;
- }
-#endif /* NSSDEBUG */
-
- if ((PRLock *)NULL == arenaOpt->lock) {
- /* Just got destroyed */
- nss_SetError(NSS_ERROR_INVALID_ARENA);
- return (void *)NULL;
- }
- PR_Lock(arenaOpt->lock);
-
-#ifdef ARENA_THREADMARK
- if ((PRThread *)NULL != arenaOpt->marking_thread) {
- if (PR_GetCurrentThread() != arenaOpt->marking_thread) {
- nss_SetError(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD);
- PR_Unlock(arenaOpt->lock);
- return (void *)NULL;
- }
- }
-#endif /* ARENA_THREADMARK */
-
- rv = nss_zalloc_arena_locked(arenaOpt, size);
-
- PR_Unlock(arenaOpt->lock);
- return rv;
- }
- /*NOTREACHED*/
-}
-
-/*
- * NSS_ZFreeIf
- *
- * If the specified pointer is non-null, then the region of memory
- * to which it points -- which must have been allocated with
- * NSS_ZAlloc -- will be zeroed and released. This routine
- * returns a PRStatus value; if successful, it will return PR_SUCCESS.
- * If unsuccessful, it will set an error on the error stack and return
- * PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_POINTER
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-NSS_IMPLEMENT PRStatus
-NSS_ZFreeIf(void *pointer)
-{
- return nss_ZFreeIf(pointer);
-}
-
-/*
- * nss_ZFreeIf
- *
- * If the specified pointer is non-null, then the region of memory
- * to which it points -- which must have been allocated with
- * nss_ZAlloc -- will be zeroed and released. This routine
- * returns a PRStatus value; if successful, it will return PR_SUCCESS.
- * If unsuccessful, it will set an error on the error stack and return
- * PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_POINTER
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-
-NSS_IMPLEMENT PRStatus
-nss_ZFreeIf(void *pointer)
-{
- struct pointer_header *h;
-
- if ((void *)NULL == pointer) {
- return PR_SUCCESS;
- }
-
- h = (struct pointer_header *)((char *)pointer -
- sizeof(struct pointer_header));
-
- /* Check any magic here */
-
- if ((NSSArena *)NULL == h->arena) {
- /* Heap */
- (void)nsslibc_memset(pointer, 0, h->size);
- PR_Free(h);
- return PR_SUCCESS;
- } else {
-/* Arena */
-#ifdef NSSDEBUG
- if (PR_SUCCESS != nssArena_verifyPointer(h->arena)) {
- return PR_FAILURE;
- }
-#endif /* NSSDEBUG */
-
- if ((PRLock *)NULL == h->arena->lock) {
- /* Just got destroyed.. so this pointer is invalid */
- nss_SetError(NSS_ERROR_INVALID_POINTER);
- return PR_FAILURE;
- }
- PR_Lock(h->arena->lock);
-
- (void)nsslibc_memset(pointer, 0, h->size);
-
- /* No way to "free" it within an NSPR arena. */
-
- PR_Unlock(h->arena->lock);
- return PR_SUCCESS;
- }
- /*NOTREACHED*/
-}
-
-/*
- * NSS_ZRealloc
- *
- * This routine reallocates a block of memory obtained by calling
- * nss_ZAlloc or nss_ZRealloc. The portion of memory
- * between the new and old sizes -- which is either being newly
- * obtained or released -- is in either case zeroed. This routine
- * may return NULL upon failure, in which case it will have placed
- * an error on the error stack.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_POINTER
- * NSS_ERROR_NO_MEMORY
- * NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD
- *
- * Return value:
- * NULL upon error
- * A pointer to the replacement segment of memory
- */
-
-NSS_EXTERN void *
-NSS_ZRealloc(void *pointer, PRUint32 newSize)
-{
- return nss_ZRealloc(pointer, newSize);
-}
-
-/*
- * nss_ZRealloc
- *
- * This routine reallocates a block of memory obtained by calling
- * nss_ZAlloc or nss_ZRealloc. The portion of memory
- * between the new and old sizes -- which is either being newly
- * obtained or released -- is in either case zeroed. This routine
- * may return NULL upon failure, in which case it will have placed
- * an error on the error stack.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_POINTER
- * NSS_ERROR_NO_MEMORY
- * NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD
- *
- * Return value:
- * NULL upon error
- * A pointer to the replacement segment of memory
- */
-
-NSS_EXTERN void *
-nss_ZRealloc(void *pointer, PRUint32 newSize)
-{
- NSSArena *arena;
- struct pointer_header *h, *new_h;
- PRUint32 my_newSize = newSize + sizeof(struct pointer_header);
- void *rv;
-
- if (my_newSize < sizeof(struct pointer_header)) {
- /* Wrapped */
- nss_SetError(NSS_ERROR_NO_MEMORY);
- return (void *)NULL;
- }
-
- if ((void *)NULL == pointer) {
- nss_SetError(NSS_ERROR_INVALID_POINTER);
- return (void *)NULL;
- }
-
- h = (struct pointer_header *)((char *)pointer -
- sizeof(struct pointer_header));
-
- /* Check any magic here */
-
- if (newSize == h->size) {
- /* saves thrashing */
- return pointer;
- }
-
- arena = h->arena;
- if (!arena) {
- /* Heap */
- new_h = (struct pointer_header *)PR_Calloc(1, my_newSize);
- if ((struct pointer_header *)NULL == new_h) {
- nss_SetError(NSS_ERROR_NO_MEMORY);
- return (void *)NULL;
- }
-
- new_h->arena = (NSSArena *)NULL;
- new_h->size = newSize;
- rv = (void *)((char *)new_h + sizeof(struct pointer_header));
-
- if (newSize > h->size) {
- (void)nsslibc_memcpy(rv, pointer, h->size);
- (void)nsslibc_memset(&((char *)rv)[h->size], 0,
- (newSize - h->size));
- } else {
- (void)nsslibc_memcpy(rv, pointer, newSize);
- }
-
- (void)nsslibc_memset(pointer, 0, h->size);
- h->size = 0;
- PR_Free(h);
-
- return rv;
- } else {
- void *p;
-/* Arena */
-#ifdef NSSDEBUG
- if (PR_SUCCESS != nssArena_verifyPointer(arena)) {
- return (void *)NULL;
- }
-#endif /* NSSDEBUG */
-
- if (!arena->lock) {
- /* Just got destroyed.. so this pointer is invalid */
- nss_SetError(NSS_ERROR_INVALID_POINTER);
- return (void *)NULL;
- }
- PR_Lock(arena->lock);
-
-#ifdef ARENA_THREADMARK
- if (arena->marking_thread) {
- if (PR_GetCurrentThread() != arena->marking_thread) {
- PR_Unlock(arena->lock);
- nss_SetError(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD);
- return (void *)NULL;
- }
- }
-#endif /* ARENA_THREADMARK */
-
- if (newSize < h->size) {
- /*
- * We have no general way of returning memory to the arena
- * (mark/release doesn't work because things may have been
- * allocated after this object), so the memory is gone
- * anyway. We might as well just return the same pointer to
- * the user, saying "yeah, uh-hunh, you can only use less of
- * it now." We'll zero the leftover part, of course. And
- * in fact we might as well *not* adjust h->size-- this way,
- * if the user reallocs back up to something not greater than
- * the original size, then voila, there's the memory! This
- * way a thrash big/small/big/small doesn't burn up the arena.
- */
- char *extra = &((char *)pointer)[newSize];
- (void)nsslibc_memset(extra, 0, (h->size - newSize));
- PR_Unlock(arena->lock);
- return pointer;
- }
-
- PL_ARENA_ALLOCATE(p, &arena->pool, my_newSize);
- if ((void *)NULL == p) {
- PR_Unlock(arena->lock);
- nss_SetError(NSS_ERROR_NO_MEMORY);
- return (void *)NULL;
- }
-
- new_h = (struct pointer_header *)p;
- new_h->arena = arena;
- new_h->size = newSize;
- rv = (void *)((char *)new_h + sizeof(struct pointer_header));
- if (rv != pointer) {
- (void)nsslibc_memcpy(rv, pointer, h->size);
- (void)nsslibc_memset(pointer, 0, h->size);
- }
- (void)nsslibc_memset(&((char *)rv)[h->size], 0, (newSize - h->size));
- h->arena = (NSSArena *)NULL;
- h->size = 0;
- PR_Unlock(arena->lock);
- return rv;
- }
- /*NOTREACHED*/
-}
-
-PRStatus
-nssArena_Shutdown(void)
-{
- PRStatus rv = PR_SUCCESS;
-#ifdef DEBUG
- rv = nssPointerTracker_finalize(&arena_pointer_tracker);
-#endif
- return rv;
-}
diff --git a/nss/lib/base/base.h b/nss/lib/base/base.h
deleted file mode 100644
index 6d8a1ba..0000000
--- a/nss/lib/base/base.h
+++ /dev/null
@@ -1,1106 +0,0 @@
-/* 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/. */
-
-#ifndef BASE_H
-#define BASE_H
-
-/*
- * base.h
- *
- * This header file contains basic prototypes and preprocessor
- * definitions used throughout nss but not available publicly.
- */
-
-#ifndef BASET_H
-#include "baset.h"
-#endif /* BASET_H */
-
-#ifndef NSSBASE_H
-#include "nssbase.h"
-#endif /* NSSBASE_H */
-
-#include "plhash.h"
-
-PR_BEGIN_EXTERN_C
-
-/*
- * NSSArena
- *
- * The nonpublic methods relating to this type are:
- *
- * nssArena_Create -- constructor
- * nssArena_Destroy
- * nssArena_Mark
- * nssArena_Release
- * nssArena_Unmark
- *
- * nss_ZAlloc
- * nss_ZFreeIf
- * nss_ZRealloc
- *
- * Additionally, there are some preprocessor macros:
- *
- * nss_ZNEW
- * nss_ZNEWARRAY
- *
- * In debug builds, the following calls are available:
- *
- * nssArena_verifyPointer
- * nssArena_registerDestructor
- * nssArena_deregisterDestructor
- *
- * The following preprocessor macro is also always available:
- *
- * nssArena_VERIFYPOINTER
- *
- * A constant PLHashAllocOps structure is available for users
- * of the NSPL PLHashTable routines.
- *
- * nssArenaHashAllocOps
- */
-
-/*
- * nssArena_Create
- *
- * This routine creates a new memory arena. This routine may return
- * NULL upon error, in which case it will have set an error on the
- * error stack.
- *
- * The error may be one of the following values:
- * NSS_ERROR_NO_MEMORY
- *
- * Return value:
- * NULL upon error
- * A pointer to an NSSArena upon success
- */
-
-/*
- * XXX fgmr
- * Arenas can be named upon creation; this is mostly of use when
- * debugging. Should we expose that here, allowing an optional
- * "const char *name" argument? Should the public version of this
- * call (NSSArena_Create) have it too?
- */
-
-NSS_EXTERN NSSArena *nssArena_Create(void);
-
-extern const NSSError NSS_ERROR_NO_MEMORY;
-
-/*
- * nssArena_Destroy
- *
- * This routine will destroy the specified arena, freeing all memory
- * allocated from it. This routine returns a PRStatus value; if
- * successful, it will return PR_SUCCESS. If unsuccessful, it will
- * set an error on the error stack and return PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-
-NSS_EXTERN PRStatus nssArena_Destroy(NSSArena *arena);
-
-extern const NSSError NSS_ERROR_INVALID_ARENA;
-
-/*
- * nssArena_Mark
- *
- * This routine "marks" the current state of an arena. Space
- * allocated after the arena has been marked can be freed by
- * releasing the arena back to the mark with nssArena_Release,
- * or committed by calling nssArena_Unmark. When successful,
- * this routine returns a valid nssArenaMark pointer. This
- * routine may return NULL upon error, in which case it will
- * have set an error on the error stack.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- * NSS_ERROR_NO_MEMORY
- * NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD
- *
- * Return value:
- * NULL upon failure
- * An nssArenaMark pointer upon success
- */
-
-NSS_EXTERN nssArenaMark *nssArena_Mark(NSSArena *arena);
-
-extern const NSSError NSS_ERROR_INVALID_ARENA;
-extern const NSSError NSS_ERROR_NO_MEMORY;
-extern const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD;
-
-/*
- * nssArena_Release
- *
- * This routine invalidates and releases all memory allocated from
- * the specified arena after the point at which the specified mark
- * was obtained. This routine returns a PRStatus value; if successful,
- * it will return PR_SUCCESS. If unsuccessful, it will set an error
- * on the error stack and return PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- * NSS_ERROR_INVALID_ARENA_MARK
- * NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-
-NSS_EXTERN PRStatus nssArena_Release(NSSArena *arena, nssArenaMark *arenaMark);
-
-extern const NSSError NSS_ERROR_INVALID_ARENA;
-extern const NSSError NSS_ERROR_INVALID_ARENA_MARK;
-
-/*
- * nssArena_Unmark
- *
- * This routine "commits" the indicated mark and any marks after
- * it, making them unreleasable. Note that any earlier marks can
- * still be released, and such a release will invalidate these
- * later unmarked regions. If an arena is to be safely shared by
- * more than one thread, all marks must be either released or
- * unmarked. This routine returns a PRStatus value; if successful,
- * it will return PR_SUCCESS. If unsuccessful, it will set an error
- * on the error stack and return PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- * NSS_ERROR_INVALID_ARENA_MARK
- * NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-
-NSS_EXTERN PRStatus nssArena_Unmark(NSSArena *arena, nssArenaMark *arenaMark);
-
-extern const NSSError NSS_ERROR_INVALID_ARENA;
-extern const NSSError NSS_ERROR_INVALID_ARENA_MARK;
-extern const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD;
-
-#ifdef ARENA_DESTRUCTOR_LIST
-
-/*
- * nssArena_registerDestructor
- *
- * This routine stores a pointer to a callback and an arbitrary
- * pointer-sized argument in the arena, at the current point in
- * the mark stack. If the arena is destroyed, or an "earlier"
- * mark is released, then this destructor will be called at that
- * time. Note that the destructor will be called with the arena
- * locked, which means the destructor may free memory in that
- * arena, but it may not allocate or cause to be allocated any
- * memory. This callback facility was included to support our
- * debug-version pointer-tracker feature; overuse runs counter to
- * the the original intent of arenas. This routine returns a
- * PRStatus value; if successful, it will return PR_SUCCESS. If
- * unsuccessful, it will set an error on the error stack and
- * return PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- * NSS_ERROR_NO_MEMORY
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-
-NSS_EXTERN PRStatus nssArena_registerDestructor(
- NSSArena *arena, void (*destructor)(void *argument), void *arg);
-
-extern const NSSError NSS_ERROR_INVALID_ARENA;
-extern const NSSError NSS_ERROR_NO_MEMORY;
-
-/*
- * nssArena_deregisterDestructor
- *
- * This routine will remove the first destructor in the specified
- * arena which has the specified destructor and argument values.
- * The destructor will not be called. This routine returns a
- * PRStatus value; if successful, it will return PR_SUCCESS. If
- * unsuccessful, it will set an error on the error stack and
- * return PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- * NSS_ERROR_NOT_FOUND
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-
-NSS_EXTERN PRStatus nssArena_deregisterDestructor(
- NSSArena *arena, void (*destructor)(void *argument), void *arg);
-
-extern const NSSError NSS_ERROR_INVALID_ITEM;
-extern const NSSError NSS_ERROR_INVALID_ARENA;
-extern const NSSError NSS_ERROR_NOT_FOUND;
-
-#endif /* ARENA_DESTRUCTOR_LIST */
-
-/*
- * nss_ZAlloc
- *
- * This routine allocates and zeroes a section of memory of the
- * size, and returns to the caller a pointer to that memory. If
- * the optional arena argument is non-null, the memory will be
- * obtained from that arena; otherwise, the memory will be obtained
- * from the heap. This routine may return NULL upon error, in
- * which case it will have set an error upon the error stack. The
- * value specified for size may be zero; in which case a valid
- * zero-length block of memory will be allocated. This block may
- * be expanded by calling nss_ZRealloc.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- * NSS_ERROR_NO_MEMORY
- * NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD
- *
- * Return value:
- * NULL upon error
- * A pointer to the new segment of zeroed memory
- */
-
-NSS_EXTERN void *nss_ZAlloc(NSSArena *arenaOpt, PRUint32 size);
-
-extern const NSSError NSS_ERROR_INVALID_ARENA;
-extern const NSSError NSS_ERROR_NO_MEMORY;
-extern const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD;
-
-/*
- * nss_ZFreeIf
- *
- * If the specified pointer is non-null, then the region of memory
- * to which it points -- which must have been allocated with
- * nss_ZAlloc -- will be zeroed and released. This routine
- * returns a PRStatus value; if successful, it will return PR_SUCCESS.
- * If unsuccessful, it will set an error on the error stack and return
- * PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_POINTER
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-
-NSS_EXTERN PRStatus nss_ZFreeIf(void *pointer);
-
-extern const NSSError NSS_ERROR_INVALID_POINTER;
-
-/*
- * nss_ZRealloc
- *
- * This routine reallocates a block of memory obtained by calling
- * nss_ZAlloc or nss_ZRealloc. The portion of memory
- * between the new and old sizes -- which is either being newly
- * obtained or released -- is in either case zeroed. This routine
- * may return NULL upon failure, in which case it will have placed
- * an error on the error stack.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_POINTER
- * NSS_ERROR_NO_MEMORY
- * NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD
- *
- * Return value:
- * NULL upon error
- * A pointer to the replacement segment of memory
- */
-
-NSS_EXTERN void *nss_ZRealloc(void *pointer, PRUint32 newSize);
-
-extern const NSSError NSS_ERROR_INVALID_POINTER;
-extern const NSSError NSS_ERROR_NO_MEMORY;
-extern const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD;
-
-/*
- * nss_ZNEW
- *
- * This preprocessor macro will allocate memory for a new object
- * of the specified type with nss_ZAlloc, and will cast the
- * return value appropriately. If the optional arena argument is
- * non-null, the memory will be obtained from that arena; otherwise,
- * the memory will be obtained from the heap. This routine may
- * return NULL upon error, in which case it will have set an error
- * upon the error stack.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- * NSS_ERROR_NO_MEMORY
- *
- * Return value:
- * NULL upon error
- * A pointer to the new segment of zeroed memory
- */
-
-#define nss_ZNEW(arenaOpt, type) ((type *)nss_ZAlloc((arenaOpt), sizeof(type)))
-
-/*
- * nss_ZNEWARRAY
- *
- * This preprocessor macro will allocate memory for an array of
- * new objects, and will cast the return value appropriately.
- * If the optional arena argument is non-null, the memory will
- * be obtained from that arena; otherwise, the memory will be
- * obtained from the heap. This routine may return NULL upon
- * error, in which case it will have set an error upon the error
- * stack. The array size may be specified as zero.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- * NSS_ERROR_NO_MEMORY
- *
- * Return value:
- * NULL upon error
- * A pointer to the new segment of zeroed memory
- */
-
-#define nss_ZNEWARRAY(arenaOpt, type, quantity) \
- ((type *)nss_ZAlloc((arenaOpt), sizeof(type) * (quantity)))
-
-/*
- * nss_ZREALLOCARRAY
- *
- * This preprocessor macro will reallocate memory for an array of
- * new objects, and will cast the return value appropriately.
- * This routine may return NULL upon error, in which case it will
- * have set an error upon the error stack.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_POINTER
- * NSS_ERROR_NO_MEMORY
- * NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD
- *
- * Return value:
- * NULL upon error
- * A pointer to the replacement segment of memory
- */
-#define nss_ZREALLOCARRAY(p, type, quantity) \
- ((type *)nss_ZRealloc((p), sizeof(type) * (quantity)))
-
-/*
- * nssArena_verifyPointer
- *
- * This method is only present in debug builds.
- *
- * If the specified pointer is a valid pointer to an NSSArena object,
- * this routine will return PR_SUCCESS. Otherwise, it will put an
- * error on the error stack and return PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_ARENA
- *
- * Return value:
- * PR_SUCCESS if the pointer is valid
- * PR_FAILURE if it isn't
- */
-
-#ifdef DEBUG
-NSS_EXTERN PRStatus nssArena_verifyPointer(const NSSArena *arena);
-
-extern const NSSError NSS_ERROR_INVALID_ARENA;
-#endif /* DEBUG */
-
-/*
- * nssArena_VERIFYPOINTER
- *
- * This macro is always available. In debug builds it will call
- * nssArena_verifyPointer; in non-debug builds, it will merely
- * check that the pointer is not null. Note that in non-debug
- * builds it cannot place an error on the error stack.
- *
- * Return value:
- * PR_SUCCESS if the pointer is valid
- * PR_FAILURE if it isn't
- */
-
-#ifdef DEBUG
-#define nssArena_VERIFYPOINTER(p) nssArena_verifyPointer(p)
-#else /* DEBUG */
-
-#define nssArena_VERIFYPOINTER(p) \
- (((NSSArena *)NULL == (p)) ? PR_FAILURE : PR_SUCCESS)
-#endif /* DEBUG */
-
-/*
- * Private function to be called by NSS_Shutdown to cleanup nssArena
- * bookkeeping.
- */
-extern PRStatus nssArena_Shutdown(void);
-
-/*
- * nssArenaHashAllocOps
- *
- * This constant structure contains allocation callbacks designed for
- * use with the NSPL routine PL_NewHashTable. For example:
- *
- * NSSArena *hashTableArena = nssArena_Create();
- * PLHashTable *t = PL_NewHashTable(n, hasher, key_compare,
- * value_compare, nssArenaHashAllocOps, hashTableArena);
- */
-
-NSS_EXTERN_DATA PLHashAllocOps nssArenaHashAllocOps;
-
-/*
- * The error stack
- *
- * The nonpublic methods relating to the error stack are:
- *
- * nss_SetError
- * nss_ClearErrorStack
- */
-
-/*
- * nss_SetError
- *
- * This routine places a new error code on the top of the calling
- * thread's error stack. Calling this routine wiht an error code
- * of zero will clear the error stack.
- */
-
-NSS_EXTERN void nss_SetError(PRUint32 error);
-
-/*
- * nss_ClearErrorStack
- *
- * This routine clears the calling thread's error stack.
- */
-
-NSS_EXTERN void nss_ClearErrorStack(void);
-
-/*
- * nss_DestroyErrorStack
- *
- * This routine frees the calling thread's error stack.
- */
-
-NSS_EXTERN void nss_DestroyErrorStack(void);
-
-/*
- * NSSItem
- *
- * nssItem_Create
- * nssItem_Duplicate
- * nssItem_Equal
- */
-
-NSS_EXTERN NSSItem *nssItem_Create(NSSArena *arenaOpt, NSSItem *rvOpt,
- PRUint32 length, const void *data);
-
-NSS_EXTERN void nssItem_Destroy(NSSItem *item);
-
-NSS_EXTERN NSSItem *nssItem_Duplicate(NSSItem *obj, NSSArena *arenaOpt,
- NSSItem *rvOpt);
-
-NSS_EXTERN PRBool nssItem_Equal(const NSSItem *one, const NSSItem *two,
- PRStatus *statusOpt);
-
-/*
- * NSSUTF8
- *
- * nssUTF8_CaseIgnoreMatch
- * nssUTF8_Duplicate
- * nssUTF8_Size
- * nssUTF8_Length
- * nssUTF8_CopyIntoFixedBuffer
- */
-
-/*
- * nssUTF8_CaseIgnoreMatch
- *
- * Returns true if the two UTF8-encoded strings pointed to by the
- * two specified NSSUTF8 pointers differ only in typcase.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_POINTER
- *
- * Return value:
- * PR_TRUE if the strings match, ignoring case
- * PR_FALSE if they don't
- * PR_FALSE upon error
- */
-
-NSS_EXTERN PRBool nssUTF8_CaseIgnoreMatch(const NSSUTF8 *a, const NSSUTF8 *b,
- PRStatus *statusOpt);
-
-/*
- * nssUTF8_Duplicate
- *
- * This routine duplicates the UTF8-encoded string pointed to by the
- * specified NSSUTF8 pointer. If the optional arenaOpt argument is
- * not null, the memory required will be obtained from that arena;
- * otherwise, the memory required will be obtained from the heap.
- * A pointer to the new string will be returned. In case of error,
- * an error will be placed on the error stack and NULL will be
- * returned.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_POINTER
- * NSS_ERROR_INVALID_ARENA
- * NSS_ERROR_NO_MEMORY
- */
-
-NSS_EXTERN NSSUTF8 *nssUTF8_Duplicate(const NSSUTF8 *s, NSSArena *arenaOpt);
-
-/*
- * nssUTF8_PrintableMatch
- *
- * Returns true if the two Printable strings pointed to by the
- * two specified NSSUTF8 pointers match when compared with the
- * rules for Printable String (leading and trailing spaces are
- * disregarded, extents of whitespace match irregardless of length,
- * and case is not significant), then PR_TRUE will be returned.
- * Otherwise, PR_FALSE will be returned. Upon failure, PR_FALSE
- * will be returned. If the optional statusOpt argument is not
- * NULL, then PR_SUCCESS or PR_FAILURE will be stored in that
- * location.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_POINTER
- *
- * Return value:
- * PR_TRUE if the strings match, ignoring case
- * PR_FALSE if they don't
- * PR_FALSE upon error
- */
-
-NSS_EXTERN PRBool nssUTF8_PrintableMatch(const NSSUTF8 *a, const NSSUTF8 *b,
- PRStatus *statusOpt);
-
-/*
- * nssUTF8_Size
- *
- * This routine returns the length in bytes (including the terminating
- * null) of the UTF8-encoded string pointed to by the specified
- * NSSUTF8 pointer. Zero is returned on error.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_POINTER
- * NSS_ERROR_VALUE_TOO_LARGE
- *
- * Return value:
- * nonzero size of the string
- * 0 on error
- */
-
-NSS_EXTERN PRUint32 nssUTF8_Size(const NSSUTF8 *s, PRStatus *statusOpt);
-
-extern const NSSError NSS_ERROR_INVALID_POINTER;
-extern const NSSError NSS_ERROR_VALUE_TOO_LARGE;
-
-/*
- * nssUTF8_Length
- *
- * This routine returns the length in characters (not including the
- * terminating null) of the UTF8-encoded string pointed to by the
- * specified NSSUTF8 pointer.
- *
- * The error may be one of the following values:
- * NSS_ERROR_INVALID_POINTER
- * NSS_ERROR_VALUE_TOO_LARGE
- * NSS_ERROR_INVALID_STRING
- *
- * Return value:
- * length of the string (which may be zero)
- * 0 on error
- */
-
-NSS_EXTERN PRUint32 nssUTF8_Length(const NSSUTF8 *s, PRStatus *statusOpt);
-
-extern const NSSError NSS_ERROR_INVALID_POINTER;
-extern const NSSError NSS_ERROR_VALUE_TOO_LARGE;
-extern const NSSError NSS_ERROR_INVALID_STRING;
-
-/*
- * nssUTF8_Create
- *
- * This routine creates a UTF8 string from a string in some other
- * format. Some types of string may include embedded null characters,
- * so for them the length parameter must be used. For string types
- * that are null-terminated, the length parameter is optional; if it
- * is zero, it will be ignored. If the optional arena argument is
- * non-null, the memory used for the new string will be obtained from
- * that arena, otherwise it will be obtained from the heap. This
- * routine may return NULL upon error, in which case it will have
- * placed an error on the error stack.
- *
- * The error may be one of the following:
- * NSS_ERROR_INVALID_POINTER
- * NSS_ERROR_NO_MEMORY
- * NSS_ERROR_UNSUPPORTED_TYPE
- *
- * Return value:
- * NULL upon error
- * A non-null pointer to a new UTF8 string otherwise
- */
-
-NSS_EXTERN NSSUTF8 *nssUTF8_Create(NSSArena *arenaOpt, nssStringType type,
- const void *inputString,
- PRUint32 size /* in bytes, not characters */
- );
-
-extern const NSSError NSS_ERROR_INVALID_POINTER;
-extern const NSSError NSS_ERROR_NO_MEMORY;
-extern const NSSError NSS_ERROR_UNSUPPORTED_TYPE;
-
-NSS_EXTERN NSSItem *nssUTF8_GetEncoding(NSSArena *arenaOpt, NSSItem *rvOpt,
- nssStringType type, NSSUTF8 *string);
-
-/*
- * nssUTF8_CopyIntoFixedBuffer
- *
- * This will copy a UTF8 string into a fixed-length buffer, making
- * sure that the all characters are valid. Any remaining space will
- * be padded with the specified ASCII character, typically either
- * null or space.
- *
- * Blah, blah, blah.
- */
-
-extern const NSSError NSS_ERROR_INVALID_POINTER;
-extern const NSSError NSS_ERROR_INVALID_ARGUMENT;
-
-NSS_EXTERN PRStatus nssUTF8_CopyIntoFixedBuffer(NSSUTF8 *string, char *buffer,
- PRUint32 bufferSize, char pad);
-
-/*
- * nssUTF8_Equal
- *
- */
-
-NSS_EXTERN PRBool nssUTF8_Equal(const NSSUTF8 *a, const NSSUTF8 *b,
- PRStatus *statusOpt);
-
-/*
- * nssList
- *
- * The goal is to provide a simple, optionally threadsafe, linked list
- * class. Since NSS did not seem to use the circularity of PRCList
- * much before, this provides a list that appears to be a linear,
- * NULL-terminated list.
- */
-
-/*
- * nssList_Create
- *
- * If threadsafe is true, the list will be locked during modifications
- * and traversals.
- */
-NSS_EXTERN nssList *nssList_Create(NSSArena *arenaOpt, PRBool threadSafe);
-
-/*
- * nssList_Destroy
- */
-NSS_EXTERN PRStatus nssList_Destroy(nssList *list);
-
-NSS_EXTERN void nssList_Clear(nssList *list,
- nssListElementDestructorFunc destructor);
-
-/*
- * nssList_SetCompareFunction
- *
- * By default, two list elements will be compared by comparing their
- * data pointers. By setting this function, the user can control
- * how elements are compared.
- */
-NSS_EXTERN void nssList_SetCompareFunction(nssList *list,
- nssListCompareFunc compareFunc);
-
-/*
- * nssList_SetSortFunction
- *
- * Sort function to use for an ordered list.
- */
-NSS_EXTERN void nssList_SetSortFunction(nssList *list,
- nssListSortFunc sortFunc);
-
-/*
- * nssList_Add
- */
-NSS_EXTERN PRStatus nssList_Add(nssList *list, void *data);
-
-/*
- * nssList_AddUnique
- *
- * This will use the compare function to see if the element is already
- * in the list.
- */
-NSS_EXTERN PRStatus nssList_AddUnique(nssList *list, void *data);
-
-/*
- * nssList_Remove
- *
- * Uses the compare function to locate the element and remove it.
- */
-NSS_EXTERN PRStatus nssList_Remove(nssList *list, void *data);
-
-/*
- * nssList_Get
- *
- * Uses the compare function to locate an element. Also serves as
- * nssList_Exists.
- */
-NSS_EXTERN void *nssList_Get(nssList *list, void *data);
-
-/*
- * nssList_Count
- */
-NSS_EXTERN PRUint32 nssList_Count(nssList *list);
-
-/*
- * nssList_GetArray
- *
- * Fill rvArray, up to maxElements, with elements in the list. The
- * array is NULL-terminated, so its allocated size must be maxElements + 1.
- */
-NSS_EXTERN PRStatus nssList_GetArray(nssList *list, void **rvArray,
- PRUint32 maxElements);
-
-/*
- * nssList_CreateIterator
- *
- * Create an iterator for list traversal.
- */
-NSS_EXTERN nssListIterator *nssList_CreateIterator(nssList *list);
-
-NSS_EXTERN nssList *nssList_Clone(nssList *list);
-
-/*
- * nssListIterator_Destroy
- */
-NSS_EXTERN void nssListIterator_Destroy(nssListIterator *iter);
-
-/*
- * nssListIterator_Start
- *
- * Begin a list iteration. After this call, if the list is threadSafe,
- * the list is *locked*.
- */
-NSS_EXTERN void *nssListIterator_Start(nssListIterator *iter);
-
-/*
- * nssListIterator_Next
- *
- * Continue a list iteration.
- */
-NSS_EXTERN void *nssListIterator_Next(nssListIterator *iter);
-
-/*
- * nssListIterator_Finish
- *
- * Complete a list iteration. This *must* be called in order for the
- * lock to be released.
- */
-NSS_EXTERN PRStatus nssListIterator_Finish(nssListIterator *iter);
-
-/*
- * nssHash
- *
- * nssHash_Create
- * nssHash_Destroy
- * nssHash_Add
- * nssHash_Remove
- * nssHash_Count
- * nssHash_Exists
- * nssHash_Lookup
- * nssHash_Iterate
- */
-
-/*
- * nssHash_Create
- *
- */
-
-NSS_EXTERN nssHash *nssHash_Create(NSSArena *arenaOpt, PRUint32 numBuckets,
- PLHashFunction keyHash,
- PLHashComparator keyCompare,
- PLHashComparator valueCompare);
-
-NSS_EXTERN nssHash *nssHash_CreatePointer(NSSArena *arenaOpt,
- PRUint32 numBuckets);
-
-NSS_EXTERN nssHash *nssHash_CreateString(NSSArena *arenaOpt,
- PRUint32 numBuckets);
-
-NSS_EXTERN nssHash *nssHash_CreateItem(NSSArena *arenaOpt, PRUint32 numBuckets);
-
-/*
- * nssHash_Destroy
- *
- */
-NSS_EXTERN void nssHash_Destroy(nssHash *hash);
-
-/*
- * nssHash_Add
- *
- */
-
-extern const NSSError NSS_ERROR_HASH_COLLISION;
-
-NSS_EXTERN PRStatus nssHash_Add(nssHash *hash, const void *key,
- const void *value);
-
-/*
- * nssHash_Remove
- *
- */
-NSS_EXTERN void nssHash_Remove(nssHash *hash, const void *it);
-
-/*
- * nssHash_Count
- *
- */
-NSS_EXTERN PRUint32 nssHash_Count(nssHash *hash);
-
-/*
- * nssHash_Exists
- *
- */
-NSS_EXTERN PRBool nssHash_Exists(nssHash *hash, const void *it);
-
-/*
- * nssHash_Lookup
- *
- */
-NSS_EXTERN void *nssHash_Lookup(nssHash *hash, const void *it);
-
-/*
- * nssHash_Iterate
- *
- */
-NSS_EXTERN void nssHash_Iterate(nssHash *hash, nssHashIterator fcn,
- void *closure);
-
-/*
- * nssPointerTracker
- *
- * This type and these methods are only present in debug builds.
- *
- * The nonpublic methods relating to this type are:
- *
- * nssPointerTracker_initialize
- * nssPointerTracker_finalize
- * nssPointerTracker_add
- * nssPointerTracker_remove
- * nssPointerTracker_verify
- */
-
-/*
- * nssPointerTracker_initialize
- *
- * This method is only present in debug builds.
- *
- * This routine initializes an nssPointerTracker object. Note that
- * the object must have been declared *static* to guarantee that it
- * is in a zeroed state initially. This routine is idempotent, and
- * may even be safely called by multiple threads simultaneously with
- * the same argument. This routine returns a PRStatus value; if
- * successful, it will return PR_SUCCESS. On failure it will set an
- * error on the error stack and return PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_NO_MEMORY
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-
-#ifdef DEBUG
-NSS_EXTERN PRStatus nssPointerTracker_initialize(nssPointerTracker *tracker);
-
-extern const NSSError NSS_ERROR_NO_MEMORY;
-#endif /* DEBUG */
-
-/*
- * nssPointerTracker_finalize
- *
- * This method is only present in debug builds.
- *
- * This routine returns the nssPointerTracker object to the pre-
- * initialized state, releasing all resources used by the object.
- * It will *NOT* destroy the objects being tracked by the pointer
- * (should any remain), and therefore cannot be used to "sweep up"
- * remaining objects. This routine returns a PRStatus value; if
- * successful, it will return PR_SUCCES. On failure it will set an
- * error on the error stack and return PR_FAILURE. If any objects
- * remain in the tracker when it is finalized, that will be treated
- * as an error.
- *
- * The error may be one of the following values:
- * NSS_ERROR_TRACKER_NOT_EMPTY
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-
-#ifdef DEBUG
-NSS_EXTERN PRStatus nssPointerTracker_finalize(nssPointerTracker *tracker);
-
-extern const NSSError NSS_ERROR_TRACKER_NOT_EMPTY;
-#endif /* DEBUG */
-
-/*
- * nssPointerTracker_add
- *
- * This method is only present in debug builds.
- *
- * This routine adds the specified pointer to the nssPointerTracker
- * object. It should be called in constructor objects to register
- * new valid objects. The nssPointerTracker is threadsafe, but this
- * call is not idempotent. This routine returns a PRStatus value;
- * if successful it will return PR_SUCCESS. On failure it will set
- * an error on the error stack and return PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_NO_MEMORY
- * NSS_ERROR_TRACKER_NOT_INITIALIZED
- * NSS_ERROR_DUPLICATE_POINTER
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-
-#ifdef DEBUG
-NSS_EXTERN PRStatus nssPointerTracker_add(nssPointerTracker *tracker,
- const void *pointer);
-
-extern const NSSError NSS_ERROR_NO_MEMORY;
-extern const NSSError NSS_ERROR_TRACKER_NOT_INITIALIZED;
-extern const NSSError NSS_ERROR_DUPLICATE_POINTER;
-#endif /* DEBUG */
-
-/*
- * nssPointerTracker_remove
- *
- * This method is only present in debug builds.
- *
- * This routine removes the specified pointer from the
- * nssPointerTracker object. It does not call any destructor for the
- * object; rather, this should be called from the object's destructor.
- * The nssPointerTracker is threadsafe, but this call is not
- * idempotent. This routine returns a PRStatus value; if successful
- * it will return PR_SUCCESS. On failure it will set an error on the
- * error stack and return PR_FAILURE.
- *
- * The error may be one of the following values:
- * NSS_ERROR_TRACKER_NOT_INITIALIZED
- * NSS_ERROR_POINTER_NOT_REGISTERED
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILURE
- */
-
-#ifdef DEBUG
-NSS_EXTERN PRStatus nssPointerTracker_remove(nssPointerTracker *tracker,
- const void *pointer);
-
-extern const NSSError NSS_ERROR_TRACKER_NOT_INITIALIZED;
-extern const NSSError NSS_ERROR_POINTER_NOT_REGISTERED;
-#endif /* DEBUG */
-
-/*
- * nssPointerTracker_verify
- *
- * This method is only present in debug builds.
- *
- * This routine verifies that the specified pointer has been registered
- * with the nssPointerTracker object. The nssPointerTracker object is
- * threadsafe, and this call may be safely called from multiple threads
- * simultaneously with the same arguments. This routine returns a
- * PRStatus value; if the pointer is registered this will return
- * PR_SUCCESS. Otherwise it will set an error on the error stack and
- * return PR_FAILURE. Although the error is suitable for leaving on
- * the stack, callers may wish to augment the information available by
- * placing a more type-specific error on the stack.
- *
- * The error may be one of the following values:
- * NSS_ERROR_POINTER_NOT_REGISTERED
- *
- * Return value:
- * PR_SUCCESS
- * PR_FAILRUE
- */
-
-#ifdef DEBUG
-NSS_EXTERN PRStatus nssPointerTracker_verify(nssPointerTracker *tracker,
- const void *pointer);
-
-extern const NSSError NSS_ERROR_POINTER_NOT_REGISTERED;
-#endif /* DEBUG */
-
-/*
- * libc
- *
- * nsslibc_memcpy
- * nsslibc_memset
- * nsslibc_offsetof
- */
-
-/*
- * nsslibc_memcpy
- *
- * Errors:
- * NSS_ERROR_INVALID_POINTER
- *
- * Return value:
- * NULL on error
- * The destination pointer on success
- */
-
-NSS_EXTERN void *nsslibc_memcpy(void *dest, const void *source, PRUint32 n);
-
-extern const NSSError NSS_ERROR_INVALID_POINTER;
-
-/*
- * nsslibc_memset
- *
- * Errors:
- * NSS_ERROR_INVALID_POINTER
- *
- * Return value:
- * NULL on error
- * The destination pointer on success
- */
-
-NSS_EXTERN void *nsslibc_memset(void *dest, PRUint8 byte, PRUint32 n);
-
-extern const NSSError NSS_ERROR_INVALID_POINTER;
-
-/*
- * nsslibc_memequal
- *
- * Errors:
- * NSS_ERROR_INVALID_POINTER
- *
- * Return value:
- * PR_TRUE if they match
- * PR_FALSE if they don't
- * PR_FALSE upon error
- */
-
-NSS_EXTERN PRBool nsslibc_memequal(const void *a, const void *b, PRUint32 len,
- PRStatus *statusOpt);
-
-extern const NSSError NSS_ERROR_INVALID_POINTER;
-
-#define nsslibc_offsetof(str, memb) ((PRPtrdiff)(&(((str *)0)->memb)))
-
-PR_END_EXTERN_C
-
-#endif /* BASE_H */
diff --git a/nss/lib/base/baset.h b/nss/lib/base/baset.h
deleted file mode 100644
index 3953a75..0000000
--- a/nss/lib/base/baset.h
+++ /dev/null
@@ -1,124 +0,0 @@
-/* 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/. */
-
-#ifndef BASET_H
-#define BASET_H
-
-/*
- * baset.h
- *
- * This file contains definitions for the basic types used throughout
- * nss but not available publicly.
- */
-
-#ifndef NSSBASET_H
-#include "nssbaset.h"
-#endif /* NSSBASET_H */
-
-#include "plhash.h"
-
-PR_BEGIN_EXTERN_C
-
-/*
- * nssArenaMark
- *
- * This type is used to mark the current state of an NSSArena.
- */
-
-struct nssArenaMarkStr;
-typedef struct nssArenaMarkStr nssArenaMark;
-
-#ifdef DEBUG
-/*
- * ARENA_THREADMARK
- *
- * Optionally, this arena implementation can be compiled with some
- * runtime checking enabled, which will catch the situation where
- * one thread "marks" the arena, another thread allocates memory,
- * and then the mark is released. Usually this is a surprise to
- * the second thread, and this leads to weird runtime errors.
- * Define ARENA_THREADMARK to catch these cases; we define it for all
- * (internal and external) debug builds.
- */
-#define ARENA_THREADMARK
-
-/*
- * ARENA_DESTRUCTOR_LIST
- *
- * Unfortunately, our pointer-tracker facility, used in debug
- * builds to agressively fight invalid pointers, requries that
- * pointers be deregistered when objects are destroyed. This
- * conflicts with the standard arena usage where "memory-only"
- * objects (that don't hold onto resources outside the arena)
- * can be allocated in an arena, and never destroyed other than
- * when the arena is destroyed. Therefore we have added a
- * destructor-registratio facility to our arenas. This was not
- * a simple decision, since we're getting ever-further away from
- * the original arena philosophy. However, it was felt that
- * adding this in debug builds wouldn't be so bad; as it would
- * discourage them from being used for "serious" purposes.
- * This facility requires ARENA_THREADMARK to be defined.
- */
-#ifdef ARENA_THREADMARK
-#define ARENA_DESTRUCTOR_LIST
-#endif /* ARENA_THREADMARK */
-
-#endif /* DEBUG */
-
-typedef struct nssListStr nssList;
-typedef struct nssListIteratorStr nssListIterator;
-typedef PRBool (*nssListCompareFunc)(void *a, void *b);
-typedef PRIntn (*nssListSortFunc)(void *a, void *b);
-typedef void (*nssListElementDestructorFunc)(void *el);
-
-typedef struct nssHashStr nssHash;
-typedef void(PR_CALLBACK *nssHashIterator)(const void *key, void *value,
- void *arg);
-
-/*
- * nssPointerTracker
- *
- * This type is used in debug builds (both external and internal) to
- * track our object pointers. Objects of this type must be statically
- * allocated, which means the structure size must be available to the
- * compiler. Therefore we must expose the contents of this structure.
- * But please don't access elements directly; use the accessors.
- */
-
-#ifdef DEBUG
-struct nssPointerTrackerStr {
- PRCallOnceType once;
- PZLock *lock;
- PLHashTable *table;
-};
-typedef struct nssPointerTrackerStr nssPointerTracker;
-#endif /* DEBUG */
-
-/*
- * nssStringType
- *
- * There are several types of strings in the real world. We try to
- * use only UTF8 and avoid the rest, but that's not always possible.
- * So we have a couple converter routines to go to and from the other
- * string types. We have to be able to specify those string types,
- * so we have this enumeration.
- */
-
-enum nssStringTypeEnum {
- nssStringType_DirectoryString,
- nssStringType_TeletexString, /* Not "teletext" with trailing 't' */
- nssStringType_PrintableString,
- nssStringType_UniversalString,
- nssStringType_BMPString,
- nssStringType_UTF8String,
- nssStringType_PHGString,
- nssStringType_GeneralString,
-
- nssStringType_Unknown = -1
-};
-typedef enum nssStringTypeEnum nssStringType;
-
-PR_END_EXTERN_C
-
-#endif /* BASET_H */
diff --git a/nss/lib/base/error.c b/nss/lib/base/error.c
deleted file mode 100644
index ea1d5e3..0000000
--- a/nss/lib/base/error.c
+++ /dev/null
@@ -1,269 +0,0 @@
-/* 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/. */
-
-/*
- * error.c
- *
- * This file contains the code implementing the per-thread error
- * stacks upon which most NSS routines report their errors.
- */
-
-#ifndef BASE_H
-#include "base.h"
-#endif /* BASE_H */
-#include <limits.h> /* for UINT_MAX */
-#include <string.h> /* for memmove */
-
-#define NSS_MAX_ERROR_STACK_COUNT 16 /* error codes */
-
-/*
- * The stack itself has a header, and a sequence of integers.
- * The header records the amount of space (as measured in stack
- * slots) already allocated for the stack, and the count of the
- * number of records currently being used.
- */
-
-struct stack_header_str {
- PRUint16 space;
- PRUint16 count;
-};
-
-struct error_stack_str {
- struct stack_header_str header;
- PRInt32 stack[1];
-};
-typedef struct error_stack_str error_stack;
-
-/*
- * error_stack_index
- *
- * Thread-private data must be indexed. This is that index.
- * See PR_NewThreadPrivateIndex for more information.
- *
- * Thread-private data indexes are in the range [0, 127].
- */
-
-#define INVALID_TPD_INDEX UINT_MAX
-static PRUintn error_stack_index = INVALID_TPD_INDEX;
-
-/*
- * call_once
- *
- * The thread-private index must be obtained (once!) at runtime.
- * This block is used for that one-time call.
- */
-
-static PRCallOnceType error_call_once;
-
-/*
- * error_once_function
- *
- * This is the once-called callback.
- */
-static PRStatus
-error_once_function(void)
-{
- return PR_NewThreadPrivateIndex(&error_stack_index, PR_Free);
-}
-
-/*
- * error_get_my_stack
- *
- * This routine returns the calling thread's error stack, creating
- * it if necessary. It may return NULL upon error, which implicitly
- * means that it ran out of memory.
- */
-
-static error_stack *
-error_get_my_stack(void)
-{
- PRStatus st;
- error_stack *rv;
- PRUintn new_size;
- PRUint32 new_bytes;
- error_stack *new_stack;
-
- if (INVALID_TPD_INDEX == error_stack_index) {
- st = PR_CallOnce(&error_call_once, error_once_function);
- if (PR_SUCCESS != st) {
- return (error_stack *)NULL;
- }
- }
-
- rv = (error_stack *)PR_GetThreadPrivate(error_stack_index);
- if ((error_stack *)NULL == rv) {
- /* Doesn't exist; create one */
- new_size = 16;
- } else if (rv->header.count == rv->header.space &&
- rv->header.count < NSS_MAX_ERROR_STACK_COUNT) {
- /* Too small, expand it */
- new_size = PR_MIN(rv->header.space * 2, NSS_MAX_ERROR_STACK_COUNT);
- } else {
- /* Okay, return it */
- return rv;
- }
-
- new_bytes = (new_size * sizeof(PRInt32)) + sizeof(error_stack);
- /* Use NSPR's calloc/realloc, not NSS's, to avoid loops! */
- new_stack = PR_Calloc(1, new_bytes);
-
- if ((error_stack *)NULL != new_stack) {
- if ((error_stack *)NULL != rv) {
- (void)nsslibc_memcpy(new_stack, rv, rv->header.space);
- }
- new_stack->header.space = new_size;
- }
-
- /* Set the value, whether or not the allocation worked */
- PR_SetThreadPrivate(error_stack_index, new_stack);
- return new_stack;
-}
-
-/*
- * The error stack
- *
- * The public methods relating to the error stack are:
- *
- * NSS_GetError
- * NSS_GetErrorStack
- *
- * The nonpublic methods relating to the error stack are:
- *
- * nss_SetError
- * nss_ClearErrorStack
- *
- */
-
-/*
- * NSS_GetError
- *
- * This routine returns the highest-level (most general) error set
- * by the most recent NSS library routine called by the same thread
- * calling this routine.
- *
- * This routine cannot fail. However, it may return zero, which
- * indicates that the previous NSS library call did not set an error.
- *
- * Return value:
- * 0 if no error has been set
- * A nonzero error number
- */
-
-NSS_IMPLEMENT PRInt32
-NSS_GetError(void)
-{
- error_stack *es = error_get_my_stack();
-
- if ((error_stack *)NULL == es) {
- return NSS_ERROR_NO_MEMORY; /* Good guess! */
- }
-
- if (0 == es->header.count) {
- return 0;
- }
-
- return es->stack[es->header.count - 1];
-}
-
-/*
- * NSS_GetErrorStack
- *
- * This routine returns a pointer to an array of integers, containing
- * the entire sequence or "stack" of errors set by the most recent NSS
- * library routine called by the same thread calling this routine.
- * NOTE: the caller DOES NOT OWN the memory pointed to by the return
- * value. The pointer will remain valid until the calling thread
- * calls another NSS routine. The lowest-level (most specific) error
- * is first in the array, and the highest-level is last. The array is
- * zero-terminated. This routine may return NULL upon error; this
- * indicates a low-memory situation.
- *
- * Return value:
- * NULL upon error, which is an implied NSS_ERROR_NO_MEMORY
- * A NON-caller-owned pointer to an array of integers
- */
-
-NSS_IMPLEMENT PRInt32 *
-NSS_GetErrorStack(void)
-{
- error_stack *es = error_get_my_stack();
-
- if ((error_stack *)NULL == es) {
- return (PRInt32 *)NULL;
- }
-
- /* Make sure it's terminated */
- es->stack[es->header.count] = 0;
-
- return es->stack;
-}
-
-/*
- * nss_SetError
- *
- * This routine places a new error code on the top of the calling
- * thread's error stack. Calling this routine wiht an error code
- * of zero will clear the error stack.
- */
-
-NSS_IMPLEMENT void
-nss_SetError(PRUint32 error)
-{
- error_stack *es;
-
- if (0 == error) {
- nss_ClearErrorStack();
- return;
- }
-
- es = error_get_my_stack();
- if ((error_stack *)NULL == es) {
- /* Oh, well. */
- return;
- }
-
- if (es->header.count < es->header.space) {
- es->stack[es->header.count++] = error;
- } else {
- memmove(es->stack, es->stack + 1,
- (es->header.space - 1) * (sizeof es->stack[0]));
- es->stack[es->header.space - 1] = error;
- }
- return;
-}
-
-/*
- * nss_ClearErrorStack
- *
- * This routine clears the calling thread's error stack.
- */
-
-NSS_IMPLEMENT void
-nss_ClearErrorStack(void)
-{
- error_stack *es = error_get_my_stack();
- if ((error_stack *)NULL == es) {
- /* Oh, well. */
- return;
- }
-
- es->header.count = 0;
- es->stack[0] = 0;
- return;
-}
-
-/*
- * nss_DestroyErrorStack
- *
- * This routine frees the calling thread's error stack.
- */
-
-NSS_IMPLEMENT void
-nss_DestroyErrorStack(void)
-{
- if (INVALID_TPD_INDEX != error_stack_index) {
- PR_SetThreadPrivate(error_stack_index, NULL);
- }
- return;
-}
diff --git a/nss/lib/base/errorval.c b/nss/lib/base/errorval.c
deleted file mode 100644
index b7045a3..0000000
--- a/nss/lib/base/errorval.c
+++ /dev/null
@@ -1,65 +0,0 @@
-/* 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/. */
-
-/*
- * errorval.c
- *
- * This file contains the actual error constants used in NSS.
- */
-
-#ifndef NSSBASET_H
-#include "nssbaset.h"
-#endif /* NSSBASET_H */
-
-/* clang-format off */
-
-const NSSError NSS_ERROR_NO_ERROR = 0;
-const NSSError NSS_ERROR_INTERNAL_ERROR = 1;
-const NSSError NSS_ERROR_NO_MEMORY = 2;
-const NSSError NSS_ERROR_INVALID_POINTER = 3;
-const NSSError NSS_ERROR_INVALID_ARENA = 4;
-const NSSError NSS_ERROR_INVALID_ARENA_MARK = 5;
-const NSSError NSS_ERROR_DUPLICATE_POINTER = 6;
-const NSSError NSS_ERROR_POINTER_NOT_REGISTERED = 7;
-const NSSError NSS_ERROR_TRACKER_NOT_EMPTY = 8;
-const NSSError NSS_ERROR_TRACKER_NOT_INITIALIZED = 9;
-const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD = 10;
-const NSSError NSS_ERROR_VALUE_TOO_LARGE = 11;
-const NSSError NSS_ERROR_UNSUPPORTED_TYPE = 12;
-const NSSError NSS_ERROR_BUFFER_TOO_SHORT = 13;
-const NSSError NSS_ERROR_INVALID_ATOB_CONTEXT = 14;
-const NSSError NSS_ERROR_INVALID_BASE64 = 15;
-const NSSError NSS_ERROR_INVALID_BTOA_CONTEXT = 16;
-const NSSError NSS_ERROR_INVALID_ITEM = 17;
-const NSSError NSS_ERROR_INVALID_STRING = 18;
-const NSSError NSS_ERROR_INVALID_ASN1ENCODER = 19;
-const NSSError NSS_ERROR_INVALID_ASN1DECODER = 20;
-
-const NSSError NSS_ERROR_INVALID_BER = 21;
-const NSSError NSS_ERROR_INVALID_ATAV = 22;
-const NSSError NSS_ERROR_INVALID_ARGUMENT = 23;
-const NSSError NSS_ERROR_INVALID_UTF8 = 24;
-const NSSError NSS_ERROR_INVALID_NSSOID = 25;
-const NSSError NSS_ERROR_UNKNOWN_ATTRIBUTE = 26;
-
-const NSSError NSS_ERROR_NOT_FOUND = 27;
-
-const NSSError NSS_ERROR_INVALID_PASSWORD = 28;
-const NSSError NSS_ERROR_USER_CANCELED = 29;
-
-const NSSError NSS_ERROR_MAXIMUM_FOUND = 30;
-
-const NSSError NSS_ERROR_CERTIFICATE_ISSUER_NOT_FOUND = 31;
-
-const NSSError NSS_ERROR_CERTIFICATE_IN_CACHE = 32;
-
-const NSSError NSS_ERROR_HASH_COLLISION = 33;
-const NSSError NSS_ERROR_DEVICE_ERROR = 34;
-const NSSError NSS_ERROR_INVALID_CERTIFICATE = 35;
-const NSSError NSS_ERROR_BUSY = 36;
-const NSSError NSS_ERROR_ALREADY_INITIALIZED = 37;
-
-const NSSError NSS_ERROR_PKCS11 = 38;
-
-/* clang-format on */
\ No newline at end of file
diff --git a/nss/lib/base/hash.c b/nss/lib/base/hash.c
deleted file mode 100644
index f9ee758..0000000
--- a/nss/lib/base/hash.c
+++ /dev/null
@@ -1,314 +0,0 @@
-/* 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/. */
-
-/*
- * hash.c
- *
- * This is merely a couple wrappers around NSPR's PLHashTable, using
- * the identity hash and arena-aware allocators.
- * This is a copy of ckfw/hash.c, with modifications to