Bugfixes of ASTERIX I034
[metze/wireshark/wip.git] / cli_main.c
1 /*
2  * Compile and link this with all CLI programs where the main routine
3  * should get UTF-8 arguments on Windows.  In those programs, include the
4  * cli_main.h header to rename main to real_main on Windows.
5  *
6  * This is used in software licensed under the GPLv2, and its license MUST
7  * be compatible with that license.
8  *
9  * This is used in software licensed under the Apache 2.0 license, and its
10  * license MUST be compatible with that license.
11  *
12  * For that purpose, we use the MIT (X11) license.
13  *
14  * SPDX-License-Identifier: MIT
15  */
16
17 #include "cli_main.h"
18
19 #ifdef _WIN32
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <windows.h>
23
24 int
25 wmain(int argc, wchar_t *wc_argv[])
26 {
27         char **argv;
28         int i;
29
30         argv = (char **)malloc((argc + 1) * sizeof(char *));
31         if (argv == NULL) {
32                 fprintf(stderr, "Out of memory for converted argument list\n");
33                 return 2;
34         }
35         for (i = 0; i < argc; i++) {
36                 /*
37                  * XXX = use WC_ERR_INVALID_CHARS rather than 0, and fail if
38                  * the argument isn't valid UTF-16?
39                  */
40                 int width;
41                 char *utf8_string;
42
43                 width = WideCharToMultiByte(CP_UTF8, 0, wc_argv[i], -1, NULL, 0,
44                     NULL, NULL);
45                 if (width == 0) {
46                         fprintf(stderr, "WideCharToMultiByte failed: %d\n",
47                             width);
48                         return 2;
49                 }
50                 utf8_string = malloc(width);
51                 if (utf8_string == NULL) {
52                         fprintf(stderr,
53                             "Out of memory for converted argument list\n");
54                         return 2;
55                 }
56                 if (WideCharToMultiByte(CP_UTF8, 0, wc_argv[i], -1, utf8_string,
57                     width, NULL, NULL) == 0) {
58                         fprintf(stderr, "WideCharToMultiByte failed: %d\n",
59                             width);
60                         return 2;
61                 }
62                 argv[i] = utf8_string;
63         }
64         argv[i] = NULL;
65         /*
66          * The original "main" routine was renamed to "real_main" via a macro in
67          * the cli_main.h header file since either "main" or "wmain" can be
68          * defined on Windows, but not both.
69          */
70         return real_main(argc, argv);
71 }
72 #endif