summaryrefslogtreecommitdiff
path: root/erts/etc/win32/win_erlexec.c
blob: 39dac358e9afa20d5b80157c1a92b4b70a86897e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
/*
 * %CopyrightBegin%
 * 
 * Copyright Ericsson AB 1997-2016. All Rights Reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * %CopyrightEnd%
 */
/*
 * Extra support for running the emulator on Windows.
 * Most of this only used when beam is run as a separate process.
 */

#pragma comment(linker,"/manifestdependency:\"type='win32' "\
		"name='Microsoft.Windows.Common-Controls' "\
		"version='6.0.0.0' processorArchitecture='*' "\
		"publicKeyToken='6595b64144ccf1df' language='*'\"")

#include <windows.h>
#include <winuser.h>
#include <wincon.h>
#include <process.h>
#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif
#include "sys.h"
#include "erl_driver.h"

extern int nohup;
extern int keep_window;
void error(char* format, ...);

/*
 * Local functions.
 */
#define  LOAD_BEAM_DYNAMICALLY 1
static int start(char* emu, char** argv);
static void start_winsock(void);
static char* last_error(void);
static char* last_wsa_error(void);
static char* win32_errorstr(int error);
static int has_console(void);
static char** fnuttify_argv(char **argv);
static void free_fnuttified(char **v);
static int windowed = 0;

#ifdef LOAD_BEAM_DYNAMICALLY
typedef int SysGetKeyFunction(int);
typedef void ErlStartFunction(int, char **);
typedef void SysPrimitiveInitFunction(HMODULE);
static SysGetKeyFunction *sys_get_key_p;
static ErlStartFunction *erl_start_p;
static SysPrimitiveInitFunction *sys_primitive_init_p;

/*
 * To enable debugging of argument processing etc
 * #define ARGS_HARDDEBUG 1
 * #define HARDDEBUG 1
 */

static HMODULE load_win_beam_dll(wchar_t *name)
{
    HMODULE beam_module;
    beam_module=LoadLibraryW(name);
    if (beam_module == INVALID_HANDLE_VALUE || beam_module == NULL) {
	error("Unable to load emulator DLL\n(%S)",name);
	return NULL;
    }
    sys_get_key_p = (SysGetKeyFunction *) 
	GetProcAddress(beam_module, "sys_get_key");
    erl_start_p = (ErlStartFunction *)
	GetProcAddress(beam_module, "erl_start");
    sys_primitive_init_p = (SysPrimitiveInitFunction *)
	GetProcAddress(beam_module, "sys_primitive_init");
    return beam_module;
}
#endif

#define DLL_ENV "ERL_EMULATOR_DLL"

static void
set_env(char *key, char *value) /* Both in UTF-8 encoding */
{
    wchar_t *wkey=NULL;
    wchar_t *wvalue=NULL;
    int keylen;
    int valuelen;


    keylen = MultiByteToWideChar(CP_UTF8, 0, key, -1, NULL, 0);
    valuelen = MultiByteToWideChar(CP_UTF8, 0, value, -1, NULL, 0);
    wkey = malloc(keylen*sizeof(wchar_t));
    wvalue = malloc(valuelen*sizeof(wchar_t));
    MultiByteToWideChar(CP_UTF8, 0, key, -1, wkey, keylen);
    MultiByteToWideChar(CP_UTF8, 0, value, -1, wvalue, valuelen);
    if (!SetEnvironmentVariableW( wkey, wvalue))
	error("SetEnvironmentVariable(\"%s\", \"%s\") failed!", key, value);
}

static char *
get_env(char *key)
{
    DWORD size = 32;
    char *value = NULL;
    while (1) {
	DWORD nsz;
	if (value)
	    free(value);
	value = malloc(size);
	if (!value)
	    error("GetEnvironmentVariable(\"%s\") failed", key);
	SetLastError(0);
	nsz = GetEnvironmentVariable((LPCTSTR) key, (LPTSTR) value, size);
	if (nsz == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
	    free(value);
	    return NULL;
	}
	if (nsz <= size)
	    return value;
	size = nsz;
    }
}

free_env_val(char *value)
{
    if (value)
	free(value);
}


