1 /* ***** BEGIN LICENSE BLOCK *****
2 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
4 * The contents of this file are subject to the Mozilla Public License Version
5 * 1.1 (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 * http://www.mozilla.org/MPL/
9 * Software distributed under the License is distributed on an "AS IS" basis,
10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11 * for the specific language governing rights and limitations under the
14 * The Original Code is the Netscape security libraries.
16 * The Initial Developer of the Original Code is
17 * Netscape Communications Corporation.
18 * Portions created by the Initial Developer are Copyright (C) 1994-2000
19 * the Initial Developer. All Rights Reserved.
23 * Alternatively, the contents of this file may be used under the terms of
24 * either the GNU General Public License Version 2 or later (the "GPL"), or
25 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
26 * in which case the provisions of the GPL or the LGPL are applicable instead
27 * of those above. If you wish to allow use of your version of this file only
28 * under the terms of either the GPL or the LGPL, and not to allow others to
29 * use your version of this file under the terms of the MPL, indicate your
30 * decision by deleting the provisions above and replace them with the notice
31 * and other provisions required by the GPL or the LGPL. If you do not delete
32 * the provisions above, a recipient may use your version of this file under
33 * the terms of any one of the MPL, the GPL or the LGPL.
35 * ***** END LICENSE BLOCK ***** */
38 * secport.c - portability interfaces for security libraries
40 * This file abstracts out libc functionality that libsec depends on
42 * NOTE - These are not public interfaces
44 * $Id: secport.c,v 1.29 2010/03/28 20:46:37 nelson%bolyard.com Exp $
63 #endif /* THREADMARK */
65 #if defined(XP_UNIX) || defined(XP_OS2) || defined(XP_BEOS)
71 #define SET_ERROR_CODE /* place holder for code to set PR error code. */
74 typedef struct threadmark_mark_str {
75 struct threadmark_mark_str *next;
79 #endif /* THREADMARK */
81 /* The value of this magic must change each time PORTArenaPool changes. */
82 #define ARENAPOOL_MAGIC 0xB8AC9BDF
84 typedef struct PORTArenaPool_str {
89 PRThread *marking_thread;
90 threadmark_mark *first_mark;
95 /* count of allocation failures. */
96 unsigned long port_allocFailures;
98 /* locations for registering Unicode conversion functions.
99 * XXX is this the appropriate location? or should they be
100 * moved to client/server specific locations?
102 PORTCharConversionFunc ucs4Utf8ConvertFunc;
103 PORTCharConversionFunc ucs2Utf8ConvertFunc;
104 PORTCharConversionWSwapFunc ucs2AsciiConvertFunc;
107 PORT_Alloc(size_t bytes)
111 /* Always allocate a non-zero amount of bytes */
112 rv = (void *)PR_Malloc(bytes ? bytes : 1);
114 ++port_allocFailures;
115 PORT_SetError(SEC_ERROR_NO_MEMORY);
121 PORT_Realloc(void *oldptr, size_t bytes)
125 rv = (void *)PR_Realloc(oldptr, bytes);
127 ++port_allocFailures;
128 PORT_SetError(SEC_ERROR_NO_MEMORY);
134 PORT_ZAlloc(size_t bytes)
138 /* Always allocate a non-zero amount of bytes */
139 rv = (void *)PR_Calloc(1, bytes ? bytes : 1);
141 ++port_allocFailures;
142 PORT_SetError(SEC_ERROR_NO_MEMORY);
156 PORT_ZFree(void *ptr, size_t len)
165 PORT_Strdup(const char *str)
167 size_t len = PORT_Strlen(str)+1;
170 newstr = (char *)PORT_Alloc(len);
172 PORT_Memcpy(newstr, str, len);
178 PORT_SetError(int value)
181 PORT_Assert(value != SEC_ERROR_REUSED_ISSUER_AND_SERIAL);
183 PR_SetError(value, 0);
190 return(PR_GetError());
193 /********************* Arena code follows *****************************
194 * ArenaPools are like heaps. The memory in them consists of large blocks,
195 * called arenas, which are allocated from the/a system heap. Inside an
196 * ArenaPool, the arenas are organized as if they were in a stack. Newly
197 * allocated arenas are "pushed" on that stack. When you attempt to
198 * allocate memory from an ArenaPool, the code first looks to see if there
199 * is enough unused space in the top arena on the stack to satisfy your
200 * request, and if so, your request is satisfied from that arena.
201 * Otherwise, a new arena is allocated (or taken from NSPR's list of freed
202 * arenas) and pushed on to the stack. The new arena is always big enough
203 * to satisfy the request, and is also at least a minimum size that is
204 * established at the time that the ArenaPool is created.
206 * The ArenaMark function returns the address of a marker in the arena at
207 * the top of the arena stack. It is the address of the place in the arena
208 * on the top of the arena stack from which the next block of memory will
209 * be allocated. Each ArenaPool has its own separate stack, and hence
210 * marks are only relevant to the ArenaPool from which they are gotten.
211 * Marks may be nested. That is, a thread can get a mark, and then get
214 * It is intended that all the marks in an ArenaPool may only be owned by a
215 * single thread. In DEBUG builds, this is enforced. In non-DEBUG builds,
216 * it is not. In DEBUG builds, when a thread gets a mark from an
217 * ArenaPool, no other thread may acquire a mark in that ArenaPool while
218 * that mark exists, that is, until that mark is unmarked or released.
219 * Therefore, it is important that every mark be unmarked or released when
220 * the creating thread has no further need for exclusive ownership of the
221 * right to manage the ArenaPool.
223 * The ArenaUnmark function discards the ArenaMark at the address given,
224 * and all marks nested inside that mark (that is, acquired from that same
225 * ArenaPool while that mark existed). It is an error for a thread other
226 * than the mark's creator to try to unmark it. When a thread has unmarked
227 * all its marks from an ArenaPool, then another thread is able to set
228 * marks in that ArenaPool. ArenaUnmark does not deallocate (or "pop") any
229 * memory allocated from the ArenaPool since the mark was created.
231 * ArenaRelease "pops" the stack back to the mark, deallocating all the
232 * memory allocated from the arenas in the ArenaPool since that mark was
233 * created, and removing any arenas from the ArenaPool that have no
234 * remaining active allocations when that is done. It implicitly releases
235 * any marks nested inside the mark being explicitly released. It is the
236 * only operation, other than destroying the arenapool, that potentially
237 * reduces the number of arenas on the stack. Otherwise, the stack grows
238 * until the arenapool is destroyed, at which point all the arenas are
239 * freed or returned to a "free arena list", depending on their sizes.
242 PORT_NewArena(unsigned long chunksize)
246 pool = PORT_ZNew(PORTArenaPool);
250 pool->magic = ARENAPOOL_MAGIC;
251 pool->lock = PZ_NewLock(nssILockArena);
253 ++port_allocFailures;
257 PL_InitArenaPool(&pool->arena, "security", chunksize, sizeof(double));
258 return(&pool->arena);
261 #define MAX_SIZE 0x7fffffffUL
264 PORT_ArenaAlloc(PLArenaPool *arena, size_t size)
268 PORTArenaPool *pool = (PORTArenaPool *)arena;
274 if (size > MAX_SIZE) {
277 /* Is it one of ours? Assume so and check the magic */
278 if (ARENAPOOL_MAGIC == pool->magic ) {
281 /* Most likely one of ours. Is there a thread id? */
282 if (pool->marking_thread &&
283 pool->marking_thread != PR_GetCurrentThread() ) {
284 /* Another thread holds a mark in this arena */
285 PZ_Unlock(pool->lock);
286 PORT_SetError(SEC_ERROR_NO_MEMORY);
290 #endif /* THREADMARK */
291 PL_ARENA_ALLOCATE(p, arena, size);
292 PZ_Unlock(pool->lock);
294 PL_ARENA_ALLOCATE(p, arena, size);
298 ++port_allocFailures;
299 PORT_SetError(SEC_ERROR_NO_MEMORY);
306 PORT_ArenaZAlloc(PLArenaPool *arena, size_t size)
313 p = PORT_ArenaAlloc(arena, size);
316 PORT_Memset(p, 0, size);
323 * If zero is true, zeroize the arena memory before freeing it.
326 PORT_FreeArena(PLArenaPool *arena, PRBool zero)
328 PORTArenaPool *pool = (PORTArenaPool *)arena;
329 PRLock * lock = (PRLock *)0;
330 size_t len = sizeof *arena;
331 static PRBool checkedEnv = PR_FALSE;
332 static PRBool doFreeArenaPool = PR_FALSE;
336 if (ARENAPOOL_MAGIC == pool->magic ) {
342 /* no need for thread protection here */
343 doFreeArenaPool = (PR_GetEnv("NSS_DISABLE_ARENA_FREE_LIST") == NULL);
344 checkedEnv = PR_TRUE;
347 PL_ClearArenaPool(arena, 0);
349 if (doFreeArenaPool) {
350 PL_FreeArenaPool(arena);
352 PL_FinishArenaPool(arena);
354 PORT_ZFree(arena, len);
357 PZ_DestroyLock(lock);
362 PORT_ArenaGrow(PLArenaPool *arena, void *ptr, size_t oldsize, size_t newsize)
364 PORTArenaPool *pool = (PORTArenaPool *)arena;
365 PORT_Assert(newsize >= oldsize);
367 if (ARENAPOOL_MAGIC == pool->magic ) {
369 /* Do we do a THREADMARK check here? */
370 PL_ARENA_GROW(ptr, arena, oldsize, ( newsize - oldsize ) );
371 PZ_Unlock(pool->lock);
373 PL_ARENA_GROW(ptr, arena, oldsize, ( newsize - oldsize ) );
380 PORT_ArenaMark(PLArenaPool *arena)
384 PORTArenaPool *pool = (PORTArenaPool *)arena;
385 if (ARENAPOOL_MAGIC == pool->magic ) {
389 threadmark_mark *tm, **pw;
390 PRThread * currentThread = PR_GetCurrentThread();
392 if (! pool->marking_thread ) {
394 pool->marking_thread = currentThread;
395 } else if (currentThread != pool->marking_thread ) {
396 PZ_Unlock(pool->lock);
397 PORT_SetError(SEC_ERROR_NO_MEMORY);
402 result = PL_ARENA_MARK(arena);
403 PL_ARENA_ALLOCATE(tm, arena, sizeof(threadmark_mark));
405 PZ_Unlock(pool->lock);
406 PORT_SetError(SEC_ERROR_NO_MEMORY);
411 tm->next = (threadmark_mark *)NULL;
413 pw = &pool->first_mark;
420 #else /* THREADMARK */
421 result = PL_ARENA_MARK(arena);
422 #endif /* THREADMARK */
423 PZ_Unlock(pool->lock);
425 /* a "pure" NSPR arena */
426 result = PL_ARENA_MARK(arena);
432 port_ArenaZeroAfterMark(PLArenaPool *arena, void *mark)
434 PLArena *a = arena->current;
435 if (a->base <= (PRUword)mark && (PRUword)mark <= a->avail) {
436 /* fast path: mark falls in the current arena */
437 memset(mark, 0, a->avail - (PRUword)mark);
439 /* slow path: need to find the arena that mark falls in */
440 for (a = arena->first.next; a; a = a->next) {
441 PR_ASSERT(a->base <= a->avail && a->avail <= a->limit);
442 if (a->base <= (PRUword)mark && (PRUword)mark <= a->avail) {
443 memset(mark, 0, a->avail - (PRUword)mark);
448 for (; a; a = a->next) {
449 PR_ASSERT(a->base <= a->avail && a->avail <= a->limit);
450 memset((void *)a->base, 0, a->avail - a->base);
456 port_ArenaRelease(PLArenaPool *arena, void *mark, PRBool zero)
458 PORTArenaPool *pool = (PORTArenaPool *)arena;
459 if (ARENAPOOL_MAGIC == pool->magic ) {
463 threadmark_mark **pw, *tm;
465 if (PR_GetCurrentThread() != pool->marking_thread ) {
466 PZ_Unlock(pool->lock);
467 PORT_SetError(SEC_ERROR_NO_MEMORY);
469 return /* no error indication available */ ;
472 pw = &pool->first_mark;
473 while( *pw && (mark != (*pw)->mark) ) {
479 PZ_Unlock(pool->lock);
480 PORT_SetError(SEC_ERROR_NO_MEMORY);
482 return /* no error indication available */ ;
486 *pw = (threadmark_mark *)NULL;
489 port_ArenaZeroAfterMark(arena, mark);
491 PL_ARENA_RELEASE(arena, mark);
493 if (! pool->first_mark ) {
494 pool->marking_thread = (PRThread *)NULL;
497 #else /* THREADMARK */
499 port_ArenaZeroAfterMark(arena, mark);
501 PL_ARENA_RELEASE(arena, mark);
502 #endif /* THREADMARK */
503 PZ_Unlock(pool->lock);
506 port_ArenaZeroAfterMark(arena, mark);
508 PL_ARENA_RELEASE(arena, mark);
513 PORT_ArenaRelease(PLArenaPool *arena, void *mark)
515 port_ArenaRelease(arena, mark, PR_FALSE);
519 * Zeroize the arena memory before releasing it.
522 PORT_ArenaZRelease(PLArenaPool *arena, void *mark)
524 port_ArenaRelease(arena, mark, PR_TRUE);
528 PORT_ArenaUnmark(PLArenaPool *arena, void *mark)
531 PORTArenaPool *pool = (PORTArenaPool *)arena;
532 if (ARENAPOOL_MAGIC == pool->magic ) {
533 threadmark_mark **pw, *tm;
537 if (PR_GetCurrentThread() != pool->marking_thread ) {
538 PZ_Unlock(pool->lock);
539 PORT_SetError(SEC_ERROR_NO_MEMORY);
541 return /* no error indication available */ ;
544 pw = &pool->first_mark;
545 while( ((threadmark_mark *)NULL != *pw) && (mark != (*pw)->mark) ) {
549 if ((threadmark_mark *)NULL == *pw ) {
551 PZ_Unlock(pool->lock);
552 PORT_SetError(SEC_ERROR_NO_MEMORY);
554 return /* no error indication available */ ;
558 *pw = (threadmark_mark *)NULL;
560 if (! pool->first_mark ) {
561 pool->marking_thread = (PRThread *)NULL;
564 PZ_Unlock(pool->lock);
566 #endif /* THREADMARK */
570 PORT_ArenaStrdup(PLArenaPool *arena, const char *str) {
571 int len = PORT_Strlen(str)+1;
574 newstr = (char*)PORT_ArenaAlloc(arena,len);
576 PORT_Memcpy(newstr,str,len);
581 /********************** end of arena functions ***********************/
583 /****************** unicode conversion functions ***********************/
585 * NOTE: These conversion functions all assume that the multibyte
586 * characters are going to be in NETWORK BYTE ORDER, not host byte
587 * order. This is because the only time we deal with UCS-2 and UCS-4
588 * are when the data was received from or is going to be sent out
589 * over the wire (in, e.g. certificates).
593 PORT_SetUCS4_UTF8ConversionFunction(PORTCharConversionFunc convFunc)
595 ucs4Utf8ConvertFunc = convFunc;
599 PORT_SetUCS2_ASCIIConversionFunction(PORTCharConversionWSwapFunc convFunc)
601 ucs2AsciiConvertFunc = convFunc;
605 PORT_SetUCS2_UTF8ConversionFunction(PORTCharConversionFunc convFunc)
607 ucs2Utf8ConvertFunc = convFunc;
611 PORT_UCS4_UTF8Conversion(PRBool toUnicode, unsigned char *inBuf,
612 unsigned int inBufLen, unsigned char *outBuf,
613 unsigned int maxOutBufLen, unsigned int *outBufLen)
615 if(!ucs4Utf8ConvertFunc) {
616 return sec_port_ucs4_utf8_conversion_function(toUnicode,
617 inBuf, inBufLen, outBuf, maxOutBufLen, outBufLen);
620 return (*ucs4Utf8ConvertFunc)(toUnicode, inBuf, inBufLen, outBuf,
621 maxOutBufLen, outBufLen);
625 PORT_UCS2_UTF8Conversion(PRBool toUnicode, unsigned char *inBuf,
626 unsigned int inBufLen, unsigned char *outBuf,
627 unsigned int maxOutBufLen, unsigned int *outBufLen)
629 if(!ucs2Utf8ConvertFunc) {
630 return sec_port_ucs2_utf8_conversion_function(toUnicode,
631 inBuf, inBufLen, outBuf, maxOutBufLen, outBufLen);
634 return (*ucs2Utf8ConvertFunc)(toUnicode, inBuf, inBufLen, outBuf,
635 maxOutBufLen, outBufLen);
639 PORT_ISO88591_UTF8Conversion(const unsigned char *inBuf,
640 unsigned int inBufLen, unsigned char *outBuf,
641 unsigned int maxOutBufLen, unsigned int *outBufLen)
643 return sec_port_iso88591_utf8_conversion_function(inBuf, inBufLen,
644 outBuf, maxOutBufLen, outBufLen);
648 PORT_UCS2_ASCIIConversion(PRBool toUnicode, unsigned char *inBuf,
649 unsigned int inBufLen, unsigned char *outBuf,
650 unsigned int maxOutBufLen, unsigned int *outBufLen,
653 if(!ucs2AsciiConvertFunc) {
657 return (*ucs2AsciiConvertFunc)(toUnicode, inBuf, inBufLen, outBuf,
658 maxOutBufLen, outBufLen, swapBytes);
662 /* Portable putenv. Creates/replaces an environment variable of the form
663 * envVarName=envValue
666 NSS_PutEnv(const char * envVarName, const char * envValue)
671 SECStatus result = SECSuccess;
677 setOK = SetEnvironmentVariable(envVarName, envValue);
684 encoded = (char *)PORT_ZAlloc(strlen(envVarName) + 2 + strlen(envValue));
685 strcpy(encoded, envVarName);
686 strcat(encoded, "=");
687 strcat(encoded, envValue);
689 putEnvFailed = putenv(encoded); /* adopt. */
700 * Perform a constant-time compare of two memory regions. The return value is
701 * 0 if the memory regions are equal and non-zero otherwise.
704 NSS_SecureMemcmp(const void *ia, const void *ib, size_t n)
706 const unsigned char *a = (const unsigned char*) ia;
707 const unsigned char *b = (const unsigned char*) ib;
711 for (i = 0; i < n; ++i) {