crypto/bio/build.info: split the source files in categories
[openssl.git] / crypto / dso / dso_win32.c
1 /*
2  * Copyright 2000-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "e_os.h"
11 #include "dso_local.h"
12
13 #if defined(DSO_WIN32)
14
15 # ifdef _WIN32_WCE
16 #  if _WIN32_WCE < 300
17 static FARPROC GetProcAddressA(HMODULE hModule, LPCSTR lpProcName)
18 {
19     WCHAR lpProcNameW[64];
20     int i;
21
22     for (i = 0; lpProcName[i] && i < 64; i++)
23         lpProcNameW[i] = (WCHAR)lpProcName[i];
24     if (i == 64)
25         return NULL;
26     lpProcNameW[i] = 0;
27
28     return GetProcAddressW(hModule, lpProcNameW);
29 }
30 #  endif
31 #  undef GetProcAddress
32 #  define GetProcAddress GetProcAddressA
33
34 static HINSTANCE LoadLibraryA(LPCSTR lpLibFileName)
35 {
36     WCHAR *fnamw;
37     size_t len_0 = strlen(lpLibFileName) + 1, i;
38
39 #  ifdef _MSC_VER
40     fnamw = (WCHAR *)_alloca(len_0 * sizeof(WCHAR));
41 #  else
42     fnamw = (WCHAR *)alloca(len_0 * sizeof(WCHAR));
43 #  endif
44     if (fnamw == NULL) {
45         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
46         return NULL;
47     }
48 #  if defined(_WIN32_WCE) && _WIN32_WCE>=101
49     if (!MultiByteToWideChar(CP_ACP, 0, lpLibFileName, len_0, fnamw, len_0))
50 #  endif
51         for (i = 0; i < len_0; i++)
52             fnamw[i] = (WCHAR)lpLibFileName[i];
53
54     return LoadLibraryW(fnamw);
55 }
56 # endif
57
58 /* Part of the hack in "win32_load" ... */
59 # define DSO_MAX_TRANSLATED_SIZE 256
60
61 static int win32_load(DSO *dso);
62 static int win32_unload(DSO *dso);
63 static DSO_FUNC_TYPE win32_bind_func(DSO *dso, const char *symname);
64 static char *win32_name_converter(DSO *dso, const char *filename);
65 static char *win32_merger(DSO *dso, const char *filespec1,
66                           const char *filespec2);
67 static int win32_pathbyaddr(void *addr, char *path, int sz);
68 static void *win32_globallookup(const char *name);
69
70 static const char *openssl_strnchr(const char *string, int c, size_t len);
71
72 static DSO_METHOD dso_meth_win32 = {
73     "OpenSSL 'win32' shared library method",
74     win32_load,
75     win32_unload,
76     win32_bind_func,
77     NULL,                       /* ctrl */
78     win32_name_converter,
79     win32_merger,
80     NULL,                       /* init */
81     NULL,                       /* finish */
82     win32_pathbyaddr,           /* pathbyaddr */
83     win32_globallookup
84 };
85
86 DSO_METHOD *DSO_METHOD_openssl(void)
87 {
88     return &dso_meth_win32;
89 }
90
91 /*
92  * For this DSO_METHOD, our meth_data STACK will contain; (i) a pointer to
93  * the handle (HINSTANCE) returned from LoadLibrary(), and copied.
94  */
95
96 static int win32_load(DSO *dso)
97 {
98     HINSTANCE h = NULL, *p = NULL;
99     /* See applicable comments from dso_dl.c */
100     char *filename = DSO_convert_filename(dso, NULL);
101
102     if (filename == NULL) {
103         DSOerr(DSO_F_WIN32_LOAD, DSO_R_NO_FILENAME);
104         goto err;
105     }
106     h = LoadLibraryA(filename);
107     if (h == NULL) {
108         DSOerr(DSO_F_WIN32_LOAD, DSO_R_LOAD_FAILED);
109         ERR_add_error_data(3, "filename(", filename, ")");
110         goto err;
111     }
112     p = OPENSSL_malloc(sizeof(*p));
113     if (p == NULL) {
114         DSOerr(DSO_F_WIN32_LOAD, ERR_R_MALLOC_FAILURE);
115         goto err;
116     }
117     *p = h;
118     if (!sk_void_push(dso->meth_data, p)) {
119         DSOerr(DSO_F_WIN32_LOAD, DSO_R_STACK_ERROR);
120         goto err;
121     }
122     /* Success */
123     dso->loaded_filename = filename;
124     return 1;
125  err:
126     /* Cleanup ! */
127     OPENSSL_free(filename);
128     OPENSSL_free(p);
129     if (h != NULL)
130         FreeLibrary(h);
131     return 0;
132 }
133
134 static int win32_unload(DSO *dso)
135 {
136     HINSTANCE *p;
137     if (dso == NULL) {
138         DSOerr(DSO_F_WIN32_UNLOAD, ERR_R_PASSED_NULL_PARAMETER);
139         return 0;
140     }
141     if (sk_void_num(dso->meth_data) < 1)
142         return 1;
143     p = sk_void_pop(dso->meth_data);
144     if (p == NULL) {
145         DSOerr(DSO_F_WIN32_UNLOAD, DSO_R_NULL_HANDLE);
146         return 0;
147     }
148     if (!FreeLibrary(*p)) {
149         DSOerr(DSO_F_WIN32_UNLOAD, DSO_R_UNLOAD_FAILED);
150         /*
151          * We should push the value back onto the stack in case of a retry.
152          */
153         sk_void_push(dso->meth_data, p);
154         return 0;
155     }
156     /* Cleanup */
157     OPENSSL_free(p);
158     return 1;
159 }
160
161 static DSO_FUNC_TYPE win32_bind_func(DSO *dso, const char *symname)
162 {
163     HINSTANCE *ptr;
164     union {
165         void *p;
166         FARPROC f;
167     } sym;
168
169     if ((dso == NULL) || (symname == NULL)) {
170         DSOerr(DSO_F_WIN32_BIND_FUNC, ERR_R_PASSED_NULL_PARAMETER);
171         return NULL;
172     }
173     if (sk_void_num(dso->meth_data) < 1) {
174         DSOerr(DSO_F_WIN32_BIND_FUNC, DSO_R_STACK_ERROR);
175         return NULL;
176     }
177     ptr = sk_void_value(dso->meth_data, sk_void_num(dso->meth_data) - 1);
178     if (ptr == NULL) {
179         DSOerr(DSO_F_WIN32_BIND_FUNC, DSO_R_NULL_HANDLE);
180         return NULL;
181     }
182     sym.f = GetProcAddress(*ptr, symname);
183     if (sym.p == NULL) {
184         DSOerr(DSO_F_WIN32_BIND_FUNC, DSO_R_SYM_FAILURE);
185         ERR_add_error_data(3, "symname(", symname, ")");
186         return NULL;
187     }
188     return (DSO_FUNC_TYPE)sym.f;
189 }
190
191 struct file_st {
192     const char *node;
193     int nodelen;
194     const char *device;
195     int devicelen;
196     const char *predir;
197     int predirlen;
198     const char *dir;
199     int dirlen;
200     const char *file;
201     int filelen;
202 };
203
204 static struct file_st *win32_splitter(DSO *dso, const char *filename,
205                                       int assume_last_is_dir)
206 {
207     struct file_st *result = NULL;
208     enum { IN_NODE, IN_DEVICE, IN_FILE } position;
209     const char *start = filename;
210     char last;
211
212     if (!filename) {
213         DSOerr(DSO_F_WIN32_SPLITTER, DSO_R_NO_FILENAME);
214         return NULL;
215     }
216
217     result = OPENSSL_zalloc(sizeof(*result));
218     if (result == NULL) {
219         DSOerr(DSO_F_WIN32_SPLITTER, ERR_R_MALLOC_FAILURE);
220         return NULL;
221     }
222
223     position = IN_DEVICE;
224
225     if ((filename[0] == '\\' && filename[1] == '\\')
226         || (filename[0] == '/' && filename[1] == '/')) {
227         position = IN_NODE;
228         filename += 2;
229         start = filename;
230         result->node = start;
231     }
232
233     do {
234         last = filename[0];
235         switch (last) {
236         case ':':
237             if (position != IN_DEVICE) {
238                 DSOerr(DSO_F_WIN32_SPLITTER, DSO_R_INCORRECT_FILE_SYNTAX);
239                 OPENSSL_free(result);
240                 return NULL;
241             }
242             result->device = start;
243             result->devicelen = (int)(filename - start);
244             position = IN_FILE;
245             start = ++filename;
246             result->dir = start;
247             break;
248         case '\\':
249         case '/':
250             if (position == IN_NODE) {
251                 result->nodelen = (int)(filename - start);
252                 position = IN_FILE;
253                 start = ++filename;
254                 result->dir = start;
255             } else if (position == IN_DEVICE) {
256                 position = IN_FILE;
257                 filename++;
258                 result->dir = start;
259                 result->dirlen = (int)(filename - start);
260                 start = filename;
261             } else {
262                 filename++;
263                 result->dirlen += (int)(filename - start);
264                 start = filename;
265             }
266             break;
267         case '\0':
268             if (position == IN_NODE) {
269                 result->nodelen = (int)(filename - start);
270             } else {
271                 if (filename - start > 0) {
272                     if (assume_last_is_dir) {
273                         if (position == IN_DEVICE) {
274                             result->dir = start;
275                             result->dirlen = 0;
276                         }
277                         result->dirlen += (int)(filename - start);
278                     } else {
279                         result->file = start;
280                         result->filelen = (int)(filename - start);
281                     }
282                 }
283             }
284             break;
285         default:
286             filename++;
287             break;
288         }
289     }
290     while (last);
291
292     if (!result->nodelen)
293         result->node = NULL;
294     if (!result->devicelen)
295         result->device = NULL;
296     if (!result->dirlen)
297         result->dir = NULL;
298     if (!result->filelen)
299         result->file = NULL;
300
301     return result;
302 }
303
304 static char *win32_joiner(DSO *dso, const struct file_st *file_split)
305 {
306     int len = 0, offset = 0;
307     char *result = NULL;
308     const char *start;
309
310     if (!file_split) {
311         DSOerr(DSO_F_WIN32_JOINER, ERR_R_PASSED_NULL_PARAMETER);
312         return NULL;
313     }
314     if (file_split->node) {
315         len += 2 + file_split->nodelen; /* 2 for starting \\ */
316         if (file_split->predir || file_split->dir || file_split->file)
317             len++;              /* 1 for ending \ */
318     } else if (file_split->device) {
319         len += file_split->devicelen + 1; /* 1 for ending : */
320     }
321     len += file_split->predirlen;
322     if (file_split->predir && (file_split->dir || file_split->file)) {
323         len++;                  /* 1 for ending \ */
324     }
325     len += file_split->dirlen;
326     if (file_split->dir && file_split->file) {
327         len++;                  /* 1 for ending \ */
328     }
329     len += file_split->filelen;
330
331     if (!len) {
332         DSOerr(DSO_F_WIN32_JOINER, DSO_R_EMPTY_FILE_STRUCTURE);
333         return NULL;
334     }
335
336     result = OPENSSL_malloc(len + 1);
337     if (result == NULL) {
338         DSOerr(DSO_F_WIN32_JOINER, ERR_R_MALLOC_FAILURE);
339         return NULL;
340     }
341
342     if (file_split->node) {
343         strcpy(&result[offset], "\\\\");
344         offset += 2;
345         strncpy(&result[offset], file_split->node, file_split->nodelen);
346         offset += file_split->nodelen;
347         if (file_split->predir || file_split->dir || file_split->file) {
348             result[offset] = '\\';
349             offset++;
350         }
351     } else if (file_split->device) {
352         strncpy(&result[offset], file_split->device, file_split->devicelen);
353         offset += file_split->devicelen;
354         result[offset] = ':';
355         offset++;
356     }
357     start = file_split->predir;
358     while (file_split->predirlen > (start - file_split->predir)) {
359         const char *end = openssl_strnchr(start, '/',
360                                           file_split->predirlen - (start -
361                                                                    file_split->predir));
362         if (!end)
363             end = start
364                 + file_split->predirlen - (start - file_split->predir);
365         strncpy(&result[offset], start, end - start);
366         offset += (int)(end - start);
367         result[offset] = '\\';
368         offset++;
369         start = end + 1;
370     }
371     start = file_split->dir;
372     while (file_split->dirlen > (start - file_split->dir)) {
373         const char *end = openssl_strnchr(start, '/',
374                                           file_split->dirlen - (start -
375                                                                 file_split->dir));
376         if (!end)
377             end = start + file_split->dirlen - (start - file_split->dir);
378         strncpy(&result[offset], start, end - start);
379         offset += (int)(end - start);
380         result[offset] = '\\';
381         offset++;
382         start = end + 1;
383     }
384     strncpy(&result[offset], file_split->file, file_split->filelen);
385     offset += file_split->filelen;
386     result[offset] = '\0';
387     return result;
388 }
389
390 static char *win32_merger(DSO *dso, const char *filespec1,
391                           const char *filespec2)
392 {
393     char *merged = NULL;
394     struct file_st *filespec1_split = NULL;
395     struct file_st *filespec2_split = NULL;
396
397     if (!filespec1 && !filespec2) {
398         DSOerr(DSO_F_WIN32_MERGER, ERR_R_PASSED_NULL_PARAMETER);
399         return NULL;
400     }
401     if (!filespec2) {
402         merged = OPENSSL_strdup(filespec1);
403         if (merged == NULL) {
404             DSOerr(DSO_F_WIN32_MERGER, ERR_R_MALLOC_FAILURE);
405             return NULL;
406         }
407     } else if (!filespec1) {
408         merged = OPENSSL_strdup(filespec2);
409         if (merged == NULL) {
410             DSOerr(DSO_F_WIN32_MERGER, ERR_R_MALLOC_FAILURE);
411             return NULL;
412         }
413     } else {
414         filespec1_split = win32_splitter(dso, filespec1, 0);
415         if (!filespec1_split) {
416             DSOerr(DSO_F_WIN32_MERGER, ERR_R_MALLOC_FAILURE);
417             return NULL;
418         }
419         filespec2_split = win32_splitter(dso, filespec2, 1);
420         if (!filespec2_split) {
421             DSOerr(DSO_F_WIN32_MERGER, ERR_R_MALLOC_FAILURE);
422             OPENSSL_free(filespec1_split);
423             return NULL;
424         }
425
426         /* Fill in into filespec1_split */
427         if (!filespec1_split->node && !filespec1_split->device) {
428             filespec1_split->node = filespec2_split->node;
429             filespec1_split->nodelen = filespec2_split->nodelen;
430             filespec1_split->device = filespec2_split->device;
431             filespec1_split->devicelen = filespec2_split->devicelen;
432         }
433         if (!filespec1_split->dir) {
434             filespec1_split->dir = filespec2_split->dir;
435             filespec1_split->dirlen = filespec2_split->dirlen;
436         } else if (filespec1_split->dir[0] != '\\'
437                    && filespec1_split->dir[0] != '/') {
438             filespec1_split->predir = filespec2_split->dir;
439             filespec1_split->predirlen = filespec2_split->dirlen;
440         }
441         if (!filespec1_split->file) {
442             filespec1_split->file = filespec2_split->file;
443             filespec1_split->filelen = filespec2_split->filelen;
444         }
445
446         merged = win32_joiner(dso, filespec1_split);
447     }
448     OPENSSL_free(filespec1_split);
449     OPENSSL_free(filespec2_split);
450     return merged;
451 }
452
453 static char *win32_name_converter(DSO *dso, const char *filename)
454 {
455     char *translated;
456     int len, transform;
457
458     len = strlen(filename);
459     transform = ((strstr(filename, "/") == NULL) &&
460                  (strstr(filename, "\\") == NULL) &&
461                  (strstr(filename, ":") == NULL));
462     if (transform)
463         /* We will convert this to "%s.dll" */
464         translated = OPENSSL_malloc(len + 5);
465     else
466         /* We will simply duplicate filename */
467         translated = OPENSSL_malloc(len + 1);
468     if (translated == NULL) {
469         DSOerr(DSO_F_WIN32_NAME_CONVERTER, DSO_R_NAME_TRANSLATION_FAILED);
470         return NULL;
471     }
472     if (transform)
473         sprintf(translated, "%s.dll", filename);
474     else
475         sprintf(translated, "%s", filename);
476     return translated;
477 }
478
479 static const char *openssl_strnchr(const char *string, int c, size_t len)
480 {
481     size_t i;
482     const char *p;
483     for (i = 0, p = string; i < len && *p; i++, p++) {
484         if (*p == c)
485             return p;
486     }
487     return NULL;
488 }
489
490 # include <tlhelp32.h>
491 # ifdef _WIN32_WCE
492 #  define DLLNAME "TOOLHELP.DLL"
493 # else
494 #  ifdef MODULEENTRY32
495 #   undef MODULEENTRY32         /* unmask the ASCII version! */
496 #  endif
497 #  define DLLNAME "KERNEL32.DLL"
498 # endif
499
500 typedef HANDLE(WINAPI *CREATETOOLHELP32SNAPSHOT) (DWORD, DWORD);
501 typedef BOOL(WINAPI *CLOSETOOLHELP32SNAPSHOT) (HANDLE);
502 typedef BOOL(WINAPI *MODULE32) (HANDLE, MODULEENTRY32 *);
503
504 static int win32_pathbyaddr(void *addr, char *path, int sz)
505 {
506     HMODULE dll;
507     HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
508     MODULEENTRY32 me32;
509     CREATETOOLHELP32SNAPSHOT create_snap;
510     CLOSETOOLHELP32SNAPSHOT close_snap;
511     MODULE32 module_first, module_next;
512
513     if (addr == NULL) {
514         union {
515             int (*f) (void *, char *, int);
516             void *p;
517         } t = {
518             win32_pathbyaddr
519         };
520         addr = t.p;
521     }
522
523     dll = LoadLibrary(TEXT(DLLNAME));
524     if (dll == NULL) {
525         DSOerr(DSO_F_WIN32_PATHBYADDR, DSO_R_UNSUPPORTED);
526         return -1;
527     }
528
529     create_snap = (CREATETOOLHELP32SNAPSHOT)
530         GetProcAddress(dll, "CreateToolhelp32Snapshot");
531     if (create_snap == NULL) {
532         FreeLibrary(dll);
533         DSOerr(DSO_F_WIN32_PATHBYADDR, DSO_R_UNSUPPORTED);
534         return -1;
535     }
536     /* We take the rest for granted... */
537 # ifdef _WIN32_WCE
538     close_snap = (CLOSETOOLHELP32SNAPSHOT)
539         GetProcAddress(dll, "CloseToolhelp32Snapshot");
540 # else
541     close_snap = (CLOSETOOLHELP32SNAPSHOT) CloseHandle;
542 # endif
543     module_first = (MODULE32) GetProcAddress(dll, "Module32First");
544     module_next = (MODULE32) GetProcAddress(dll, "Module32Next");
545
546     /*
547      * Take a snapshot of current process which includes
548      * list of all involved modules.
549      */
550     hModuleSnap = (*create_snap) (TH32CS_SNAPMODULE, 0);
551     if (hModuleSnap == INVALID_HANDLE_VALUE) {
552         FreeLibrary(dll);
553         DSOerr(DSO_F_WIN32_PATHBYADDR, DSO_R_UNSUPPORTED);
554         return -1;
555     }
556
557     me32.dwSize = sizeof(me32);
558
559     if (!(*module_first) (hModuleSnap, &me32)) {
560         (*close_snap) (hModuleSnap);
561         FreeLibrary(dll);
562         DSOerr(DSO_F_WIN32_PATHBYADDR, DSO_R_FAILURE);
563         return -1;
564     }
565
566     /* Enumerate the modules to find one which includes me. */
567     do {
568         if ((uintptr_t) addr >= (uintptr_t) me32.modBaseAddr &&
569             (uintptr_t) addr < (uintptr_t) (me32.modBaseAddr + me32.modBaseSize)) {
570             (*close_snap) (hModuleSnap);
571             FreeLibrary(dll);
572 # ifdef _WIN32_WCE
573 #  if _WIN32_WCE >= 101
574             return WideCharToMultiByte(CP_ACP, 0, me32.szExePath, -1,
575                                        path, sz, NULL, NULL);
576 #  else
577             {
578                 int i, len = (int)wcslen(me32.szExePath);
579                 if (sz <= 0)
580                     return len + 1;
581                 if (len >= sz)
582                     len = sz - 1;
583                 for (i = 0; i < len; i++)
584                     path[i] = (char)me32.szExePath[i];
585                 path[len++] = '\0';
586                 return len;
587             }
588 #  endif
589 # else
590             {
591                 int len = (int)strlen(me32.szExePath);
592                 if (sz <= 0)
593                     return len + 1;
594                 if (len >= sz)
595                     len = sz - 1;
596                 memcpy(path, me32.szExePath, len);
597                 path[len++] = '\0';
598                 return len;
599             }
600 # endif
601         }
602     } while ((*module_next) (hModuleSnap, &me32));
603
604     (*close_snap) (hModuleSnap);
605     FreeLibrary(dll);
606     return 0;
607 }
608
609 static void *win32_globallookup(const char *name)
610 {
611     HMODULE dll;
612     HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
613     MODULEENTRY32 me32;
614     CREATETOOLHELP32SNAPSHOT create_snap;
615     CLOSETOOLHELP32SNAPSHOT close_snap;
616     MODULE32 module_first, module_next;
617     union {
618         void *p;
619         FARPROC f;
620     } ret = { NULL };
621
622     dll = LoadLibrary(TEXT(DLLNAME));
623     if (dll == NULL) {
624         DSOerr(DSO_F_WIN32_GLOBALLOOKUP, DSO_R_UNSUPPORTED);
625         return NULL;
626     }
627
628     create_snap = (CREATETOOLHELP32SNAPSHOT)
629         GetProcAddress(dll, "CreateToolhelp32Snapshot");
630     if (create_snap == NULL) {
631         FreeLibrary(dll);
632         DSOerr(DSO_F_WIN32_GLOBALLOOKUP, DSO_R_UNSUPPORTED);
633         return NULL;
634     }
635     /* We take the rest for granted... */
636 # ifdef _WIN32_WCE
637     close_snap = (CLOSETOOLHELP32SNAPSHOT)
638         GetProcAddress(dll, "CloseToolhelp32Snapshot");
639 # else
640     close_snap = (CLOSETOOLHELP32SNAPSHOT) CloseHandle;
641 # endif
642     module_first = (MODULE32) GetProcAddress(dll, "Module32First");
643     module_next = (MODULE32) GetProcAddress(dll, "Module32Next");
644
645     hModuleSnap = (*create_snap) (TH32CS_SNAPMODULE, 0);
646     if (hModuleSnap == INVALID_HANDLE_VALUE) {
647         FreeLibrary(dll);
648         DSOerr(DSO_F_WIN32_GLOBALLOOKUP, DSO_R_UNSUPPORTED);
649         return NULL;
650     }
651
652     me32.dwSize = sizeof(me32);
653
654     if (!(*module_first) (hModuleSnap, &me32)) {
655         (*close_snap) (hModuleSnap);
656         FreeLibrary(dll);
657         return NULL;
658     }
659
660     do {
661         if ((ret.f = GetProcAddress(me32.hModule, name))) {
662             (*close_snap) (hModuleSnap);
663             FreeLibrary(dll);
664             return ret.p;
665         }
666     } while ((*module_next) (hModuleSnap, &me32));
667
668     (*close_snap) (hModuleSnap);
669     FreeLibrary(dll);
670     return NULL;
671 }
672 #endif                          /* DSO_WIN32 */