Flatten the Curve 448 source structure
[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 int OPENSSL_isservice(void)
124 {
125     HWINSTA h;
126     DWORD len;
127     WCHAR *name;
128     static union {
129         void *p;
130         FARPROC f;
131     } _OPENSSL_isservice = {
132         NULL
133     };
134
135     if (_OPENSSL_isservice.p == NULL) {
136         HANDLE mod = GetModuleHandle(NULL);
137         if (mod != NULL)
138             _OPENSSL_isservice.f = GetProcAddress(mod, "_OPENSSL_isservice");
139         if (_OPENSSL_isservice.p == NULL)
140             _OPENSSL_isservice.p = (void *)-1;
141     }
142
143     if (_OPENSSL_isservice.p != (void *)-1)
144         return (*_OPENSSL_isservice.f) ();
145
146     h = GetProcessWindowStation();
147     if (h == NULL)
148         return -1;
149
150     if (GetUserObjectInformationW(h, UOI_NAME, NULL, 0, &len) ||
151         GetLastError() != ERROR_INSUFFICIENT_BUFFER)
152         return -1;
153
154     if (len > 512)
155         return -1;              /* paranoia */
156     len++, len &= ~1;           /* paranoia */
157     name = (WCHAR *)alloca(len + sizeof(WCHAR));
158     if (!GetUserObjectInformationW(h, UOI_NAME, name, len, &len))
159         return -1;
160
161     len++, len &= ~1;           /* paranoia */
162     name[len / sizeof(WCHAR)] = L'\0'; /* paranoia */
163 #  if 1
164     /*
165      * This doesn't cover "interactive" services [working with real
166      * WinSta0's] nor programs started non-interactively by Task Scheduler
167      * [those are working with SAWinSta].
168      */
169     if (wcsstr(name, L"Service-0x"))
170         return 1;
171 #  else
172     /* This covers all non-interactive programs such as services. */
173     if (!wcsstr(name, L"WinSta0"))
174         return 1;
175 #  endif
176     else
177         return 0;
178 }
179 # else
180 int OPENSSL_isservice(void)
181 {
182     return 0;
183 }
184 # endif
185
186 void OPENSSL_showfatal(const char *fmta, ...)
187 {
188     va_list ap;
189     TCHAR buf[256];
190     const TCHAR *fmt;
191     /*
192      * First check if it's a console application, in which case the
193      * error message would be printed to standard error.
194      * Windows CE does not have a concept of a console application,
195      * so we need to guard the check.
196      */
197 # ifdef STD_ERROR_HANDLE
198     HANDLE h;
199
200     if ((h = GetStdHandle(STD_ERROR_HANDLE)) != NULL &&
201         GetFileType(h) != FILE_TYPE_UNKNOWN) {
202         /* must be console application */
203         int len;
204         DWORD out;
205
206         va_start(ap, fmta);
207         len = _vsnprintf((char *)buf, sizeof(buf), fmta, ap);
208         WriteFile(h, buf, len < 0 ? sizeof(buf) : (DWORD) len, &out, NULL);
209         va_end(ap);
210         return;
211     }
212 # endif
213
214     if (sizeof(TCHAR) == sizeof(char))
215         fmt = (const TCHAR *)fmta;
216     else
217         do {
218             int keepgoing;
219             size_t len_0 = strlen(fmta) + 1, i;
220             WCHAR *fmtw;
221
222             fmtw = (WCHAR *)alloca(len_0 * sizeof(WCHAR));
223             if (fmtw == NULL) {
224                 fmt = (const TCHAR *)L"no stack?";
225                 break;
226             }
227             if (!MultiByteToWideChar(CP_ACP, 0, fmta, len_0, fmtw, len_0))
228                 for (i = 0; i < len_0; i++)
229                     fmtw[i] = (WCHAR)fmta[i];
230             for (i = 0; i < len_0; i++) {
231                 if (fmtw[i] == L'%')
232                     do {
233                         keepgoing = 0;
234                         switch (fmtw[i + 1]) {
235                         case L'0':
236                         case L'1':
237                         case L'2':
238                         case L'3':
239                         case L'4':
240                         case L'5':
241                         case L'6':
242                         case L'7':
243                         case L'8':
244                         case L'9':
245                         case L'.':
246                         case L'*':
247                         case L'-':
248                             i++;
249                             keepgoing = 1;
250                             break;
251                         case L's':
252                             fmtw[i + 1] = L'S';
253                             break;
254                         case L'S':
255                             fmtw[i + 1] = L's';
256                             break;
257                         case L'c':
258                             fmtw[i + 1] = L'C';
259                             break;
260                         case L'C':
261                             fmtw[i + 1] = L'c';
262                             break;
263                         }
264                     } while (keepgoing);
265             }
266             fmt = (const TCHAR *)fmtw;
267         } while (0);
268
269     va_start(ap, fmta);
270     _vsntprintf(buf, OSSL_NELEM(buf) - 1, fmt, ap);
271     buf[OSSL_NELEM(buf) - 1] = _T('\0');
272     va_end(ap);
273
274 # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
275     /* this -------------v--- guards NT-specific calls */
276     if (check_winnt() && OPENSSL_isservice() > 0) {
277         HANDLE hEventLog = RegisterEventSource(NULL, _T("OpenSSL"));
278
279         if (hEventLog != NULL) {
280             const TCHAR *pmsg = buf;
281
282             if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, 0, 0, NULL,
283                              1, 0, &pmsg, NULL)) {
284 #if defined(DEBUG)
285                 /*
286                  * We are in a situation where we tried to report a critical
287                  * error and this failed for some reason. As a last resort,
288                  * in debug builds, send output to the debugger or any other
289                  * tool like DebugView which can monitor the output.
290                  */
291                 OutputDebugString(pmsg);
292 #endif
293             }
294
295             (void)DeregisterEventSource(hEventLog);
296         }
297     } else
298 # endif
299         MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONERROR);
300 }
301 #else
302 void OPENSSL_showfatal(const char *fmta, ...)
303 {
304 #ifndef OPENSSL_NO_STDIO
305     va_list ap;
306
307     va_start(ap, fmta);
308     vfprintf(stderr, fmta, ap);
309     va_end(ap);
310 #endif
311 }
312
313 int OPENSSL_isservice(void)
314 {
315     return 0;
316 }
317 #endif
318
319 void OPENSSL_die(const char *message, const char *file, int line)
320 {
321     OPENSSL_showfatal("%s:%d: OpenSSL internal error: %s\n",
322                       file, line, message);
323 #if !defined(_WIN32)
324     abort();
325 #else
326     /*
327      * Win32 abort() customarily shows a dialog, but we just did that...
328      */
329 # if !defined(_WIN32_WCE)
330     raise(SIGABRT);
331 # endif
332     _exit(3);
333 #endif
334 }
335
336 #if !defined(OPENSSL_CPUID_OBJ)
337 /*
338  * The volatile is used to to ensure that the compiler generates code that reads
339  * all values from the array and doesn't try to optimize this away. The standard
340  * doesn't actually require this behavior if the original data pointed to is
341  * not volatile, but compilers do this in practice anyway.
342  *
343  * There are also assembler versions of this function.
344  */
345 # undef CRYPTO_memcmp
346 int CRYPTO_memcmp(const void * in_a, const void * in_b, size_t len)
347 {
348     size_t i;
349     const volatile unsigned char *a = in_a;
350     const volatile unsigned char *b = in_b;
351     unsigned char x = 0;
352
353     for (i = 0; i < len; i++)
354         x |= a[i] ^ b[i];
355
356     return x;
357 }
358
359 /*
360  * For systems that don't provide an instruction counter register or equivalent.
361  */
362 uint32_t OPENSSL_rdtsc(void)
363 {
364     return 0;
365 }
366 #endif