int
start_win_emulator(char* utf8emu, char *utf8start_prog, char** utf8argv, int start_detached)
{
    int len;
    int argc = 0;

    windowed = 1;
    while (utf8argv[argc] != NULL) {
	++argc;
    }

    if (start_detached) {
	wchar_t *start_prog=NULL;
	int result;
	int i;
	wchar_t **argv;
	close(0);
	close(1);
	close(2);
	
	set_env("ERL_CONSOLE_MODE", "detached");
	set_env(DLL_ENV, utf8emu);

	utf8argv[0] = utf8start_prog;
	utf8argv = fnuttify_argv(utf8argv);

	len = MultiByteToWideChar(CP_UTF8, 0, utf8start_prog, -1, NULL, 0);
	start_prog = malloc(len*sizeof(wchar_t));
	MultiByteToWideChar(CP_UTF8, 0, utf8start_prog, -1, start_prog, len);

	/* Convert utf8argv to multibyte argv */
	argv = malloc((argc+1) * sizeof(wchar_t*));
	for (i=0; i<argc; i++) {
	    len = MultiByteToWideChar(CP_UTF8, 0, utf8argv[i], -1, NULL, 0);
	    argv[i] = malloc(len*sizeof(wchar_t));
	    MultiByteToWideChar(CP_UTF8, 0, utf8argv[i], -1, argv[i], len);
	}
	argv[argc] = NULL;

#ifdef ARGS_HARDDEBUG
	{
	    wchar_t tempbuf[2048] = L"";
	    wchar_t *sbuf;
	    int i;
	    sbuf=tempbuf;
	    sbuf += swprintf(sbuf, 2048, L"utf16: %s\n", start_prog);
	    for (i = 0; i < argc; ++i) {
		sbuf += swprintf(sbuf, 2048, L"|%s|", argv[i]);
	    };
	    sbuf += swprintf(sbuf, 2048, L"\nutf8: \n");
	    for (i = 0; i < argc; ++i) {
		sbuf += swprintf(sbuf, 2048, L"|%S|", utf8argv[i]);
	    };
	    MessageBoxW(NULL, tempbuf, L"respawn args", MB_OK|MB_ICONERROR);
	}
#endif

	result = _wspawnv(_P_DETACH, start_prog, argv);
	free_fnuttified(utf8argv);
	if (result == -1) {
	    error("Failed to execute %S: %s", start_prog, win32_errorstr(_doserrno));
	}
    } else {
	wchar_t *emu=NULL;
#ifdef LOAD_BEAM_DYNAMICALLY
	HMODULE beam_module = NULL;
	len = MultiByteToWideChar(CP_UTF8, 0, utf8emu, -1, NULL, 0);
	emu = malloc(len*sizeof(wchar_t));
	MultiByteToWideChar(CP_UTF8, 0, utf8emu, -1, emu, len);
#ifdef ARGS_HARDDEBUG
	{
	    char sbuf[2048] = "";
	    int i;
	    strcat(sbuf,utf8emu);
	    strcat(sbuf,":");
	    for (i = 0; i < argc; ++i) {
		strcat(sbuf,"|");
		strcat(sbuf, utf8argv[i]);
		strcat(sbuf,"| ");
	    }
	    MessageBox(NULL, sbuf, "erl_start args", MB_OK|MB_ICONERROR);
	}
#endif
	beam_module = load_win_beam_dll(emu);
#endif	
	set_env("ERL_CONSOLE_MODE", "window");
#ifdef LOAD_BEAM_DYNAMICALLY
	(*sys_primitive_init_p)(beam_module);
	(*erl_start_p)(argc,utf8argv);
#else
	erl_start(argc,utf8argv);
#endif
    }
    return 0;
}

void __cdecl 
do_keep_window(void)
{
    printf("\nPress any key to close window.\n");
#ifdef LOAD_BEAM_DYNAMICALLY
    (*sys_get_key_p)(0);
#else 
    sys_get_key(0);
#endif 
}

