Don't build AFALG on android
[openssl.git] / crypto / cryptlib.c
1 /*
2  * Copyright 1998-2018 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  *
5  * Licensed under the OpenSSL license (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10
11 #include "e_os.h"
12 #include "internal/cryptlib_int.h"
13 #include <openssl/safestack.h>
14
15 #if     defined(__i386)   || defined(__i386__)   || defined(_M_IX86) || \
16         defined(__x86_64) || defined(__x86_64__) || \
17         defined(_M_AMD64) || defined(_M_X64)
18
19 extern unsigned int OPENSSL_ia32cap_P[4];
20
21 # if defined(OPENSSL_CPUID_OBJ) && !defined(OPENSSL_NO_ASM) && !defined(I386_ONLY)
22 #include <stdio.h>
23 #  define OPENSSL_CPUID_SETUP
24 typedef uint64_t IA32CAP;
25 void OPENSSL_cpuid_setup(void)
26 {
27     static int trigger = 0;
28     IA32CAP OPENSSL_ia32_cpuid(unsigned int *);
29     IA32CAP vec;
30     char *env;
31
32     if (trigger)
33         return;
34
35     trigger = 1;
36     if ((env = getenv("OPENSSL_ia32cap"))) {
37         int off = (env[0] == '~') ? 1 : 0;
38 #  if defined(_WIN32)
39         if (!sscanf(env + off, "%I64i", &vec))
40             vec = strtoul(env + off, NULL, 0);
41 #  else
42         if (!sscanf(env + off, "%lli", (long long *)&vec))
43             vec = strtoul(env + off, NULL, 0);
44 #  endif
45         if (off) {
46             IA32CAP mask = vec;
47             vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P) & ~mask;
48             if (mask & (1<<24)) {
49                 /*
50                  * User disables FXSR bit, mask even other capabilities
51                  * that operate exclusively on XMM, so we don't have to
52                  * double-check all the time. We mask PCLMULQDQ, AMD XOP,
53                  * AES-NI and AVX. Formally speaking we don't have to
54                  * do it in x86_64 case, but we can safely assume that
55                  * x86_64 users won't actually flip this flag.
56                  */
57                 vec &= ~((IA32CAP)(1<<1|1<<11|1<<25|1<<28) << 32);
58             }
59         } else if (env[0] == ':') {
60             vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
61         }
62
63         if ((env = strchr(env, ':'))) {
64             IA32CAP vecx;
65             env++;
66             off = (env[0] == '~') ? 1 : 0;
67 #  if defined(_WIN32)
68             if (!sscanf(env + off, "%I64i", &vecx))
69                 vecx = strtoul(env + off, NULL, 0);
70 #  else
71             if (!sscanf(env + off, "%lli", (long long *)&vecx))
72                 vecx = strtoul(env + off, NULL, 0);
73 #  endif
74             if (off) {
75                 OPENSSL_ia32cap_P[2] &= ~(unsigned int)vecx;
76                 OPENSSL_ia32cap_P[3] &= ~(unsigned int)(vecx >> 32);
77             } else {
78                 OPENSSL_ia32cap_P[2] = (unsigned int)vecx;
79                 OPENSSL_ia32cap_P[3] = (unsigned int)(vecx >> 32);
80             }
81         } else {
82             OPENSSL_ia32cap_P[2] = 0;
83             OPENSSL_ia32cap_P[3] = 0;
84         }
85     } else {
86         vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
87     }
88
89     /*
90      * |(1<<10) sets a reserved bit to signal that variable
91      * was initialized already... This is to avoid interference
92      * with cpuid snippets in ELF .init segment.
93      */
94     OPENSSL_ia32cap_P[0] = (unsigned int)vec | (1 << 10);
95     OPENSSL_ia32cap_P[1] = (unsigned int)(vec >> 32);
96 }
97 # else
98 unsigned int OPENSSL_ia32cap_P[4];
99 # endif
100 #endif
101 int OPENSSL_NONPIC_relocated = 0;
102 #if !defined(OPENSSL_CPUID_SETUP) && !defined(OPENSSL_CPUID_OBJ)
103 void OPENSSL_cpuid_setup(void)
104 {
105 }
106 #endif
107
108 #if defined(_WIN32)
109 # include <tchar.h>
110 # include <signal.h>
111 # ifdef __WATCOMC__
112 #  if defined(_UNICODE) || defined(__UNICODE__)
113 #   define _vsntprintf _vsnwprintf
114 #  else
115 #   define _vsntprintf _vsnprintf
116 #  endif
117 # endif
118 # ifdef _MSC_VER
119 #  define alloca _alloca
120 # endif
121
122 # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
123 #  ifdef OPENSSL_SYS_WIN_CORE
124
125 int OPENSSL_isservice(void)
126 {
127     /* OneCore API cannot interact with GUI */
128     return 1;
129 }
130 #  else
131 int OPENSSL_isservice(void)
132 {
133     HWINSTA h;
134     DWORD len;
135     WCHAR *name;
136     static union {
137         void *p;
138         FARPROC f;
139     } _OPENSSL_isservice = {
140         NULL
141     };
142
143     if (_OPENSSL_isservice.p == NULL) {
144         HANDLE mod = GetModuleHandle(NULL);
145         if (mod != NULL)
146             _OPENSSL_isservice.f = GetProcAddress(mod, "_OPENSSL_isservice");
147         if (_OPENSSL_isservice.p == NULL)
148             _OPENSSL_isservice.p = (void *)-1;
149     }
150
151     if (_OPENSSL_isservice.p != (void *)-1)
152         return (*_OPENSSL_isservice.f) ();
153
154     h = GetProcessWindowStation();
155     if (h == NULL)
156         return -1;
157
158     if (GetUserObjectInformationW(h, UOI_NAME, NULL, 0, &len) ||
159         GetLastError() != ERROR_INSUFFICIENT_BUFFER)
160         return -1;
161
162     if (len > 512)
163         return -1;              /* paranoia */
164     len++, len &= ~1;           /* paranoia */
165     name = (WCHAR *)alloca(len + sizeof(WCHAR));
166     if (!GetUserObjectInformationW(h, UOI_NAME, name, len, &len))
167         return -1;
168
169     len++, len &= ~1;           /* paranoia */
170     name[len / sizeof(WCHAR)] = L'\0'; /* paranoia */
171 #   if 1
172     /*
173      * This doesn't cover "interactive" services [working with real
174      * WinSta0's] nor programs started non-interactively by Task Scheduler
175      * [those are working with SAWinSta].
176      */
177     if (wcsstr(name, L"Service-0x"))
178         return 1;
179 #   else
180     /* This covers all non-interactive programs such as services. */
181     if (!wcsstr(name, L"WinSta0"))
182         return 1;
183 #   endif
184     else
185         return 0;
186 }
187 #  endif
188 # else
189 int OPENSSL_isservice(void)
190 {
191     return 0;
192 }
193 # endif
194
195 void OPENSSL_showfatal(const char *fmta, ...)
196 {
197     va_list ap;
198     TCHAR buf[256];
199     const TCHAR *fmt;
200     /*
201      * First check if it's a console application, in which case the
202      * error message would be printed to standard error.
203      * Windows CE does not have a concept of a console application,
204      * so we need to guard the check.
205      */
206 # ifdef STD_ERROR_HANDLE
207     HANDLE h;
208
209     if ((h = GetStdHandle(STD_ERROR_HANDLE)) != NULL &&
210         GetFileType(h) != FILE_TYPE_UNKNOWN) {
211         /* must be console application */
212         int len;
213         DWORD out;
214
215         va_start(ap, fmta);
216         len = _vsnprintf((char *)buf, sizeof(buf), fmta, ap);
217         WriteFile(h, buf, len < 0 ? sizeof(buf) : (DWORD) len, &out, NULL);
218         va_end(ap);
219         return;
220     }
221 # endif
222
223     if (sizeof(TCHAR) == sizeof(char))
224         fmt = (const TCHAR *)fmta;
225     else
226         do {
227             int keepgoing;
228             size_t len_0 = strlen(fmta) + 1, i;
229             WCHAR *fmtw;
230
231             fmtw = (WCHAR *)alloca(len_0 * sizeof(WCHAR));
232             if (fmtw == NULL) {
233                 fmt = (const TCHAR *)L"no stack?";
234                 break;
235             }
236             if (!MultiByteToWideChar(CP_ACP, 0, fmta, len_0, fmtw, len_0))
237                 for (i = 0; i < len_0; i++)
238                     fmtw[i] = (WCHAR)fmta[i];
239             for (i = 0; i < len_0; i++) {
240                 if (fmtw[i] == L'%')
241                     do {
242                         keepgoing = 0;
243                         switch (fmtw[i + 1]) {
244                         case L'0':
245                         case L'1':
246                         case L'2':
247                         case L'3':
248                         case L'4':
249                         case L'5':
250                         case L'6':
251                         case L'7':
252                         case L'8':
253                         case L'9':
254                         case L'.':
255                         case L'*':
256                         case L'-':
257                             i++;
258                             keepgoing = 1;
259                             break;
260                         case L's':
261                             fmtw[i + 1] = L'S';
262                             break;
263                         case L'S':
264                             fmtw[i + 1] = L's';
265                             break;
266                         case L'c':
267                             fmtw[i + 1] = L'C';
268                             break;
269                         case L'C':
270                             fmtw[i + 1] = L'c';
271                             break;
272                         }
273                     } while (keepgoing);
274             }
275             fmt = (const TCHAR *)fmtw;
276         } while (0);
277
278     va_start(ap, fmta);
279     _vsntprintf(buf, OSSL_NELEM(buf) - 1, fmt, ap);
280     buf[OSSL_NELEM(buf) - 1] = _T('\0');
281     va_end(ap);
282
283 # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
284 #  ifdef OPENSSL_SYS_WIN_CORE
285     /* ONECORE is always NONGUI and NT >= 0x0601 */
286
287     /*
288     * TODO: (For non GUI and no std error cases)
289     * Add event logging feature here. 
290     */
291     
292 #   if !defined(NDEBUG)
293         /*
294         * We are in a situation where we tried to report a critical
295         * error and this failed for some reason. As a last resort,
296         * in debug builds, send output to the debugger or any other
297         * tool like DebugView which can monitor the output.
298         */
299         OutputDebugString(buf);
300 #   endif
301 #  else
302     /* this -------------v--- guards NT-specific calls */
303     if (check_winnt() && OPENSSL_isservice() > 0) {
304         HANDLE hEventLog = RegisterEventSource(NULL, _T("OpenSSL"));
305
306         if (hEventLog != NULL) {
307             const TCHAR *pmsg = buf;
308
309             if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, 0, 0, NULL,
310                              1, 0, &pmsg, NULL)) {
311 #   if !defined(NDEBUG)
312                 /*
313                  * We are in a situation where we tried to report a critical
314                  * error and this failed for some reason. As a last resort,
315                  * in debug builds, send output to the debugger or any other
316                  * tool like DebugView which can monitor the output.
317                  */
318                 OutputDebugString(pmsg);
319 #   endif
320             }
321
322             (void)DeregisterEventSource(hEventLog);
323         }
324     } else {
325         MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONERROR);
326     }
327 #  endif
328 # else
329     MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONERROR);
330 # endif     
331 }
332 #else
333 void OPENSSL_showfatal(const char *fmta, ...)
334 {
335 #ifndef OPENSSL_NO_STDIO
336     va_list ap;
337
338     va_start(ap, fmta);
339     vfprintf(stderr, fmta, ap);
340     va_end(ap);
341 #endif
342 }
343
344 int OPENSSL_isservice(void)
345 {
346     return 0;
347 }
348 #endif
349
350 void OPENSSL_die(const char *message, const char *file, int line)
351 {
352     OPENSSL_showfatal("%s:%d: OpenSSL internal error: %s\n",
353                       file, line, message);
354 #if !defined(_WIN32)
355     abort();
356 #else
357     /*
358      * Win32 abort() customarily shows a dialog, but we just did that...
359      */
360 # if !defined(_WIN32_WCE)
361     raise(SIGABRT);
362 # endif
363     _exit(3);
364 #endif
365 }
366
367 #if !defined(OPENSSL_CPUID_OBJ)
368 /*
369  * The volatile is used to to ensure that the compiler generates code that reads
370  * all values from the array and doesn't try to optimize this away. The standard
371  * doesn't actually require this behavior if the original data pointed to is
372  * not volatile, but compilers do this in practice anyway.
373  *
374  * There are also assembler versions of this function.
375  */
376 # undef CRYPTO_memcmp
377 int CRYPTO_memcmp(const void * in_a, const void * in_b, size_t len)
378 {
379     size_t i;
380     const volatile unsigned char *a = in_a;
381     const volatile unsigned char *b = in_b;
382     unsigned char x = 0;
383
384     for (i = 0; i < len; i++)
385         x |= a[i] ^ b[i];
386
387     return x;
388 }
389
390 /*
391  * For systems that don't provide an instruction counter register or equivalent.
392  */
393 uint32_t OPENSSL_rdtsc(void)
394 {
395     return 0;
396 }
397 #endif