cryptlib.c revision 160814
16562Sphk/* crypto/cryptlib.c */
237421Scharnier/* ====================================================================
36562Sphk * Copyright (c) 1998-2003 The OpenSSL Project.  All rights reserved.
46562Sphk *
53995Spst * Redistribution and use in source and binary forms, with or without
63995Spst * modification, are permitted provided that the following conditions
76562Sphk * are met:
86562Sphk *
96562Sphk * 1. Redistributions of source code must retain the above copyright
106562Sphk *    notice, this list of conditions and the following disclaimer.
116562Sphk *
126562Sphk * 2. Redistributions in binary form must reproduce the above copyright
136562Sphk *    notice, this list of conditions and the following disclaimer in
146562Sphk *    the documentation and/or other materials provided with the
156562Sphk *    distribution.
166562Sphk *
176562Sphk * 3. All advertising materials mentioning features or use of this
183995Spst *    software must display the following acknowledgment:
193995Spst *    "This product includes software developed by the OpenSSL Project
20114589Sobrien *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
21114589Sobrien *
2237421Scharnier * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
2319168Sbde *    endorse or promote products derived from this software without
24110840Ssilby *    prior written permission. For written permission, please contact
25110840Ssilby *    openssl-core@openssl.org.
2637421Scharnier *
2719168Sbde * 5. Products derived from this software may not be called "OpenSSL"
28130351Seik *    nor may "OpenSSL" appear in their names without prior written
29130351Seik *    permission of the OpenSSL Project.
30143334Scperciva *
313995Spst * 6. Redistributions of any form whatsoever must retain the following
3278949Sdes *    acknowledgment:
3378949Sdes *    "This product includes software developed by the OpenSSL Project
343995Spst *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
3532074Ssteve *
3619168Sbde * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
376562Sphk * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
386562Sphk * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
393995Spst * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
4046226Skris * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
4146226Skris * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42130351Seik * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
433995Spst * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4454109Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
4552949Sobrien * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
4688226Sphk * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47229680Seadler * OF THE POSSIBILITY OF SUCH DAMAGE.
48229680Seadler * ====================================================================
4952949Sobrien *
50130351Seik * This product includes cryptographic software written by Eric Young
51130351Seik * (eay@cryptsoft.com).  This product includes software written by Tim
52130351Seik * Hudson (tjh@cryptsoft.com).
533995Spst *
54130351Seik */
55130351Seik/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
56143334Scperciva * All rights reserved.
57130351Seik *
58130351Seik * This package is an SSL implementation written
59130351Seik * by Eric Young (eay@cryptsoft.com).
60130351Seik * The implementation was written so as to conform with Netscapes SSL.
61130351Seik *
62130351Seik * This library is free for commercial and non-commercial use as long as
63130351Seik * the following conditions are aheared to.  The following conditions
64130351Seik * apply to all code found in this distribution, be it the RC4, RSA,
65130351Seik * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
66154479Sphk * included with this distribution is covered by the same copyright terms
67130351Seik * except that the holder is Tim Hudson (tjh@cryptsoft.com).
68130351Seik *
69130351Seik * Copyright remains Eric Young's, and as such any Copyright notices in
70130351Seik * the code are not to be removed.
71130351Seik * If this package is used in a product, Eric Young should be given attribution
72130351Seik * as the author of the parts of the library used.
73130351Seik * This can be in the form of a textual message at program startup or
74130351Seik * in documentation (online or textual) provided with the package.
75130351Seik *
76130351Seik * Redistribution and use in source and binary forms, with or without
77130351Seik * modification, are permitted provided that the following conditions
78130351Seik * are met:
79130351Seik * 1. Redistributions of source code must retain the copyright
80143334Scperciva *    notice, this list of conditions and the following disclaimer.
81130351Seik * 2. Redistributions in binary form must reproduce the above copyright
82130351Seik *    notice, this list of conditions and the following disclaimer in the
83130351Seik *    documentation and/or other materials provided with the distribution.
84176095Sobrien * 3. All advertising materials mentioning features or use of this software
85143334Scperciva *    must display the following acknowledgement:
86143334Scperciva *    "This product includes cryptographic software written by
87130351Seik *     Eric Young (eay@cryptsoft.com)"
88130351Seik *    The word 'cryptographic' can be left out if the rouines from the library
89130351Seik *    being used are not cryptographic related :-).
90130351Seik * 4. If you include any Windows specific code (or a derivative thereof) from
91130351Seik *    the apps directory (application code) you must include an acknowledgement:
92130351Seik *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
93130351Seik *
94130351Seik * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
95130351Seik * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
96130351Seik * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
97143334Scperciva * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
98143334Scperciva * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
99143334Scperciva * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
100130351Seik * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
101130351Seik * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
102130351Seik * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
103130351Seik * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
104130351Seik * SUCH DAMAGE.
105130351Seik *
106130351Seik * The licence and distribution terms for any publically available version or
107130351Seik * derivative of this code cannot be changed.  i.e. this code cannot simply be
108130351Seik * copied and put under another distribution licence
109130351Seik * [including the GNU Public Licence.]
110130351Seik */
1113995Spst/* ====================================================================
1123995Spst * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
1133995Spst * ECDH support in OpenSSL originally developed by
1143995Spst * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
1153995Spst */
1163995Spst
1173995Spst#include "cryptlib.h"
1183995Spst#include <openssl/safestack.h>
1193995Spst
1206562Sphk#if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16)
12176988Srustatic double SSLeay_MSVC5_hack=0.0; /* and for VC1.5 */
1223995Spst#endif
123176095Sobrien
1246562SphkDECLARE_STACK_OF(CRYPTO_dynlock)
125130351SeikIMPLEMENT_STACK_OF(CRYPTO_dynlock)
126176095Sobrien
127130351Seik/* real #defines in crypto.h, keep these upto date */
128130351Seikstatic const char* lock_names[CRYPTO_NUM_LOCKS] =
129176095Sobrien	{
130130351Seik	"<<ERROR>>",
131130351Seik	"err",
132130351Seik	"ex_data",
133130351Seik	"x509",
134176095Sobrien	"x509_info",
135130351Seik	"x509_pkey",
136130351Seik	"x509_crl",
137130351Seik	"x509_req",
138176095Sobrien	"dsa",
139130918Seik	"rsa",
140130351Seik	"evp_pkey",
1413995Spst	"x509_store",
142121914Sse	"ssl_ctx",
143229680Seadler	"ssl_cert",
144229680Seadler	"ssl_session",
145229680Seadler	"ssl_sess_cert",
14676988Sru	"ssl",
147229680Seadler	"ssl_method",
148229680Seadler	"rand",
149229680Seadler	"rand2",
15076988Sru	"debug_malloc",
151130351Seik	"BIO",
15276988Sru	"gethostbyname",
15376988Sru	"getservbyname",
15476988Sru	"readdir",
15576988Sru	"RSA_blinding",
15676988Sru	"dh",
15776988Sru	"debug_malloc2",
15876988Sru	"dso",
15976988Sru	"dynlock",
16088226Sphk	"engine",
161130351Seik	"ui",
16276988Sru	"ecdsa",
16376988Sru	"ec",
164130351Seik	"ecdh",
16576988Sru	"bn",
16676988Sru	"ec_pre_comp",
167130351Seik	"store",
16876988Sru	"comp",
16976988Sru#if CRYPTO_NUM_LOCKS != 39
170130351Seik# error "Inconsistency between crypto.h and cryptlib.c"
17132074Ssteve#endif
17276988Sru	};
17376988Sru
17476988Sru/* This is for applications to allocate new type names in the non-dynamic
17576988Sru   array of lock names.  These are numbered with positive numbers.  */
17676988Srustatic STACK *app_locks=NULL;
177130351Seik
178121914Sse/* For applications that want a more dynamic way of handling threads, the
17976988Sru   following stack is used.  These are externally numbered with negative
180121914Sse   numbers.  */
181121914Ssestatic STACK_OF(CRYPTO_dynlock) *dyn_locks=NULL;
18254109Sobrien
183229680Seadler
18454109Sobrienstatic void (MS_FAR *locking_callback)(int mode,int type,
185229680Seadler	const char *file,int line)=NULL;
18652949Sobrienstatic int (MS_FAR *add_lock_callback)(int *pointer,int amount,
187229680Seadler	int type,const char *file,int line)=NULL;
188176095Sobrienstatic unsigned long (MS_FAR *id_callback)(void)=NULL;
189229680Seadlerstatic struct CRYPTO_dynlock_value *(MS_FAR *dynlock_create_callback)
190229680Seadler	(const char *file,int line)=NULL;
191229680Seadlerstatic void (MS_FAR *dynlock_lock_callback)(int mode,
192229680Seadler	struct CRYPTO_dynlock_value *l, const char *file,int line)=NULL;
193229680Seadlerstatic void (MS_FAR *dynlock_destroy_callback)(struct CRYPTO_dynlock_value *l,
194229680Seadler	const char *file,int line)=NULL;
195229680Seadler
196121914Sseint CRYPTO_get_new_lockid(char *name)
19776988Sru	{
19888226Sphk	char *str;
199130351Seik	int i;
2003995Spst
201121914Sse#if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16)
202121914Sse	/* A hack to make Visual C++ 5.0 work correctly when linking as
203229680Seadler	 * a DLL using /MT. Without this, the application cannot use
204229680Seadler	 * and floating point printf's.
205176095Sobrien	 * It also seems to be needed for Visual C 1.5 (win16) */
2066562Sphk	SSLeay_MSVC5_hack=(double)name[0]*(double)name[1];
2073995Spst#endif
2086562Sphk
2096562Sphk	if ((app_locks == NULL) && ((app_locks=sk_new_null()) == NULL))
2103995Spst		{
2116562Sphk		CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_LOCKID,ERR_R_MALLOC_FAILURE);
212130351Seik		return(0);
2133995Spst		}
21448953Sbillf	if ((str=BUF_strdup(name)) == NULL)
215130351Seik		{
2163995Spst		CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_LOCKID,ERR_R_MALLOC_FAILURE);
217229680Seadler		return(0);
21854109Sobrien		}
219229680Seadler	i=sk_push(app_locks,str);
22054109Sobrien	if (!i)
221229680Seadler		OPENSSL_free(str);
22252949Sobrien	else
223229680Seadler		i+=CRYPTO_NUM_LOCKS; /* gap of one :-) */
224229680Seadler	return(i);
225229680Seadler	}
226229680Seadler
227229680Seadlerint CRYPTO_num_locks(void)
228229680Seadler	{
229229680Seadler	return CRYPTO_NUM_LOCKS;
230229680Seadler	}
2313995Spst
2326562Sphkint CRYPTO_get_new_dynlockid(void)
2336562Sphk	{
2343995Spst	int i = 0;
2356562Sphk	CRYPTO_dynlock *pointer = NULL;
236130351Seik
2373995Spst	if (dynlock_create_callback == NULL)
238130351Seik		{
239110840Ssilby		CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,CRYPTO_R_NO_DYNLOCK_CREATE_CALLBACK);
240110840Ssilby		return(0);
241110840Ssilby		}
2426725Sphk	CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
2436562Sphk	if ((dyn_locks == NULL)
244176095Sobrien		&& ((dyn_locks=sk_CRYPTO_dynlock_new_null()) == NULL))
2453995Spst		{
246176095Sobrien		CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
247130351Seik		CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,ERR_R_MALLOC_FAILURE);
24846226Skris		return(0);
2493995Spst		}
2506562Sphk	CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
2516562Sphk
2526562Sphk	pointer = (CRYPTO_dynlock *)OPENSSL_malloc(sizeof(CRYPTO_dynlock));
2533995Spst	if (pointer == NULL)
2546562Sphk		{
255182672Skevlo		CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,ERR_R_MALLOC_FAILURE);
2563995Spst		return(0);
2576562Sphk		}
258130351Seik	pointer->references = 1;
2596562Sphk	pointer->data = dynlock_create_callback(__FILE__,__LINE__);
260130351Seik	if (pointer->data == NULL)
261130351Seik		{
2623995Spst		OPENSSL_free(pointer);
2636562Sphk		CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,ERR_R_MALLOC_FAILURE);
264182672Skevlo		return(0);
265110840Ssilby		}
266110840Ssilby
2673995Spst	CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
2686562Sphk	/* First, try to find an existing empty slot */
2696562Sphk	i=sk_CRYPTO_dynlock_find(dyn_locks,NULL);
270110840Ssilby	/* If there was none, push, thereby creating a new one */
271176095Sobrien	if (i == -1)
272110840Ssilby		/* Since sk_push() returns the number of items on the
2733995Spst		   stack, not the location of the pushed item, we need
2746562Sphk		   to transform the returned number into a position,
2756562Sphk		   by decreasing it.  */
2763995Spst		i=sk_CRYPTO_dynlock_push(dyn_locks,pointer) - 1;
277109870Ssilby	else
278130351Seik		/* If we found a place with a NULL pointer, put our pointer
279176095Sobrien		   in it.  */
280109870Ssilby		sk_CRYPTO_dynlock_set(dyn_locks,i,pointer);
281109870Ssilby	CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
282109870Ssilby
283109870Ssilby	if (i == -1)
284109870Ssilby		{
285109870Ssilby		dynlock_destroy_callback(pointer->data,__FILE__,__LINE__);
286130351Seik		OPENSSL_free(pointer);
287130351Seik		}
288109870Ssilby	else
289109870Ssilby		i += 1; /* to avoid 0 */
290130351Seik	return -i;
291109870Ssilby	}
292109870Ssilby
293109870Ssilbyvoid CRYPTO_destroy_dynlockid(int i)
294109870Ssilby	{
295109870Ssilby	CRYPTO_dynlock *pointer = NULL;
296109870Ssilby	if (i)
297109870Ssilby		i = -i-1;
298109870Ssilby	if (dynlock_destroy_callback == NULL)
299109870Ssilby		return;
300109870Ssilby
301130351Seik	CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
302130351Seik
303130351Seik	if (dyn_locks == NULL || i >= sk_CRYPTO_dynlock_num(dyn_locks))
304130351Seik		{
305130351Seik		CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
306130351Seik		return;
307130351Seik		}
308130351Seik	pointer = sk_CRYPTO_dynlock_value(dyn_locks, i);
309130351Seik	if (pointer != NULL)
310130351Seik		{
311130351Seik		--pointer->references;
312143334Scperciva#ifdef REF_CHECK
313143334Scperciva		if (pointer->references < 0)
314143334Scperciva			{
315143334Scperciva			fprintf(stderr,"CRYPTO_destroy_dynlockid, bad reference count\n");
316143334Scperciva			abort();
317143334Scperciva			}
318143334Scperciva		else
319143334Scperciva#endif
320143334Scperciva			if (pointer->references <= 0)
321143334Scperciva				{
322143334Scperciva				sk_CRYPTO_dynlock_set(dyn_locks, i, NULL);
323130351Seik				}
324130351Seik			else
325130351Seik				pointer = NULL;
326130351Seik		}
327130351Seik	CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
328130351Seik
329130351Seik	if (pointer)
330130351Seik		{
331130351Seik		dynlock_destroy_callback(pointer->data,__FILE__,__LINE__);
332130351Seik		OPENSSL_free(pointer);
333130351Seik		}
3346562Sphk	}
335130351Seik
3363995Spststruct CRYPTO_dynlock_value *CRYPTO_get_dynlock_value(int i)
337109870Ssilby	{
338130351Seik	CRYPTO_dynlock *pointer = NULL;
33932086Ssteve	if (i)
340130351Seik		i = -i-1;
341130351Seik
342130351Seik	CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
343130351Seik
344130351Seik	if (dyn_locks != NULL && i < sk_CRYPTO_dynlock_num(dyn_locks))
345109870Ssilby		pointer = sk_CRYPTO_dynlock_value(dyn_locks, i);
346109870Ssilby	if (pointer)
347109870Ssilby		pointer->references++;
348109870Ssilby
3493995Spst	CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
3503995Spst
3516562Sphk	if (pointer)
3526562Sphk		return pointer->data;
3533995Spst	return NULL;
3546562Sphk	}
355130351Seik
3563995Spststruct CRYPTO_dynlock_value *(*CRYPTO_get_dynlock_create_callback(void))
357130351Seik	(const char *file,int line)
35876988Sru	{
35932074Ssteve	return(dynlock_create_callback);
360130351Seik	}
3613995Spst
362130351Seikvoid (*CRYPTO_get_dynlock_lock_callback(void))(int mode,
36332074Ssteve	struct CRYPTO_dynlock_value *l, const char *file,int line)
36476988Sru	{
36537421Scharnier	return(dynlock_lock_callback);
366130351Seik	}
3676725Sphk
368130351Seikvoid (*CRYPTO_get_dynlock_destroy_callback(void))
3693995Spst	(struct CRYPTO_dynlock_value *l, const char *file,int line)
37032074Ssteve	{
37132074Ssteve	return(dynlock_destroy_callback);
372130351Seik	}
37332074Ssteve
37432086Sstevevoid CRYPTO_set_dynlock_create_callback(struct CRYPTO_dynlock_value *(*func)
375235309Seadler	(const char *file, int line))
37632074Ssteve	{
37732074Ssteve	dynlock_create_callback=func;
378	}
379
380void CRYPTO_set_dynlock_lock_callback(void (*func)(int mode,
381	struct CRYPTO_dynlock_value *l, const char *file, int line))
382	{
383	dynlock_lock_callback=func;
384	}
385
386void CRYPTO_set_dynlock_destroy_callback(void (*func)
387	(struct CRYPTO_dynlock_value *l, const char *file, int line))
388	{
389	dynlock_destroy_callback=func;
390	}
391
392
393void (*CRYPTO_get_locking_callback(void))(int mode,int type,const char *file,
394		int line)
395	{
396	return(locking_callback);
397	}
398
399int (*CRYPTO_get_add_lock_callback(void))(int *num,int mount,int type,
400					  const char *file,int line)
401	{
402	return(add_lock_callback);
403	}
404
405void CRYPTO_set_locking_callback(void (*func)(int mode,int type,
406					      const char *file,int line))
407	{
408	locking_callback=func;
409	}
410
411void CRYPTO_set_add_lock_callback(int (*func)(int *num,int mount,int type,
412					      const char *file,int line))
413	{
414	add_lock_callback=func;
415	}
416
417unsigned long (*CRYPTO_get_id_callback(void))(void)
418	{
419	return(id_callback);
420	}
421
422void CRYPTO_set_id_callback(unsigned long (*func)(void))
423	{
424	id_callback=func;
425	}
426
427unsigned long CRYPTO_thread_id(void)
428	{
429	unsigned long ret=0;
430
431	if (id_callback == NULL)
432		{
433#ifdef OPENSSL_SYS_WIN16
434		ret=(unsigned long)GetCurrentTask();
435#elif defined(OPENSSL_SYS_WIN32)
436		ret=(unsigned long)GetCurrentThreadId();
437#elif defined(GETPID_IS_MEANINGLESS)
438		ret=1L;
439#else
440		ret=(unsigned long)getpid();
441#endif
442		}
443	else
444		ret=id_callback();
445	return(ret);
446	}
447
448void CRYPTO_lock(int mode, int type, const char *file, int line)
449	{
450#ifdef LOCK_DEBUG
451		{
452		char *rw_text,*operation_text;
453
454		if (mode & CRYPTO_LOCK)
455			operation_text="lock  ";
456		else if (mode & CRYPTO_UNLOCK)
457			operation_text="unlock";
458		else
459			operation_text="ERROR ";
460
461		if (mode & CRYPTO_READ)
462			rw_text="r";
463		else if (mode & CRYPTO_WRITE)
464			rw_text="w";
465		else
466			rw_text="ERROR";
467
468		fprintf(stderr,"lock:%08lx:(%s)%s %-18s %s:%d\n",
469			CRYPTO_thread_id(), rw_text, operation_text,
470			CRYPTO_get_lock_name(type), file, line);
471		}
472#endif
473	if (type < 0)
474		{
475		if (dynlock_lock_callback != NULL)
476			{
477			struct CRYPTO_dynlock_value *pointer
478				= CRYPTO_get_dynlock_value(type);
479
480			OPENSSL_assert(pointer != NULL);
481
482			dynlock_lock_callback(mode, pointer, file, line);
483
484			CRYPTO_destroy_dynlockid(type);
485			}
486		}
487	else
488		if (locking_callback != NULL)
489			locking_callback(mode,type,file,line);
490	}
491
492int CRYPTO_add_lock(int *pointer, int amount, int type, const char *file,
493	     int line)
494	{
495	int ret = 0;
496
497	if (add_lock_callback != NULL)
498		{
499#ifdef LOCK_DEBUG
500		int before= *pointer;
501#endif
502
503		ret=add_lock_callback(pointer,amount,type,file,line);
504#ifdef LOCK_DEBUG
505		fprintf(stderr,"ladd:%08lx:%2d+%2d->%2d %-18s %s:%d\n",
506			CRYPTO_thread_id(),
507			before,amount,ret,
508			CRYPTO_get_lock_name(type),
509			file,line);
510#endif
511		}
512	else
513		{
514		CRYPTO_lock(CRYPTO_LOCK|CRYPTO_WRITE,type,file,line);
515
516		ret= *pointer+amount;
517#ifdef LOCK_DEBUG
518		fprintf(stderr,"ladd:%08lx:%2d+%2d->%2d %-18s %s:%d\n",
519			CRYPTO_thread_id(),
520			*pointer,amount,ret,
521			CRYPTO_get_lock_name(type),
522			file,line);
523#endif
524		*pointer=ret;
525		CRYPTO_lock(CRYPTO_UNLOCK|CRYPTO_WRITE,type,file,line);
526		}
527	return(ret);
528	}
529
530const char *CRYPTO_get_lock_name(int type)
531	{
532	if (type < 0)
533		return("dynamic");
534	else if (type < CRYPTO_NUM_LOCKS)
535		return(lock_names[type]);
536	else if (type-CRYPTO_NUM_LOCKS > sk_num(app_locks))
537		return("ERROR");
538	else
539		return(sk_value(app_locks,type-CRYPTO_NUM_LOCKS));
540	}
541
542#if	defined(__i386)   || defined(__i386__)   || defined(_M_IX86) || \
543	defined(__INTEL__) || \
544	defined(__x86_64) || defined(__x86_64__) || defined(_M_AMD64)
545
546unsigned long  OPENSSL_ia32cap_P=0;
547unsigned long *OPENSSL_ia32cap_loc(void) { return &OPENSSL_ia32cap_P; }
548
549#if defined(OPENSSL_CPUID_OBJ) && !defined(OPENSSL_NO_ASM) && !defined(I386_ONLY)
550#define OPENSSL_CPUID_SETUP
551void OPENSSL_cpuid_setup(void)
552{ static int trigger=0;
553  unsigned long OPENSSL_ia32_cpuid(void);
554  char *env;
555
556    if (trigger)	return;
557
558    trigger=1;
559    if ((env=getenv("OPENSSL_ia32cap")))
560	OPENSSL_ia32cap_P = strtoul(env,NULL,0)|(1<<10);
561    else
562	OPENSSL_ia32cap_P = OPENSSL_ia32_cpuid()|(1<<10);
563    /*
564     * |(1<<10) sets a reserved bit to signal that variable
565     * was initialized already... This is to avoid interference
566     * with cpuid snippets in ELF .init segment.
567     */
568}
569#endif
570
571#else
572unsigned long *OPENSSL_ia32cap_loc(void) { return NULL; }
573#endif
574int OPENSSL_NONPIC_relocated = 0;
575#if !defined(OPENSSL_CPUID_SETUP)
576void OPENSSL_cpuid_setup(void) {}
577#endif
578
579#if (defined(_WIN32) || defined(__CYGWIN__)) && defined(_WINDLL)
580#ifdef __CYGWIN__
581/* pick DLL_[PROCESS|THREAD]_[ATTACH|DETACH] definitions */
582#include <windows.h>
583#endif
584
585/* All we really need to do is remove the 'error' state when a thread
586 * detaches */
587
588BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason,
589	     LPVOID lpvReserved)
590	{
591	switch(fdwReason)
592		{
593	case DLL_PROCESS_ATTACH:
594		OPENSSL_cpuid_setup();
595#if defined(_WIN32_WINNT)
596		{
597		IMAGE_DOS_HEADER *dos_header = (IMAGE_DOS_HEADER *)hinstDLL;
598		IMAGE_NT_HEADERS *nt_headers;
599
600		if (dos_header->e_magic==IMAGE_DOS_SIGNATURE)
601			{
602			nt_headers = (IMAGE_NT_HEADERS *)((char *)dos_header
603						+ dos_header->e_lfanew);
604			if (nt_headers->Signature==IMAGE_NT_SIGNATURE &&
605			    hinstDLL!=(HINSTANCE)(nt_headers->OptionalHeader.ImageBase))
606				OPENSSL_NONPIC_relocated=1;
607			}
608		}
609#endif
610		break;
611	case DLL_THREAD_ATTACH:
612		break;
613	case DLL_THREAD_DETACH:
614		ERR_remove_state(0);
615		break;
616	case DLL_PROCESS_DETACH:
617		break;
618		}
619	return(TRUE);
620	}
621#endif
622
623#if defined(_WIN32) && !defined(__CYGWIN__)
624#include <tchar.h>
625
626#if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
627int OPENSSL_isservice(void)
628{ HWINSTA h;
629  DWORD len;
630  WCHAR *name;
631
632    (void)GetDesktopWindow(); /* return value is ignored */
633
634    h = GetProcessWindowStation();
635    if (h==NULL) return -1;
636
637    if (GetUserObjectInformationW (h,UOI_NAME,NULL,0,&len) ||
638	GetLastError() != ERROR_INSUFFICIENT_BUFFER)
639	return -1;
640
641    if (len>512) return -1;		/* paranoia */
642    len++,len&=~1;			/* paranoia */
643#ifdef _MSC_VER
644    name=(WCHAR *)_alloca(len+sizeof(WCHAR));
645#else
646    name=(WCHAR *)alloca(len+sizeof(WCHAR));
647#endif
648    if (!GetUserObjectInformationW (h,UOI_NAME,name,len,&len))
649	return -1;
650
651    len++,len&=~1;			/* paranoia */
652    name[len/sizeof(WCHAR)]=L'\0';	/* paranoia */
653#if 1
654    /* This doesn't cover "interactive" services [working with real
655     * WinSta0's] nor programs started non-interactively by Task
656     * Scheduler [those are working with SAWinSta]. */
657    if (wcsstr(name,L"Service-0x"))	return 1;
658#else
659    /* This covers all non-interactive programs such as services. */
660    if (!wcsstr(name,L"WinSta0"))	return 1;
661#endif
662    else				return 0;
663}
664#else
665int OPENSSL_isservice(void) { return 0; }
666#endif
667
668void OPENSSL_showfatal (const char *fmta,...)
669{ va_list ap;
670  TCHAR buf[256];
671  const TCHAR *fmt;
672#ifdef STD_ERROR_HANDLE	/* what a dirty trick! */
673  HANDLE h;
674
675    if ((h=GetStdHandle(STD_ERROR_HANDLE)) != NULL &&
676	GetFileType(h)!=FILE_TYPE_UNKNOWN)
677    {	/* must be console application */
678	va_start (ap,fmta);
679	vfprintf (stderr,fmta,ap);
680	va_end (ap);
681	return;
682    }
683#endif
684
685    if (sizeof(TCHAR)==sizeof(char))
686	fmt=(const TCHAR *)fmta;
687    else do
688    { int    keepgoing;
689      size_t len_0=strlen(fmta)+1,i;
690      WCHAR *fmtw;
691
692#ifdef _MSC_VER
693	fmtw = (WCHAR *)_alloca (len_0*sizeof(WCHAR));
694#else
695	fmtw = (WCHAR *)alloca (len_0*sizeof(WCHAR));
696#endif
697	if (fmtw == NULL) { fmt=(const TCHAR *)L"no stack?"; break; }
698
699#ifndef OPENSSL_NO_MULTIBYTE
700	if (!MultiByteToWideChar(CP_ACP,0,fmta,len_0,fmtw,len_0))
701#endif
702	    for (i=0;i<len_0;i++) fmtw[i]=(WCHAR)fmta[i];
703
704	for (i=0;i<len_0;i++)
705	{   if (fmtw[i]==L'%') do
706	    {	keepgoing=0;
707		switch (fmtw[i+1])
708		{   case L'0': case L'1': case L'2': case L'3': case L'4':
709		    case L'5': case L'6': case L'7': case L'8': case L'9':
710		    case L'.': case L'*':
711		    case L'-':	i++; keepgoing=1; break;
712		    case L's':	fmtw[i+1]=L'S';   break;
713		    case L'S':	fmtw[i+1]=L's';   break;
714		    case L'c':	fmtw[i+1]=L'C';   break;
715		    case L'C':	fmtw[i+1]=L'c';   break;
716		}
717	    } while (keepgoing);
718	}
719	fmt = (const TCHAR *)fmtw;
720    } while (0);
721
722    va_start (ap,fmta);
723    _vsntprintf (buf,sizeof(buf)/sizeof(TCHAR)-1,fmt,ap);
724    buf [sizeof(buf)/sizeof(TCHAR)-1] = _T('\0');
725    va_end (ap);
726
727#if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
728    /* this -------------v--- guards NT-specific calls */
729    if (GetVersion() < 0x80000000 && OPENSSL_isservice())
730    {	HANDLE h = RegisterEventSource(0,_T("OPENSSL"));
731	const TCHAR *pmsg=buf;
732	ReportEvent(h,EVENTLOG_ERROR_TYPE,0,0,0,1,0,&pmsg,0);
733	DeregisterEventSource(h);
734    }
735    else
736#endif
737	MessageBox (NULL,buf,_T("OpenSSL: FATAL"),MB_OK|MB_ICONSTOP);
738}
739#else
740void OPENSSL_showfatal (const char *fmta,...)
741{ va_list ap;
742
743    va_start (ap,fmta);
744    vfprintf (stderr,fmta,ap);
745    va_end (ap);
746}
747int OPENSSL_isservice (void) { return 0; }
748#endif
749
750void OpenSSLDie(const char *file,int line,const char *assertion)
751	{
752	OPENSSL_showfatal(
753		"%s(%d): OpenSSL internal error, assertion failed: %s\n",
754		file,line,assertion);
755	abort();
756	}
757
758void *OPENSSL_stderr(void)	{ return stderr; }
759