int
start_emulator(char* utf8emu, char *utf8start_prog, char** utf8argv, int start_detached)
{
    static char console_mode[] = "tty:ccc";
    char* fd_type;
    char* title;
    int len;
    int argc = 0;

#ifdef HARDDEBUG
    fprintf(stderr,"utf8emu = %s, start_prog = %s\n", utf8emu, utf8start_prog);
#endif

    fd_type = strchr(console_mode, ':');
    fd_type++;
    _flushall();

    while (utf8argv[argc] != NULL) {
	++argc;
    }

    /*
     * If no console, we will spawn the emulator detached.
     */

    if (start_detached) {
	int result;
	int i;
	wchar_t *start_prog=NULL;
	wchar_t **argv;
	close(0);
	close(1);
	close(2);
	set_env("ERL_CONSOLE_MODE", "detached");
	set_env(DLL_ENV, utf8emu);

	utf8argv[0] = utf8start_prog;
	utf8argv = fnuttify_argv(utf8argv);

	len = MultiByteToWideChar(CP_UTF8, 0, utf8start_prog, -1, NULL, 0);
	start_prog = malloc(len*sizeof(wchar_t));
	MultiByteToWideChar(CP_UTF8, 0, utf8start_prog, -1, start_prog, len);

	/* Convert utf8argv to multibyte argv */
	argv = malloc((argc+1) * sizeof(wchar_t*));
	for (i=0; i<argc; i++) {
	    len = MultiByteToWideChar(CP_UTF8, 0,utf8argv[i], -1, NULL, 0);
	    argv[i] = malloc(len*sizeof(wchar_t));
	    MultiByteToWideChar(CP_UTF8, 0, utf8argv[i], -1, argv[i], len);
	}
	argv[argc] = NULL;

#ifdef ARGS_HARDDEBUG
	{
	    wchar_t buffer[2048];
	    int i;
	    wsprintfW(buffer,L"Start detached [%s]\n",start_prog);
	    for(i=0;argv[i] != NULL;++i) {
		wcscat(buffer,L"|");
		wcscat(buffer,argv[i]);
		wcscat(buffer,L"|\n");
	    }
	    MessageBoxW(NULL, buffer, L"Start detached",MB_OK);
	}
#endif
	result = _wspawnv(_P_DETACH, start_prog, argv);
	free_fnuttified(utf8argv);
	free(start_prog);

	if (result == -1) {
#ifdef ARGS_HARDDEBUG
	    MessageBox(NULL, "_wspawnv failed","Start detached",MB_OK);
#endif
	    return 1;
	}
	SetPriorityClass((HANDLE) result, GetPriorityClass(GetCurrentProcess()));
    } else {
	wchar_t *emu=NULL;
#ifdef LOAD_BEAM_DYNAMICALLY
	HMODULE beam_module;
	len = MultiByteToWideChar(CP_UTF8, 0, utf8emu, -1, NULL, 0);
	emu = malloc(len*sizeof(wchar_t));
	MultiByteToWideChar(CP_UTF8, 0, utf8emu, -1, emu, len);
#ifdef ARGS_HARDDEBUG
	{
	    char sbuf[2048] = "";
	    int i;
	    strcat(sbuf,utf8emu);
	    strcat(sbuf,":");
	    for (i = 0; i < argc; ++i) {
		strcat(sbuf,"|");
		strcat(sbuf, utf8argv[i]);
		strcat(sbuf,"| ");
	    }
	    MessageBox(NULL, sbuf, "erl_start args", MB_OK|MB_ICONERROR);
	}
#endif
	beam_module = load_win_beam_dll(emu);
#endif	

	/*
	 * Start the emulator.
	 */

	title = get_env("ERL_WINDOW_TITLE");
	if (title) {
	    SetConsoleTitle(title);
	}
	free_env_val(title);
	
	set_env("ERL_CONSOLE_MODE", console_mode);
	if (keep_window) {
	    atexit(do_keep_window);
	}
#ifdef ARGS_HARDDEBUG
	{
	    char sbuf[2048] = "";
	    int i;
	    for (i = 0; i < argc; ++i) {
		strcat(sbuf,"|");
		strcat(sbuf, utf8argv[i]);
		strcat(sbuf,"|\n");
	    }
	    MessageBox(NULL, sbuf, "erl_start", MB_OK);
	}
#endif
#ifdef LOAD_BEAM_DYNAMICALLY
	(*sys_primitive_init_p)(beam_module);
	(*erl_start_p)(argc,utf8argv);
#else
	erl_start(argc, utf8argv);
#endif
    }
    return 0;
}

void
error(char* format, ...)
{
    char sbuf[2048];
    va_list ap;

    va_start(ap, format);
    vsprintf(sbuf, format, ap);
    va_end(ap);

    if (!windowed && has_console()) {
	fprintf(stderr, "%s\n", sbuf);
    } else {
	MessageBox(NULL, sbuf, "Werl", MB_OK|MB_ICONERROR);
    }
    exit(1);
}

static char*
last_error(void)
{
    return win32_errorstr(GetLastError());
}

/*
 * Returns a human-readable description of the last error.
 * The returned pointer will be valid only as long as last-error()
 * isn't called again.
 */

static char*
win32_errorstr(int error)
{
    static LPTSTR lpBufPtr = NULL;

    if (lpBufPtr)
	LocalFree(lpBufPtr);
    FormatMessage(
		  FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
		  NULL,
		  error,
		  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		  (LPTSTR) &lpBufPtr,
		  0,
		  NULL);
    SetLastError(error);
    return lpBufPtr;
}

static int
has_console(void)
{
    HANDLE handle = CreateFile("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE,
			       NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    if (handle != INVALID_HANDLE_VALUE) {
        CloseHandle(handle);
	return 1;
    } else {
        return 0;
    }
}

static char** fnuttify_argv(char **argv)
{
    char **v;
    char *p;
    char *q;
    int c;
    int i;
    int n;
    int m;

    for (c = 0; argv[c]; ++c)
	;

    v = malloc(sizeof(char *) * (c+1));
    v[c] = NULL;
    for (i = 0; i < c; ++i) {
	p = argv[i];
	n = m = 0;
	while (*p) {
	    if (*p == ' ') {
		m = 2;
	    } else if (*p == '"') {
		m = 2;
		++n;
	    }
	    ++p;
	}
	v[i] = malloc((p - argv[i]) + 1 + n + m);
	p = argv[i];
	q = v[i];
	if (n || m) {
	    if (m) {
		*q++ = '"';
	    }
	    while (*p) {
		if (*p == '"') {
		    *q++ = '\\';
		}
		*q++ = *p++;
	    }
	    if (m) {
		*q++ = '"';
	    }
	    *q = '\0';
	} else {
	    strcpy(q,p);
	}
    }
    return v;
}

static void free_fnuttified(char **v)
{
    char **t = v;

    while(*t) {
	free(*t);
	++t;
    }
    free(v);
}